diff --git a/Makefile.in b/Makefile.in index fef026eb40..0cb97aa983 100644 --- a/Makefile.in +++ b/Makefile.in @@ -87,7 +87,8 @@ DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ config.guess config.rpath config.sub install-sh missing \ ltmain.sh ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -236,6 +237,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -309,6 +311,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/README.md b/README.md index 6e3c09568b..7c799b8ee0 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ create cross platform applications. It is an open source implementation of Microsoft's .NET Framework based on the ECMA standards for C# and the Common Language Runtime. -The Mono project is part of the [.NET Foundation](http://www.dotnetfoundation.org/) +The Mono project is part of the [.NET Foundation](https://www.dotnetfoundation.org/) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mono/mono?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) @@ -66,15 +66,15 @@ Building the Software --------------------- Please see our guides for building Mono on -[Mac OS X](http://www.mono-project.com/docs/compiling-mono/mac/), -[Linux](http://www.mono-project.com/docs/compiling-mono/linux/) and -[Windows](http://www.mono-project.com/docs/compiling-mono/windows/). +[Mac OS X](https://www.mono-project.com/docs/compiling-mono/mac/), +[Linux](https://www.mono-project.com/docs/compiling-mono/linux/) and +[Windows](https://www.mono-project.com/docs/compiling-mono/windows/). Note that building from Git assumes that you already have Mono installed, -so please download and [install the latest Mono release](http://www.mono-project.com/download/) +so please download and [install the latest Mono release](https://www.mono-project.com/download/) before trying to build from Git. This is required because the Mono build relies on a working Mono C# compiler to compile itself -(also known as [bootstrapping](http://en.wikipedia.org/wiki/Bootstrapping_(compilers))). +(also known as [bootstrapping](https://en.wikipedia.org/wiki/Bootstrapping_(compilers))). If you don't have a working Mono installation --------------------------------------------- @@ -203,9 +203,9 @@ Contributing to Mono ==================== Before submitting changes to Mono, please review the [contribution -guidelines](http://www.mono-project.com/community/contributing/). +guidelines](https://www.mono-project.com/community/contributing/). Please pay particular attention to the [Important -Rules](http://www.mono-project.com/community/contributing/#important-rules) +Rules](https://www.mono-project.com/community/contributing/#important-rules) section. Reporting bugs @@ -215,7 +215,7 @@ To submit bug reports, please [open an issue on the mono GitHub repo](https://gi Please use the search facility to ensure the same bug hasn't already been submitted and follow our -[guidelines](http://www.mono-project.com/community/bugs/make-a-good-bug-report/) +[guidelines](https://www.mono-project.com/community/bugs/make-a-good-bug-report/) on how to make a good bug report. Configuration Options @@ -435,7 +435,7 @@ for Mono. The LLVM code generator and optimizer will be used instead of Mono's built-in code generator for both Just in Time and Ahead of Time compilations. - * See http://www.mono-project.com/docs/advanced/mono-llvm/ for the + * See https://www.mono-project.com/docs/advanced/mono-llvm/ for the full details and up-to-date information on this feature. * You will need to have an LLVM built that Mono can link @@ -504,7 +504,7 @@ also, see the man page. * This configures the Mono compiler to generate code suitable to be used by Google's Native Client: -http://code.google.com/p/nativeclient/ +https://code.google.com/p/nativeclient/ * Currently this is used with Mono's AOT engine as Native Client does not support JIT engines yet. @@ -578,7 +578,7 @@ file for information about Microsoft's patent grant. Mono Trademark Use Policy ========================= -The use of trademarks and logos for Mono can be found [here](http://www.dotnetfoundation.org/legal/mono-tm). +The use of trademarks and logos for Mono can be found [here](https://www.dotnetfoundation.org/legal/mono-tm). Maintaining the Class Library Solution Files ============================================ diff --git a/acceptance-tests/Makefile.in.REMOVED.git-id b/acceptance-tests/Makefile.in.REMOVED.git-id index 25ac7ffc84..730e13893d 100644 --- a/acceptance-tests/Makefile.in.REMOVED.git-id +++ b/acceptance-tests/Makefile.in.REMOVED.git-id @@ -1 +1 @@ -7f3958be9a6931aca43164ee90cc309157607744 \ No newline at end of file +cb058025d26cfa053c0882a56a7f57c3c6f3039f \ No newline at end of file diff --git a/acceptance-tests/SUBMODULES.json b/acceptance-tests/SUBMODULES.json index 106bd8f81e..66b35cb1d2 100644 --- a/acceptance-tests/SUBMODULES.json +++ b/acceptance-tests/SUBMODULES.json @@ -2,7 +2,7 @@ { "name": "roslyn", "url": "git://github.com/mono/roslyn.git", - "rev": "380eec412868464a132cdcd3a45ef457fab6e060", + "rev": "7a840bd5697ef6ea41f554a09d837636fba9d88d", "remote-branch": "origin/mono-testing", "branch": "mono-testing", "directory": "roslyn" @@ -10,7 +10,7 @@ { "name": "coreclr", "url": "git://github.com/mono/coreclr.git", - "rev": "aa62c0382ae79562293f3ea1a94ef0f16f80f498", + "rev": "f3d9c9f742f9dcb5faf40080db5e7f464dab7e7c", "remote-branch": "origin/mono", "branch": "mono", "directory": "coreclr" diff --git a/acceptance-tests/coreclr.mk.REMOVED.git-id b/acceptance-tests/coreclr.mk.REMOVED.git-id index b0809b57c9..f1a9263098 100644 --- a/acceptance-tests/coreclr.mk.REMOVED.git-id +++ b/acceptance-tests/coreclr.mk.REMOVED.git-id @@ -1 +1 @@ -51dbbe569e45412d294d6d996ba1a802f3f87374 \ No newline at end of file +13b43e9df6ba9f7daec06423c357a9e67e9b082a \ No newline at end of file diff --git a/acceptance-tests/roslyn.mk b/acceptance-tests/roslyn.mk index c4e8c86649..ab1a86652e 100644 --- a/acceptance-tests/roslyn.mk +++ b/acceptance-tests/roslyn.mk @@ -1,5 +1,5 @@ check-roslyn: @$(MAKE) validate-roslyn RESET_VERSIONS=1 cd $(ROSLYN_PATH); \ - ./mono-testing.sh "$(XUNIT)" || exit; \ + ./build.sh --restore --build --test --mono || exit; \ echo "done" diff --git a/aclocal.m4 b/aclocal.m4 index 3c4db3fe8d..9de67f985c 100644 --- a/aclocal.m4 +++ b/aclocal.m4 @@ -1203,6 +1203,7 @@ AC_SUBST([am__tar]) AC_SUBST([am__untar]) ]) # _AM_PROG_TAR +m4_include([m4/apple-target.m4]) m4_include([m4/ax_check_compile_flag.m4]) m4_include([m4/libtool.m4]) m4_include([m4/ltoptions.m4]) diff --git a/config.h.in b/config.h.in index 1827c4a43a..c37dddab5f 100644 --- a/config.h.in +++ b/config.h.in @@ -191,9 +191,6 @@ /* Have access */ #undef HAVE_ACCESS -/* Has the 'aintl' function */ -#undef HAVE_AINTL - /* Define to 1 if you have the header file. */ #undef HAVE_ALLOCA_H @@ -386,9 +383,6 @@ /* Define to 1 if you have the `fgetpwent' function. */ #undef HAVE_FGETPWENT -/* Define to 1 if you have the `finite' function. */ -#undef HAVE_FINITE - /* struct flock64 */ #undef HAVE_FLOCK64 @@ -485,6 +479,9 @@ /* Have getprotobyname */ #undef HAVE_GETPROTOBYNAME +/* Have getprotobyname_r */ +#undef HAVE_GETPROTOBYNAME_R + /* Define to 1 if you have the `getpwent' function. */ #undef HAVE_GETPWENT @@ -512,15 +509,18 @@ /* Define to 1 if you have the header file. */ #undef HAVE_GRP_H +/* GSS/GSS.h */ +#undef HAVE_GSSFW_HEADERS + +/* GSS_SPNEGO_MECHANISM */ +#undef HAVE_GSS_SPNEGO_MECHANISM + /* ICANON */ #undef HAVE_ICANON /* Define to 1 if you have the header file. */ #undef HAVE_ICONV_H -/* Define to 1 if you have the header file. */ -#undef HAVE_IEEEFP_H - /* Have if_nametoindex */ #undef HAVE_IF_NAMETOINDEX @@ -587,12 +587,6 @@ /* Have IP_PMTUDISC_DO */ #undef HAVE_IP_PMTUDISC_DO -/* Define to 1 if you have the `isfinite' function. */ -#undef HAVE_ISFINITE - -/* isinf available */ -#undef HAVE_ISINF - /* Define to 1 if you have the `kill' function. */ #undef HAVE_KILL @@ -629,9 +623,6 @@ /* Define to 1 if you have the header file. */ #undef HAVE_LINUX_SERIAL_H -/* Define to 1 if you have the header file. */ -#undef HAVE_LOCALCHARSET_H - /* Define to 1 if you have the `localtime_r' function. */ #undef HAVE_LOCALTIME_R @@ -659,7 +650,7 @@ /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H -/* Have mincore */ +/* Define to 1 if you have the `mincore' function. */ #undef HAVE_MINCORE /* Define to 1 if you have the `mkdtemp' function. */ @@ -674,6 +665,9 @@ /* mkstemps */ #undef HAVE_MKSTEMPS +/* Define to 1 if you have the `mlock' function. */ +#undef HAVE_MLOCK + /* Define to 1 if you have the `mmap' function. */ #undef HAVE_MMAP @@ -689,6 +683,9 @@ /* Have MSG_NOSIGNAL */ #undef HAVE_MSG_NOSIGNAL +/* Define to 1 if you have the `munlock' function. */ +#undef HAVE_MUNLOCK + /* Define to 1 if you have the header file. */ #undef HAVE_NETDB_H @@ -701,6 +698,9 @@ /* Define to 1 if you have the header file. */ #undef HAVE_NET_IF_H +/* Define to 1 if you have the `nl_langinfo' function. */ +#undef HAVE_NL_LANGINFO + /* _NSGetEnviron */ #undef HAVE_NSGETENVIRON @@ -885,9 +885,6 @@ /* Define to 1 if you have the header file. */ #undef HAVE_SIGNAL_H -/* Have signbit */ -#undef HAVE_SIGNBIT - /* Can get interface list */ #undef HAVE_SIOCGIFCONF @@ -984,6 +981,9 @@ /* Define to 1 if the system has the type `struct flock'. */ #undef HAVE_STRUCT_FLOCK +/* Define to 1 if the system has the type `struct flock64'. */ +#undef HAVE_STRUCT_FLOCK64 + /* Define to 1 if the system has the type `struct iovec'. */ #undef HAVE_STRUCT_IOVEC @@ -1227,9 +1227,6 @@ /* Have tm_gmtoff */ #undef HAVE_TM_GMTOFF -/* Define to 1 if you have the `trunc' function. */ -#undef HAVE_TRUNC - /* Define to 1 if you have the `ttyname_r' function. */ #undef HAVE_TTYNAME_R @@ -1287,9 +1284,6 @@ /* Have system zlib */ #undef HAVE_ZLIB -/* Define to 1 if you have the `_finite' function. */ -#undef HAVE__FINITE - /* ... */ #undef HOST_AMD64 @@ -1326,7 +1320,7 @@ /* ... */ #undef HOST_SPARC64 -/* Host wasm */ +/* ... */ #undef HOST_WASM /* Host Platform is Win32 */ @@ -1371,6 +1365,9 @@ /* The architecture this is running on */ #undef MONO_ARCHITECTURE +/* 64 bit mode with 4 byte longs and pointers */ +#undef MONO_ARCH_ILP32 + /* Enable the allocation and indexing of arrays greater than Int32.MaxValue */ #undef MONO_BIG_ARRAYS @@ -1521,7 +1518,7 @@ /* ... */ #undef TARGET_SPARC64 -/* Target wasm */ +/* ... */ #undef TARGET_WASM /* The JIT/AOT targets WatchOS */ @@ -1563,8 +1560,5 @@ # endif #endif -/* 64 bit mode with 4 byte longs and pointers */ -#undef __mono_ilp32__ - /* ... */ #undef __mono_ppc64__ diff --git a/configure.REMOVED.git-id b/configure.REMOVED.git-id index ae98540aa8..42d67b623a 100644 --- a/configure.REMOVED.git-id +++ b/configure.REMOVED.git-id @@ -1 +1 @@ -abcafbe084344540b260daaaa4b5b185cd31ac72 \ No newline at end of file +7ea109857e824ef015de7d2a2c808d994f6356b7 \ No newline at end of file diff --git a/configure.ac.REMOVED.git-id b/configure.ac.REMOVED.git-id index f88d6d9a70..343d4fdf71 100644 --- a/configure.ac.REMOVED.git-id +++ b/configure.ac.REMOVED.git-id @@ -1 +1 @@ -e812cfaf4527e5c2e22f750867ee8e073846bc28 \ No newline at end of file +38a8192e8bea043bb0bc52e78aa307fb8fade1b7 \ No newline at end of file diff --git a/data/Makefile.in b/data/Makefile.in index f35ba4b1bc..8503baa0fa 100644 --- a/data/Makefile.in +++ b/data/Makefile.in @@ -94,7 +94,8 @@ DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(srcdir)/system.web.mvc3.pc.in $(srcdir)/aspnetwebstack.pc.in \ $(srcdir)/reactive.pc.in $(srcdir)/config.in README ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -259,6 +260,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -332,6 +334,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/data/config.in b/data/config.in index dbef498893..7cbb9cdb0f 100644 --- a/data/config.in +++ b/data/config.in @@ -11,7 +11,9 @@ - + + + diff --git a/data/net_2_0/Browsers/Makefile.in b/data/net_2_0/Browsers/Makefile.in index 5956659304..0ce3d46672 100644 --- a/data/net_2_0/Browsers/Makefile.in +++ b/data/net_2_0/Browsers/Makefile.in @@ -83,7 +83,8 @@ subdir = data/net_2_0/Browsers DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -181,6 +182,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -254,6 +256,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/data/net_2_0/Makefile.in b/data/net_2_0/Makefile.in index 5041e25914..6647604800 100644 --- a/data/net_2_0/Makefile.in +++ b/data/net_2_0/Makefile.in @@ -83,7 +83,8 @@ subdir = data/net_2_0 DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -241,6 +242,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -314,6 +316,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/data/net_4_0/Browsers/Makefile.in b/data/net_4_0/Browsers/Makefile.in index 694fb1572c..ca25034bae 100644 --- a/data/net_4_0/Browsers/Makefile.in +++ b/data/net_4_0/Browsers/Makefile.in @@ -83,7 +83,8 @@ subdir = data/net_4_0/Browsers DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -181,6 +182,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -254,6 +256,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/data/net_4_0/Makefile.in b/data/net_4_0/Makefile.in index 181bc6702f..3815e135cb 100644 --- a/data/net_4_0/Makefile.in +++ b/data/net_4_0/Makefile.in @@ -83,7 +83,8 @@ subdir = data/net_4_0 DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -241,6 +242,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -314,6 +316,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/data/net_4_5/Browsers/Makefile.in b/data/net_4_5/Browsers/Makefile.in index ad44cac612..36a524a0c3 100644 --- a/data/net_4_5/Browsers/Makefile.in +++ b/data/net_4_5/Browsers/Makefile.in @@ -83,7 +83,8 @@ subdir = data/net_4_5/Browsers DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -181,6 +182,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -254,6 +256,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/data/net_4_5/Makefile.in b/data/net_4_5/Makefile.in index 723f4318b0..2bf6d3bedd 100644 --- a/data/net_4_5/Makefile.in +++ b/data/net_4_5/Makefile.in @@ -83,7 +83,8 @@ subdir = data/net_4_5 DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -241,6 +242,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -314,6 +316,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/docs/Makefile.in b/docs/Makefile.in index 1de153f572..cdf89799fe 100644 --- a/docs/Makefile.in +++ b/docs/Makefile.in @@ -83,7 +83,8 @@ subdir = docs DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs README TODO ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -181,6 +182,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -254,6 +256,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/docs/deploy/mono-api-assembly.html b/docs/deploy/mono-api-assembly.html index 855961bc6e..da902c70b1 100644 --- a/docs/deploy/mono-api-assembly.html +++ b/docs/deploy/mono-api-assembly.html @@ -1,4 +1,4 @@ - + mono-api-assembly.html diff --git a/docs/deploy/mono-api-class.html b/docs/deploy/mono-api-class.html index 92b8c0fe92..dd1c8fd863 100644 --- a/docs/deploy/mono-api-class.html +++ b/docs/deploy/mono-api-class.html @@ -1,4 +1,4 @@ - + mono-api-class.html diff --git a/docs/deploy/mono-api-counters.html b/docs/deploy/mono-api-counters.html index 51b4f8f122..72d3d6766a 100644 --- a/docs/deploy/mono-api-counters.html +++ b/docs/deploy/mono-api-counters.html @@ -1,4 +1,4 @@ - + mono-api-counters.html diff --git a/docs/deploy/mono-api-debug.html b/docs/deploy/mono-api-debug.html index d83560fe1e..1ec044611e 100644 --- a/docs/deploy/mono-api-debug.html +++ b/docs/deploy/mono-api-debug.html @@ -1,4 +1,4 @@ - + mono-api-debug.html diff --git a/docs/deploy/mono-api-domains.html b/docs/deploy/mono-api-domains.html index 539a77f6ea..1d2a2b6126 100644 --- a/docs/deploy/mono-api-domains.html +++ b/docs/deploy/mono-api-domains.html @@ -1,4 +1,4 @@ - + mono-api-domains.html @@ -664,7 +664,7 @@ mono_domain_set (MonoDomain *domain, gboolean force)
Syntax
MonoReflectionAssembly* -mono_domain_try_type_resolve (MonoDomain *domain, char *name, MonoObject *typebuilder) +mono_domain_try_type_resolve (MonoDomain *domain, char *name, MonoObject *typebuilder_raw)

diff --git a/docs/deploy/mono-api-dynamic-codegen.html b/docs/deploy/mono-api-dynamic-codegen.html index 3cba3a70fd..82f03fffdb 100644 --- a/docs/deploy/mono-api-dynamic-codegen.html +++ b/docs/deploy/mono-api-dynamic-codegen.html @@ -1,4 +1,4 @@ - + mono-api-dynamic-codegen.html diff --git a/docs/deploy/mono-api-embedding.html b/docs/deploy/mono-api-embedding.html index fd7b4b5e07..c2a713164e 100644 --- a/docs/deploy/mono-api-embedding.html +++ b/docs/deploy/mono-api-embedding.html @@ -1,4 +1,4 @@ - + mono-api-embedding.html diff --git a/docs/deploy/mono-api-exc.html b/docs/deploy/mono-api-exc.html index 9ed0638f36..208155bfa2 100644 --- a/docs/deploy/mono-api-exc.html +++ b/docs/deploy/mono-api-exc.html @@ -1,4 +1,4 @@ - + mono-api-exc.html diff --git a/docs/deploy/mono-api-gc.html b/docs/deploy/mono-api-gc.html index c39b898e4c..732506115b 100644 --- a/docs/deploy/mono-api-gc.html +++ b/docs/deploy/mono-api-gc.html @@ -1,4 +1,4 @@ - + mono-api-gc.html diff --git a/docs/deploy/mono-api-gchandle.html b/docs/deploy/mono-api-gchandle.html index 6c9dac5d73..e522cffa8f 100644 --- a/docs/deploy/mono-api-gchandle.html +++ b/docs/deploy/mono-api-gchandle.html @@ -1,4 +1,4 @@ - + mono-api-gchandle.html diff --git a/docs/deploy/mono-api-image.html b/docs/deploy/mono-api-image.html index b8f536f782..795bdd0ce0 100644 --- a/docs/deploy/mono-api-image.html +++ b/docs/deploy/mono-api-image.html @@ -1,4 +1,4 @@ - + mono-api-image.html diff --git a/docs/deploy/mono-api-internal.html b/docs/deploy/mono-api-internal.html index 49ffbbe089..ada34d925e 100644 --- a/docs/deploy/mono-api-internal.html +++ b/docs/deploy/mono-api-internal.html @@ -1,4 +1,4 @@ - + mono-api-internal.html @@ -992,7 +992,7 @@ mono_loader_unlock (void)

Syntax
-
void* +
MonoObject* mono_gc_alloc_fixed (size_t size, MonoGCDescriptor descr, MonoGCRootSource source, void *key, const char *msg)
diff --git a/docs/deploy/mono-api-jit.html b/docs/deploy/mono-api-jit.html index bdb10fbf04..02d7b8f1fb 100644 --- a/docs/deploy/mono-api-jit.html +++ b/docs/deploy/mono-api-jit.html @@ -1,4 +1,4 @@ - + mono-api-jit.html diff --git a/docs/deploy/mono-api-jitinternal.html b/docs/deploy/mono-api-jitinternal.html index 870398e307..7a875586f4 100644 --- a/docs/deploy/mono-api-jitinternal.html +++ b/docs/deploy/mono-api-jitinternal.html @@ -1,4 +1,4 @@ - + mono-api-jitinternal.html @@ -681,7 +681,7 @@ mono_mempool_destroy (MonoMemPool *pool)
Syntax
gpointer -mono_mempool_alloc (MonoMemPool *pool, guint size) +(mono_mempool_alloc) (MonoMemPool *pool, guint size)

@@ -708,7 +708,7 @@ mono_mempool_alloc (MonoMemPool *pool, guint size)

Syntax
gpointer -mono_mempool_alloc0 (MonoMemPool *pool, guint size) +(mono_mempool_alloc0) (MonoMemPool *pool, guint size)

@@ -1352,10 +1352,7 @@ mono_bitset_intersection_2 (MonoBitSet *dest, const MonoBitSet *src1, const Mono

Syntax
-
int -mono_signbit_double (double x) - -
+
mono_signbit_double

@@ -1370,10 +1367,7 @@ mono_signbit_double (double x)
Syntax
-
int -mono_signbit_float (float x) - -
+
mono_signbit_float

diff --git a/docs/deploy/mono-api-metadata.html b/docs/deploy/mono-api-metadata.html index ea0ea63480..b765c3076e 100644 --- a/docs/deploy/mono-api-metadata.html +++ b/docs/deploy/mono-api-metadata.html @@ -1,4 +1,4 @@ - + mono-api-metadata.html diff --git a/docs/deploy/mono-api-methods.html b/docs/deploy/mono-api-methods.html index 0c2d1ce457..4d18ca5f87 100644 --- a/docs/deploy/mono-api-methods.html +++ b/docs/deploy/mono-api-methods.html @@ -1,4 +1,4 @@ - + mono-api-methods.html diff --git a/docs/deploy/mono-api-object.html b/docs/deploy/mono-api-object.html index cd348b014d..0596008f84 100644 --- a/docs/deploy/mono-api-object.html +++ b/docs/deploy/mono-api-object.html @@ -1,4 +1,4 @@ - + mono-api-object.html diff --git a/docs/deploy/mono-api-profiler.html b/docs/deploy/mono-api-profiler.html index 65304476aa..224091d366 100644 --- a/docs/deploy/mono-api-profiler.html +++ b/docs/deploy/mono-api-profiler.html @@ -1,4 +1,4 @@ - + mono-api-profiler.html diff --git a/docs/deploy/mono-api-reflection.html b/docs/deploy/mono-api-reflection.html index 23ec6ae18a..bc95706675 100644 --- a/docs/deploy/mono-api-reflection.html +++ b/docs/deploy/mono-api-reflection.html @@ -1,4 +1,4 @@ - + mono-api-reflection.html diff --git a/docs/deploy/mono-api-security.html b/docs/deploy/mono-api-security.html index f628a86a69..6dd7b22940 100644 --- a/docs/deploy/mono-api-security.html +++ b/docs/deploy/mono-api-security.html @@ -1,4 +1,4 @@ - + mono-api-security.html diff --git a/docs/deploy/mono-api-string.html b/docs/deploy/mono-api-string.html index d22f40b8b7..ec277c1c9f 100644 --- a/docs/deploy/mono-api-string.html +++ b/docs/deploy/mono-api-string.html @@ -1,4 +1,4 @@ - + mono-api-string.html @@ -311,7 +311,7 @@ mono_string_new_size (MonoDomain *domain, gint32 len)

Syntax
MonoString* -mono_string_new_utf16 (MonoDomain *domain, const guint16 *text, gint32 len) +mono_string_new_utf16 (MonoDomain *domain, const mono_unichar2 *text, gint32 len)

diff --git a/docs/deploy/mono-api-threads.html b/docs/deploy/mono-api-threads.html index 0a00a25546..8fb6ff8c56 100644 --- a/docs/deploy/mono-api-threads.html +++ b/docs/deploy/mono-api-threads.html @@ -1,4 +1,4 @@ - + mono-api-threads.html diff --git a/docs/deploy/mono-api-type.html b/docs/deploy/mono-api-type.html index 710c6cb463..553e76d96f 100644 --- a/docs/deploy/mono-api-type.html +++ b/docs/deploy/mono-api-type.html @@ -1,4 +1,4 @@ - + mono-api-type.html @@ -636,7 +636,7 @@ mono_type_stack_size (MonoType *t, int *align)

Syntax
-
guint32 +
guint32 // FIXMEcxx MonoMarshalNative mono_type_to_unmanaged (MonoType *type, MonoMarshalSpec *mspec, gboolean as_field, gboolean unicode, MonoMarshalConv *conv) diff --git a/docs/deploy/mono-api-types.html b/docs/deploy/mono-api-types.html index 67d90b0f9a..bed233b3ef 100644 --- a/docs/deploy/mono-api-types.html +++ b/docs/deploy/mono-api-types.html @@ -1,4 +1,4 @@ - + mono-api-types.html diff --git a/docs/deploy/mono-api-unsorted.html b/docs/deploy/mono-api-unsorted.html index 5e9cd43730..2636f26daf 100644 --- a/docs/deploy/mono-api-unsorted.html +++ b/docs/deploy/mono-api-unsorted.html @@ -1,4 +1,4 @@ - + mono-api-unsorted.html diff --git a/docs/deploy/mono-api-utils.html b/docs/deploy/mono-api-utils.html index b37f830a6d..6b452fab0e 100644 --- a/docs/deploy/mono-api-utils.html +++ b/docs/deploy/mono-api-utils.html @@ -1,4 +1,4 @@ - + mono-api-utils.html diff --git a/docs/deploy/mono-api-vm.html b/docs/deploy/mono-api-vm.html index e9be0fc0b0..f8259f747f 100644 --- a/docs/deploy/mono-api-vm.html +++ b/docs/deploy/mono-api-vm.html @@ -1,4 +1,4 @@ - + mono-api-vm.html diff --git a/docs/deploy/mono-api-wapi.html b/docs/deploy/mono-api-wapi.html index 6c18a3d9fe..f289536021 100644 --- a/docs/deploy/mono-api-wapi.html +++ b/docs/deploy/mono-api-wapi.html @@ -1,4 +1,4 @@ - + mono-api-wapi.html diff --git a/external/api-snapshot/profiles/monodroid/Facades/System.Drawing.Common.cs b/external/api-snapshot/profiles/monodroid/Facades/System.Drawing.Common.cs deleted file mode 100644 index b8872bf40b..0000000000 --- a/external/api-snapshot/profiles/monodroid/Facades/System.Drawing.Common.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -[assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] -[assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] -[assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] -[assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Drawing.Common")] -[assembly:System.Reflection.AssemblyDescriptionAttribute("System.Drawing.Common")] -[assembly:System.Reflection.AssemblyFileVersionAttribute("4.0.0.0")] -[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.0.0.0")] -[assembly:System.Reflection.AssemblyProductAttribute("Mono Common Language Infrastructure")] -[assembly:System.Reflection.AssemblyTitleAttribute("System.Drawing.Common")] -[assembly:System.Runtime.CompilerServices.CompilationRelaxationsAttribute(8)] -[assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] diff --git a/external/api-snapshot/profiles/monodroid/Facades/System.Drawing.Common.cs.REMOVED.git-id b/external/api-snapshot/profiles/monodroid/Facades/System.Drawing.Common.cs.REMOVED.git-id new file mode 100644 index 0000000000..511151d24c --- /dev/null +++ b/external/api-snapshot/profiles/monodroid/Facades/System.Drawing.Common.cs.REMOVED.git-id @@ -0,0 +1 @@ +9f290631c6b4164ddb0330177fa773f02a2111be \ No newline at end of file diff --git a/external/api-snapshot/profiles/monodroid/System.ServiceModel.cs.REMOVED.git-id b/external/api-snapshot/profiles/monodroid/System.ServiceModel.cs.REMOVED.git-id index 189e87c972..bf6cebc7bf 100644 --- a/external/api-snapshot/profiles/monodroid/System.ServiceModel.cs.REMOVED.git-id +++ b/external/api-snapshot/profiles/monodroid/System.ServiceModel.cs.REMOVED.git-id @@ -1 +1 @@ -fdbaba096bec0ae20215f815e316f483b0560f77 \ No newline at end of file +7442513f82b49faa3a1dc98725c31a7ef138f0af \ No newline at end of file diff --git a/external/api-snapshot/profiles/monodroid/System.cs.REMOVED.git-id b/external/api-snapshot/profiles/monodroid/System.cs.REMOVED.git-id index e6bf759e3e..909eeb86fe 100644 --- a/external/api-snapshot/profiles/monodroid/System.cs.REMOVED.git-id +++ b/external/api-snapshot/profiles/monodroid/System.cs.REMOVED.git-id @@ -1 +1 @@ -a4d41f54aa4e797510b7305e90672d0f0b716d01 \ No newline at end of file +36d622527efb75a14820450ce9af1c8b3b1e1990 \ No newline at end of file diff --git a/external/api-snapshot/profiles/monodroid/mscorlib.cs.REMOVED.git-id b/external/api-snapshot/profiles/monodroid/mscorlib.cs.REMOVED.git-id index fbe1182957..5500937f8a 100644 --- a/external/api-snapshot/profiles/monodroid/mscorlib.cs.REMOVED.git-id +++ b/external/api-snapshot/profiles/monodroid/mscorlib.cs.REMOVED.git-id @@ -1 +1 @@ -0966d02146233778bc2bff5c642a72b4db22341e \ No newline at end of file +5720eb204ffdc35ca77f9c0f4c69efa1779a6fe7 \ No newline at end of file diff --git a/external/api-snapshot/profiles/monotouch/Facades/System.Drawing.Common.cs b/external/api-snapshot/profiles/monotouch/Facades/System.Drawing.Common.cs deleted file mode 100644 index b8872bf40b..0000000000 --- a/external/api-snapshot/profiles/monotouch/Facades/System.Drawing.Common.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -[assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] -[assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] -[assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] -[assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Drawing.Common")] -[assembly:System.Reflection.AssemblyDescriptionAttribute("System.Drawing.Common")] -[assembly:System.Reflection.AssemblyFileVersionAttribute("4.0.0.0")] -[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.0.0.0")] -[assembly:System.Reflection.AssemblyProductAttribute("Mono Common Language Infrastructure")] -[assembly:System.Reflection.AssemblyTitleAttribute("System.Drawing.Common")] -[assembly:System.Runtime.CompilerServices.CompilationRelaxationsAttribute(8)] -[assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] diff --git a/external/api-snapshot/profiles/monotouch/Facades/System.Drawing.Common.cs.REMOVED.git-id b/external/api-snapshot/profiles/monotouch/Facades/System.Drawing.Common.cs.REMOVED.git-id new file mode 100644 index 0000000000..511151d24c --- /dev/null +++ b/external/api-snapshot/profiles/monotouch/Facades/System.Drawing.Common.cs.REMOVED.git-id @@ -0,0 +1 @@ +9f290631c6b4164ddb0330177fa773f02a2111be \ No newline at end of file diff --git a/external/api-snapshot/profiles/monotouch/System.ServiceModel.cs.REMOVED.git-id b/external/api-snapshot/profiles/monotouch/System.ServiceModel.cs.REMOVED.git-id index aa6763d456..e6e055e957 100644 --- a/external/api-snapshot/profiles/monotouch/System.ServiceModel.cs.REMOVED.git-id +++ b/external/api-snapshot/profiles/monotouch/System.ServiceModel.cs.REMOVED.git-id @@ -1 +1 @@ -7f4bd88d08376ff5e225bb16fc63563555843a56 \ No newline at end of file +2540e1a0a3b3da9acb5d41aa33f08b1573d567cd \ No newline at end of file diff --git a/external/api-snapshot/profiles/monotouch/System.cs.REMOVED.git-id b/external/api-snapshot/profiles/monotouch/System.cs.REMOVED.git-id index 9027baaebc..f2cf825a47 100644 --- a/external/api-snapshot/profiles/monotouch/System.cs.REMOVED.git-id +++ b/external/api-snapshot/profiles/monotouch/System.cs.REMOVED.git-id @@ -1 +1 @@ -e7cc3043af28842bbfcbfcc3e778a58f8ee6e205 \ No newline at end of file +e049fee6a661dc60bd8c9f9e5e64a9bc250fc55a \ No newline at end of file diff --git a/external/api-snapshot/profiles/monotouch/mscorlib.cs.REMOVED.git-id b/external/api-snapshot/profiles/monotouch/mscorlib.cs.REMOVED.git-id index 9339e0f4fc..53a5cfdd1d 100644 --- a/external/api-snapshot/profiles/monotouch/mscorlib.cs.REMOVED.git-id +++ b/external/api-snapshot/profiles/monotouch/mscorlib.cs.REMOVED.git-id @@ -1 +1 @@ -2ae9ab2e8d1f583ad2c036454fb3b79ecbc39035 \ No newline at end of file +3bfb5c5d5207383227a9277b36b995ff585297ba \ No newline at end of file diff --git a/external/api-snapshot/profiles/net_4_x/Mono.Cecil.Mdb.cs b/external/api-snapshot/profiles/net_4_x/Mono.Cecil.Mdb.cs index d2db334776..3443507c0d 100644 --- a/external/api-snapshot/profiles/net_4_x/Mono.Cecil.Mdb.cs +++ b/external/api-snapshot/profiles/net_4_x/Mono.Cecil.Mdb.cs @@ -2,12 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -[assembly:System.Reflection.AssemblyVersionAttribute("0.10.0.0")] +[assembly:System.Reflection.AssemblyVersionAttribute("0.10.1.0")] [assembly:System.CLSCompliantAttribute(false)] [assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] [assembly:System.Reflection.AssemblyCopyrightAttribute("Copyright © 2008 - 2018 Jb Evain")] -[assembly:System.Reflection.AssemblyFileVersionAttribute("0.10.0.0")] -[assembly:System.Reflection.AssemblyInformationalVersionAttribute("0.10.0.0")] +[assembly:System.Reflection.AssemblyFileVersionAttribute("0.10.1.0")] +[assembly:System.Reflection.AssemblyInformationalVersionAttribute("0.10.1.0")] [assembly:System.Reflection.AssemblyProductAttribute("Mono.Cecil")] [assembly:System.Reflection.AssemblyTitleAttribute("Mono.Cecil.Mdb")] [assembly:System.Runtime.CompilerServices.CompilationRelaxationsAttribute(8)] diff --git a/external/api-snapshot/profiles/net_4_x/Mono.Cecil.cs.REMOVED.git-id b/external/api-snapshot/profiles/net_4_x/Mono.Cecil.cs.REMOVED.git-id index 3359f9aeac..8f77ac4c64 100644 --- a/external/api-snapshot/profiles/net_4_x/Mono.Cecil.cs.REMOVED.git-id +++ b/external/api-snapshot/profiles/net_4_x/Mono.Cecil.cs.REMOVED.git-id @@ -1 +1 @@ -8d89b5ff7f8c0d7a260c7d6ec5d1b9baf4b22fd2 \ No newline at end of file +19b503b65f6796fbd03668ae2a73555fcb8fda32 \ No newline at end of file diff --git a/external/api-snapshot/profiles/net_4_x/Mono.Options.cs b/external/api-snapshot/profiles/net_4_x/Mono.Options.cs index 6666ca25c0..ef831fb3de 100644 --- a/external/api-snapshot/profiles/net_4_x/Mono.Options.cs +++ b/external/api-snapshot/profiles/net_4_x/Mono.Options.cs @@ -54,6 +54,7 @@ namespace Mono.Options public Mono.Options.CommandSet Add(string prototype, string description, System.Action action) { throw null; } public Mono.Options.CommandSet Add(string prototype, Mono.Options.OptionAction action) { throw null; } public Mono.Options.CommandSet Add(string prototype, string description, Mono.Options.OptionAction action) { throw null; } + public System.Collections.Generic.IEnumerable GetCompletions(string prefix=null) { throw null; } protected override string GetKeyForItem(Mono.Options.Command item) { throw null; } public int Run(System.Collections.Generic.IEnumerable arguments) { throw null; } } diff --git a/external/api-snapshot/profiles/net_4_x/System.Core.cs.REMOVED.git-id b/external/api-snapshot/profiles/net_4_x/System.Core.cs.REMOVED.git-id index 0d79b13d6d..d3fc4127dd 100644 --- a/external/api-snapshot/profiles/net_4_x/System.Core.cs.REMOVED.git-id +++ b/external/api-snapshot/profiles/net_4_x/System.Core.cs.REMOVED.git-id @@ -1 +1 @@ -5bb99bc8c448a147d4fd5de3bd1798df7015810b \ No newline at end of file +498a444723bd3202ba25a869506c30422b3c6a5a \ No newline at end of file diff --git a/external/api-snapshot/profiles/net_4_x/System.ServiceModel.cs.REMOVED.git-id b/external/api-snapshot/profiles/net_4_x/System.ServiceModel.cs.REMOVED.git-id index d86e379f55..c793b6dd98 100644 --- a/external/api-snapshot/profiles/net_4_x/System.ServiceModel.cs.REMOVED.git-id +++ b/external/api-snapshot/profiles/net_4_x/System.ServiceModel.cs.REMOVED.git-id @@ -1 +1 @@ -a1df3f83332859870e1cf4a20ceeeed89728c785 \ No newline at end of file +3582707a8ab0f5fadf682711906367dd6f4e52f7 \ No newline at end of file diff --git a/external/api-snapshot/profiles/net_4_x/System.cs.REMOVED.git-id b/external/api-snapshot/profiles/net_4_x/System.cs.REMOVED.git-id index c01074bc7f..c899890771 100644 --- a/external/api-snapshot/profiles/net_4_x/System.cs.REMOVED.git-id +++ b/external/api-snapshot/profiles/net_4_x/System.cs.REMOVED.git-id @@ -1 +1 @@ -b081ba1d1e3552cb0f915ccd31f8797bf18c73b5 \ No newline at end of file +45466de46f91e4c641d500853fd27848a22c01f4 \ No newline at end of file diff --git a/external/api-snapshot/profiles/net_4_x/mscorlib.cs.REMOVED.git-id b/external/api-snapshot/profiles/net_4_x/mscorlib.cs.REMOVED.git-id index 9ee1faf0ec..0fad55ac87 100644 --- a/external/api-snapshot/profiles/net_4_x/mscorlib.cs.REMOVED.git-id +++ b/external/api-snapshot/profiles/net_4_x/mscorlib.cs.REMOVED.git-id @@ -1 +1 @@ -0fc46f55fa06c9cc6efd0610c0aca16bae0936d0 \ No newline at end of file +ed19cc64be777080a3bba2cb682288cc5b3e9d20 \ No newline at end of file diff --git a/external/binary-reference-assemblies/generate-refasm-sources.sh b/external/binary-reference-assemblies/generate-refasm-sources.sh index 9717dd75c5..5ea35e306f 100755 --- a/external/binary-reference-assemblies/generate-refasm-sources.sh +++ b/external/binary-reference-assemblies/generate-refasm-sources.sh @@ -18,7 +18,7 @@ for i in *.dll Facades/*.dll; do if [[ "$i" = "Facades"* ]]; then outpath="$outpath/Facades"; fi echo "Processing $i" - mono "$REPODIR/../api-snapshot/tools/genapi/GenAPI.exe" -assembly:"$i" -out:"$outpath" -typeforwardedTo -assemblyVersion -assemblyAttributes -headerFile:"$REPODIR/../api-snapshot/profiles/license-header.txt" -libPath:"$NETFXSOURCE" + mono "$REPODIR/../api-snapshot/tools/genapi/Microsoft.DotNet.GenAPI.exe" -assembly:"$i" -out:"$outpath" -typeforwardedTo -assemblyVersion -assemblyAttributes -headerFile:"$REPODIR/../api-snapshot/profiles/license-header.txt" -libPath:"$NETFXSOURCE" done cd "$REPODIR/src/$NETFXPROFILE" diff --git a/external/binary-reference-assemblies/src/v4.5.1/Microsoft.Build.Framework.cs b/external/binary-reference-assemblies/src/v4.5.1/Microsoft.Build.Framework.cs index 46ae3ce9e0..f3a71e319d 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/Microsoft.Build.Framework.cs +++ b/external/binary-reference-assemblies/src/v4.5.1/Microsoft.Build.Framework.cs @@ -26,6 +26,8 @@ namespace Microsoft.Build.Framework [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BuildEngineResult { + private object _dummy; + private int _dummyPrimitive; public BuildEngineResult(bool result, System.Collections.Generic.List> targetOutputsPerProject) { throw null;} public bool Result { get { throw null; } } public System.Collections.Generic.IList> TargetOutputsPerProject { get { throw null; } } diff --git a/external/binary-reference-assemblies/src/v4.5.1/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.1/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id index a42f0d7c00..d81e14648b 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.1/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id @@ -1 +1 @@ -cb0a075a9f294098a6b4ea79d60b405568e7cac2 \ No newline at end of file +580e1b7e8bd7f71a0a165a0092e13b357816b5b6 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.1/Microsoft.Build.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.1/Microsoft.Build.cs.REMOVED.git-id index 9eae8aba4d..db98ce261c 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/Microsoft.Build.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.1/Microsoft.Build.cs.REMOVED.git-id @@ -1 +1 @@ -eec3b5e71cf3fe71667427e0c35beceb80440e58 \ No newline at end of file +f1d066985d6e33e8602fa2c2993fa18134b7d5c4 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.ComponentModel.Composition.cs b/external/binary-reference-assemblies/src/v4.5.1/System.ComponentModel.Composition.cs index e454761d86..e0fbe73e2b 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.ComponentModel.Composition.cs +++ b/external/binary-reference-assemblies/src/v4.5.1/System.ComponentModel.Composition.cs @@ -655,6 +655,8 @@ namespace System.ComponentModel.Composition.ReflectionModel [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct LazyMemberInfo { + private object _dummy; + private int _dummyPrimitive; public LazyMemberInfo(System.Reflection.MemberInfo member) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, System.Func accessorsCreator) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, params System.Reflection.MemberInfo[] accessors) { throw null;} diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.Core.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.1/System.Core.cs.REMOVED.git-id index a6d2b716b4..25fb21be5f 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.Core.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.1/System.Core.cs.REMOVED.git-id @@ -1 +1 @@ -b49e4ddb5e1aa3f9a0215daacd141b85094a6692 \ No newline at end of file +885f7221115e7fc1d9e09719a3aa83506d2bdc14 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.Data.Entity.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.1/System.Data.Entity.cs.REMOVED.git-id index 288b0b88eb..c2baea98d0 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.Data.Entity.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.1/System.Data.Entity.cs.REMOVED.git-id @@ -1 +1 @@ -51ca2fda2e2b7db932eced2091a57b6896af09c7 \ No newline at end of file +ee21fac6b587504d2dc88648b0dd3c4e9d87dc6d \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.Data.Linq.cs b/external/binary-reference-assemblies/src/v4.5.1/System.Data.Linq.cs index 851be2aa04..e9cd120bb7 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.Data.Linq.cs +++ b/external/binary-reference-assemblies/src/v4.5.1/System.Data.Linq.cs @@ -262,6 +262,8 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EntityRef where TEntity : class { + private TEntity entity; + private object _dummy; public EntityRef(System.Collections.Generic.IEnumerable source) { throw null;} public EntityRef(System.Data.Linq.EntityRef entityRef) { throw null;} public EntityRef(TEntity entity) { throw null;} @@ -354,6 +356,9 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size=1)] public partial struct Link { + private T underlyingValue; + private object _dummy; + private int _dummyPrimitive; [System.MonoTODOAttribute] public Link(System.Collections.Generic.IEnumerable source) { throw null;} [System.MonoTODOAttribute] @@ -390,6 +395,7 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size=1)] public partial struct ModifiedMemberInfo { + private object _dummy; [System.MonoTODOAttribute] public object CurrentValue { get { throw null; } } [System.MonoTODOAttribute] diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.Data.OracleClient.cs b/external/binary-reference-assemblies/src/v4.5.1/System.Data.OracleClient.cs index 020f23a26c..d43abd556b 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.Data.OracleClient.cs +++ b/external/binary-reference-assemblies/src/v4.5.1/System.Data.OracleClient.cs @@ -98,6 +98,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBinary : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleBinary Null; public OracleBinary(byte[] b) { throw null;} public bool IsNull { get { throw null; } } @@ -136,6 +137,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBoolean : System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleBoolean False; public static readonly System.Data.OracleClient.OracleBoolean Null; public static readonly System.Data.OracleClient.OracleBoolean One; @@ -478,6 +480,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleDateTime : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleDateTime MaxValue; public static readonly System.Data.OracleClient.OracleDateTime MinValue; public static readonly System.Data.OracleClient.OracleDateTime Null; @@ -582,6 +585,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleMonthSpan : System.Data.SqlTypes.INullable, System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleMonthSpan MaxValue; public static readonly System.Data.OracleClient.OracleMonthSpan MinValue; public static readonly System.Data.OracleClient.OracleMonthSpan Null; @@ -614,6 +618,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleNumber : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleNumber E; public static readonly int MaxPrecision; public static readonly int MaxScale; @@ -832,6 +837,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleString : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleString Empty; public static readonly System.Data.OracleClient.OracleString Null; public OracleString(string s) { throw null;} @@ -865,6 +871,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleTimeSpan : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleTimeSpan MaxValue; public static readonly System.Data.OracleClient.OracleTimeSpan MinValue; public static readonly System.Data.OracleClient.OracleTimeSpan Null; diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.Data.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.1/System.Data.cs.REMOVED.git-id index 9987444cb5..111cb49557 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.Data.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.1/System.Data.cs.REMOVED.git-id @@ -1 +1 @@ -c2fb90d4cb0cd5253515cb7183a091ecc3612f9b \ No newline at end of file +58c4c70fa71e1fd6e480d0dda4fdb41091d21a73 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.Drawing.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.1/System.Drawing.cs.REMOVED.git-id index 1b49746dc8..adc2ea04e5 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.Drawing.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.1/System.Drawing.cs.REMOVED.git-id @@ -1 +1 @@ -18100c5c0edc9612c1099f75c2fe19c623b05582 \ No newline at end of file +7fa7683eea2b9a746517c96e4cc6230797cba2a7 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.Numerics.cs b/external/binary-reference-assemblies/src/v4.5.1/System.Numerics.cs index 86f845f894..ff86c49e77 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.Numerics.cs +++ b/external/binary-reference-assemblies/src/v4.5.1/System.Numerics.cs @@ -26,6 +26,8 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BigInteger : System.IComparable, System.IComparable, System.IEquatable, System.IFormattable { + private object _dummy; + private int _dummyPrimitive; [System.CLSCompliantAttribute(false)] public BigInteger(byte[] value) { throw null;} public BigInteger(decimal value) { throw null;} @@ -176,6 +178,7 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Complex : System.IEquatable, System.IFormattable { + private int _dummyPrimitive; public static readonly System.Numerics.Complex ImaginaryOne; public static readonly System.Numerics.Complex One; public static readonly System.Numerics.Complex Zero; diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.Security.cs b/external/binary-reference-assemblies/src/v4.5.1/System.Security.cs index e236a9f52e..ddbdc7f9b1 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.Security.cs +++ b/external/binary-reference-assemblies/src/v4.5.1/System.Security.cs @@ -918,6 +918,7 @@ namespace System.Security.Cryptography.Xml [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct X509IssuerSerial { + private object _dummy; public string IssuerName { get { throw null; } set { } } public string SerialNumber { get { throw null; } set { } } } diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.ServiceProcess.cs b/external/binary-reference-assemblies/src/v4.5.1/System.ServiceProcess.cs index fc78087b39..e1d74ad660 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.ServiceProcess.cs +++ b/external/binary-reference-assemblies/src/v4.5.1/System.ServiceProcess.cs @@ -325,6 +325,7 @@ namespace System.ServiceProcess [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct SessionChangeDescription { + private int _dummyPrimitive; public System.ServiceProcess.SessionChangeReason Reason { get { throw null; } } public int SessionId { get { throw null; } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.Transactions.cs b/external/binary-reference-assemblies/src/v4.5.1/System.Transactions.cs index a304cca276..a0cb07af57 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.Transactions.cs +++ b/external/binary-reference-assemblies/src/v4.5.1/System.Transactions.cs @@ -300,6 +300,7 @@ namespace System.Transactions [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct TransactionOptions { + private int _dummyPrimitive; public System.Transactions.IsolationLevel IsolationLevel { get { throw null; } set { } } public System.TimeSpan Timeout { get { throw null; } set { } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.Web.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.1/System.Web.cs.REMOVED.git-id index ec7a5cb599..2762a561e0 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.Web.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.1/System.Web.cs.REMOVED.git-id @@ -1 +1 @@ -b57f16e120d9226ed25f10a170b4ab6e034720b8 \ No newline at end of file +fd7aa3292c43999e5f01ccd7924cd59ab00d09e6 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.Windows.Forms.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.1/System.Windows.Forms.cs.REMOVED.git-id index 16c00f4dea..0170751c2e 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.Windows.Forms.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.1/System.Windows.Forms.cs.REMOVED.git-id @@ -1 +1 @@ -bfd029e75d1b15b354d101d32f5938e1b8ed43ea \ No newline at end of file +f1d3de8d737ac6b40240410bbeaa309df6969f35 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.Xml.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.1/System.Xml.cs.REMOVED.git-id index 56607fd46c..33d5530bbf 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.Xml.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.1/System.Xml.cs.REMOVED.git-id @@ -1 +1 @@ -739753aa230fb7c26c07373f777a9c2b47556218 \ No newline at end of file +bed0768be7e623a6e3d290181b559cb4253ecb43 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.1/System.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.1/System.cs.REMOVED.git-id index 4ce5feac84..f503937b1b 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/System.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.1/System.cs.REMOVED.git-id @@ -1 +1 @@ -d5d063af300aa7c993efc5d5824f79f1442a32db \ No newline at end of file +76a0826386f311b1ac463c8293522efdc2fc4bf3 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.1/WindowsBase.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.1/WindowsBase.cs.REMOVED.git-id index d88fbb4564..025728f8bc 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/WindowsBase.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.1/WindowsBase.cs.REMOVED.git-id @@ -1 +1 @@ -77fe49e51289ab178451d25d0f09eed5dd1fecc2 \ No newline at end of file +e00a0c765d8bf59400abd329e1ab419480c04942 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.1/mscorlib.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.1/mscorlib.cs.REMOVED.git-id index 3dd1f22706..020a607bea 100644 --- a/external/binary-reference-assemblies/src/v4.5.1/mscorlib.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.1/mscorlib.cs.REMOVED.git-id @@ -1 +1 @@ -24874deb7e529323d167bc80e2c9894efdb4f68c \ No newline at end of file +6d0176a7cdef0d364ea1558b1f1aa6d0fb4ea838 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.2/Microsoft.Build.Framework.cs b/external/binary-reference-assemblies/src/v4.5.2/Microsoft.Build.Framework.cs index 46ae3ce9e0..f3a71e319d 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/Microsoft.Build.Framework.cs +++ b/external/binary-reference-assemblies/src/v4.5.2/Microsoft.Build.Framework.cs @@ -26,6 +26,8 @@ namespace Microsoft.Build.Framework [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BuildEngineResult { + private object _dummy; + private int _dummyPrimitive; public BuildEngineResult(bool result, System.Collections.Generic.List> targetOutputsPerProject) { throw null;} public bool Result { get { throw null; } } public System.Collections.Generic.IList> TargetOutputsPerProject { get { throw null; } } diff --git a/external/binary-reference-assemblies/src/v4.5.2/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.2/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id index a42f0d7c00..d81e14648b 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.2/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id @@ -1 +1 @@ -cb0a075a9f294098a6b4ea79d60b405568e7cac2 \ No newline at end of file +580e1b7e8bd7f71a0a165a0092e13b357816b5b6 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.2/Microsoft.Build.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.2/Microsoft.Build.cs.REMOVED.git-id index 9eae8aba4d..db98ce261c 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/Microsoft.Build.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.2/Microsoft.Build.cs.REMOVED.git-id @@ -1 +1 @@ -eec3b5e71cf3fe71667427e0c35beceb80440e58 \ No newline at end of file +f1d066985d6e33e8602fa2c2993fa18134b7d5c4 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.ComponentModel.Composition.cs b/external/binary-reference-assemblies/src/v4.5.2/System.ComponentModel.Composition.cs index e454761d86..e0fbe73e2b 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.ComponentModel.Composition.cs +++ b/external/binary-reference-assemblies/src/v4.5.2/System.ComponentModel.Composition.cs @@ -655,6 +655,8 @@ namespace System.ComponentModel.Composition.ReflectionModel [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct LazyMemberInfo { + private object _dummy; + private int _dummyPrimitive; public LazyMemberInfo(System.Reflection.MemberInfo member) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, System.Func accessorsCreator) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, params System.Reflection.MemberInfo[] accessors) { throw null;} diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.Core.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.2/System.Core.cs.REMOVED.git-id index a6d2b716b4..25fb21be5f 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.Core.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.2/System.Core.cs.REMOVED.git-id @@ -1 +1 @@ -b49e4ddb5e1aa3f9a0215daacd141b85094a6692 \ No newline at end of file +885f7221115e7fc1d9e09719a3aa83506d2bdc14 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.Data.Entity.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.2/System.Data.Entity.cs.REMOVED.git-id index 288b0b88eb..c2baea98d0 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.Data.Entity.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.2/System.Data.Entity.cs.REMOVED.git-id @@ -1 +1 @@ -51ca2fda2e2b7db932eced2091a57b6896af09c7 \ No newline at end of file +ee21fac6b587504d2dc88648b0dd3c4e9d87dc6d \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.Data.Linq.cs b/external/binary-reference-assemblies/src/v4.5.2/System.Data.Linq.cs index 851be2aa04..e9cd120bb7 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.Data.Linq.cs +++ b/external/binary-reference-assemblies/src/v4.5.2/System.Data.Linq.cs @@ -262,6 +262,8 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EntityRef where TEntity : class { + private TEntity entity; + private object _dummy; public EntityRef(System.Collections.Generic.IEnumerable source) { throw null;} public EntityRef(System.Data.Linq.EntityRef entityRef) { throw null;} public EntityRef(TEntity entity) { throw null;} @@ -354,6 +356,9 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size=1)] public partial struct Link { + private T underlyingValue; + private object _dummy; + private int _dummyPrimitive; [System.MonoTODOAttribute] public Link(System.Collections.Generic.IEnumerable source) { throw null;} [System.MonoTODOAttribute] @@ -390,6 +395,7 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size=1)] public partial struct ModifiedMemberInfo { + private object _dummy; [System.MonoTODOAttribute] public object CurrentValue { get { throw null; } } [System.MonoTODOAttribute] diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.Data.OracleClient.cs b/external/binary-reference-assemblies/src/v4.5.2/System.Data.OracleClient.cs index 020f23a26c..d43abd556b 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.Data.OracleClient.cs +++ b/external/binary-reference-assemblies/src/v4.5.2/System.Data.OracleClient.cs @@ -98,6 +98,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBinary : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleBinary Null; public OracleBinary(byte[] b) { throw null;} public bool IsNull { get { throw null; } } @@ -136,6 +137,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBoolean : System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleBoolean False; public static readonly System.Data.OracleClient.OracleBoolean Null; public static readonly System.Data.OracleClient.OracleBoolean One; @@ -478,6 +480,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleDateTime : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleDateTime MaxValue; public static readonly System.Data.OracleClient.OracleDateTime MinValue; public static readonly System.Data.OracleClient.OracleDateTime Null; @@ -582,6 +585,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleMonthSpan : System.Data.SqlTypes.INullable, System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleMonthSpan MaxValue; public static readonly System.Data.OracleClient.OracleMonthSpan MinValue; public static readonly System.Data.OracleClient.OracleMonthSpan Null; @@ -614,6 +618,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleNumber : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleNumber E; public static readonly int MaxPrecision; public static readonly int MaxScale; @@ -832,6 +837,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleString : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleString Empty; public static readonly System.Data.OracleClient.OracleString Null; public OracleString(string s) { throw null;} @@ -865,6 +871,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleTimeSpan : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleTimeSpan MaxValue; public static readonly System.Data.OracleClient.OracleTimeSpan MinValue; public static readonly System.Data.OracleClient.OracleTimeSpan Null; diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.Data.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.2/System.Data.cs.REMOVED.git-id index 9987444cb5..111cb49557 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.Data.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.2/System.Data.cs.REMOVED.git-id @@ -1 +1 @@ -c2fb90d4cb0cd5253515cb7183a091ecc3612f9b \ No newline at end of file +58c4c70fa71e1fd6e480d0dda4fdb41091d21a73 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.Drawing.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.2/System.Drawing.cs.REMOVED.git-id index 1b49746dc8..adc2ea04e5 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.Drawing.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.2/System.Drawing.cs.REMOVED.git-id @@ -1 +1 @@ -18100c5c0edc9612c1099f75c2fe19c623b05582 \ No newline at end of file +7fa7683eea2b9a746517c96e4cc6230797cba2a7 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.Numerics.cs b/external/binary-reference-assemblies/src/v4.5.2/System.Numerics.cs index 86f845f894..ff86c49e77 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.Numerics.cs +++ b/external/binary-reference-assemblies/src/v4.5.2/System.Numerics.cs @@ -26,6 +26,8 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BigInteger : System.IComparable, System.IComparable, System.IEquatable, System.IFormattable { + private object _dummy; + private int _dummyPrimitive; [System.CLSCompliantAttribute(false)] public BigInteger(byte[] value) { throw null;} public BigInteger(decimal value) { throw null;} @@ -176,6 +178,7 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Complex : System.IEquatable, System.IFormattable { + private int _dummyPrimitive; public static readonly System.Numerics.Complex ImaginaryOne; public static readonly System.Numerics.Complex One; public static readonly System.Numerics.Complex Zero; diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.Security.cs b/external/binary-reference-assemblies/src/v4.5.2/System.Security.cs index e236a9f52e..ddbdc7f9b1 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.Security.cs +++ b/external/binary-reference-assemblies/src/v4.5.2/System.Security.cs @@ -918,6 +918,7 @@ namespace System.Security.Cryptography.Xml [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct X509IssuerSerial { + private object _dummy; public string IssuerName { get { throw null; } set { } } public string SerialNumber { get { throw null; } set { } } } diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.ServiceProcess.cs b/external/binary-reference-assemblies/src/v4.5.2/System.ServiceProcess.cs index fc78087b39..e1d74ad660 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.ServiceProcess.cs +++ b/external/binary-reference-assemblies/src/v4.5.2/System.ServiceProcess.cs @@ -325,6 +325,7 @@ namespace System.ServiceProcess [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct SessionChangeDescription { + private int _dummyPrimitive; public System.ServiceProcess.SessionChangeReason Reason { get { throw null; } } public int SessionId { get { throw null; } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.Transactions.cs b/external/binary-reference-assemblies/src/v4.5.2/System.Transactions.cs index 274322c57a..60c3abc8a2 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.Transactions.cs +++ b/external/binary-reference-assemblies/src/v4.5.2/System.Transactions.cs @@ -301,6 +301,7 @@ namespace System.Transactions [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct TransactionOptions { + private int _dummyPrimitive; public System.Transactions.IsolationLevel IsolationLevel { get { throw null; } set { } } public System.TimeSpan Timeout { get { throw null; } set { } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.Web.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.2/System.Web.cs.REMOVED.git-id index 66c3cf3432..a6fe096d9f 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.Web.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.2/System.Web.cs.REMOVED.git-id @@ -1 +1 @@ -c8d9aa760c9f262ba8cf1f8d4eab073c6cce4a36 \ No newline at end of file +fd19c6845e8b5459f78204e6d5734ead8e5f66b8 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.Windows.Forms.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.2/System.Windows.Forms.cs.REMOVED.git-id index f7d279d60b..a681023be2 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.Windows.Forms.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.2/System.Windows.Forms.cs.REMOVED.git-id @@ -1 +1 @@ -5c73dcaf5449ca1adf35a02e14fe547d971a220b \ No newline at end of file +eb2b9a4de0a991b099fdc18e3082dc0346b80649 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.Xml.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.2/System.Xml.cs.REMOVED.git-id index 56607fd46c..33d5530bbf 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.Xml.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.2/System.Xml.cs.REMOVED.git-id @@ -1 +1 @@ -739753aa230fb7c26c07373f777a9c2b47556218 \ No newline at end of file +bed0768be7e623a6e3d290181b559cb4253ecb43 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.2/System.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.2/System.cs.REMOVED.git-id index 4ce5feac84..f503937b1b 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/System.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.2/System.cs.REMOVED.git-id @@ -1 +1 @@ -d5d063af300aa7c993efc5d5824f79f1442a32db \ No newline at end of file +76a0826386f311b1ac463c8293522efdc2fc4bf3 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.2/WindowsBase.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.2/WindowsBase.cs.REMOVED.git-id index d88fbb4564..025728f8bc 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/WindowsBase.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.2/WindowsBase.cs.REMOVED.git-id @@ -1 +1 @@ -77fe49e51289ab178451d25d0f09eed5dd1fecc2 \ No newline at end of file +e00a0c765d8bf59400abd329e1ab419480c04942 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5.2/mscorlib.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5.2/mscorlib.cs.REMOVED.git-id index 20e0d12f64..e6a4b0fd85 100644 --- a/external/binary-reference-assemblies/src/v4.5.2/mscorlib.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5.2/mscorlib.cs.REMOVED.git-id @@ -1 +1 @@ -2d7d6219479e21a935fbc3e1b58806f856d47bc4 \ No newline at end of file +4d81548e6580ea868e449f534be58e04ca9712e0 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5/Microsoft.Build.Framework.cs b/external/binary-reference-assemblies/src/v4.5/Microsoft.Build.Framework.cs index 46ae3ce9e0..f3a71e319d 100644 --- a/external/binary-reference-assemblies/src/v4.5/Microsoft.Build.Framework.cs +++ b/external/binary-reference-assemblies/src/v4.5/Microsoft.Build.Framework.cs @@ -26,6 +26,8 @@ namespace Microsoft.Build.Framework [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BuildEngineResult { + private object _dummy; + private int _dummyPrimitive; public BuildEngineResult(bool result, System.Collections.Generic.List> targetOutputsPerProject) { throw null;} public bool Result { get { throw null; } } public System.Collections.Generic.IList> TargetOutputsPerProject { get { throw null; } } diff --git a/external/binary-reference-assemblies/src/v4.5/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id index a42f0d7c00..d81e14648b 100644 --- a/external/binary-reference-assemblies/src/v4.5/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id @@ -1 +1 @@ -cb0a075a9f294098a6b4ea79d60b405568e7cac2 \ No newline at end of file +580e1b7e8bd7f71a0a165a0092e13b357816b5b6 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5/Microsoft.Build.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5/Microsoft.Build.cs.REMOVED.git-id index 9eae8aba4d..db98ce261c 100644 --- a/external/binary-reference-assemblies/src/v4.5/Microsoft.Build.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5/Microsoft.Build.cs.REMOVED.git-id @@ -1 +1 @@ -eec3b5e71cf3fe71667427e0c35beceb80440e58 \ No newline at end of file +f1d066985d6e33e8602fa2c2993fa18134b7d5c4 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5/System.ComponentModel.Composition.cs b/external/binary-reference-assemblies/src/v4.5/System.ComponentModel.Composition.cs index e454761d86..e0fbe73e2b 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.ComponentModel.Composition.cs +++ b/external/binary-reference-assemblies/src/v4.5/System.ComponentModel.Composition.cs @@ -655,6 +655,8 @@ namespace System.ComponentModel.Composition.ReflectionModel [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct LazyMemberInfo { + private object _dummy; + private int _dummyPrimitive; public LazyMemberInfo(System.Reflection.MemberInfo member) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, System.Func accessorsCreator) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, params System.Reflection.MemberInfo[] accessors) { throw null;} diff --git a/external/binary-reference-assemblies/src/v4.5/System.Core.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5/System.Core.cs.REMOVED.git-id index 6ae1edb27d..c9c9c82f4a 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.Core.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5/System.Core.cs.REMOVED.git-id @@ -1 +1 @@ -0e327929daf8f8d7de1a69204a07effaf1b1d6ba \ No newline at end of file +888e3555b02231110f7e5777793a3692b56e5dee \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5/System.Data.Entity.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5/System.Data.Entity.cs.REMOVED.git-id index 868c37882f..9e67386761 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.Data.Entity.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5/System.Data.Entity.cs.REMOVED.git-id @@ -1 +1 @@ -b7d9daca0e60a450b9eeb0b5632d5cd2efd633e5 \ No newline at end of file +24b3ba76a08c5afb67696160f3e8190bccec54f8 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5/System.Data.Linq.cs b/external/binary-reference-assemblies/src/v4.5/System.Data.Linq.cs index 851be2aa04..e9cd120bb7 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.Data.Linq.cs +++ b/external/binary-reference-assemblies/src/v4.5/System.Data.Linq.cs @@ -262,6 +262,8 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EntityRef where TEntity : class { + private TEntity entity; + private object _dummy; public EntityRef(System.Collections.Generic.IEnumerable source) { throw null;} public EntityRef(System.Data.Linq.EntityRef entityRef) { throw null;} public EntityRef(TEntity entity) { throw null;} @@ -354,6 +356,9 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size=1)] public partial struct Link { + private T underlyingValue; + private object _dummy; + private int _dummyPrimitive; [System.MonoTODOAttribute] public Link(System.Collections.Generic.IEnumerable source) { throw null;} [System.MonoTODOAttribute] @@ -390,6 +395,7 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size=1)] public partial struct ModifiedMemberInfo { + private object _dummy; [System.MonoTODOAttribute] public object CurrentValue { get { throw null; } } [System.MonoTODOAttribute] diff --git a/external/binary-reference-assemblies/src/v4.5/System.Data.OracleClient.cs b/external/binary-reference-assemblies/src/v4.5/System.Data.OracleClient.cs index 24975b0e94..2f12545348 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.Data.OracleClient.cs +++ b/external/binary-reference-assemblies/src/v4.5/System.Data.OracleClient.cs @@ -98,6 +98,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBinary : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleBinary Null; public OracleBinary(byte[] b) { throw null;} public bool IsNull { get { throw null; } } @@ -136,6 +137,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBoolean : System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleBoolean False; public static readonly System.Data.OracleClient.OracleBoolean Null; public static readonly System.Data.OracleClient.OracleBoolean One; @@ -478,6 +480,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleDateTime : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleDateTime MaxValue; public static readonly System.Data.OracleClient.OracleDateTime MinValue; public static readonly System.Data.OracleClient.OracleDateTime Null; @@ -582,6 +585,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleMonthSpan : System.Data.SqlTypes.INullable, System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleMonthSpan MaxValue; public static readonly System.Data.OracleClient.OracleMonthSpan MinValue; public static readonly System.Data.OracleClient.OracleMonthSpan Null; @@ -614,6 +618,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleNumber : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleNumber E; public static readonly int MaxPrecision; public static readonly int MaxScale; @@ -832,6 +837,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleString : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleString Empty; public static readonly System.Data.OracleClient.OracleString Null; public OracleString(string s) { throw null;} @@ -865,6 +871,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleTimeSpan : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleTimeSpan MaxValue; public static readonly System.Data.OracleClient.OracleTimeSpan MinValue; public static readonly System.Data.OracleClient.OracleTimeSpan Null; diff --git a/external/binary-reference-assemblies/src/v4.5/System.Data.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5/System.Data.cs.REMOVED.git-id index ea21fa3d66..0e6d32f432 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.Data.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5/System.Data.cs.REMOVED.git-id @@ -1 +1 @@ -17aaedace86cdf539d3c8088c795d35bd87a26b9 \ No newline at end of file +3fae53bf61c57a664630d0ca283c1f55a90ed3da \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5/System.Drawing.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5/System.Drawing.cs.REMOVED.git-id index 1b49746dc8..adc2ea04e5 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.Drawing.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5/System.Drawing.cs.REMOVED.git-id @@ -1 +1 @@ -18100c5c0edc9612c1099f75c2fe19c623b05582 \ No newline at end of file +7fa7683eea2b9a746517c96e4cc6230797cba2a7 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5/System.Numerics.cs b/external/binary-reference-assemblies/src/v4.5/System.Numerics.cs index 86f845f894..ff86c49e77 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.Numerics.cs +++ b/external/binary-reference-assemblies/src/v4.5/System.Numerics.cs @@ -26,6 +26,8 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BigInteger : System.IComparable, System.IComparable, System.IEquatable, System.IFormattable { + private object _dummy; + private int _dummyPrimitive; [System.CLSCompliantAttribute(false)] public BigInteger(byte[] value) { throw null;} public BigInteger(decimal value) { throw null;} @@ -176,6 +178,7 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Complex : System.IEquatable, System.IFormattable { + private int _dummyPrimitive; public static readonly System.Numerics.Complex ImaginaryOne; public static readonly System.Numerics.Complex One; public static readonly System.Numerics.Complex Zero; diff --git a/external/binary-reference-assemblies/src/v4.5/System.Security.cs b/external/binary-reference-assemblies/src/v4.5/System.Security.cs index 679e903e0a..a1d330c56e 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.Security.cs +++ b/external/binary-reference-assemblies/src/v4.5/System.Security.cs @@ -917,6 +917,7 @@ namespace System.Security.Cryptography.Xml [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct X509IssuerSerial { + private object _dummy; public string IssuerName { get { throw null; } set { } } public string SerialNumber { get { throw null; } set { } } } diff --git a/external/binary-reference-assemblies/src/v4.5/System.ServiceProcess.cs b/external/binary-reference-assemblies/src/v4.5/System.ServiceProcess.cs index fc78087b39..e1d74ad660 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.ServiceProcess.cs +++ b/external/binary-reference-assemblies/src/v4.5/System.ServiceProcess.cs @@ -325,6 +325,7 @@ namespace System.ServiceProcess [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct SessionChangeDescription { + private int _dummyPrimitive; public System.ServiceProcess.SessionChangeReason Reason { get { throw null; } } public int SessionId { get { throw null; } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.5/System.Transactions.cs b/external/binary-reference-assemblies/src/v4.5/System.Transactions.cs index 563c41cf04..6bfcf4dbec 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.Transactions.cs +++ b/external/binary-reference-assemblies/src/v4.5/System.Transactions.cs @@ -300,6 +300,7 @@ namespace System.Transactions [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct TransactionOptions { + private int _dummyPrimitive; public System.Transactions.IsolationLevel IsolationLevel { get { throw null; } set { } } public System.TimeSpan Timeout { get { throw null; } set { } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.5/System.Web.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5/System.Web.cs.REMOVED.git-id index ff6b309d21..0fcce93554 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.Web.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5/System.Web.cs.REMOVED.git-id @@ -1 +1 @@ -4642fdc681dc7f343dd8601cfb6305990fac92f3 \ No newline at end of file +d2eef6f49ca8404852826389c9b41802f6f3bdb9 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5/System.Windows.Forms.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5/System.Windows.Forms.cs.REMOVED.git-id index 16c00f4dea..0170751c2e 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.Windows.Forms.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5/System.Windows.Forms.cs.REMOVED.git-id @@ -1 +1 @@ -bfd029e75d1b15b354d101d32f5938e1b8ed43ea \ No newline at end of file +f1d3de8d737ac6b40240410bbeaa309df6969f35 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5/System.Xml.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5/System.Xml.cs.REMOVED.git-id index 56607fd46c..33d5530bbf 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.Xml.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5/System.Xml.cs.REMOVED.git-id @@ -1 +1 @@ -739753aa230fb7c26c07373f777a9c2b47556218 \ No newline at end of file +bed0768be7e623a6e3d290181b559cb4253ecb43 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5/System.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5/System.cs.REMOVED.git-id index 4ce5feac84..f503937b1b 100644 --- a/external/binary-reference-assemblies/src/v4.5/System.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5/System.cs.REMOVED.git-id @@ -1 +1 @@ -d5d063af300aa7c993efc5d5824f79f1442a32db \ No newline at end of file +76a0826386f311b1ac463c8293522efdc2fc4bf3 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5/WindowsBase.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5/WindowsBase.cs.REMOVED.git-id index d88fbb4564..025728f8bc 100644 --- a/external/binary-reference-assemblies/src/v4.5/WindowsBase.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5/WindowsBase.cs.REMOVED.git-id @@ -1 +1 @@ -77fe49e51289ab178451d25d0f09eed5dd1fecc2 \ No newline at end of file +e00a0c765d8bf59400abd329e1ab419480c04942 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.5/mscorlib.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.5/mscorlib.cs.REMOVED.git-id index 1686b5ae03..b2c13a64b2 100644 --- a/external/binary-reference-assemblies/src/v4.5/mscorlib.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.5/mscorlib.cs.REMOVED.git-id @@ -1 +1 @@ -a4626f36341cbb3d42ece4865fc8f6a508d0af2c \ No newline at end of file +17e5c6b7914a6967787586944a5fce396e61f77a \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.1/Microsoft.Build.Framework.cs b/external/binary-reference-assemblies/src/v4.6.1/Microsoft.Build.Framework.cs index 450a3de0c2..322678d58a 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/Microsoft.Build.Framework.cs +++ b/external/binary-reference-assemblies/src/v4.6.1/Microsoft.Build.Framework.cs @@ -27,6 +27,8 @@ namespace Microsoft.Build.Framework [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BuildEngineResult { + private object _dummy; + private int _dummyPrimitive; public BuildEngineResult(bool result, System.Collections.Generic.List> targetOutputsPerProject) { throw null;} public bool Result { get { throw null; } } public System.Collections.Generic.IList> TargetOutputsPerProject { get { throw null; } } diff --git a/external/binary-reference-assemblies/src/v4.6.1/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.1/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id index cb684c8215..c3c9990348 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.1/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id @@ -1 +1 @@ -76a62a09b763430d423d698a2d3fa27cac10acb0 \ No newline at end of file +9e883964e19ff34d271f1448a829869f9100f8d3 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.1/Microsoft.Build.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.1/Microsoft.Build.cs.REMOVED.git-id index 4fc2e4fa91..db227bfe99 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/Microsoft.Build.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.1/Microsoft.Build.cs.REMOVED.git-id @@ -1 +1 @@ -573cc4d17bde773be4891cb1324773bd938ade6d \ No newline at end of file +6f33b4e835976888e70de3373052fd283ee27f37 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.ComponentModel.Composition.cs b/external/binary-reference-assemblies/src/v4.6.1/System.ComponentModel.Composition.cs index b4415ad0ab..4a4be1a7c3 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.ComponentModel.Composition.cs +++ b/external/binary-reference-assemblies/src/v4.6.1/System.ComponentModel.Composition.cs @@ -656,6 +656,8 @@ namespace System.ComponentModel.Composition.ReflectionModel [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct LazyMemberInfo { + private object _dummy; + private int _dummyPrimitive; public LazyMemberInfo(System.Reflection.MemberInfo member) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, System.Func accessorsCreator) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, params System.Reflection.MemberInfo[] accessors) { throw null;} diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.Core.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.1/System.Core.cs.REMOVED.git-id index 8493f5f284..21d52a61ef 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.Core.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.1/System.Core.cs.REMOVED.git-id @@ -1 +1 @@ -71aec14708cae5568347a764ed1cf954fe8261a4 \ No newline at end of file +1cb366fe0d20565998e29ccc9b8500606aab1df7 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.Data.Entity.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.1/System.Data.Entity.cs.REMOVED.git-id index 9964ee8b79..610b96cbcd 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.Data.Entity.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.1/System.Data.Entity.cs.REMOVED.git-id @@ -1 +1 @@ -7e8ae7363ba439b0378939b0fc19711c78545c75 \ No newline at end of file +a00dec6d9ef041387129ec6e1a9f632e1a0a5232 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.Data.Linq.cs b/external/binary-reference-assemblies/src/v4.6.1/System.Data.Linq.cs index 937fd74329..cd3a565b97 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.Data.Linq.cs +++ b/external/binary-reference-assemblies/src/v4.6.1/System.Data.Linq.cs @@ -263,6 +263,8 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EntityRef where TEntity : class { + private TEntity entity; + private object _dummy; public EntityRef(System.Collections.Generic.IEnumerable source) { throw null;} public EntityRef(System.Data.Linq.EntityRef entityRef) { throw null;} public EntityRef(TEntity entity) { throw null;} @@ -355,6 +357,9 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size=1)] public partial struct Link { + private T underlyingValue; + private object _dummy; + private int _dummyPrimitive; [System.MonoTODOAttribute] public Link(System.Collections.Generic.IEnumerable source) { throw null;} [System.MonoTODOAttribute] @@ -391,6 +396,7 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size=1)] public partial struct ModifiedMemberInfo { + private object _dummy; [System.MonoTODOAttribute] public object CurrentValue { get { throw null; } } [System.MonoTODOAttribute] diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.Data.OracleClient.cs b/external/binary-reference-assemblies/src/v4.6.1/System.Data.OracleClient.cs index fe745fddcb..a6138f6e68 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.Data.OracleClient.cs +++ b/external/binary-reference-assemblies/src/v4.6.1/System.Data.OracleClient.cs @@ -99,6 +99,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBinary : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleBinary Null; public OracleBinary(byte[] b) { throw null;} public bool IsNull { get { throw null; } } @@ -137,6 +138,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBoolean : System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleBoolean False; public static readonly System.Data.OracleClient.OracleBoolean Null; public static readonly System.Data.OracleClient.OracleBoolean One; @@ -479,6 +481,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleDateTime : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleDateTime MaxValue; public static readonly System.Data.OracleClient.OracleDateTime MinValue; public static readonly System.Data.OracleClient.OracleDateTime Null; @@ -583,6 +586,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleMonthSpan : System.Data.SqlTypes.INullable, System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleMonthSpan MaxValue; public static readonly System.Data.OracleClient.OracleMonthSpan MinValue; public static readonly System.Data.OracleClient.OracleMonthSpan Null; @@ -615,6 +619,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleNumber : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleNumber E; public static readonly int MaxPrecision; public static readonly int MaxScale; @@ -833,6 +838,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleString : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleString Empty; public static readonly System.Data.OracleClient.OracleString Null; public OracleString(string s) { throw null;} @@ -866,6 +872,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleTimeSpan : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleTimeSpan MaxValue; public static readonly System.Data.OracleClient.OracleTimeSpan MinValue; public static readonly System.Data.OracleClient.OracleTimeSpan Null; diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.Data.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.1/System.Data.cs.REMOVED.git-id index 93339f55da..523f2fed8a 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.Data.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.1/System.Data.cs.REMOVED.git-id @@ -1 +1 @@ -67f8c8ab4f3fbe15018c0647f8282f346f0b08f8 \ No newline at end of file +bc793ee99003202c7b85ec8ea9f600d0563f93bf \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.Drawing.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.1/System.Drawing.cs.REMOVED.git-id index 3e14771f8c..6fc2263bc4 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.Drawing.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.1/System.Drawing.cs.REMOVED.git-id @@ -1 +1 @@ -fcb7096576a7d1b4b428a16749c979da858d7e31 \ No newline at end of file +ccf75ca37579f401d6325b797a65702df5986b10 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.Numerics.cs b/external/binary-reference-assemblies/src/v4.6.1/System.Numerics.cs index 9db971a3b6..736309d70a 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.Numerics.cs +++ b/external/binary-reference-assemblies/src/v4.6.1/System.Numerics.cs @@ -27,6 +27,8 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BigInteger : System.IComparable, System.IComparable, System.IEquatable, System.IFormattable { + private object _dummy; + private int _dummyPrimitive; [System.CLSCompliantAttribute(false)] public BigInteger(byte[] value) { throw null;} public BigInteger(decimal value) { throw null;} @@ -177,6 +179,7 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Complex : System.IEquatable, System.IFormattable { + private int _dummyPrimitive; public static readonly System.Numerics.Complex ImaginaryOne; public static readonly System.Numerics.Complex One; public static readonly System.Numerics.Complex Zero; diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.Security.cs b/external/binary-reference-assemblies/src/v4.6.1/System.Security.cs index e26987e63e..93da2cafc6 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.Security.cs +++ b/external/binary-reference-assemblies/src/v4.6.1/System.Security.cs @@ -920,6 +920,7 @@ namespace System.Security.Cryptography.Xml [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct X509IssuerSerial { + private object _dummy; public string IssuerName { get { throw null; } set { } } public string SerialNumber { get { throw null; } set { } } } diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.ServiceProcess.cs b/external/binary-reference-assemblies/src/v4.6.1/System.ServiceProcess.cs index 84197b9e6c..3c7e4c29ef 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.ServiceProcess.cs +++ b/external/binary-reference-assemblies/src/v4.6.1/System.ServiceProcess.cs @@ -328,6 +328,7 @@ namespace System.ServiceProcess [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct SessionChangeDescription { + private int _dummyPrimitive; public System.ServiceProcess.SessionChangeReason Reason { get { throw null; } } public int SessionId { get { throw null; } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.Transactions.cs b/external/binary-reference-assemblies/src/v4.6.1/System.Transactions.cs index a8c6263551..0fc0e33c01 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.Transactions.cs +++ b/external/binary-reference-assemblies/src/v4.6.1/System.Transactions.cs @@ -309,6 +309,7 @@ namespace System.Transactions [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct TransactionOptions { + private int _dummyPrimitive; public System.Transactions.IsolationLevel IsolationLevel { get { throw null; } set { } } public System.TimeSpan Timeout { get { throw null; } set { } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.Web.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.1/System.Web.cs.REMOVED.git-id index 454f5b3254..1c537d7894 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.Web.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.1/System.Web.cs.REMOVED.git-id @@ -1 +1 @@ -404af02a5137baf7901544f9c06bf2e9b11dc16f \ No newline at end of file +ffec26b552cb75c2c5bd5ec9b0f5e1bd14ec7b0d \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.Windows.Forms.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.1/System.Windows.Forms.cs.REMOVED.git-id index 93c1aa21bf..776b67519c 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.Windows.Forms.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.1/System.Windows.Forms.cs.REMOVED.git-id @@ -1 +1 @@ -874450606f0e1078464e7a0eb777d639693ec5dd \ No newline at end of file +701925adbb877f26add4c59af8e286c65dbffdc0 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.Xml.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.1/System.Xml.cs.REMOVED.git-id index 4ae8a8aa8b..ce9ab2caa5 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.Xml.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.1/System.Xml.cs.REMOVED.git-id @@ -1 +1 @@ -5107cfbcfa0eb5e078ee6bf478f0a64e7eacd9a6 \ No newline at end of file +8df0ad5e599801c7c73c65efca00abbf4213e9a1 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.1/System.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.1/System.cs.REMOVED.git-id index d9405d99af..39c8734436 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/System.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.1/System.cs.REMOVED.git-id @@ -1 +1 @@ -49f7036349c8b1fde1bb37d13374cb53294e57d0 \ No newline at end of file +4ce5299a573b88e356799dc58865b8d17fa9f5cf \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.1/WindowsBase.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.1/WindowsBase.cs.REMOVED.git-id index 9ca7ed3db0..21a2d43dfa 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/WindowsBase.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.1/WindowsBase.cs.REMOVED.git-id @@ -1 +1 @@ -a7bcea8673e6ca324056dde19e1a7e12f566868c \ No newline at end of file +f4d24ee332f56938161d38fd8e41a123daa91aac \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.1/mscorlib.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.1/mscorlib.cs.REMOVED.git-id index 20e24b1c63..cf3632ef90 100644 --- a/external/binary-reference-assemblies/src/v4.6.1/mscorlib.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.1/mscorlib.cs.REMOVED.git-id @@ -1 +1 @@ -439b0f54411ec562e9dccf42a514dcef454985c9 \ No newline at end of file +1b9826edab4fd9a6494a09e3ff591e7207b1e0a3 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.2/Microsoft.Build.Framework.cs b/external/binary-reference-assemblies/src/v4.6.2/Microsoft.Build.Framework.cs index 450a3de0c2..322678d58a 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/Microsoft.Build.Framework.cs +++ b/external/binary-reference-assemblies/src/v4.6.2/Microsoft.Build.Framework.cs @@ -27,6 +27,8 @@ namespace Microsoft.Build.Framework [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BuildEngineResult { + private object _dummy; + private int _dummyPrimitive; public BuildEngineResult(bool result, System.Collections.Generic.List> targetOutputsPerProject) { throw null;} public bool Result { get { throw null; } } public System.Collections.Generic.IList> TargetOutputsPerProject { get { throw null; } } diff --git a/external/binary-reference-assemblies/src/v4.6.2/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.2/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id index cb684c8215..c3c9990348 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.2/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id @@ -1 +1 @@ -76a62a09b763430d423d698a2d3fa27cac10acb0 \ No newline at end of file +9e883964e19ff34d271f1448a829869f9100f8d3 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.2/Microsoft.Build.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.2/Microsoft.Build.cs.REMOVED.git-id index 4fc2e4fa91..db227bfe99 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/Microsoft.Build.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.2/Microsoft.Build.cs.REMOVED.git-id @@ -1 +1 @@ -573cc4d17bde773be4891cb1324773bd938ade6d \ No newline at end of file +6f33b4e835976888e70de3373052fd283ee27f37 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.ComponentModel.Composition.cs b/external/binary-reference-assemblies/src/v4.6.2/System.ComponentModel.Composition.cs index b4415ad0ab..4a4be1a7c3 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.ComponentModel.Composition.cs +++ b/external/binary-reference-assemblies/src/v4.6.2/System.ComponentModel.Composition.cs @@ -656,6 +656,8 @@ namespace System.ComponentModel.Composition.ReflectionModel [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct LazyMemberInfo { + private object _dummy; + private int _dummyPrimitive; public LazyMemberInfo(System.Reflection.MemberInfo member) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, System.Func accessorsCreator) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, params System.Reflection.MemberInfo[] accessors) { throw null;} diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.Core.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.2/System.Core.cs.REMOVED.git-id index 44cdea9e65..f15e235142 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.Core.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.2/System.Core.cs.REMOVED.git-id @@ -1 +1 @@ -6c0caf23d1d265629fac3091f32b1cdd24834a46 \ No newline at end of file +649a1dfe82f63c5742345a304f0af55a9eb94ee4 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.Data.Entity.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.2/System.Data.Entity.cs.REMOVED.git-id index 9964ee8b79..610b96cbcd 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.Data.Entity.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.2/System.Data.Entity.cs.REMOVED.git-id @@ -1 +1 @@ -7e8ae7363ba439b0378939b0fc19711c78545c75 \ No newline at end of file +a00dec6d9ef041387129ec6e1a9f632e1a0a5232 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.Data.Linq.cs b/external/binary-reference-assemblies/src/v4.6.2/System.Data.Linq.cs index 937fd74329..cd3a565b97 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.Data.Linq.cs +++ b/external/binary-reference-assemblies/src/v4.6.2/System.Data.Linq.cs @@ -263,6 +263,8 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EntityRef where TEntity : class { + private TEntity entity; + private object _dummy; public EntityRef(System.Collections.Generic.IEnumerable source) { throw null;} public EntityRef(System.Data.Linq.EntityRef entityRef) { throw null;} public EntityRef(TEntity entity) { throw null;} @@ -355,6 +357,9 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size=1)] public partial struct Link { + private T underlyingValue; + private object _dummy; + private int _dummyPrimitive; [System.MonoTODOAttribute] public Link(System.Collections.Generic.IEnumerable source) { throw null;} [System.MonoTODOAttribute] @@ -391,6 +396,7 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size=1)] public partial struct ModifiedMemberInfo { + private object _dummy; [System.MonoTODOAttribute] public object CurrentValue { get { throw null; } } [System.MonoTODOAttribute] diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.Data.OracleClient.cs b/external/binary-reference-assemblies/src/v4.6.2/System.Data.OracleClient.cs index fe745fddcb..a6138f6e68 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.Data.OracleClient.cs +++ b/external/binary-reference-assemblies/src/v4.6.2/System.Data.OracleClient.cs @@ -99,6 +99,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBinary : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleBinary Null; public OracleBinary(byte[] b) { throw null;} public bool IsNull { get { throw null; } } @@ -137,6 +138,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBoolean : System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleBoolean False; public static readonly System.Data.OracleClient.OracleBoolean Null; public static readonly System.Data.OracleClient.OracleBoolean One; @@ -479,6 +481,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleDateTime : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleDateTime MaxValue; public static readonly System.Data.OracleClient.OracleDateTime MinValue; public static readonly System.Data.OracleClient.OracleDateTime Null; @@ -583,6 +586,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleMonthSpan : System.Data.SqlTypes.INullable, System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleMonthSpan MaxValue; public static readonly System.Data.OracleClient.OracleMonthSpan MinValue; public static readonly System.Data.OracleClient.OracleMonthSpan Null; @@ -615,6 +619,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleNumber : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleNumber E; public static readonly int MaxPrecision; public static readonly int MaxScale; @@ -833,6 +838,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleString : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleString Empty; public static readonly System.Data.OracleClient.OracleString Null; public OracleString(string s) { throw null;} @@ -866,6 +872,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleTimeSpan : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleTimeSpan MaxValue; public static readonly System.Data.OracleClient.OracleTimeSpan MinValue; public static readonly System.Data.OracleClient.OracleTimeSpan Null; diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.Data.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.2/System.Data.cs.REMOVED.git-id index 51fc69dd5f..a3c123318e 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.Data.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.2/System.Data.cs.REMOVED.git-id @@ -1 +1 @@ -58a60e07a527de9a5e5d065378dc043da4b6f6bd \ No newline at end of file +8e0b53fa7b760c4187f3fa0ed612ba85a131777a \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.Drawing.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.2/System.Drawing.cs.REMOVED.git-id index 3e14771f8c..6fc2263bc4 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.Drawing.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.2/System.Drawing.cs.REMOVED.git-id @@ -1 +1 @@ -fcb7096576a7d1b4b428a16749c979da858d7e31 \ No newline at end of file +ccf75ca37579f401d6325b797a65702df5986b10 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.Numerics.cs b/external/binary-reference-assemblies/src/v4.6.2/System.Numerics.cs index 9db971a3b6..736309d70a 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.Numerics.cs +++ b/external/binary-reference-assemblies/src/v4.6.2/System.Numerics.cs @@ -27,6 +27,8 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BigInteger : System.IComparable, System.IComparable, System.IEquatable, System.IFormattable { + private object _dummy; + private int _dummyPrimitive; [System.CLSCompliantAttribute(false)] public BigInteger(byte[] value) { throw null;} public BigInteger(decimal value) { throw null;} @@ -177,6 +179,7 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Complex : System.IEquatable, System.IFormattable { + private int _dummyPrimitive; public static readonly System.Numerics.Complex ImaginaryOne; public static readonly System.Numerics.Complex One; public static readonly System.Numerics.Complex Zero; diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.Security.cs b/external/binary-reference-assemblies/src/v4.6.2/System.Security.cs index 736dfba13b..03d25475d1 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.Security.cs +++ b/external/binary-reference-assemblies/src/v4.6.2/System.Security.cs @@ -926,6 +926,7 @@ namespace System.Security.Cryptography.Xml [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct X509IssuerSerial { + private object _dummy; public string IssuerName { get { throw null; } set { } } public string SerialNumber { get { throw null; } set { } } } diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.ServiceProcess.cs b/external/binary-reference-assemblies/src/v4.6.2/System.ServiceProcess.cs index 84197b9e6c..3c7e4c29ef 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.ServiceProcess.cs +++ b/external/binary-reference-assemblies/src/v4.6.2/System.ServiceProcess.cs @@ -328,6 +328,7 @@ namespace System.ServiceProcess [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct SessionChangeDescription { + private int _dummyPrimitive; public System.ServiceProcess.SessionChangeReason Reason { get { throw null; } } public int SessionId { get { throw null; } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.Transactions.cs b/external/binary-reference-assemblies/src/v4.6.2/System.Transactions.cs index a8c6263551..0fc0e33c01 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.Transactions.cs +++ b/external/binary-reference-assemblies/src/v4.6.2/System.Transactions.cs @@ -309,6 +309,7 @@ namespace System.Transactions [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct TransactionOptions { + private int _dummyPrimitive; public System.Transactions.IsolationLevel IsolationLevel { get { throw null; } set { } } public System.TimeSpan Timeout { get { throw null; } set { } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.Web.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.2/System.Web.cs.REMOVED.git-id index eab99e7b58..65c2cdc4f5 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.Web.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.2/System.Web.cs.REMOVED.git-id @@ -1 +1 @@ -4dbbe2568093cdf1a5e41ecf069a655c415b3755 \ No newline at end of file +7bff5f0e9c9fc51700a2e043335c3e0951551e71 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.Windows.Forms.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.2/System.Windows.Forms.cs.REMOVED.git-id index 93c1aa21bf..776b67519c 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.Windows.Forms.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.2/System.Windows.Forms.cs.REMOVED.git-id @@ -1 +1 @@ -874450606f0e1078464e7a0eb777d639693ec5dd \ No newline at end of file +701925adbb877f26add4c59af8e286c65dbffdc0 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.Xml.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.2/System.Xml.cs.REMOVED.git-id index 4ae8a8aa8b..ce9ab2caa5 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.Xml.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.2/System.Xml.cs.REMOVED.git-id @@ -1 +1 @@ -5107cfbcfa0eb5e078ee6bf478f0a64e7eacd9a6 \ No newline at end of file +8df0ad5e599801c7c73c65efca00abbf4213e9a1 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.2/System.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.2/System.cs.REMOVED.git-id index d9405d99af..39c8734436 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/System.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.2/System.cs.REMOVED.git-id @@ -1 +1 @@ -49f7036349c8b1fde1bb37d13374cb53294e57d0 \ No newline at end of file +4ce5299a573b88e356799dc58865b8d17fa9f5cf \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.2/WindowsBase.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.2/WindowsBase.cs.REMOVED.git-id index ce7aa71ba2..8bcb9dfe05 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/WindowsBase.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.2/WindowsBase.cs.REMOVED.git-id @@ -1 +1 @@ -2b4a18e828762bbeeea390a30fb88dab9017adb5 \ No newline at end of file +e805574c979747075442d3c3f53942319b47d28f \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6.2/mscorlib.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6.2/mscorlib.cs.REMOVED.git-id index c05d77cd89..df333fb728 100644 --- a/external/binary-reference-assemblies/src/v4.6.2/mscorlib.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6.2/mscorlib.cs.REMOVED.git-id @@ -1 +1 @@ -db94af8743d91ab1956f9cc2ea91b3970da6c543 \ No newline at end of file +dfb9325101cd5adf050876a64721932a9a5697fb \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6/Microsoft.Build.Framework.cs b/external/binary-reference-assemblies/src/v4.6/Microsoft.Build.Framework.cs index 450a3de0c2..322678d58a 100644 --- a/external/binary-reference-assemblies/src/v4.6/Microsoft.Build.Framework.cs +++ b/external/binary-reference-assemblies/src/v4.6/Microsoft.Build.Framework.cs @@ -27,6 +27,8 @@ namespace Microsoft.Build.Framework [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BuildEngineResult { + private object _dummy; + private int _dummyPrimitive; public BuildEngineResult(bool result, System.Collections.Generic.List> targetOutputsPerProject) { throw null;} public bool Result { get { throw null; } } public System.Collections.Generic.IList> TargetOutputsPerProject { get { throw null; } } diff --git a/external/binary-reference-assemblies/src/v4.6/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id index cb684c8215..c3c9990348 100644 --- a/external/binary-reference-assemblies/src/v4.6/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id @@ -1 +1 @@ -76a62a09b763430d423d698a2d3fa27cac10acb0 \ No newline at end of file +9e883964e19ff34d271f1448a829869f9100f8d3 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6/Microsoft.Build.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6/Microsoft.Build.cs.REMOVED.git-id index 4fc2e4fa91..db227bfe99 100644 --- a/external/binary-reference-assemblies/src/v4.6/Microsoft.Build.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6/Microsoft.Build.cs.REMOVED.git-id @@ -1 +1 @@ -573cc4d17bde773be4891cb1324773bd938ade6d \ No newline at end of file +6f33b4e835976888e70de3373052fd283ee27f37 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6/System.ComponentModel.Composition.cs b/external/binary-reference-assemblies/src/v4.6/System.ComponentModel.Composition.cs index b4415ad0ab..4a4be1a7c3 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.ComponentModel.Composition.cs +++ b/external/binary-reference-assemblies/src/v4.6/System.ComponentModel.Composition.cs @@ -656,6 +656,8 @@ namespace System.ComponentModel.Composition.ReflectionModel [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct LazyMemberInfo { + private object _dummy; + private int _dummyPrimitive; public LazyMemberInfo(System.Reflection.MemberInfo member) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, System.Func accessorsCreator) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, params System.Reflection.MemberInfo[] accessors) { throw null;} diff --git a/external/binary-reference-assemblies/src/v4.6/System.Core.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6/System.Core.cs.REMOVED.git-id index 4b54824dcb..39be6492bf 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.Core.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6/System.Core.cs.REMOVED.git-id @@ -1 +1 @@ -02484706e755a4b6cd73ff521071c6d631636d60 \ No newline at end of file +c529a8f763ddd2e6e80e6104c41975182b7f7d62 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6/System.Data.Entity.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6/System.Data.Entity.cs.REMOVED.git-id index 9964ee8b79..610b96cbcd 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.Data.Entity.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6/System.Data.Entity.cs.REMOVED.git-id @@ -1 +1 @@ -7e8ae7363ba439b0378939b0fc19711c78545c75 \ No newline at end of file +a00dec6d9ef041387129ec6e1a9f632e1a0a5232 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6/System.Data.Linq.cs b/external/binary-reference-assemblies/src/v4.6/System.Data.Linq.cs index 937fd74329..cd3a565b97 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.Data.Linq.cs +++ b/external/binary-reference-assemblies/src/v4.6/System.Data.Linq.cs @@ -263,6 +263,8 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EntityRef where TEntity : class { + private TEntity entity; + private object _dummy; public EntityRef(System.Collections.Generic.IEnumerable source) { throw null;} public EntityRef(System.Data.Linq.EntityRef entityRef) { throw null;} public EntityRef(TEntity entity) { throw null;} @@ -355,6 +357,9 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size=1)] public partial struct Link { + private T underlyingValue; + private object _dummy; + private int _dummyPrimitive; [System.MonoTODOAttribute] public Link(System.Collections.Generic.IEnumerable source) { throw null;} [System.MonoTODOAttribute] @@ -391,6 +396,7 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size=1)] public partial struct ModifiedMemberInfo { + private object _dummy; [System.MonoTODOAttribute] public object CurrentValue { get { throw null; } } [System.MonoTODOAttribute] diff --git a/external/binary-reference-assemblies/src/v4.6/System.Data.OracleClient.cs b/external/binary-reference-assemblies/src/v4.6/System.Data.OracleClient.cs index fe745fddcb..a6138f6e68 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.Data.OracleClient.cs +++ b/external/binary-reference-assemblies/src/v4.6/System.Data.OracleClient.cs @@ -99,6 +99,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBinary : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleBinary Null; public OracleBinary(byte[] b) { throw null;} public bool IsNull { get { throw null; } } @@ -137,6 +138,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBoolean : System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleBoolean False; public static readonly System.Data.OracleClient.OracleBoolean Null; public static readonly System.Data.OracleClient.OracleBoolean One; @@ -479,6 +481,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleDateTime : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleDateTime MaxValue; public static readonly System.Data.OracleClient.OracleDateTime MinValue; public static readonly System.Data.OracleClient.OracleDateTime Null; @@ -583,6 +586,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleMonthSpan : System.Data.SqlTypes.INullable, System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleMonthSpan MaxValue; public static readonly System.Data.OracleClient.OracleMonthSpan MinValue; public static readonly System.Data.OracleClient.OracleMonthSpan Null; @@ -615,6 +619,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleNumber : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleNumber E; public static readonly int MaxPrecision; public static readonly int MaxScale; @@ -833,6 +838,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleString : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleString Empty; public static readonly System.Data.OracleClient.OracleString Null; public OracleString(string s) { throw null;} @@ -866,6 +872,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleTimeSpan : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleTimeSpan MaxValue; public static readonly System.Data.OracleClient.OracleTimeSpan MinValue; public static readonly System.Data.OracleClient.OracleTimeSpan Null; diff --git a/external/binary-reference-assemblies/src/v4.6/System.Data.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6/System.Data.cs.REMOVED.git-id index 1f5ac3e921..172df8ec2d 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.Data.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6/System.Data.cs.REMOVED.git-id @@ -1 +1 @@ -81b6be18aaf8c5b481d0b4c844f6fc4155da8d6a \ No newline at end of file +c78fdc059a703a95224c67ed2810a82a07a73efc \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6/System.Drawing.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6/System.Drawing.cs.REMOVED.git-id index 755cfd1483..34a7e5251a 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.Drawing.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6/System.Drawing.cs.REMOVED.git-id @@ -1 +1 @@ -b40cca8224f6a6f1c859867f3fa162bb84475df7 \ No newline at end of file +15ede396c7334465b391aa1593c2c72d0f0797f5 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6/System.Numerics.cs b/external/binary-reference-assemblies/src/v4.6/System.Numerics.cs index 9db971a3b6..736309d70a 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.Numerics.cs +++ b/external/binary-reference-assemblies/src/v4.6/System.Numerics.cs @@ -27,6 +27,8 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BigInteger : System.IComparable, System.IComparable, System.IEquatable, System.IFormattable { + private object _dummy; + private int _dummyPrimitive; [System.CLSCompliantAttribute(false)] public BigInteger(byte[] value) { throw null;} public BigInteger(decimal value) { throw null;} @@ -177,6 +179,7 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Complex : System.IEquatable, System.IFormattable { + private int _dummyPrimitive; public static readonly System.Numerics.Complex ImaginaryOne; public static readonly System.Numerics.Complex One; public static readonly System.Numerics.Complex Zero; diff --git a/external/binary-reference-assemblies/src/v4.6/System.Security.cs b/external/binary-reference-assemblies/src/v4.6/System.Security.cs index e26987e63e..93da2cafc6 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.Security.cs +++ b/external/binary-reference-assemblies/src/v4.6/System.Security.cs @@ -920,6 +920,7 @@ namespace System.Security.Cryptography.Xml [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct X509IssuerSerial { + private object _dummy; public string IssuerName { get { throw null; } set { } } public string SerialNumber { get { throw null; } set { } } } diff --git a/external/binary-reference-assemblies/src/v4.6/System.ServiceProcess.cs b/external/binary-reference-assemblies/src/v4.6/System.ServiceProcess.cs index c35621e1fd..2d86135a99 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.ServiceProcess.cs +++ b/external/binary-reference-assemblies/src/v4.6/System.ServiceProcess.cs @@ -325,6 +325,7 @@ namespace System.ServiceProcess [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct SessionChangeDescription { + private int _dummyPrimitive; public System.ServiceProcess.SessionChangeReason Reason { get { throw null; } } public int SessionId { get { throw null; } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.6/System.Transactions.cs b/external/binary-reference-assemblies/src/v4.6/System.Transactions.cs index 03501644a3..87fc507aec 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.Transactions.cs +++ b/external/binary-reference-assemblies/src/v4.6/System.Transactions.cs @@ -304,6 +304,7 @@ namespace System.Transactions [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct TransactionOptions { + private int _dummyPrimitive; public System.Transactions.IsolationLevel IsolationLevel { get { throw null; } set { } } public System.TimeSpan Timeout { get { throw null; } set { } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.6/System.Web.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6/System.Web.cs.REMOVED.git-id index 7c012f040f..f1b7fcb029 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.Web.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6/System.Web.cs.REMOVED.git-id @@ -1 +1 @@ -fdcdb3bac070fa338caea3ed9f2c8960f230ed48 \ No newline at end of file +38b69693b562d82c1b30594e75ade9817f3ed498 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6/System.Windows.Forms.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6/System.Windows.Forms.cs.REMOVED.git-id index d2f7708357..25842111bc 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.Windows.Forms.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6/System.Windows.Forms.cs.REMOVED.git-id @@ -1 +1 @@ -00505c693532bf18d8a76ede342c90f6121c33de \ No newline at end of file +40e073a43d8eaf5db2e9cd3fcff19a782aba36b5 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6/System.Xml.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6/System.Xml.cs.REMOVED.git-id index 4ae8a8aa8b..ce9ab2caa5 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.Xml.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6/System.Xml.cs.REMOVED.git-id @@ -1 +1 @@ -5107cfbcfa0eb5e078ee6bf478f0a64e7eacd9a6 \ No newline at end of file +8df0ad5e599801c7c73c65efca00abbf4213e9a1 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6/System.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6/System.cs.REMOVED.git-id index ef545bea71..3008d81c77 100644 --- a/external/binary-reference-assemblies/src/v4.6/System.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6/System.cs.REMOVED.git-id @@ -1 +1 @@ -05a9af63f2ced4bd1e8c75f5a180e217426e53ba \ No newline at end of file +2a7546d3153ad8b97c13643e8858b609f7dec7fe \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6/WindowsBase.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6/WindowsBase.cs.REMOVED.git-id index 9ca7ed3db0..21a2d43dfa 100644 --- a/external/binary-reference-assemblies/src/v4.6/WindowsBase.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6/WindowsBase.cs.REMOVED.git-id @@ -1 +1 @@ -a7bcea8673e6ca324056dde19e1a7e12f566868c \ No newline at end of file +f4d24ee332f56938161d38fd8e41a123daa91aac \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.6/mscorlib.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.6/mscorlib.cs.REMOVED.git-id index 20e24b1c63..cf3632ef90 100644 --- a/external/binary-reference-assemblies/src/v4.6/mscorlib.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.6/mscorlib.cs.REMOVED.git-id @@ -1 +1 @@ -439b0f54411ec562e9dccf42a514dcef454985c9 \ No newline at end of file +1b9826edab4fd9a6494a09e3ff591e7207b1e0a3 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.1/Microsoft.Build.Framework.cs b/external/binary-reference-assemblies/src/v4.7.1/Microsoft.Build.Framework.cs index 1b9643d14c..f55767710e 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/Microsoft.Build.Framework.cs +++ b/external/binary-reference-assemblies/src/v4.7.1/Microsoft.Build.Framework.cs @@ -32,6 +32,8 @@ namespace Microsoft.Build.Framework [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BuildEngineResult { + private object _dummy; + private int _dummyPrimitive; public BuildEngineResult(bool result, System.Collections.Generic.List> targetOutputsPerProject) { throw null;} public bool Result { get { throw null; } } public System.Collections.Generic.IList> TargetOutputsPerProject { get { throw null; } } diff --git a/external/binary-reference-assemblies/src/v4.7.1/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.1/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id index a2ef09fb05..b5852dbea8 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.1/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id @@ -1 +1 @@ -7f4092bc6227081eb136eb7d12fb4ac43ef15079 \ No newline at end of file +6b57b88787452042c64d8d744d5b0b68678cd259 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.1/Microsoft.Build.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.1/Microsoft.Build.cs.REMOVED.git-id index e6dec15b35..a7be8a07e7 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/Microsoft.Build.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.1/Microsoft.Build.cs.REMOVED.git-id @@ -1 +1 @@ -a856a227c5701ba844edc85de7873f0ad61099f5 \ No newline at end of file +9f5f2e011dbcf98287ef95cc48ec5368f7e235b2 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.ComponentModel.Composition.cs b/external/binary-reference-assemblies/src/v4.7.1/System.ComponentModel.Composition.cs index 2ab0aecf1d..f6b9719e3b 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.ComponentModel.Composition.cs +++ b/external/binary-reference-assemblies/src/v4.7.1/System.ComponentModel.Composition.cs @@ -657,6 +657,8 @@ namespace System.ComponentModel.Composition.ReflectionModel [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct LazyMemberInfo { + private object _dummy; + private int _dummyPrimitive; public LazyMemberInfo(System.Reflection.MemberInfo member) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, System.Func accessorsCreator) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, params System.Reflection.MemberInfo[] accessors) { throw null;} diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.Core.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.1/System.Core.cs.REMOVED.git-id index 8ccd8f57e4..f6f468fb45 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.Core.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.1/System.Core.cs.REMOVED.git-id @@ -1 +1 @@ -c2326f36f5006caa96a72f19b0fff05aa338e9d6 \ No newline at end of file +8a62fc12cb915280dc717aaf6522a83d620c8018 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.Data.Entity.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.1/System.Data.Entity.cs.REMOVED.git-id index 6397f9973a..cdbc206a20 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.Data.Entity.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.1/System.Data.Entity.cs.REMOVED.git-id @@ -1 +1 @@ -0f897698c0229494b0def6f4870c1d9ac2df87a4 \ No newline at end of file +cbaee212ef47f30aa7d3d8a730e66884328c953d \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.Data.Linq.cs b/external/binary-reference-assemblies/src/v4.7.1/System.Data.Linq.cs index 685278151a..3604f5e602 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.Data.Linq.cs +++ b/external/binary-reference-assemblies/src/v4.7.1/System.Data.Linq.cs @@ -170,6 +170,8 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EntityRef where TEntity : class { + private TEntity entity; + private object _dummy; public EntityRef(System.Collections.Generic.IEnumerable source) { throw null;} public EntityRef(System.Data.Linq.EntityRef entityRef) { throw null;} public EntityRef(TEntity entity) { throw null;} @@ -262,6 +264,9 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Link { + private T underlyingValue; + private object _dummy; + private int _dummyPrimitive; public Link(System.Collections.Generic.IEnumerable source) { throw null;} public Link(System.Data.Linq.Link link) { throw null;} public Link(T value) { throw null;} @@ -284,6 +289,7 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ModifiedMemberInfo { + private object _dummy; public object CurrentValue { get { throw null; } } public System.Reflection.MemberInfo Member { get { throw null; } } public object OriginalValue { get { throw null; } } diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.Data.OracleClient.cs b/external/binary-reference-assemblies/src/v4.7.1/System.Data.OracleClient.cs index 0c2b211936..da47efdca0 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.Data.OracleClient.cs +++ b/external/binary-reference-assemblies/src/v4.7.1/System.Data.OracleClient.cs @@ -53,6 +53,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBinary : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleBinary Null; public OracleBinary(byte[] b) { throw null;} public bool IsNull { get { throw null; } } @@ -82,6 +83,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBoolean : System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleBoolean False; public static readonly System.Data.OracleClient.OracleBoolean Null; public static readonly System.Data.OracleClient.OracleBoolean One; @@ -415,6 +417,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack=1)] public partial struct OracleDateTime : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleDateTime MaxValue; public static readonly System.Data.OracleClient.OracleDateTime MinValue; public static readonly System.Data.OracleClient.OracleDateTime Null; @@ -515,6 +518,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack=1)] public partial struct OracleMonthSpan : System.Data.SqlTypes.INullable, System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleMonthSpan MaxValue; public static readonly System.Data.OracleClient.OracleMonthSpan MinValue; public static readonly System.Data.OracleClient.OracleMonthSpan Null; @@ -546,6 +550,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack=1)] public partial struct OracleNumber : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleNumber E; public static readonly int MaxPrecision; public static readonly int MaxScale; @@ -764,6 +769,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleString : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleString Empty; public static readonly System.Data.OracleClient.OracleString Null; public OracleString(string s) { throw null;} @@ -795,6 +801,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack=1)] public partial struct OracleTimeSpan : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleTimeSpan MaxValue; public static readonly System.Data.OracleClient.OracleTimeSpan MinValue; public static readonly System.Data.OracleClient.OracleTimeSpan Null; diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.Data.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.1/System.Data.cs.REMOVED.git-id index 12ff218373..ab436cf37c 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.Data.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.1/System.Data.cs.REMOVED.git-id @@ -1 +1 @@ -bd7cf5b5fd5aff34a37a56c42cbb83f0f2cef4b9 \ No newline at end of file +5c8febe4e5806dcdedc6b398492b2cd030d85c9c \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.Drawing.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.1/System.Drawing.cs.REMOVED.git-id index b6df57fc10..31665a2708 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.Drawing.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.1/System.Drawing.cs.REMOVED.git-id @@ -1 +1 @@ -90c687c3e1908f3db4d3afad02fabfb65f3c4b49 \ No newline at end of file +fc452a297aaf22ca5f9c88a7663a645bcc23875e \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.Numerics.cs b/external/binary-reference-assemblies/src/v4.7.1/System.Numerics.cs index 3fe9c48e7e..2fd92c56f8 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.Numerics.cs +++ b/external/binary-reference-assemblies/src/v4.7.1/System.Numerics.cs @@ -29,6 +29,8 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BigInteger : System.IComparable, System.IComparable, System.IEquatable, System.IFormattable { + private object _dummy; + private int _dummyPrimitive; [System.CLSCompliantAttribute(false)] public BigInteger(byte[] value) { throw null;} public BigInteger(decimal value) { throw null;} @@ -179,6 +181,7 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Complex : System.IEquatable, System.IFormattable { + private int _dummyPrimitive; public static readonly System.Numerics.Complex ImaginaryOne; public static readonly System.Numerics.Complex One; public static readonly System.Numerics.Complex Zero; diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.Security.cs b/external/binary-reference-assemblies/src/v4.7.1/System.Security.cs index 3b8184548d..122decf02d 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.Security.cs +++ b/external/binary-reference-assemblies/src/v4.7.1/System.Security.cs @@ -935,6 +935,7 @@ namespace System.Security.Cryptography.Xml [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct X509IssuerSerial { + private object _dummy; public string IssuerName { get { throw null; } set { } } public string SerialNumber { get { throw null; } set { } } } diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.ServiceProcess.cs b/external/binary-reference-assemblies/src/v4.7.1/System.ServiceProcess.cs index 9cb1445c6e..9f37444ea7 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.ServiceProcess.cs +++ b/external/binary-reference-assemblies/src/v4.7.1/System.ServiceProcess.cs @@ -289,6 +289,7 @@ namespace System.ServiceProcess [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct SessionChangeDescription { + private int _dummyPrimitive; public System.ServiceProcess.SessionChangeReason Reason { get { throw null; } } public int SessionId { get { throw null; } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.Transactions.cs b/external/binary-reference-assemblies/src/v4.7.1/System.Transactions.cs index 97cc769285..ebea2cd2b2 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.Transactions.cs +++ b/external/binary-reference-assemblies/src/v4.7.1/System.Transactions.cs @@ -261,6 +261,7 @@ namespace System.Transactions [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct TransactionOptions { + private int _dummyPrimitive; public System.Transactions.IsolationLevel IsolationLevel { get { throw null; } set { } } public System.TimeSpan Timeout { get { throw null; } set { } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.Web.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.1/System.Web.cs.REMOVED.git-id index 79708e8512..2cf8febf15 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.Web.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.1/System.Web.cs.REMOVED.git-id @@ -1 +1 @@ -30396592542e04793e4b67371dfb9af8ed92a285 \ No newline at end of file +0ccb881385af4572a28a6196e5cc16c70d9a4762 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.Windows.Forms.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.1/System.Windows.Forms.cs.REMOVED.git-id index a98bff6de3..91ba4eb30f 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.Windows.Forms.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.1/System.Windows.Forms.cs.REMOVED.git-id @@ -1 +1 @@ -84e543e06ed3e5e935a09a04f3073133d41ff2d2 \ No newline at end of file +a0b24882e3fa594d600c7c27a9bd2eeaa7a15dac \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.Xml.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.1/System.Xml.cs.REMOVED.git-id index d9cf0f6d26..dd72d066d4 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.Xml.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.1/System.Xml.cs.REMOVED.git-id @@ -1 +1 @@ -42a84d6511b4f1705ca565cf3ca74386f5257ca0 \ No newline at end of file +fc77ef88da53b04518c070fc9d6f8fca552ee306 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.1/System.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.1/System.cs.REMOVED.git-id index 4bf0ad474d..0053554273 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/System.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.1/System.cs.REMOVED.git-id @@ -1 +1 @@ -2a68828e1d77e0c328deb56e2a81d938a5c2b129 \ No newline at end of file +2e5122c363b7a8e41160893c0d7245527a9c258b \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.1/WindowsBase.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.1/WindowsBase.cs.REMOVED.git-id index ade04ee06f..38f6adbea9 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/WindowsBase.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.1/WindowsBase.cs.REMOVED.git-id @@ -1 +1 @@ -951098fd0033f9db067b6598a1a033d8cf41b77e \ No newline at end of file +0ddfd3038d2f4daf7b81e03d0ff4d33e08daaaba \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.1/mscorlib.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.1/mscorlib.cs.REMOVED.git-id index 210d8d0b58..75652102e3 100644 --- a/external/binary-reference-assemblies/src/v4.7.1/mscorlib.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.1/mscorlib.cs.REMOVED.git-id @@ -1 +1 @@ -a196c6b0788a58bd69da6085e55300cd9bcded48 \ No newline at end of file +2a16d177f2f1a32aa8c2543f4fdca92577153d66 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/Accessibility.cs b/external/binary-reference-assemblies/src/v4.7.2/Accessibility.cs index aa22f29dcc..fbbcf3c417 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/Accessibility.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/Accessibility.cs @@ -4,13 +4,13 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(257))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.Default | System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("Accessibility.dll")] [assembly:System.Reflection.AssemblyDescriptionAttribute("Accessibility.dll")] -[assembly:System.Reflection.AssemblyFileVersionAttribute("4.7.2558.0")] -[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.7.2558.0")] +[assembly:System.Reflection.AssemblyFileVersionAttribute("4.7.3062.0")] +[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.7.3062.0")] [assembly:System.Reflection.AssemblyProductAttribute("Mono Common Language Infrastructure")] [assembly:System.Reflection.AssemblyTitleAttribute("Accessibility.dll")] [assembly:System.Resources.NeutralResourcesLanguageAttribute("en-US")] @@ -19,12 +19,12 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(true)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Runtime.InteropServices.GuidAttribute("1EA4DBF0-3C3B-11CF-810C-00AA00389B71")] [assembly:System.Runtime.InteropServices.ImportedFromTypeLibAttribute("Accessibility")] [assembly:System.Runtime.InteropServices.TypeLibVersionAttribute(1, 1)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] namespace Accessibility { public enum AnnoScope @@ -37,10 +37,10 @@ namespace Accessibility public partial interface CAccPropServices : Accessibility.IAccPropServices { } - [System.Runtime.InteropServices.ClassInterfaceAttribute((System.Runtime.InteropServices.ClassInterfaceType)(0))] + [System.Runtime.InteropServices.ClassInterfaceAttribute(System.Runtime.InteropServices.ClassInterfaceType.None)] [System.Runtime.InteropServices.ComConversionLossAttribute] [System.Runtime.InteropServices.GuidAttribute("B5F8350B-0548-48B1-A6EE-88BD00B4A5E7")] - [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)(2))] + [System.Runtime.InteropServices.TypeLibTypeAttribute(System.Runtime.InteropServices.TypeLibTypeFlags.FCanCreate)] public partial class CAccPropServicesClass : Accessibility.CAccPropServices, Accessibility.IAccPropServices { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]public CAccPropServicesClass() { } @@ -61,7 +61,7 @@ namespace Accessibility [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]public virtual void SetPropValue([System.Runtime.InteropServices.In]ref byte pIDString, [System.Runtime.InteropServices.In]uint dwIDStringLen, [System.Runtime.InteropServices.In]System.Guid idProp, [System.Runtime.InteropServices.In][System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Struct)]object var) { } } [System.Runtime.InteropServices.GuidAttribute("618736E0-3C3D-11CF-810C-00AA00389B71")] - [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)(4176))] + [System.Runtime.InteropServices.TypeLibTypeAttribute(System.Runtime.InteropServices.TypeLibTypeFlags.FDispatchable | System.Runtime.InteropServices.TypeLibTypeFlags.FDual | System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)] public partial interface IAccessible { int accChildCount { get; } @@ -87,28 +87,28 @@ namespace Accessibility void set_accValue(object childID, string newValue); } [System.Runtime.InteropServices.GuidAttribute("03022430-ABC4-11D0-BDE2-00AA001A1953")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] - [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)(272))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] + [System.Runtime.InteropServices.TypeLibTypeAttribute(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FOleAutomation)] public partial interface IAccessibleHandler { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]void AccessibleObjectFromID([System.Runtime.InteropServices.In]int hwnd, [System.Runtime.InteropServices.In]int lObjectID, [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Interface)]out Accessibility.IAccessible pIAccessible); } [System.Runtime.InteropServices.ComConversionLossAttribute] [System.Runtime.InteropServices.GuidAttribute("7852B78D-1CFD-41C1-A615-9C0C85960B5F")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface IAccIdentity { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]void GetIdentityString([System.Runtime.InteropServices.In]uint dwIDChild, [System.Runtime.InteropServices.Out]System.IntPtr ppIDString, out uint pdwIDStringLen); } [System.Runtime.InteropServices.GuidAttribute("76C0DBBB-15E0-4E7B-B61B-20EEEA2001E0")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface IAccPropServer { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]void GetPropValue([System.Runtime.InteropServices.In]ref byte pIDString, [System.Runtime.InteropServices.In]uint dwIDStringLen, [System.Runtime.InteropServices.In]System.Guid idProp, [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Struct)]out object pvarValue, out int pfHasProp); } [System.Runtime.InteropServices.ComConversionLossAttribute] [System.Runtime.InteropServices.GuidAttribute("6E26E776-04F0-495D-80E4-3330352E3169")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface IAccPropServices { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]void ClearHmenuProps([System.Runtime.InteropServices.ComAliasNameAttribute("Accessibility.wireHMENU")][System.Runtime.InteropServices.In]ref Accessibility._RemotableHandle hmenu, [System.Runtime.InteropServices.In]uint idChild, [System.Runtime.InteropServices.In]ref System.Guid paProps, [System.Runtime.InteropServices.In]int cProps); diff --git a/external/binary-reference-assemblies/src/v4.7.2/CustomMarshalers.cs b/external/binary-reference-assemblies/src/v4.7.2/CustomMarshalers.cs index 7d43c2d361..a8e2bdbfea 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/CustomMarshalers.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/CustomMarshalers.cs @@ -17,7 +17,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1))] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace System.Runtime.InteropServices.CustomMarshalers { diff --git a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Engine.cs b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Engine.cs index 4b79e7efde..e0b59b755a 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Engine.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Engine.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("Microsoft.Build.Engine.dll")] @@ -19,8 +19,8 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] -[assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Flags=(System.Security.Permissions.SecurityPermissionFlag)(8))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] +[assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Flags=System.Security.Permissions.SecurityPermissionFlag.Execution)] namespace Microsoft.Build.BuildEngine { [System.Diagnostics.DebuggerDisplayAttribute("BuildItem (Name = { Name }, Include = { Include }, FinalItemSpec = { FinalItemSpec }, Condition = { Condition } )")] diff --git a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Framework.cs b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Framework.cs index f6e8c7df83..17c14c3bbd 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Framework.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Framework.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("Microsoft.Build.Framework.dll")] @@ -19,12 +19,12 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(4096))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.SafeDirectories)] [assembly:System.Runtime.InteropServices.GuidAttribute("D8A9BA71-4724-481d-9CA7-0DA23A1D615C")] #if false [assembly:System.Windows.Markup.XmlnsDefinitionAttribute("http://schemas.microsoft.com/build/2009/properties", "Microsoft.Build.Framework.XamlTypes")] #endif -[assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Flags=(System.Security.Permissions.SecurityPermissionFlag)(8))] +[assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Flags=System.Security.Permissions.SecurityPermissionFlag.Execution)] namespace Microsoft.Build.Framework { public delegate void AnyEventHandler(object sender, Microsoft.Build.Framework.BuildEventArgs e); @@ -32,7 +32,9 @@ namespace Microsoft.Build.Framework [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BuildEngineResult { - public BuildEngineResult(bool result, System.Collections.Generic.List> targetOutputsPerProject) { throw null;} + private object _dummy; + private int _dummyPrimitive; + public BuildEngineResult(bool result, System.Collections.Generic.List> targetOutputsPerProject) { throw null; } public bool Result { get { throw null; } } public System.Collections.Generic.IList> TargetOutputsPerProject { get { throw null; } } } @@ -294,7 +296,7 @@ namespace Microsoft.Build.Framework } [System.Runtime.InteropServices.ComVisibleAttribute(true)] [System.Runtime.InteropServices.GuidAttribute("9049A481-D0E9-414f-8F92-D4F67A0359A6")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface ITaskHost { } @@ -328,7 +330,7 @@ namespace Microsoft.Build.Framework public LazyFormattedBuildEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { } public override string Message { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed partial class LoadInSeparateAppDomainAttribute : System.Attribute { public LoadInSeparateAppDomainAttribute() { } @@ -362,7 +364,7 @@ namespace Microsoft.Build.Framework Low = 2, Normal = 1, } - [System.AttributeUsageAttribute((System.AttributeTargets)(128), AllowMultiple=false, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] public sealed partial class OutputAttribute : System.Attribute { public OutputAttribute() { } @@ -402,23 +404,23 @@ namespace Microsoft.Build.Framework AppDomain = 1, Build = 0, } - [System.AttributeUsageAttribute((System.AttributeTargets)(128), AllowMultiple=false, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] public sealed partial class RequiredAttribute : System.Attribute { public RequiredAttribute() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] public sealed partial class RequiredRuntimeAttribute : System.Attribute { public RequiredRuntimeAttribute(string runtimeVersion) { } public string RuntimeVersion { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] public sealed partial class RunInMTAAttribute : System.Attribute { public RunInMTAAttribute() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] public sealed partial class RunInSTAAttribute : System.Attribute { public RunInSTAAttribute() { } diff --git a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id index ba4b77f74b..850b34fbe1 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id @@ -1 +1 @@ -607db940f06aa602b2c4f59799563b14acc1e64e \ No newline at end of file +bbff38dbf0754668f85614034c3197fe0df2b9e4 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Utilities.v4.0.cs b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Utilities.v4.0.cs index 4bf3ecfda8..c163972cc9 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Utilities.v4.0.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.Utilities.v4.0.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("Microsoft.Build.Utilities.v4.0.dll")] @@ -19,8 +19,8 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(4096))] -[assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Flags=(System.Security.Permissions.SecurityPermissionFlag)(8))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.SafeDirectories)] +[assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Flags=System.Security.Permissions.SecurityPermissionFlag.Execution)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace Microsoft.Build.Utilities { @@ -318,7 +318,7 @@ namespace Microsoft.Build.Utilities public string HelpKeywordPrefix { get { throw null; } set { } } protected string TaskName { get { throw null; } } public System.Resources.ResourceManager TaskResources { get { throw null; } set { } } - public string ExtractMessageCode(string message, out string messageWithoutCodePrefix) { messageWithoutCodePrefix = default(string); throw null; } + public string ExtractMessageCode(string message, out string messageWithoutCodePrefix) { throw null; } public virtual string FormatResourceString(string resourceName, params object[] args) { throw null; } public virtual string FormatString(string unformatted, params object[] args) { throw null; } public virtual string GetResourceMessage(string resourceName) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.cs.REMOVED.git-id index b838d61b0c..d5bd0c4829 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.Build.cs.REMOVED.git-id @@ -1 +1 @@ -dcf313dceafcc945212a967769e143c6b493469c \ No newline at end of file +6dbc7becd87877eeb72ba2817634bca412faaf85 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.CSharp.cs b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.CSharp.cs index e78bd92477..d805dea7e4 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.CSharp.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.CSharp.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("Microsoft.CSharp.dll")] @@ -19,13 +19,13 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.SecurityTransparentAttribute] namespace Microsoft.CSharp.RuntimeBinder { - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static partial class Binder { public static System.Runtime.CompilerServices.CallSiteBinder BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags flags, System.Linq.Expressions.ExpressionType operation, System.Type context, System.Collections.Generic.IEnumerable argumentInfo) { throw null; } @@ -40,13 +40,13 @@ namespace Microsoft.CSharp.RuntimeBinder public static System.Runtime.CompilerServices.CallSiteBinder SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags flags, string name, System.Type context, System.Collections.Generic.IEnumerable argumentInfo) { throw null; } public static System.Runtime.CompilerServices.CallSiteBinder UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags flags, System.Linq.Expressions.ExpressionType operation, System.Type context, System.Collections.Generic.IEnumerable argumentInfo) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class CSharpArgumentInfo { internal CSharpArgumentInfo() { } public static Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags flags, string name) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.FlagsAttribute] public enum CSharpArgumentInfoFlags { @@ -58,7 +58,7 @@ namespace Microsoft.CSharp.RuntimeBinder None = 0, UseCompileTimeType = 1, } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.FlagsAttribute] public enum CSharpBinderFlags { diff --git a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.VisualBasic.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.VisualBasic.cs.REMOVED.git-id index a72da9bbe6..c00e7e39e0 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.VisualBasic.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.VisualBasic.cs.REMOVED.git-id @@ -1 +1 @@ -cc3f77c6046ae7aff01b75cb35c5de063583c4b3 \ No newline at end of file +85daf44a96b5fdad4f272508fc6ff44365fbd0ef \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.VisualC.cs b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.VisualC.cs index c2432e7b3d..e4a293b110 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/Microsoft.VisualC.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/Microsoft.VisualC.cs @@ -5,21 +5,20 @@ [assembly:System.Reflection.AssemblyVersionAttribute("10.0.0.0")] [assembly:System.CLSCompliantAttribute(false)] [assembly:System.Runtime.AssemblyTargetedPatchBandAttribute("1.0.23-245435169")] -[assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.InteropServices.ComCompatibleVersionAttribute(1, 0, 3300, 0)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] [assembly:System.Runtime.InteropServices.TypeLibVersionAttribute(8, 0)] [assembly:System.Security.SecurityTransparentAttribute] namespace Microsoft.VisualC { - [System.AttributeUsageAttribute((System.AttributeTargets)(32767))] + [System.AttributeUsageAttribute(System.AttributeTargets.All)] [System.ObsoleteAttribute("Microsoft.VisualC.dll is an obsolete assembly and exists only for backwards compatibility.")] public sealed partial class DebugInfoInPDBAttribute : System.Attribute { [System.Runtime.TargetedPatchingOptOutAttribute("Performance critical to inline this type of method across NGen image boundaries")] public DebugInfoInPDBAttribute() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(32767))] + [System.AttributeUsageAttribute(System.AttributeTargets.All)] [System.ObsoleteAttribute("Microsoft.VisualC.dll is an obsolete assembly and exists only for backwards compatibility.")] public sealed partial class DecoratedNameAttribute : System.Attribute { @@ -58,7 +57,7 @@ namespace Microsoft.VisualC [System.Runtime.TargetedPatchingOptOutAttribute("Performance critical to inline this type of method across NGen image boundaries")] public IsVolatileModifier() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(32767))] + [System.AttributeUsageAttribute(System.AttributeTargets.All)] [System.ObsoleteAttribute("Microsoft.VisualC.dll is an obsolete assembly and exists only for backwards compatibility.")] public sealed partial class MiscellaneousBitsAttribute : System.Attribute { diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.ComponentModel.Composition.cs b/external/binary-reference-assemblies/src/v4.7.2/System.ComponentModel.Composition.cs index 99b0578254..a2a292d2c2 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.ComponentModel.Composition.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.ComponentModel.Composition.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.ComponentModel.Composition.dll")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] namespace System { @@ -63,7 +63,7 @@ namespace System.ComponentModel.Composition public static System.ComponentModel.Composition.Primitives.ComposablePart SatisfyImportsOnce(this System.ComponentModel.Composition.ICompositionService compositionService, object attributedPart) { throw null; } public static System.ComponentModel.Composition.Primitives.ComposablePart SatisfyImportsOnce(this System.ComponentModel.Composition.ICompositionService compositionService, object attributedPart, System.Reflection.ReflectionContext reflectionContext) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(1), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly, AllowMultiple=false, Inherited=true)] public partial class CatalogReflectionContextAttribute : System.Attribute { public CatalogReflectionContextAttribute(System.Type reflectionContextType) { } @@ -119,7 +119,7 @@ namespace System.ComponentModel.Composition NonShared = 2, Shared = 1, } - [System.AttributeUsageAttribute((System.AttributeTargets)(452), AllowMultiple=true, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Property, AllowMultiple=true, Inherited=false)] public partial class ExportAttribute : System.Attribute { public ExportAttribute() { } @@ -145,7 +145,7 @@ namespace System.ComponentModel.Composition public T Value { get { throw null; } } public void Dispose() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(1476), AllowMultiple=true, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Field | System.AttributeTargets.Interface | System.AttributeTargets.Method | System.AttributeTargets.Property, AllowMultiple=true, Inherited=false)] public sealed partial class ExportMetadataAttribute : System.Attribute { public ExportMetadataAttribute(string name, object value) { } @@ -157,7 +157,7 @@ namespace System.ComponentModel.Composition { void SatisfyImportsOnce(System.ComponentModel.Composition.Primitives.ComposablePart part); } - [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] public partial class ImportAttribute : System.Attribute { public ImportAttribute() { } @@ -182,12 +182,12 @@ namespace System.ComponentModel.Composition public ImportCardinalityMismatchException(string message) { } public ImportCardinalityMismatchException(string message, System.Exception innerException) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(32), AllowMultiple=false, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Constructor, AllowMultiple=false, Inherited=false)] public partial class ImportingConstructorAttribute : System.Attribute { public ImportingConstructorAttribute() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] public partial class ImportManyAttribute : System.Attribute { public ImportManyAttribute() { } @@ -206,7 +206,7 @@ namespace System.ComponentModel.Composition Local = 1, NonLocal = 2, } - [System.AttributeUsageAttribute((System.AttributeTargets)(1028), AllowMultiple=true, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Interface, AllowMultiple=true, Inherited=true)] public partial class InheritedExportAttribute : System.ComponentModel.Composition.ExportAttribute { public InheritedExportAttribute() { } @@ -218,31 +218,31 @@ namespace System.ComponentModel.Composition { void OnImportsSatisfied(); } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed partial class MetadataAttributeAttribute : System.Attribute { public MetadataAttributeAttribute() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(1024), AllowMultiple=false, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Interface, AllowMultiple=false, Inherited=false)] public sealed partial class MetadataViewImplementationAttribute : System.Attribute { public MetadataViewImplementationAttribute(System.Type implementationType) { } public System.Type ImplementationType { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] public sealed partial class PartCreationPolicyAttribute : System.Attribute { public PartCreationPolicyAttribute(System.ComponentModel.Composition.CreationPolicy creationPolicy) { } public System.ComponentModel.Composition.CreationPolicy CreationPolicy { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=true, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] public sealed partial class PartMetadataAttribute : System.Attribute { public PartMetadataAttribute(string name, object value) { } public string Name { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public object Value { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] public sealed partial class PartNotDiscoverableAttribute : System.Attribute { public PartNotDiscoverableAttribute() { } @@ -315,8 +315,8 @@ namespace System.ComponentModel.Composition.Hosting public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void SetValue(object key, object value) { } - public bool TryGetValue(object key, bool localAtomicCompositionOnly, out T value) { value = default(T); throw null; } - public bool TryGetValue(object key, out T value) { value = default(T); throw null; } + public bool TryGetValue(object key, bool localAtomicCompositionOnly, out T value) { throw null; } + public bool TryGetValue(object key, out T value) { throw null; } } public partial class CatalogExportProvider : System.ComponentModel.Composition.Hosting.ExportProvider, System.IDisposable { @@ -473,7 +473,7 @@ namespace System.ComponentModel.Composition.Hosting public System.Lazy GetExport(string contractName) { throw null; } protected virtual void OnExportsChanged(System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs e) { } protected virtual void OnExportsChanging(System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs e) { } - public bool TryGetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition, out System.Collections.Generic.IEnumerable exports) { exports = default(System.Collections.Generic.IEnumerable); throw null; } + public bool TryGetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition, out System.Collections.Generic.IEnumerable exports) { throw null; } } public partial class ExportsChangeEventArgs : System.EventArgs { @@ -556,7 +556,7 @@ namespace System.ComponentModel.Composition.Primitives public abstract partial class ComposablePartCatalog : System.Collections.Generic.IEnumerable, System.Collections.IEnumerable, System.IDisposable { protected ComposablePartCatalog() { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public virtual System.Linq.IQueryable Parts { get { throw null; } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } @@ -657,9 +657,11 @@ namespace System.ComponentModel.Composition.ReflectionModel [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct LazyMemberInfo { - public LazyMemberInfo(System.Reflection.MemberInfo member) { throw null;} - public LazyMemberInfo(System.Reflection.MemberTypes memberType, System.Func accessorsCreator) { throw null;} - public LazyMemberInfo(System.Reflection.MemberTypes memberType, params System.Reflection.MemberInfo[] accessors) { throw null;} + private object _dummy; + private int _dummyPrimitive; + public LazyMemberInfo(System.Reflection.MemberInfo member) { throw null; } + public LazyMemberInfo(System.Reflection.MemberTypes memberType, System.Func accessorsCreator) { throw null; } + public LazyMemberInfo(System.Reflection.MemberTypes memberType, params System.Reflection.MemberInfo[] accessors) { throw null; } public System.Reflection.MemberTypes MemberType { get { throw null; } } public override bool Equals(object obj) { throw null; } public System.Reflection.MemberInfo[] GetAccessors() { throw null; } @@ -685,6 +687,6 @@ namespace System.ComponentModel.Composition.ReflectionModel public static bool IsDisposalRequired(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition) { throw null; } public static bool IsExportFactoryImportDefinition(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; } public static bool IsImportingParameter(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; } - public static bool TryMakeGenericPartDefinition(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition, System.Collections.Generic.IEnumerable genericParameters, out System.ComponentModel.Composition.Primitives.ComposablePartDefinition specialization) { specialization = default(System.ComponentModel.Composition.Primitives.ComposablePartDefinition); throw null; } + public static bool TryMakeGenericPartDefinition(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition, System.Collections.Generic.IEnumerable genericParameters, out System.ComponentModel.Composition.Primitives.ComposablePartDefinition specialization) { throw null; } } } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.ComponentModel.DataAnnotations.cs b/external/binary-reference-assemblies/src/v4.7.2/System.ComponentModel.DataAnnotations.cs index 47c2fcacc1..b8988e18cb 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.ComponentModel.DataAnnotations.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.ComponentModel.DataAnnotations.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.ComponentModel.DataAnnotations.dll")] @@ -19,9 +19,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.SecurityTransparentAttribute] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Execution=true)] namespace System.ComponentModel.DataAnnotations @@ -32,7 +32,7 @@ namespace System.ComponentModel.DataAnnotations public AssociatedMetadataTypeTypeDescriptionProvider(System.Type type, System.Type associatedMetadataType) { } public override System.ComponentModel.ICustomTypeDescriptor GetTypeDescriptor(System.Type objectType, object instance) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)] public sealed partial class AssociationAttribute : System.Attribute { public AssociationAttribute(string name, string thisKey, string otherKey) { } @@ -43,13 +43,13 @@ namespace System.ComponentModel.DataAnnotations public string ThisKey { get { throw null; } } public System.Collections.Generic.IEnumerable ThisKeyMembers { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(28), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Struct, AllowMultiple=false, Inherited=true)] public sealed partial class BindableTypeAttribute : System.Attribute { public BindableTypeAttribute() { } public bool IsBindable { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(128), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false)] public partial class CompareAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public CompareAttribute(string otherProperty) { } @@ -59,18 +59,18 @@ namespace System.ComponentModel.DataAnnotations public override string FormatErrorMessage(string name) { throw null; } protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)] public sealed partial class ConcurrencyCheckAttribute : System.Attribute { public ConcurrencyCheckAttribute() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class CreditCardAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute { public CreditCardAttribute() : base (default(System.ComponentModel.DataAnnotations.DataType)) { } public override bool IsValid(object value) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2500), AllowMultiple=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=true)] public sealed partial class CustomValidationAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public CustomValidationAttribute(System.Type validatorType, string method) { } @@ -100,7 +100,7 @@ namespace System.ComponentModel.DataAnnotations Upload = 16, Url = 12, } - [System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public partial class DataTypeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public DataTypeAttribute(System.ComponentModel.DataAnnotations.DataType dataType) { } @@ -111,7 +111,7 @@ namespace System.ComponentModel.DataAnnotations public virtual string GetDataTypeName() { throw null; } public override bool IsValid(object value) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class DisplayAttribute : System.Attribute { public DisplayAttribute() { } @@ -133,7 +133,7 @@ namespace System.ComponentModel.DataAnnotations public string GetPrompt() { throw null; } public string GetShortName() { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true, AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true, AllowMultiple=false)] public partial class DisplayColumnAttribute : System.Attribute { public DisplayColumnAttribute(string displayColumn) { } @@ -143,7 +143,7 @@ namespace System.ComponentModel.DataAnnotations public string SortColumn { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public bool SortDescending { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public partial class DisplayFormatAttribute : System.Attribute { public DisplayFormatAttribute() { } @@ -153,27 +153,27 @@ namespace System.ComponentModel.DataAnnotations public bool HtmlEncode { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public string NullDisplayText { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)] public sealed partial class EditableAttribute : System.Attribute { public EditableAttribute(bool allowEdit) { } public bool AllowEdit { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public bool AllowInitialValue { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class EmailAddressAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute { public EmailAddressAttribute() : base (default(System.ComponentModel.DataAnnotations.DataType)) { } public override bool IsValid(object value) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class EnumDataTypeAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute { public EnumDataTypeAttribute(System.Type enumType) : base (default(System.ComponentModel.DataAnnotations.DataType)) { } public System.Type EnumType { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public override bool IsValid(object value) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class FileExtensionsAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute { public FileExtensionsAttribute() : base (default(System.ComponentModel.DataAnnotations.DataType)) { } @@ -181,7 +181,7 @@ namespace System.ComponentModel.DataAnnotations public override string FormatErrorMessage(string name) { throw null; } public override bool IsValid(object value) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class FilterUIHintAttribute : System.Attribute { public FilterUIHintAttribute(string filterUIHint) { } @@ -198,12 +198,12 @@ namespace System.ComponentModel.DataAnnotations { System.Collections.Generic.IEnumerable Validate(System.ComponentModel.DataAnnotations.ValidationContext validationContext); } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)] public sealed partial class KeyAttribute : System.Attribute { public KeyAttribute() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public partial class MaxLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public MaxLengthAttribute() { } @@ -212,13 +212,13 @@ namespace System.ComponentModel.DataAnnotations public override string FormatErrorMessage(string name) { throw null; } public override bool IsValid(object value) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] public sealed partial class MetadataTypeAttribute : System.Attribute { public MetadataTypeAttribute(System.Type metadataClassType) { } public System.Type MetadataClassType { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public partial class MinLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public MinLengthAttribute(int length) { } @@ -226,13 +226,13 @@ namespace System.ComponentModel.DataAnnotations public override string FormatErrorMessage(string name) { throw null; } public override bool IsValid(object value) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class PhoneAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute { public PhoneAttribute() : base (default(System.ComponentModel.DataAnnotations.DataType)) { } public override bool IsValid(object value) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public partial class RangeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public RangeAttribute(double minimum, double maximum) { } @@ -244,7 +244,7 @@ namespace System.ComponentModel.DataAnnotations public override string FormatErrorMessage(string name) { throw null; } public override bool IsValid(object value) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public partial class RegularExpressionAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public RegularExpressionAttribute(string pattern) { } @@ -253,26 +253,26 @@ namespace System.ComponentModel.DataAnnotations public override string FormatErrorMessage(string name) { throw null; } public override bool IsValid(object value) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public partial class RequiredAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public RequiredAttribute() { } public bool AllowEmptyStrings { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public override bool IsValid(object value) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public partial class ScaffoldColumnAttribute : System.Attribute { public ScaffoldColumnAttribute(bool scaffold) { } public bool Scaffold { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] public partial class ScaffoldTableAttribute : System.Attribute { public ScaffoldTableAttribute(bool scaffold) { } public bool Scaffold { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public partial class StringLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public StringLengthAttribute(int maximumLength) { } @@ -281,12 +281,12 @@ namespace System.ComponentModel.DataAnnotations public override string FormatErrorMessage(string name) { throw null; } public override bool IsValid(object value) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)] public sealed partial class TimestampAttribute : System.Attribute { public TimestampAttribute() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=true)] public partial class UIHintAttribute : System.Attribute { public UIHintAttribute(string uiHint) { } @@ -299,7 +299,7 @@ namespace System.ComponentModel.DataAnnotations public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class UrlAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute { public UrlAttribute() : base (default(System.ComponentModel.DataAnnotations.DataType)) { } @@ -373,7 +373,7 @@ namespace System.ComponentModel.DataAnnotations } namespace System.ComponentModel.DataAnnotations.Schema { - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public partial class ColumnAttribute : System.Attribute { public ColumnAttribute() { } @@ -382,12 +382,12 @@ namespace System.ComponentModel.DataAnnotations.Schema public int Order { get { throw null; } set { } } public string TypeName { get { throw null; } set { } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] public partial class ComplexTypeAttribute : System.Attribute { public ComplexTypeAttribute() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public partial class DatabaseGeneratedAttribute : System.Attribute { public DatabaseGeneratedAttribute(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption databaseGeneratedOption) { } @@ -399,24 +399,24 @@ namespace System.ComponentModel.DataAnnotations.Schema Identity = 1, None = 0, } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public partial class ForeignKeyAttribute : System.Attribute { public ForeignKeyAttribute(string name) { } public string Name { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public partial class InversePropertyAttribute : System.Attribute { public InversePropertyAttribute(string property) { } public string Property { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(388), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public partial class NotMappedAttribute : System.Attribute { public NotMappedAttribute() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] public partial class TableAttribute : System.Attribute { public TableAttribute(string name) { } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Configuration.Install.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Configuration.Install.cs index 1ebcdb6066..89f60fe93d 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Configuration.Install.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Configuration.Install.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Configuration.Install.dll")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] namespace System.Configuration.Install { public partial class AssemblyInstaller : System.Configuration.Install.Installer @@ -45,7 +45,7 @@ namespace System.Configuration.Install public virtual bool IsEquivalentInstaller(System.Configuration.Install.ComponentInstaller otherInstaller) { throw null; } } [System.Runtime.InteropServices.GuidAttribute("1E233FE7-C16D-4512-8C3B-2E9988F08D38")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface IManagedInstaller { [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.I4)] @@ -65,14 +65,14 @@ namespace System.Configuration.Install { public Installer() { } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public System.Configuration.Install.InstallContext Context { get { throw null; } set { } } public virtual string HelpText { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(2))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)] public System.Configuration.Install.InstallerCollection Installers { get { throw null; } } [System.ComponentModel.BrowsableAttribute(true)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.TypeConverterAttribute("System.Configuration.Install.InstallerParentConverter")] public System.Configuration.Install.Installer Parent { get { throw null; } set { } } public event System.Configuration.Install.InstallEventHandler AfterInstall { add { } remove { } } @@ -170,7 +170,7 @@ namespace System.Diagnostics public string ParameterResourceFile { get { throw null; } set { } } [System.ComponentModel.TypeConverterAttribute("System.Diagnostics.Design.StringValueConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public string Source { get { throw null; } set { } } - [System.ComponentModel.DefaultValueAttribute((System.Configuration.Install.UninstallAction)(0))] + [System.ComponentModel.DefaultValueAttribute(System.Configuration.Install.UninstallAction.Remove)] public System.Configuration.Install.UninstallAction UninstallAction { get { throw null; } set { } } public override void CopyFromComponent(System.ComponentModel.IComponent component) { } public override void Install(System.Collections.IDictionary stateSaver) { } @@ -186,12 +186,12 @@ namespace System.Diagnostics [System.ComponentModel.DefaultValueAttribute("")] [System.ComponentModel.TypeConverterAttribute("System.Diagnostics.Design.StringValueConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public string CategoryName { get { throw null; } set { } } - [System.ComponentModel.DefaultValueAttribute((System.Diagnostics.PerformanceCounterCategoryType)(-1))] + [System.ComponentModel.DefaultValueAttribute(System.Diagnostics.PerformanceCounterCategoryType.Unknown)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public System.Diagnostics.PerformanceCounterCategoryType CategoryType { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(2))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)] public System.Diagnostics.CounterCreationDataCollection Counters { get { throw null; } } - [System.ComponentModel.DefaultValueAttribute((System.Configuration.Install.UninstallAction)(0))] + [System.ComponentModel.DefaultValueAttribute(System.Configuration.Install.UninstallAction.Remove)] public System.Configuration.Install.UninstallAction UninstallAction { get { throw null; } set { } } public override void CopyFromComponent(System.ComponentModel.IComponent component) { } public override void Install(System.Collections.IDictionary stateSaver) { } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Configuration.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Configuration.cs index c14406a6a2..ec1e9ad632 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Configuration.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Configuration.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Configuration.dll")] @@ -20,9 +20,9 @@ [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComCompatibleVersionAttribute(1, 0, 3300, 0)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace System.Configuration { @@ -46,7 +46,7 @@ namespace System.Configuration public override bool CanValidate(System.Type type) { throw null; } public override void Validate(object value) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(128))] + [System.AttributeUsageAttribute(System.AttributeTargets.Property)] public sealed partial class CallbackValidatorAttribute : System.Configuration.ConfigurationValidatorAttribute { public CallbackValidatorAttribute() { } @@ -129,7 +129,7 @@ namespace System.Configuration public partial class ConfigurationBuilderSettings : System.Configuration.ConfigurationElement { public ConfigurationBuilderSettings() { } - [System.Configuration.ConfigurationPropertyAttribute("", IsDefaultCollection=true, Options=(System.Configuration.ConfigurationPropertyOptions)(1))] + [System.Configuration.ConfigurationPropertyAttribute("", IsDefaultCollection=true, Options=System.Configuration.ConfigurationPropertyOptions.IsDefaultCollection)] public System.Configuration.ProviderSettingsCollection Builders { get { throw null; } } protected internal override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } } } @@ -141,7 +141,7 @@ namespace System.Configuration protected internal override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } } public System.Configuration.ConfigurationBuilder GetBuilderFromName(string builderName) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(132))] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Property)] public sealed partial class ConfigurationCollectionAttribute : System.Attribute { public ConfigurationCollectionAttribute(System.Type itemType) { } @@ -343,7 +343,7 @@ namespace System.Configuration public override System.Security.SecurityElement ToXml() { throw null; } public override System.Security.IPermission Union(System.Security.IPermission target) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(32767), AllowMultiple=true, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.All, AllowMultiple=true, Inherited=false)] [System.SerializableAttribute] public sealed partial class ConfigurationPermissionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute { @@ -370,7 +370,7 @@ namespace System.Configuration public System.Type Type { get { throw null; } } public System.Configuration.ConfigurationValidatorBase Validator { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(128))] + [System.AttributeUsageAttribute(System.AttributeTargets.Property)] public sealed partial class ConfigurationPropertyAttribute : System.Attribute { public ConfigurationPropertyAttribute(string name) { } @@ -486,7 +486,7 @@ namespace System.Configuration PerUserRoaming = 10, PerUserRoamingAndLocal = 20, } - [System.AttributeUsageAttribute((System.AttributeTargets)(128))] + [System.AttributeUsageAttribute(System.AttributeTargets.Property)] public partial class ConfigurationValidatorAttribute : System.Attribute { protected ConfigurationValidatorAttribute() { } @@ -505,9 +505,9 @@ namespace System.Configuration public ConnectionStringSettings() { } public ConnectionStringSettings(string name, string connectionString) { } public ConnectionStringSettings(string name, string connectionString, string providerName) { } - [System.Configuration.ConfigurationPropertyAttribute("connectionString", Options=(System.Configuration.ConfigurationPropertyOptions)(2), DefaultValue="")] + [System.Configuration.ConfigurationPropertyAttribute("connectionString", Options=System.Configuration.ConfigurationPropertyOptions.IsRequired, DefaultValue="")] public string ConnectionString { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("name", Options=(System.Configuration.ConfigurationPropertyOptions)(6), DefaultValue="")] + [System.Configuration.ConfigurationPropertyAttribute("name", Options=System.Configuration.ConfigurationPropertyOptions.IsKey | System.Configuration.ConfigurationPropertyOptions.IsRequired, DefaultValue="")] public string Name { get { throw null; } set { } } protected internal override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } } [System.Configuration.ConfigurationPropertyAttribute("providerName", DefaultValue="System.Data.SqlClient")] @@ -534,7 +534,7 @@ namespace System.Configuration public sealed partial class ConnectionStringsSection : System.Configuration.ConfigurationSection { public ConnectionStringsSection() { } - [System.Configuration.ConfigurationPropertyAttribute("", Options=(System.Configuration.ConfigurationPropertyOptions)(1))] + [System.Configuration.ConfigurationPropertyAttribute("", Options=System.Configuration.ConfigurationPropertyOptions.IsDefaultCollection)] public System.Configuration.ConnectionStringSettingsCollection ConnectionStrings { get { throw null; } } protected internal override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } } protected internal override object GetRuntimeObject() { throw null; } @@ -635,7 +635,7 @@ namespace System.Configuration public override bool CanValidate(System.Type type) { throw null; } public override void Validate(object value) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(128))] + [System.AttributeUsageAttribute(System.AttributeTargets.Property)] public sealed partial class IntegerValidatorAttribute : System.Configuration.ConfigurationValidatorAttribute { public IntegerValidatorAttribute() { } @@ -662,7 +662,7 @@ namespace System.Configuration public partial class KeyValueConfigurationElement : System.Configuration.ConfigurationElement { public KeyValueConfigurationElement(string key, string value) { } - [System.Configuration.ConfigurationPropertyAttribute("key", Options=(System.Configuration.ConfigurationPropertyOptions)(4), DefaultValue="")] + [System.Configuration.ConfigurationPropertyAttribute("key", Options=System.Configuration.ConfigurationPropertyOptions.IsKey, DefaultValue="")] public string Key { get { throw null; } } protected internal override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } } [System.Configuration.ConfigurationPropertyAttribute("value", DefaultValue="")] @@ -677,7 +677,7 @@ namespace System.Configuration public override bool CanValidate(System.Type type) { throw null; } public override void Validate(object value) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(128))] + [System.AttributeUsageAttribute(System.AttributeTargets.Property)] public sealed partial class LongValidatorAttribute : System.Configuration.ConfigurationValidatorAttribute { public LongValidatorAttribute() { } @@ -721,7 +721,7 @@ namespace System.Configuration public override bool CanValidate(System.Type type) { throw null; } public override void Validate(object value) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(128))] + [System.AttributeUsageAttribute(System.AttributeTargets.Property)] public sealed partial class PositiveTimeSpanValidatorAttribute : System.Configuration.ConfigurationValidatorAttribute { public PositiveTimeSpanValidatorAttribute() { } @@ -795,7 +795,7 @@ namespace System.Configuration { public ProtectedProviderSettings() { } protected internal override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } } - [System.Configuration.ConfigurationPropertyAttribute("", IsDefaultCollection=true, Options=(System.Configuration.ConfigurationPropertyOptions)(1))] + [System.Configuration.ConfigurationPropertyAttribute("", IsDefaultCollection=true, Options=System.Configuration.ConfigurationPropertyOptions.IsDefaultCollection)] public System.Configuration.ProviderSettingsCollection Providers { get { throw null; } } } public sealed partial class ProviderSettings : System.Configuration.ConfigurationElement @@ -832,7 +832,7 @@ namespace System.Configuration public override bool CanValidate(System.Type type) { throw null; } public override void Validate(object value) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(128))] + [System.AttributeUsageAttribute(System.AttributeTargets.Property)] public sealed partial class RegexStringValidatorAttribute : System.Configuration.ConfigurationValidatorAttribute { public RegexStringValidatorAttribute(string regex) { } @@ -898,7 +898,7 @@ namespace System.Configuration public override bool CanValidate(System.Type type) { throw null; } public override void Validate(object value) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(128))] + [System.AttributeUsageAttribute(System.AttributeTargets.Property)] public sealed partial class StringValidatorAttribute : System.Configuration.ConfigurationValidatorAttribute { public StringValidatorAttribute() { } @@ -913,7 +913,7 @@ namespace System.Configuration public override bool CanValidate(System.Type type) { throw null; } public override void Validate(object value) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(128))] + [System.AttributeUsageAttribute(System.AttributeTargets.Property)] public sealed partial class SubclassTypeValidatorAttribute : System.Configuration.ConfigurationValidatorAttribute { public SubclassTypeValidatorAttribute(System.Type baseClass) { } @@ -952,7 +952,7 @@ namespace System.Configuration public override bool CanValidate(System.Type type) { throw null; } public override void Validate(object value) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(128))] + [System.AttributeUsageAttribute(System.AttributeTargets.Property)] public sealed partial class TimeSpanValidatorAttribute : System.Configuration.ConfigurationValidatorAttribute { public const string TimeSpanMaxValue = "10675199.02:48:05.4775807"; @@ -999,13 +999,13 @@ namespace System.Configuration.Internal public virtual string GetConfigPathFromLocationSubPath(string configPath, string locationSubPath) { throw null; } public virtual System.Type GetConfigType(string typeName, bool throwOnError) { throw null; } public virtual string GetConfigTypeName(System.Type t) { throw null; } - public virtual void GetRestrictedPermissions(System.Configuration.Internal.IInternalConfigRecord configRecord, out System.Security.PermissionSet permissionSet, out bool isHostReady) { permissionSet = default(System.Security.PermissionSet); isHostReady = default(bool); } + public virtual void GetRestrictedPermissions(System.Configuration.Internal.IInternalConfigRecord configRecord, out System.Security.PermissionSet permissionSet, out bool isHostReady) { throw null; } public virtual string GetStreamName(string configPath) { throw null; } public virtual string GetStreamNameForConfigSource(string streamName, string configSource) { throw null; } public virtual object GetStreamVersion(string streamName) { throw null; } public virtual System.IDisposable Impersonate() { throw null; } public virtual void Init(System.Configuration.Internal.IInternalConfigRoot configRoot, params object[] hostInitParams) { } - public virtual void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath, System.Configuration.Internal.IInternalConfigRoot configRoot, params object[] hostInitConfigurationParams) { configPath = default(string); locationConfigPath = default(string); } + public virtual void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath, System.Configuration.Internal.IInternalConfigRoot configRoot, params object[] hostInitConfigurationParams) { throw null; } public virtual bool IsAboveApplication(string configPath) { throw null; } public virtual bool IsConfigRecordRequired(string configPath) { throw null; } public virtual bool IsDefinitionAllowed(string configPath, System.Configuration.ConfigurationAllowDefinition allowDefinition, System.Configuration.ConfigurationAllowExeDefinition allowExeDefinition) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Core.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.Core.cs.REMOVED.git-id index f0ad034e7b..f533b4fc1d 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Core.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Core.cs.REMOVED.git-id @@ -1 +1 @@ -53bb5168fc610ba437d81a420f96f0e6c133996a \ No newline at end of file +68fbd042184f23bdb07775ac782ab55886319a1f \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Data.DataSetExtensions.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Data.DataSetExtensions.cs index 6b64da2f48..dd3e5ac456 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Data.DataSetExtensions.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Data.DataSetExtensions.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Data.DataSetExtensions.dll")] @@ -20,10 +20,10 @@ [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComCompatibleVersionAttribute(1, 0, 3300, 0)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] [assembly:System.Security.SecurityCriticalAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] namespace System.Data { public static partial class DataRowComparer diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Data.Entity.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.Data.Entity.cs.REMOVED.git-id index 263d8677fe..9c71d21036 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Data.Entity.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Data.Entity.cs.REMOVED.git-id @@ -1 +1 @@ -4a24d8399d036071b03614a4b39705c5dc1ac32d \ No newline at end of file +0aca6e8e9ef08e7faf126bf456158b8e90aa6c24 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Data.Linq.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Data.Linq.cs index 685278151a..e6c97825bd 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Data.Linq.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Data.Linq.cs @@ -4,13 +4,13 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Data.Linq.dll")] [assembly:System.Reflection.AssemblyDescriptionAttribute("System.Data.Linq.dll")] -[assembly:System.Reflection.AssemblyFileVersionAttribute("4.7.2558.0")] -[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.7.2558.0")] +[assembly:System.Reflection.AssemblyFileVersionAttribute("4.7.3062.0")] +[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.7.3062.0")] [assembly:System.Reflection.AssemblyProductAttribute("Mono Common Language Infrastructure")] [assembly:System.Reflection.AssemblyTitleAttribute("System.Data.Linq.dll")] [assembly:System.Resources.NeutralResourcesLanguageAttribute("en-US")] @@ -19,9 +19,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] [assembly:System.Security.SecurityTransparentAttribute] namespace System.Data.Linq { @@ -170,9 +170,11 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EntityRef where TEntity : class { - public EntityRef(System.Collections.Generic.IEnumerable source) { throw null;} - public EntityRef(System.Data.Linq.EntityRef entityRef) { throw null;} - public EntityRef(TEntity entity) { throw null;} + private TEntity entity; + private object _dummy; + public EntityRef(System.Collections.Generic.IEnumerable source) { throw null; } + public EntityRef(System.Data.Linq.EntityRef entityRef) { throw null; } + public EntityRef(TEntity entity) { throw null; } public TEntity Entity { get { throw null; } set { } } public bool HasLoadedOrAssignedValue { get { throw null; } } } @@ -262,9 +264,12 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Link { - public Link(System.Collections.Generic.IEnumerable source) { throw null;} - public Link(System.Data.Linq.Link link) { throw null;} - public Link(T value) { throw null;} + private T underlyingValue; + private object _dummy; + private int _dummyPrimitive; + public Link(System.Collections.Generic.IEnumerable source) { throw null; } + public Link(System.Data.Linq.Link link) { throw null; } + public Link(T value) { throw null; } public bool HasLoadedOrAssignedValue { get { throw null; } } public bool HasValue { get { throw null; } } public T Value { get { throw null; } set { } } @@ -284,6 +289,7 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ModifiedMemberInfo { + private object _dummy; public object CurrentValue { get { throw null; } } public System.Reflection.MemberInfo Member { get { throw null; } } public object OriginalValue { get { throw null; } } @@ -350,7 +356,7 @@ namespace System.Data.Linq } namespace System.Data.Linq.Mapping { - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class AssociationAttribute : System.Data.Linq.Mapping.DataAttribute { public AssociationAttribute() { } @@ -374,7 +380,7 @@ namespace System.Data.Linq.Mapping OnInsert = 3, OnUpdate = 4, } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class ColumnAttribute : System.Data.Linq.Mapping.DataAttribute { public ColumnAttribute() { } @@ -394,20 +400,20 @@ namespace System.Data.Linq.Mapping public string Name { get { throw null; } set { } } public string Storage { get { throw null; } set { } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] public sealed partial class DatabaseAttribute : System.Attribute { public DatabaseAttribute() { } public string Name { get { throw null; } set { } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(64), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Method, AllowMultiple=false)] public sealed partial class FunctionAttribute : System.Attribute { public FunctionAttribute() { } public bool IsComposable { get { throw null; } set { } } public string Name { get { throw null; } set { } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=true, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] public sealed partial class InheritanceMappingAttribute : System.Attribute { public InheritanceMappingAttribute() { } @@ -566,27 +572,27 @@ namespace System.Data.Linq.Mapping public abstract System.Data.Linq.Mapping.MetaType GetInheritanceType(System.Type type); public abstract System.Data.Linq.Mapping.MetaType GetTypeForInheritanceCode(object code); } - [System.AttributeUsageAttribute((System.AttributeTargets)(10240), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Parameter | System.AttributeTargets.ReturnValue, AllowMultiple=false)] public sealed partial class ParameterAttribute : System.Attribute { public ParameterAttribute() { } public string DbType { get { throw null; } set { } } public string Name { get { throw null; } set { } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] public sealed partial class ProviderAttribute : System.Attribute { public ProviderAttribute() { } public ProviderAttribute(System.Type type) { } public System.Type Type { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(64), AllowMultiple=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Method, AllowMultiple=true)] public sealed partial class ResultTypeAttribute : System.Attribute { public ResultTypeAttribute(System.Type type) { } public System.Type Type { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] public sealed partial class TableAttribute : System.Attribute { public TableAttribute() { } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Data.OracleClient.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Data.OracleClient.cs index 5eb63439a4..2609a5124b 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Data.OracleClient.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Data.OracleClient.cs @@ -17,9 +17,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.InteropServices.ComCompatibleVersionAttribute(1, 0, 3300, 0)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace System.Data.OracleClient { @@ -53,8 +53,9 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBinary : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleBinary Null; - public OracleBinary(byte[] b) { throw null;} + public OracleBinary(byte[] b) { throw null; } public bool IsNull { get { throw null; } } public byte this[int index] { get { throw null; } } public int Length { get { throw null; } } @@ -82,13 +83,14 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBoolean : System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleBoolean False; public static readonly System.Data.OracleClient.OracleBoolean Null; public static readonly System.Data.OracleClient.OracleBoolean One; public static readonly System.Data.OracleClient.OracleBoolean True; public static readonly System.Data.OracleClient.OracleBoolean Zero; - public OracleBoolean(bool value) { throw null;} - public OracleBoolean(int value) { throw null;} + public OracleBoolean(bool value) { throw null; } + public OracleBoolean(int value) { throw null; } public bool IsFalse { get { throw null; } } public bool IsNull { get { throw null; } } public bool IsTrue { get { throw null; } } @@ -143,14 +145,14 @@ namespace System.Data.OracleClient public OracleCommand(string commandText, System.Data.OracleClient.OracleConnection connection, System.Data.OracleClient.OracleTransaction tx) { } [System.ComponentModel.DefaultValueAttribute("")] [System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.Data.Oracle.Design.OracleCommandTextEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public override string CommandText { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int CommandTimeout { get { throw null; } set { } } - [System.ComponentModel.DefaultValueAttribute((System.Data.CommandType)(1))] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.DefaultValueAttribute(System.Data.CommandType.Text)] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public override System.Data.CommandType CommandType { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(null)] [System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] @@ -161,14 +163,14 @@ namespace System.Data.OracleClient [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DefaultValueAttribute(true)] [System.ComponentModel.DesignOnlyAttribute(true)] - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool DesignTimeVisible { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(2))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)] public new System.Data.OracleClient.OracleParameterCollection Parameters { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public new System.Data.OracleClient.OracleTransaction Transaction { get { throw null; } set { } } - [System.ComponentModel.DefaultValueAttribute((System.Data.UpdateRowSource)(3))] + [System.ComponentModel.DefaultValueAttribute(System.Data.UpdateRowSource.Both)] public override System.Data.UpdateRowSource UpdatedRowSource { get { throw null; } set { } } public override void Cancel() { } public object Clone() { throw null; } @@ -176,7 +178,7 @@ namespace System.Data.OracleClient public new System.Data.OracleClient.OracleParameter CreateParameter() { throw null; } protected override System.Data.Common.DbDataReader ExecuteDbDataReader(System.Data.CommandBehavior behavior) { throw null; } public override int ExecuteNonQuery() { throw null; } - public int ExecuteOracleNonQuery(out System.Data.OracleClient.OracleString rowid) { rowid = default(System.Data.OracleClient.OracleString); throw null; } + public int ExecuteOracleNonQuery(out System.Data.OracleClient.OracleString rowid) { throw null; } public object ExecuteOracleScalar() { throw null; } public new System.Data.OracleClient.OracleDataReader ExecuteReader() { throw null; } public new System.Data.OracleClient.OracleDataReader ExecuteReader(System.Data.CommandBehavior behavior) { throw null; } @@ -190,18 +192,18 @@ namespace System.Data.OracleClient public OracleCommandBuilder() { } public OracleCommandBuilder(System.Data.OracleClient.OracleDataAdapter adapter) { } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override System.Data.Common.CatalogLocation CatalogLocation { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string CatalogSeparator { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(null)] public new System.Data.OracleClient.OracleDataAdapter DataAdapter { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string SchemaSeparator { get { throw null; } set { } } protected override void ApplyParameterInfo(System.Data.Common.DbParameter parameter, System.Data.DataRow datarow, System.Data.StatementType statementType, bool whereClause) { } public static void DeriveParameters(System.Data.OracleClient.OracleCommand command) { } @@ -227,23 +229,23 @@ namespace System.Data.OracleClient [System.ComponentModel.DefaultValueAttribute("")] [System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.Data.Oracle.Design.OracleConnectionStringEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [System.ComponentModel.RecommendedAsConfigurableAttribute(true)] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] [System.ComponentModel.SettingsBindableAttribute(true)] public override string ConnectionString { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int ConnectionTimeout { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string Database { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public override string DataSource { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public override string ServerVersion { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public override System.Data.ConnectionState State { get { throw null; } } public event System.Data.OracleClient.OracleInfoMessageEventHandler InfoMessage { add { } remove { } } protected override System.Data.Common.DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel) { throw null; } @@ -272,44 +274,44 @@ namespace System.Data.OracleClient public OracleConnectionStringBuilder() { } public OracleConnectionStringBuilder(string connectionString) { } [System.ComponentModel.DisplayNameAttribute("Data Source")] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string DataSource { get { throw null; } set { } } [System.ComponentModel.DisplayNameAttribute("Enlist")] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public bool Enlist { get { throw null; } set { } } [System.ComponentModel.DisplayNameAttribute("Integrated Security")] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public bool IntegratedSecurity { get { throw null; } set { } } public override bool IsFixedSize { get { throw null; } } public override object this[string keyword] { get { throw null; } set { } } public override System.Collections.ICollection Keys { get { throw null; } } [System.ComponentModel.DisplayNameAttribute("Load Balance Timeout")] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public int LoadBalanceTimeout { get { throw null; } set { } } [System.ComponentModel.DisplayNameAttribute("Max Pool Size")] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public int MaxPoolSize { get { throw null; } set { } } [System.ComponentModel.DisplayNameAttribute("Min Pool Size")] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public int MinPoolSize { get { throw null; } set { } } [System.ComponentModel.DisplayNameAttribute("Omit Oracle Connection Name")] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public bool OmitOracleConnectionName { get { throw null; } set { } } [System.ComponentModel.DisplayNameAttribute("Password")] [System.ComponentModel.PasswordPropertyTextAttribute(true)] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string Password { get { throw null; } set { } } [System.ComponentModel.DisplayNameAttribute("Persist Security Info")] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public bool PersistSecurityInfo { get { throw null; } set { } } [System.ComponentModel.DisplayNameAttribute("Pooling")] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public bool Pooling { get { throw null; } set { } } [System.ComponentModel.DisplayNameAttribute("Unicode")] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public bool Unicode { get { throw null; } set { } } [System.ComponentModel.DisplayNameAttribute("User ID")] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string UserID { get { throw null; } set { } } public override System.Collections.ICollection Values { get { throw null; } } public override void Clear() { } @@ -317,7 +319,7 @@ namespace System.Data.OracleClient protected override void GetProperties(System.Collections.Hashtable propertyDescriptors) { } public override bool Remove(string keyword) { throw null; } public override bool ShouldSerialize(string keyword) { throw null; } - public override bool TryGetValue(string keyword, out object value) { value = default(object); throw null; } + public override bool TryGetValue(string keyword, out object value) { throw null; } } [System.ComponentModel.DefaultEventAttribute("RowUpdated")] [System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.Data.VS.OracleDataAdapterDesigner, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] @@ -354,7 +356,7 @@ namespace System.Data.OracleClient protected override System.Data.Common.RowUpdatingEventArgs CreateRowUpdatingEvent(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; } protected override int ExecuteBatch() { throw null; } protected override System.Data.IDataParameter GetBatchedParameter(int commandIdentifier, int parameterIndex) { throw null; } - protected override bool GetBatchedRecordsAffected(int commandIdentifier, out int recordsAffected, out System.Exception error) { recordsAffected = default(int); error = default(System.Exception); throw null; } + protected override bool GetBatchedRecordsAffected(int commandIdentifier, out int recordsAffected, out System.Exception error) { throw null; } protected override void InitializeBatching() { } protected override void OnRowUpdated(System.Data.Common.RowUpdatedEventArgs value) { } protected override void OnRowUpdating(System.Data.Common.RowUpdatingEventArgs value) { } @@ -415,18 +417,19 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack=1)] public partial struct OracleDateTime : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleDateTime MaxValue; public static readonly System.Data.OracleClient.OracleDateTime MinValue; public static readonly System.Data.OracleClient.OracleDateTime Null; - public OracleDateTime(System.Data.OracleClient.OracleDateTime from) { throw null;} - public OracleDateTime(System.DateTime dt) { throw null;} - public OracleDateTime(int year, int month, int day) { throw null;} - public OracleDateTime(int year, int month, int day, System.Globalization.Calendar calendar) { throw null;} - public OracleDateTime(int year, int month, int day, int hour, int minute, int second) { throw null;} - public OracleDateTime(int year, int month, int day, int hour, int minute, int second, System.Globalization.Calendar calendar) { throw null;} - public OracleDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { throw null;} - public OracleDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, System.Globalization.Calendar calendar) { throw null;} - public OracleDateTime(long ticks) { throw null;} + public OracleDateTime(System.Data.OracleClient.OracleDateTime from) { throw null; } + public OracleDateTime(System.DateTime dt) { throw null; } + public OracleDateTime(int year, int month, int day) { throw null; } + public OracleDateTime(int year, int month, int day, System.Globalization.Calendar calendar) { throw null; } + public OracleDateTime(int year, int month, int day, int hour, int minute, int second) { throw null; } + public OracleDateTime(int year, int month, int day, int hour, int minute, int second, System.Globalization.Calendar calendar) { throw null; } + public OracleDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { throw null; } + public OracleDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, System.Globalization.Calendar calendar) { throw null; } + public OracleDateTime(long ticks) { throw null; } public int Day { get { throw null; } } public int Hour { get { throw null; } } public bool IsNull { get { throw null; } } @@ -461,7 +464,7 @@ namespace System.Data.OracleClient { internal OracleException() { } public int Code { get { throw null; } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context) { } } public sealed partial class OracleInfoMessageEventArgs : System.EventArgs @@ -515,12 +518,13 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack=1)] public partial struct OracleMonthSpan : System.Data.SqlTypes.INullable, System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleMonthSpan MaxValue; public static readonly System.Data.OracleClient.OracleMonthSpan MinValue; public static readonly System.Data.OracleClient.OracleMonthSpan Null; - public OracleMonthSpan(System.Data.OracleClient.OracleMonthSpan from) { throw null;} - public OracleMonthSpan(int months) { throw null;} - public OracleMonthSpan(int years, int months) { throw null;} + public OracleMonthSpan(System.Data.OracleClient.OracleMonthSpan from) { throw null; } + public OracleMonthSpan(int months) { throw null; } + public OracleMonthSpan(int years, int months) { throw null; } public bool IsNull { get { throw null; } } public int Value { get { throw null; } } public int CompareTo(object obj) { throw null; } @@ -546,6 +550,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack=1)] public partial struct OracleNumber : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleNumber E; public static readonly int MaxPrecision; public static readonly int MaxScale; @@ -557,11 +562,11 @@ namespace System.Data.OracleClient public static readonly System.Data.OracleClient.OracleNumber One; public static readonly System.Data.OracleClient.OracleNumber PI; public static readonly System.Data.OracleClient.OracleNumber Zero; - public OracleNumber(System.Data.OracleClient.OracleNumber from) { throw null;} - public OracleNumber(decimal decValue) { throw null;} - public OracleNumber(double dblValue) { throw null;} - public OracleNumber(int intValue) { throw null;} - public OracleNumber(long longValue) { throw null;} + public OracleNumber(System.Data.OracleClient.OracleNumber from) { throw null; } + public OracleNumber(decimal decValue) { throw null; } + public OracleNumber(double dblValue) { throw null; } + public OracleNumber(int intValue) { throw null; } + public OracleNumber(long longValue) { throw null; } public bool IsNull { get { throw null; } } public decimal Value { get { throw null; } } public static System.Data.OracleClient.OracleNumber Abs(System.Data.OracleClient.OracleNumber n) { throw null; } @@ -641,30 +646,30 @@ namespace System.Data.OracleClient public OracleParameter(string name, System.Data.OracleClient.OracleType oracleType, int size, string srcColumn) { } public OracleParameter(string name, object value) { } public override System.Data.DbType DbType { get { throw null; } set { } } - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public override System.Data.ParameterDirection Direction { get { throw null; } set { } } public override bool IsNullable { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(2))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public int Offset { get { throw null; } set { } } - [System.ComponentModel.DefaultValueAttribute((System.Data.OracleClient.OracleType)(22))] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.DefaultValueAttribute(System.Data.OracleClient.OracleType.VarChar)] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] [System.Data.Common.DbProviderSpecificTypePropertyAttribute(true)] public System.Data.OracleClient.OracleType OracleType { get { throw null; } set { } } public override string ParameterName { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("Precision has been deprecated. Use the Math classes to explicitly set the precision of a decimal. http://go.microsoft.com/fwlink/?linkid=14202")] public new byte Precision { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("Scale has been deprecated. Use the Math classes to explicitly set the scale of a decimal. http://go.microsoft.com/fwlink/?linkid=14202")] public new byte Scale { get { throw null; } set { } } public override int Size { get { throw null; } set { } } public override string SourceColumn { get { throw null; } set { } } public override bool SourceColumnNullMapping { get { throw null; } set { } } public override System.Data.DataRowVersion SourceVersion { get { throw null; } set { } } - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] [System.ComponentModel.TypeConverterAttribute(typeof(System.ComponentModel.StringConverter))] public override object Value { get { throw null; } set { } } public override void ResetDbType() { } @@ -685,12 +690,12 @@ namespace System.Data.OracleClient public new System.Data.OracleClient.OracleParameter this[string parameterName] { get { throw null; } set { } } public override object SyncRoot { get { throw null; } } public System.Data.OracleClient.OracleParameter Add(System.Data.OracleClient.OracleParameter value) { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int Add(object value) { throw null; } public System.Data.OracleClient.OracleParameter Add(string parameterName, System.Data.OracleClient.OracleType dataType) { throw null; } public System.Data.OracleClient.OracleParameter Add(string parameterName, System.Data.OracleClient.OracleType dataType, int size) { throw null; } public System.Data.OracleClient.OracleParameter Add(string parameterName, System.Data.OracleClient.OracleType dataType, int size, string srcColumn) { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("Add(String parameterName, Object value) has been deprecated. Use AddWithValue(String parameterName, Object value). http://go.microsoft.com/fwlink/?linkid=14202", false)] public System.Data.OracleClient.OracleParameter Add(string parameterName, object value) { throw null; } public override void AddRange(System.Array values) { } @@ -732,7 +737,7 @@ namespace System.Data.OracleClient public override System.Security.SecurityElement ToXml() { throw null; } public override System.Security.IPermission Union(System.Security.IPermission target) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(109), AllowMultiple=true, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)] [System.ObsoleteAttribute("OraclePermissionAttribute has been deprecated. http://go.microsoft.com/fwlink/?LinkID=144260", false)] [System.SerializableAttribute] public sealed partial class OraclePermissionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute @@ -743,9 +748,9 @@ namespace System.Data.OracleClient public System.Data.KeyRestrictionBehavior KeyRestrictionBehavior { get { throw null; } set { } } public string KeyRestrictions { get { throw null; } set { } } public override System.Security.IPermission CreatePermission() { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public bool ShouldSerializeConnectionString() { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public bool ShouldSerializeKeyRestrictions() { throw null; } } public sealed partial class OracleRowUpdatedEventArgs : System.Data.Common.RowUpdatedEventArgs @@ -764,9 +769,10 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleString : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleString Empty; public static readonly System.Data.OracleClient.OracleString Null; - public OracleString(string s) { throw null;} + public OracleString(string s) { throw null; } public bool IsNull { get { throw null; } } public char this[int index] { get { throw null; } } public int Length { get { throw null; } } @@ -795,15 +801,16 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack=1)] public partial struct OracleTimeSpan : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleTimeSpan MaxValue; public static readonly System.Data.OracleClient.OracleTimeSpan MinValue; public static readonly System.Data.OracleClient.OracleTimeSpan Null; - public OracleTimeSpan(System.Data.OracleClient.OracleTimeSpan from) { throw null;} - public OracleTimeSpan(int hours, int minutes, int seconds) { throw null;} - public OracleTimeSpan(int days, int hours, int minutes, int seconds) { throw null;} - public OracleTimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) { throw null;} - public OracleTimeSpan(long ticks) { throw null;} - public OracleTimeSpan(System.TimeSpan ts) { throw null;} + public OracleTimeSpan(System.Data.OracleClient.OracleTimeSpan from) { throw null; } + public OracleTimeSpan(int hours, int minutes, int seconds) { throw null; } + public OracleTimeSpan(int days, int hours, int minutes, int seconds) { throw null; } + public OracleTimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) { throw null; } + public OracleTimeSpan(long ticks) { throw null; } + public OracleTimeSpan(System.TimeSpan ts) { throw null; } public int Days { get { throw null; } } public int Hours { get { throw null; } } public bool IsNull { get { throw null; } } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Data.Services.Client.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Data.Services.Client.cs index 6f7d2e00ca..4d5372c039 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Data.Services.Client.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Data.Services.Client.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Data.Services.Client.dll")] @@ -19,10 +19,10 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] [assembly:System.Security.SecurityCriticalAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] namespace System.Data.Services.Client { public sealed partial class ChangeOperationResponse : System.Data.Services.Client.OperationResponse @@ -127,8 +127,8 @@ namespace System.Data.Services.Client public void SetLink(object source, string sourceProperty, object target) { } public void SetSaveStream(object entity, System.IO.Stream stream, bool closeStream, System.Data.Services.Client.DataServiceRequestArgs args) { } public void SetSaveStream(object entity, System.IO.Stream stream, bool closeStream, string contentType, string slug) { } - public bool TryGetEntity(System.Uri identity, out TEntity entity) where TEntity : class { entity = default(TEntity); throw null; } - public bool TryGetUri(object entity, out System.Uri identity) { identity = default(System.Uri); throw null; } + public bool TryGetEntity(System.Uri identity, out TEntity entity) where TEntity : class { throw null; } + public bool TryGetUri(object entity, out System.Uri identity) { throw null; } public void UpdateObject(object entity) { } } public abstract partial class DataServiceQuery : System.Data.Services.Client.DataServiceRequest, System.Collections.IEnumerable, System.Linq.IQueryable @@ -290,7 +290,7 @@ namespace System.Data.Services.Client public string SourceProperty { get { throw null; } } public object Target { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed partial class MediaEntryAttribute : System.Attribute { public MediaEntryAttribute(string mediaMemberName) { } @@ -303,7 +303,7 @@ namespace System.Data.Services.Client OverwriteChanges = 1, PreserveChanges = 2, } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed partial class MimeTypePropertyAttribute : System.Attribute { public MimeTypePropertyAttribute(string dataPropertyName, string mimeTypePropertyName) { } @@ -362,12 +362,12 @@ namespace System.Data.Services.Client } namespace System.Data.Services.Common { - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] public sealed partial class DataServiceEntityAttribute : System.Attribute { public DataServiceEntityAttribute() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] public sealed partial class DataServiceKeyAttribute : System.Attribute { public DataServiceKeyAttribute(string keyName) { } @@ -379,7 +379,7 @@ namespace System.Data.Services.Common V1 = 0, V2 = 1, } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=true, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true, Inherited=true)] public sealed partial class EntityPropertyMappingAttribute : System.Attribute { public EntityPropertyMappingAttribute(string sourcePath, System.Data.Services.Common.SyndicationItemProperty targetSyndicationItem, System.Data.Services.Common.SyndicationTextContentKind targetTextContentKind, bool keepInContent) { } @@ -392,13 +392,13 @@ namespace System.Data.Services.Common public System.Data.Services.Common.SyndicationItemProperty TargetSyndicationItem { get { throw null; } } public System.Data.Services.Common.SyndicationTextContentKind TargetTextContentKind { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] public sealed partial class EntitySetAttribute : System.Attribute { public EntitySetAttribute(string entitySet) { } public string EntitySet { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true, AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true, AllowMultiple=false)] public sealed partial class HasStreamAttribute : System.Attribute { public HasStreamAttribute() { } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Data.Services.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Data.Services.cs index 4d76930e04..e576adb3e6 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Data.Services.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Data.Services.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Data.Services.dll")] @@ -20,13 +20,13 @@ [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComCompatibleVersionAttribute(1, 0, 3300, 0)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] [assembly:System.Security.SecurityCriticalAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] namespace System.Data.Services { - [System.AttributeUsageAttribute((System.AttributeTargets)(64), AllowMultiple=true, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Method, AllowMultiple=true, Inherited=true)] public sealed partial class ChangeInterceptorAttribute : System.Attribute { public ChangeInterceptorAttribute(string entitySetName) { } @@ -110,8 +110,8 @@ namespace System.Data.Services internal DataServiceProcessingPipelineEventArgs() { } public System.Data.Services.DataServiceOperationContext OperationContext { [System.Diagnostics.DebuggerStepThroughAttribute]get { throw null; } } } - [System.ServiceModel.Activation.AspNetCompatibilityRequirementsAttribute(RequirementsMode=(System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode)(1))] - [System.ServiceModel.ServiceBehaviorAttribute(InstanceContextMode=(System.ServiceModel.InstanceContextMode)(1))] + [System.ServiceModel.Activation.AspNetCompatibilityRequirementsAttribute(RequirementsMode=System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Allowed)] + [System.ServiceModel.ServiceBehaviorAttribute(InstanceContextMode=System.ServiceModel.InstanceContextMode.PerCall)] public partial class DataService : System.Data.Services.IRequestHandler { public DataService() { } @@ -138,7 +138,7 @@ namespace System.Data.Services WriteMerge = 32, WriteReplace = 8, } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed partial class ETagAttribute : System.Attribute { public ETagAttribute(string propertyName) { } @@ -221,7 +221,7 @@ namespace System.Data.Services { System.Collections.IEnumerable ApplyExpansions(System.Linq.IQueryable queryable, System.Collections.Generic.ICollection expandPaths); } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed partial class IgnorePropertiesAttribute : System.Attribute { public IgnorePropertiesAttribute(string propertyName) { } @@ -250,7 +250,7 @@ namespace System.Data.Services void SetReference(object targetResource, string propertyName, object propertyValue); void SetValue(object targetResource, string propertyName, object propertyValue); } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed partial class MimeTypeAttribute : System.Attribute { public MimeTypeAttribute(string memberName, string mimeType) { } @@ -264,7 +264,7 @@ namespace System.Data.Services public System.Data.Services.DataServiceOperationContext OperationContext { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public System.Uri RequestUri { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(64), AllowMultiple=true, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Method, AllowMultiple=true, Inherited=true)] public sealed partial class QueryInterceptorAttribute : System.Attribute { public QueryInterceptorAttribute(string entitySetName) { } @@ -280,7 +280,7 @@ namespace System.Data.Services ReadMultiple = 2, ReadSingle = 1, } - [System.AttributeUsageAttribute((System.AttributeTargets)(64), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public sealed partial class SingleResultAttribute : System.Attribute { public SingleResultAttribute() { } @@ -317,7 +317,7 @@ namespace System.Data.Services.Configuration } namespace System.Data.Services.Internal { - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public abstract partial class ExpandedWrapper : System.Data.Services.IExpandedResult { protected ExpandedWrapper() { } @@ -327,7 +327,7 @@ namespace System.Data.Services.Internal public object GetExpandedPropertyValue(string name) { throw null; } protected abstract object InternalGetExpandedPropertyValue(int nameIndex); } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ExpandedWrapper : System.Data.Services.Internal.ExpandedWrapper { public ExpandedWrapper() { } @@ -342,7 +342,7 @@ namespace System.Data.Services.Internal public TProperty8 ProjectedProperty8 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetExpandedPropertyValue(int nameIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ExpandedWrapper : System.Data.Services.Internal.ExpandedWrapper { public ExpandedWrapper() { } @@ -358,7 +358,7 @@ namespace System.Data.Services.Internal public TProperty9 ProjectedProperty9 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetExpandedPropertyValue(int nameIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ExpandedWrapper : System.Data.Services.Internal.ExpandedWrapper { public ExpandedWrapper() { } @@ -375,7 +375,7 @@ namespace System.Data.Services.Internal public TProperty9 ProjectedProperty9 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetExpandedPropertyValue(int nameIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ExpandedWrapper : System.Data.Services.Internal.ExpandedWrapper { public ExpandedWrapper() { } @@ -393,14 +393,14 @@ namespace System.Data.Services.Internal public TProperty9 ProjectedProperty9 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetExpandedPropertyValue(int nameIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ExpandedWrapper : System.Data.Services.Internal.ExpandedWrapper { public ExpandedWrapper() { } public TProperty0 ProjectedProperty0 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetExpandedPropertyValue(int nameIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ExpandedWrapper : System.Data.Services.Internal.ExpandedWrapper { public ExpandedWrapper() { } @@ -408,7 +408,7 @@ namespace System.Data.Services.Internal public TProperty1 ProjectedProperty1 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetExpandedPropertyValue(int nameIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ExpandedWrapper : System.Data.Services.Internal.ExpandedWrapper { public ExpandedWrapper() { } @@ -417,7 +417,7 @@ namespace System.Data.Services.Internal public TProperty2 ProjectedProperty2 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetExpandedPropertyValue(int nameIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ExpandedWrapper : System.Data.Services.Internal.ExpandedWrapper { public ExpandedWrapper() { } @@ -427,7 +427,7 @@ namespace System.Data.Services.Internal public TProperty3 ProjectedProperty3 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetExpandedPropertyValue(int nameIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ExpandedWrapper : System.Data.Services.Internal.ExpandedWrapper { public ExpandedWrapper() { } @@ -438,7 +438,7 @@ namespace System.Data.Services.Internal public TProperty4 ProjectedProperty4 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetExpandedPropertyValue(int nameIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ExpandedWrapper : System.Data.Services.Internal.ExpandedWrapper { public ExpandedWrapper() { } @@ -450,7 +450,7 @@ namespace System.Data.Services.Internal public TProperty5 ProjectedProperty5 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetExpandedPropertyValue(int nameIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ExpandedWrapper : System.Data.Services.Internal.ExpandedWrapper { public ExpandedWrapper() { } @@ -463,7 +463,7 @@ namespace System.Data.Services.Internal public TProperty6 ProjectedProperty6 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetExpandedPropertyValue(int nameIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ExpandedWrapper : System.Data.Services.Internal.ExpandedWrapper { public ExpandedWrapper() { } @@ -477,7 +477,7 @@ namespace System.Data.Services.Internal public TProperty7 ProjectedProperty7 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetExpandedPropertyValue(int nameIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public abstract partial class ProjectedWrapper { protected ProjectedWrapper() { } @@ -486,20 +486,20 @@ namespace System.Data.Services.Internal public object GetProjectedPropertyValue(string propertyName) { throw null; } protected abstract object InternalGetProjectedPropertyValue(int propertyIndex); } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ProjectedWrapper0 : System.Data.Services.Internal.ProjectedWrapper { public ProjectedWrapper0() { } protected override object InternalGetProjectedPropertyValue(int propertyIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ProjectedWrapper1 : System.Data.Services.Internal.ProjectedWrapper { public ProjectedWrapper1() { } public object ProjectedProperty0 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetProjectedPropertyValue(int propertyIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ProjectedWrapper2 : System.Data.Services.Internal.ProjectedWrapper { public ProjectedWrapper2() { } @@ -507,7 +507,7 @@ namespace System.Data.Services.Internal public object ProjectedProperty1 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetProjectedPropertyValue(int propertyIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ProjectedWrapper3 : System.Data.Services.Internal.ProjectedWrapper { public ProjectedWrapper3() { } @@ -516,7 +516,7 @@ namespace System.Data.Services.Internal public object ProjectedProperty2 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetProjectedPropertyValue(int propertyIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ProjectedWrapper4 : System.Data.Services.Internal.ProjectedWrapper { public ProjectedWrapper4() { } @@ -526,7 +526,7 @@ namespace System.Data.Services.Internal public object ProjectedProperty3 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetProjectedPropertyValue(int propertyIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ProjectedWrapper5 : System.Data.Services.Internal.ProjectedWrapper { public ProjectedWrapper5() { } @@ -537,7 +537,7 @@ namespace System.Data.Services.Internal public object ProjectedProperty4 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetProjectedPropertyValue(int propertyIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ProjectedWrapper6 : System.Data.Services.Internal.ProjectedWrapper { public ProjectedWrapper6() { } @@ -549,7 +549,7 @@ namespace System.Data.Services.Internal public object ProjectedProperty5 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetProjectedPropertyValue(int propertyIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ProjectedWrapper7 : System.Data.Services.Internal.ProjectedWrapper { public ProjectedWrapper7() { } @@ -562,7 +562,7 @@ namespace System.Data.Services.Internal public object ProjectedProperty6 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetProjectedPropertyValue(int propertyIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ProjectedWrapper8 : System.Data.Services.Internal.ProjectedWrapper { public ProjectedWrapper8() { } @@ -576,7 +576,7 @@ namespace System.Data.Services.Internal public object ProjectedProperty7 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetProjectedPropertyValue(int propertyIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public partial class ProjectedWrapperMany : System.Data.Services.Internal.ProjectedWrapper { public ProjectedWrapperMany() { } @@ -591,7 +591,7 @@ namespace System.Data.Services.Internal public object ProjectedProperty7 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override object InternalGetProjectedPropertyValue(int propertyIndex) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class ProjectedWrapperManyEnd : System.Data.Services.Internal.ProjectedWrapperMany { public ProjectedWrapperManyEnd() { } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Data.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.Data.cs.REMOVED.git-id index fe2c7c2ff9..d098bf4ff0 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Data.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Data.cs.REMOVED.git-id @@ -1 +1 @@ -1123759f5028f1f3fe0521609af058321b321522 \ No newline at end of file +fce542a3aec107da9433f0bd2b901444043603d0 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Deployment.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Deployment.cs index f6888a859c..8b77b1304f 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Deployment.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Deployment.cs @@ -4,13 +4,13 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Deployment.dll")] [assembly:System.Reflection.AssemblyDescriptionAttribute("System.Deployment.dll")] -[assembly:System.Reflection.AssemblyFileVersionAttribute("4.7.2558.0")] -[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.7.2558.0")] +[assembly:System.Reflection.AssemblyFileVersionAttribute("4.7.3062.0")] +[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.7.3062.0")] [assembly:System.Reflection.AssemblyProductAttribute("Mono Common Language Infrastructure")] [assembly:System.Reflection.AssemblyTitleAttribute("System.Deployment.dll")] [assembly:System.Resources.NeutralResourcesLanguageAttribute("en-US")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] -[assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] +[assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Design.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.Design.cs.REMOVED.git-id index 30b6f502ee..a8df2f688c 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Design.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Design.cs.REMOVED.git-id @@ -1 +1 @@ -e6920be4b2ecdf8aaf875336c7b9bb6abbb070b2 \ No newline at end of file +93dc1175187a481e504dcd417f9f2df4a2625e0c \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Diagnostics.Tracing.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Diagnostics.Tracing.cs index b0f099cf1d..da392febb9 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Diagnostics.Tracing.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Diagnostics.Tracing.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.2.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Diagnostics.Tracing.dll")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Diagnostics.Tracing.EventActivityOptions))] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Diagnostics.Tracing.EventAttribute))] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Diagnostics.Tracing.EventChannel))] diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.DirectoryServices.Protocols.cs b/external/binary-reference-assemblies/src/v4.7.2/System.DirectoryServices.Protocols.cs index 241fdf3d24..b9e0a705d6 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.DirectoryServices.Protocols.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.DirectoryServices.Protocols.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.DirectoryServices.Protocols.dll")] @@ -19,9 +19,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] [assembly:System.Net.WebPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Unrestricted=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, UnmanagedCode=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] @@ -189,7 +189,7 @@ namespace System.DirectoryServices.Protocols { protected DirectoryConnection() { } public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { throw null; } } - public virtual System.Net.NetworkCredential Credential { [System.Security.Permissions.EnvironmentPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, Unrestricted=true), System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, Flags=(System.Security.Permissions.SecurityPermissionFlag)(2)), System.DirectoryServices.DirectoryServicesPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Unrestricted=true)]set { } } + public virtual System.Net.NetworkCredential Credential { [System.Security.Permissions.EnvironmentPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, Unrestricted=true), System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode), System.DirectoryServices.DirectoryServicesPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Unrestricted=true)]set { } } public virtual System.DirectoryServices.Protocols.DirectoryIdentifier Directory { get { throw null; } } public virtual System.TimeSpan Timeout { get { throw null; } set { } } [System.DirectoryServices.DirectoryServicesPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Unrestricted=true)] @@ -427,7 +427,7 @@ namespace System.DirectoryServices.Protocols [System.DirectoryServices.DirectoryServicesPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Unrestricted=true)] public DsmlSoapHttpConnection(System.DirectoryServices.Protocols.DsmlDirectoryIdentifier identifier) { } [System.Security.Permissions.EnvironmentPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, Unrestricted=true)] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, Flags=(System.Security.Permissions.SecurityPermissionFlag)(2))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)] [System.DirectoryServices.DirectoryServicesPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Unrestricted=true)] public DsmlSoapHttpConnection(System.DirectoryServices.Protocols.DsmlDirectoryIdentifier identifier, System.Net.NetworkCredential credential) { } [System.DirectoryServices.DirectoryServicesPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Unrestricted=true)] @@ -521,14 +521,14 @@ namespace System.DirectoryServices.Protocols [System.DirectoryServices.DirectoryServicesPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Unrestricted=true)] public LdapConnection(System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential) { } [System.Security.Permissions.EnvironmentPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, Unrestricted=true)] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, Flags=(System.Security.Permissions.SecurityPermissionFlag)(2))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)] [System.DirectoryServices.DirectoryServicesPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Unrestricted=true)] public LdapConnection(System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential, System.DirectoryServices.Protocols.AuthType authType) { } [System.DirectoryServices.DirectoryServicesPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Unrestricted=true)] public LdapConnection(string server) { } public System.DirectoryServices.Protocols.AuthType AuthType { get { throw null; } set { } } public bool AutoBind { get { throw null; } set { } } - public override System.Net.NetworkCredential Credential { [System.Security.Permissions.EnvironmentPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, Unrestricted=true), System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, Flags=(System.Security.Permissions.SecurityPermissionFlag)(2)), System.DirectoryServices.DirectoryServicesPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Unrestricted=true)]set { } } + public override System.Net.NetworkCredential Credential { [System.Security.Permissions.EnvironmentPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, Unrestricted=true), System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode), System.DirectoryServices.DirectoryServicesPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Unrestricted=true)]set { } } public System.DirectoryServices.Protocols.LdapSessionOptions SessionOptions { get { throw null; } } public override System.TimeSpan Timeout { get { throw null; } set { } } [System.DirectoryServices.DirectoryServicesPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Unrestricted=true)] diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.DirectoryServices.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.DirectoryServices.cs.REMOVED.git-id index 0106f512b8..ca5a748542 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.DirectoryServices.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.DirectoryServices.cs.REMOVED.git-id @@ -1 +1 @@ -cfc32e7bac69a7cd3bb58e85acc463ee5ffc5c4b \ No newline at end of file +a80f68cf8145ae68fc2db37357230b008388ef99 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Drawing.Design.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Drawing.Design.cs index 2baa5d763e..cee0edf1a6 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Drawing.Design.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Drawing.Design.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Drawing.Design.dll")] @@ -19,11 +19,11 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] namespace System.Drawing.Design { [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(2))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)] [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.InheritanceDemand, Name="FullTrust")] public partial class BitmapEditor : System.Drawing.Design.ImageEditor { @@ -32,7 +32,7 @@ namespace System.Drawing.Design protected override string GetFileDialogDescription() { throw null; } protected override System.Drawing.Image LoadFromStream(System.IO.Stream stream) { throw null; } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(2))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)] public partial class ColorEditor : System.Drawing.Design.UITypeEditor { public ColorEditor() { } @@ -42,7 +42,7 @@ namespace System.Drawing.Design public override void PaintValue(System.Drawing.Design.PaintValueEventArgs e) { } } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(2))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)] [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.InheritanceDemand, Name="FullTrust")] public partial class ContentAlignmentEditor : System.Drawing.Design.UITypeEditor { @@ -51,7 +51,7 @@ namespace System.Drawing.Design public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) { throw null; } } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(2))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)] [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.InheritanceDemand, Name="FullTrust")] public partial class CursorEditor : System.Drawing.Design.UITypeEditor { @@ -61,7 +61,7 @@ namespace System.Drawing.Design public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) { throw null; } } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(2))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)] [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.InheritanceDemand, Name="FullTrust")] public partial class FontEditor : System.Drawing.Design.UITypeEditor { @@ -77,7 +77,7 @@ namespace System.Drawing.Design public override bool GetPaintValueSupported(System.ComponentModel.ITypeDescriptorContext context) { throw null; } public override void PaintValue(System.Drawing.Design.PaintValueEventArgs e) { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(2))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)] public partial class IconEditor : System.Drawing.Design.UITypeEditor { public IconEditor() { } @@ -91,7 +91,7 @@ namespace System.Drawing.Design protected virtual System.Drawing.Icon LoadFromStream(System.IO.Stream stream) { throw null; } public override void PaintValue(System.Drawing.Design.PaintValueEventArgs e) { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(2))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)] public partial class ImageEditor : System.Drawing.Design.UITypeEditor { public ImageEditor() { } @@ -107,7 +107,7 @@ namespace System.Drawing.Design public override void PaintValue(System.Drawing.Design.PaintValueEventArgs e) { } } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(2))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)] [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.InheritanceDemand, Name="FullTrust")] public partial class MetafileEditor : System.Drawing.Design.ImageEditor { diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Drawing.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.Drawing.cs.REMOVED.git-id index 40fd0c3dd6..4abe5bd245 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Drawing.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Drawing.cs.REMOVED.git-id @@ -1 +1 @@ -5457e0ab643ce03c446497ff7d1bd4ce412ea6d1 \ No newline at end of file +215d24a535f41fe5c73998d3d761b1e3f562c287 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Dynamic.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Dynamic.cs index c57e44c947..63c1962ac5 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Dynamic.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Dynamic.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Dynamic.dll")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.EnterpriseServices.cs b/external/binary-reference-assemblies/src/v4.7.2/System.EnterpriseServices.cs index 9a464a1919..eee2d8c90a 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.EnterpriseServices.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.EnterpriseServices.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.EnterpriseServices.ApplicationIDAttribute("1e246775-2281-484f-8ad4-044c15b86eb7")] [assembly:System.EnterpriseServices.ApplicationNameAttribute(".NET Utilities")] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] @@ -22,10 +22,10 @@ [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComCompatibleVersionAttribute(1, 0, 3300, 0)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(true)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Runtime.InteropServices.GuidAttribute("4fb2d46f-efc8-4643-bcd0-6e5bfa6a174c")] [assembly:System.Runtime.InteropServices.TypeLibVersionAttribute(2, 4)] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1))] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace System.EnterpriseServices @@ -51,7 +51,7 @@ namespace System.EnterpriseServices public void SynchronousCall(System.EnterpriseServices.IServiceCall serviceCall) { } public void UnbindFromThread() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(1), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class ApplicationAccessControlAttribute : System.Attribute { @@ -62,7 +62,7 @@ namespace System.EnterpriseServices public System.EnterpriseServices.ImpersonationLevelOption ImpersonationLevel { get { throw null; } set { } } public bool Value { get { throw null; } set { } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(1), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class ApplicationActivationAttribute : System.Attribute { @@ -71,21 +71,21 @@ namespace System.EnterpriseServices public string SoapVRoot { get { throw null; } set { } } public System.EnterpriseServices.ActivationOption Value { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(1), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class ApplicationIDAttribute : System.Attribute { public ApplicationIDAttribute(string guid) { } public System.Guid Value { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(1), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class ApplicationNameAttribute : System.Attribute { public ApplicationNameAttribute(string name) { } public string Value { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(1), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class ApplicationQueuingAttribute : System.Attribute { @@ -105,7 +105,7 @@ namespace System.EnterpriseServices Packet = 4, Privacy = 6, } - [System.AttributeUsageAttribute((System.AttributeTargets)(64), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Method, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class AutoCompleteAttribute : System.Attribute { @@ -133,7 +133,7 @@ namespace System.EnterpriseServices public static object CreateWithTipTransaction(string url, System.Type t) { throw null; } public static object CreateWithTransaction(object transaction, System.Type t) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class ComponentAccessControlAttribute : System.Attribute { @@ -141,7 +141,7 @@ namespace System.EnterpriseServices public ComponentAccessControlAttribute(bool val) { } public bool Value { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class COMTIIntrinsicsAttribute : System.Attribute { @@ -149,7 +149,7 @@ namespace System.EnterpriseServices public COMTIIntrinsicsAttribute(bool val) { } public bool Value { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class ConstructionEnabledAttribute : System.Attribute { @@ -182,13 +182,13 @@ namespace System.EnterpriseServices public static void SetComplete() { } public static void SetNamedProperty(string name, object value) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(1093), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Interface | System.AttributeTargets.Method, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string desc) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class EventClassAttribute : System.Attribute { @@ -197,7 +197,7 @@ namespace System.EnterpriseServices public bool FireInParallel { get { throw null; } set { } } public string PublisherFilter { get { throw null; } set { } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class EventTrackingEnabledAttribute : System.Attribute { @@ -205,7 +205,7 @@ namespace System.EnterpriseServices public EventTrackingEnabledAttribute(bool val) { } public bool Value { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class ExceptionClassAttribute : System.Attribute { @@ -213,12 +213,12 @@ namespace System.EnterpriseServices public string Value { get { throw null; } } } [System.Runtime.InteropServices.GuidAttribute("FE6777FB-A674-4177-8F32-6D707E113484")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface IAsyncErrorNotify { void OnError(int hresult); } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class IISIntrinsicsAttribute : System.Attribute { @@ -257,7 +257,7 @@ namespace System.EnterpriseServices Register = 256, ReportWarningsToConsole = 32, } - [System.AttributeUsageAttribute((System.AttributeTargets)(1028), Inherited=true, AllowMultiple=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Interface, Inherited=true, AllowMultiple=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class InterfaceQueuingAttribute : System.Attribute { @@ -267,27 +267,27 @@ namespace System.EnterpriseServices public string Interface { get { throw null; } set { } } } [System.Runtime.InteropServices.GuidAttribute("51372AFD-CAE7-11CF-BE81-00AA00A2FA25")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface IPlaybackControl { void FinalClientRetry(); void FinalServerRetry(); } [System.Runtime.InteropServices.GuidAttribute("72380d55-8d2b-43a3-8513-2b6ef31434e9")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface IProcessInitControl { void ResetInitializerTimeout(int dwSecondsRemaining); } [System.Runtime.InteropServices.GuidAttribute("1113f52d-dc7f-4943-aed6-88d04027e32a")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface IProcessInitializer { void Shutdown(); void Startup([System.Runtime.InteropServices.In][System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.IUnknown)]object punkProcessControl); } [System.Runtime.InteropServices.GuidAttribute("55e3ea25-55cb-4650-8887-18e8d30bb4bc")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface IRegistrationHelper { void InstallAssembly([System.Runtime.InteropServices.In][System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)]string assembly, [System.Runtime.InteropServices.In][System.Runtime.InteropServices.Out][System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)]ref string application, [System.Runtime.InteropServices.In][System.Runtime.InteropServices.Out][System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)]ref string tlb, [System.Runtime.InteropServices.In]System.EnterpriseServices.InstallationFlags installFlags); @@ -302,26 +302,26 @@ namespace System.EnterpriseServices string RemoteDispatchNotAutoDone(string s); } [System.Runtime.InteropServices.GuidAttribute("BD3E2E12-42DD-40f4-A09A-95A50C58304B")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface IServiceCall { void OnCall(); } [System.Runtime.InteropServices.GuidAttribute("8165B19E-8D3A-4d0b-80C8-97DE310DB583")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface IServicedComponentInfo { void GetComponentInfo(ref int infoMask, out string[] infoArray); } [System.Runtime.InteropServices.GuidAttribute("0FB15084-AF41-11CE-BD2B-204C4F4F5020")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface ITransaction { void Abort(ref System.EnterpriseServices.BOID pboidReason, int fRetaining, int fAsync); void Commit(int fRetaining, int grfTC, int grfRM); void GetTransactionInfo(out System.EnterpriseServices.XACTTRANSINFO pinfo); } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class JustInTimeActivationAttribute : System.Attribute { @@ -329,7 +329,7 @@ namespace System.EnterpriseServices public JustInTimeActivationAttribute(bool val) { } public bool Value { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class LoadBalancingSupportedAttribute : System.Attribute { @@ -337,7 +337,7 @@ namespace System.EnterpriseServices public LoadBalancingSupportedAttribute(bool val) { } public bool Value { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class MustRunInClientContextAttribute : System.Attribute { @@ -345,7 +345,7 @@ namespace System.EnterpriseServices public MustRunInClientContextAttribute(bool val) { } public bool Value { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class ObjectPoolingAttribute : System.Attribute { @@ -369,7 +369,7 @@ namespace System.EnterpriseServices Inherit = 1, New = 2, } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class PrivateComponentAttribute : System.Attribute { @@ -431,7 +431,7 @@ namespace System.EnterpriseServices public void UninstallAssembly(string assembly, string application, string partition) { } public void UninstallAssemblyFromConfig([System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.IUnknown)]ref System.EnterpriseServices.RegistrationConfig regConfig) { } } - [System.EnterpriseServices.TransactionAttribute((System.EnterpriseServices.TransactionOption)(4))] + [System.EnterpriseServices.TransactionAttribute(System.EnterpriseServices.TransactionOption.RequiresNew)] [System.ObsoleteAttribute("The RegistrationHelperTx class has been deprecated.")] [System.Runtime.InteropServices.GuidAttribute("c89ac250-e18a-4fc7-abd5-b8897b6a78a5")] public sealed partial class RegistrationHelperTx : System.EnterpriseServices.ServicedComponent @@ -454,7 +454,7 @@ namespace System.EnterpriseServices public bool PutResource(object resource) { throw null; } public delegate void TransactionEndDelegate(object resource); } - [System.AttributeUsageAttribute((System.AttributeTargets)(68), Inherited=true, AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Method, Inherited=true, AllowMultiple=false)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class SecureMethodAttribute : System.Attribute { @@ -488,7 +488,7 @@ namespace System.EnterpriseServices public int AuthenticationService { get { throw null; } } public System.EnterpriseServices.ImpersonationLevelOption ImpersonationLevel { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(1093), Inherited=true, AllowMultiple=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Interface | System.AttributeTargets.Method, Inherited=true, AllowMultiple=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class SecurityRoleAttribute : System.Attribute { @@ -539,7 +539,7 @@ namespace System.EnterpriseServices string System.EnterpriseServices.IRemoteDispatch.RemoteDispatchAutoDone(string s) { throw null; } [System.EnterpriseServices.AutoCompleteAttribute(false)] string System.EnterpriseServices.IRemoteDispatch.RemoteDispatchNotAutoDone(string s) { throw null; } - void System.EnterpriseServices.IServicedComponentInfo.GetComponentInfo(ref int infoMask, out string[] infoArray) { infoArray = default(string[]); } + void System.EnterpriseServices.IServicedComponentInfo.GetComponentInfo(ref int infoMask, out string[] infoArray) { throw null; } } [System.Runtime.InteropServices.ComVisibleAttribute(false)] [System.SerializableAttribute] @@ -566,8 +566,8 @@ namespace System.EnterpriseServices public sealed partial class SharedPropertyGroup { internal SharedPropertyGroup() { } - public System.EnterpriseServices.SharedProperty CreateProperty(string name, out bool fExists) { fExists = default(bool); throw null; } - public System.EnterpriseServices.SharedProperty CreatePropertyByPosition(int position, out bool fExists) { fExists = default(bool); throw null; } + public System.EnterpriseServices.SharedProperty CreateProperty(string name, out bool fExists) { throw null; } + public System.EnterpriseServices.SharedProperty CreatePropertyByPosition(int position, out bool fExists) { throw null; } public System.EnterpriseServices.SharedProperty Property(string name) { throw null; } public System.EnterpriseServices.SharedProperty PropertyByPosition(int position) { throw null; } } @@ -575,7 +575,7 @@ namespace System.EnterpriseServices public sealed partial class SharedPropertyGroupManager : System.Collections.IEnumerable { public SharedPropertyGroupManager() { } - public System.EnterpriseServices.SharedPropertyGroup CreatePropertyGroup(string name, ref System.EnterpriseServices.PropertyLockMode dwIsoMode, ref System.EnterpriseServices.PropertyReleaseMode dwRelMode, out bool fExist) { fExist = default(bool); throw null; } + public System.EnterpriseServices.SharedPropertyGroup CreatePropertyGroup(string name, ref System.EnterpriseServices.PropertyLockMode dwIsoMode, ref System.EnterpriseServices.PropertyReleaseMode dwRelMode, out bool fExist) { throw null; } public System.Collections.IEnumerator GetEnumerator() { throw null; } public System.EnterpriseServices.SharedPropertyGroup Group(string name) { throw null; } } @@ -587,7 +587,7 @@ namespace System.EnterpriseServices Inherit = 1, New = 2, } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class SynchronizationAttribute : System.Attribute { @@ -613,7 +613,7 @@ namespace System.EnterpriseServices None = 0, STA = 2, } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public sealed partial class TransactionAttribute : System.Attribute { @@ -673,7 +673,7 @@ namespace System.EnterpriseServices } namespace System.EnterpriseServices.CompensatingResourceManager { - [System.AttributeUsageAttribute((System.AttributeTargets)(1), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly, Inherited=true)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] [System.Runtime.InteropServices.ProgIdAttribute("System.EnterpriseServices.Crm.ApplicationCrmEnabledAttribute")] public sealed partial class ApplicationCrmEnabledAttribute : System.Attribute @@ -798,7 +798,7 @@ namespace System.EnterpriseServices.Internal public partial class ComManagedImportUtil : System.EnterpriseServices.Internal.IComManagedImportUtil { public ComManagedImportUtil() { } - public void GetComponentInfo(string assemblyPath, out string numComponents, out string componentInfo) { numComponents = default(string); componentInfo = default(string); } + public void GetComponentInfo(string assemblyPath, out string numComponents, out string componentInfo) { throw null; } public void InstallAssembly(string asmpath, string parname, string appname) { } } public partial class ComSoapPublishError @@ -812,7 +812,7 @@ namespace System.EnterpriseServices.Internal public GenerateMetadata() { } public string Generate(string strSrcTypeLib, string outPath) { throw null; } public string GenerateMetaData(string strSrcTypeLib, string outPath, byte[] PublicKey, System.Reflection.StrongNameKeyPair KeyPair) { throw null; } - public string GenerateSigned(string strSrcTypeLib, string outPath, bool InstallGac, out string Error) { Error = default(string); throw null; } + public string GenerateSigned(string strSrcTypeLib, string outPath, bool InstallGac, out string Error) { throw null; } [System.Runtime.InteropServices.DllImport("kernel32.dll")][System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.PreserveSig)]public static extern int SearchPath(string path, string fileName, string extension, int numBufferChars, string buffer, int[] filePart); } [System.Runtime.InteropServices.GuidAttribute("ecabafd2-7f19-11d2-978e-0000f8757e2a")] @@ -890,8 +890,8 @@ namespace System.EnterpriseServices.Internal public partial class IISVirtualRoot : System.EnterpriseServices.Internal.IComSoapIISVRoot { public IISVirtualRoot() { } - public void Create(string RootWeb, string inPhysicalDirectory, string VirtualDirectory, out string Error) { Error = default(string); } - public void Delete(string RootWeb, string PhysicalDirectory, string VirtualDirectory, out string Error) { Error = default(string); } + public void Create(string RootWeb, string inPhysicalDirectory, string VirtualDirectory, out string Error) { throw null; } + public void Delete(string RootWeb, string PhysicalDirectory, string VirtualDirectory, out string Error) { throw null; } } [System.Runtime.InteropServices.GuidAttribute("6261e4b5-572a-4142-a2f9-1fe1a0c97097")] public partial interface IServerWebConfig @@ -939,26 +939,26 @@ namespace System.EnterpriseServices.Internal public partial class Publish : System.EnterpriseServices.Internal.IComSoapPublisher { public Publish() { } - public void CreateMailBox(string RootMailServer, string MailBox, out string SmtpName, out string Domain, out string PhysicalPath, out string Error) { SmtpName = default(string); Domain = default(string); PhysicalPath = default(string); Error = default(string); } - public void CreateVirtualRoot(string Operation, string FullUrl, out string BaseUrl, out string VirtualRoot, out string PhysicalPath, out string Error) { BaseUrl = default(string); VirtualRoot = default(string); PhysicalPath = default(string); Error = default(string); } - public void DeleteMailBox(string RootMailServer, string MailBox, out string Error) { Error = default(string); } - public void DeleteVirtualRoot(string RootWebServer, string FullUrl, out string Error) { Error = default(string); } + public void CreateMailBox(string RootMailServer, string MailBox, out string SmtpName, out string Domain, out string PhysicalPath, out string Error) { throw null; } + public void CreateVirtualRoot(string Operation, string FullUrl, out string BaseUrl, out string VirtualRoot, out string PhysicalPath, out string Error) { throw null; } + public void DeleteMailBox(string RootMailServer, string MailBox, out string Error) { throw null; } + public void DeleteVirtualRoot(string RootWebServer, string FullUrl, out string Error) { throw null; } public void GacInstall(string AssemblyPath) { } public void GacRemove(string AssemblyPath) { } - public void GetAssemblyNameForCache(string TypeLibPath, out string CachePath) { CachePath = default(string); } + public void GetAssemblyNameForCache(string TypeLibPath, out string CachePath) { throw null; } public static string GetClientPhysicalPath(bool CreateDir) { throw null; } public string GetTypeNameFromProgId(string AssemblyPath, string ProgId) { throw null; } - public static void ParseUrl(string FullUrl, out string BaseUrl, out string VirtualRoot) { BaseUrl = default(string); VirtualRoot = default(string); } - public void ProcessClientTlb(string ProgId, string SrcTlbPath, string PhysicalPath, string VRoot, string BaseUrl, string Mode, string Transport, out string AssemblyName, out string TypeName, out string Error) { AssemblyName = default(string); TypeName = default(string); Error = default(string); } - public void ProcessServerTlb(string ProgId, string SrcTlbPath, string PhysicalPath, string Operation, out string strAssemblyName, out string TypeName, out string Error) { strAssemblyName = default(string); TypeName = default(string); Error = default(string); } + public static void ParseUrl(string FullUrl, out string BaseUrl, out string VirtualRoot) { throw null; } + public void ProcessClientTlb(string ProgId, string SrcTlbPath, string PhysicalPath, string VRoot, string BaseUrl, string Mode, string Transport, out string AssemblyName, out string TypeName, out string Error) { throw null; } + public void ProcessServerTlb(string ProgId, string SrcTlbPath, string PhysicalPath, string Operation, out string strAssemblyName, out string TypeName, out string Error) { throw null; } public void RegisterAssembly(string AssemblyPath) { } public void UnRegisterAssembly(string AssemblyPath) { } } public partial class ServerWebConfig : System.EnterpriseServices.Internal.IServerWebConfig { public ServerWebConfig() { } - public void AddElement(string FilePath, string AssemblyName, string TypeName, string ProgId, string WkoMode, out string Error) { Error = default(string); } - public void Create(string FilePath, string FilePrefix, out string Error) { Error = default(string); } + public void AddElement(string FilePath, string AssemblyName, string TypeName, string ProgId, string WkoMode, out string Error) { throw null; } + public void Create(string FilePath, string FilePrefix, out string Error) { throw null; } } [System.Runtime.InteropServices.GuidAttribute("346D5B9F-45E1-45c0-AADF-1B7D221E9063")] public sealed partial class SoapClientImport : System.EnterpriseServices.Internal.ISoapClientImport @@ -970,23 +970,23 @@ namespace System.EnterpriseServices.Internal public sealed partial class SoapServerTlb : System.EnterpriseServices.Internal.ISoapServerTlb { public SoapServerTlb() { } - public void AddServerTlb(string progId, string classId, string interfaceId, string srcTlbPath, string rootWebServer, string inBaseUrl, string inVirtualRoot, string clientActivated, string wellKnown, string discoFile, string operation, out string strAssemblyName, out string typeName) { strAssemblyName = default(string); typeName = default(string); } + public void AddServerTlb(string progId, string classId, string interfaceId, string srcTlbPath, string rootWebServer, string inBaseUrl, string inVirtualRoot, string clientActivated, string wellKnown, string discoFile, string operation, out string strAssemblyName, out string typeName) { throw null; } public void DeleteServerTlb(string progId, string classId, string interfaceId, string srcTlbPath, string rootWebServer, string baseUrl, string virtualRoot, string operation, string assemblyName, string typeName) { } } [System.Runtime.InteropServices.GuidAttribute("CAA817CC-0C04-4d22-A05C-2B7E162F4E8F")] public sealed partial class SoapServerVRoot : System.EnterpriseServices.Internal.ISoapServerVRoot { public SoapServerVRoot() { } - public void CreateVirtualRootEx(string rootWebServer, string inBaseUrl, string inVirtualRoot, string homePage, string discoFile, string secureSockets, string authentication, string operation, out string baseUrl, out string virtualRoot, out string physicalPath) { baseUrl = default(string); virtualRoot = default(string); physicalPath = default(string); } + public void CreateVirtualRootEx(string rootWebServer, string inBaseUrl, string inVirtualRoot, string homePage, string discoFile, string secureSockets, string authentication, string operation, out string baseUrl, out string virtualRoot, out string physicalPath) { throw null; } public void DeleteVirtualRootEx(string rootWebServer, string inBaseUrl, string inVirtualRoot) { } - public void GetVirtualRootStatus(string RootWebServer, string inBaseUrl, string inVirtualRoot, out string Exists, out string SSL, out string WindowsAuth, out string Anonymous, out string HomePage, out string DiscoFile, out string PhysicalPath, out string BaseUrl, out string VirtualRoot) { Exists = default(string); SSL = default(string); WindowsAuth = default(string); Anonymous = default(string); HomePage = default(string); DiscoFile = default(string); PhysicalPath = default(string); BaseUrl = default(string); VirtualRoot = default(string); } + public void GetVirtualRootStatus(string RootWebServer, string inBaseUrl, string inVirtualRoot, out string Exists, out string SSL, out string WindowsAuth, out string Anonymous, out string HomePage, out string DiscoFile, out string PhysicalPath, out string BaseUrl, out string VirtualRoot) { throw null; } } [System.Runtime.InteropServices.GuidAttribute("5F9A955F-AA55-4127-A32B-33496AA8A44E")] public sealed partial class SoapUtility : System.EnterpriseServices.Internal.ISoapUtility { public SoapUtility() { } - public void GetServerBinPath(string rootWebServer, string inBaseUrl, string inVirtualRoot, out string binPath) { binPath = default(string); } - public void GetServerPhysicalPath(string rootWebServer, string inBaseUrl, string inVirtualRoot, out string physicalPath) { physicalPath = default(string); } + public void GetServerBinPath(string rootWebServer, string inBaseUrl, string inVirtualRoot, out string binPath) { throw null; } + public void GetServerPhysicalPath(string rootWebServer, string inBaseUrl, string inVirtualRoot, out string physicalPath) { throw null; } public void Present() { } } } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.IO.Compression.FileSystem.cs b/external/binary-reference-assemblies/src/v4.7.2/System.IO.Compression.FileSystem.cs index b30fc5294c..6bc84e291e 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.IO.Compression.FileSystem.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.IO.Compression.FileSystem.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.IO.Compression.FileSystem.dll")] @@ -19,8 +19,8 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.SecurityTransparentAttribute] namespace System.IO.Compression { @@ -35,7 +35,7 @@ namespace System.IO.Compression public static System.IO.Compression.ZipArchive Open(string archiveFileName, System.IO.Compression.ZipArchiveMode mode, System.Text.Encoding entryNameEncoding) { throw null; } public static System.IO.Compression.ZipArchive OpenRead(string archiveFileName) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static partial class ZipFileExtensions { public static System.IO.Compression.ZipArchiveEntry CreateEntryFromFile(this System.IO.Compression.ZipArchive destination, string sourceFileName, string entryName) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.IO.Compression.cs b/external/binary-reference-assemblies/src/v4.7.2/System.IO.Compression.cs index c65b350016..0ba298c12d 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.IO.Compression.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.IO.Compression.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.2.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.IO.Compression.dll")] @@ -19,8 +19,8 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.SecurityTransparentAttribute] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.IO.Compression.CompressionLevel))] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.IO.Compression.CompressionMode))] diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.IdentityModel.Selectors.cs b/external/binary-reference-assemblies/src/v4.7.2/System.IdentityModel.Selectors.cs index 9dbd733219..28dee8528c 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.IdentityModel.Selectors.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.IdentityModel.Selectors.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.IdentityModel.Selectors.dll")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace System.IdentityModel.Selectors { diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.IdentityModel.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.IdentityModel.cs.REMOVED.git-id index b7e70849f6..bb8fb5fe47 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.IdentityModel.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.IdentityModel.cs.REMOVED.git-id @@ -1 +1 @@ -91dd0d533cfc372708ea128f0465b25f83382b03 \ No newline at end of file +2e5e51e8ae24b32a92545cfa585574ec9dff5606 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Management.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Management.cs index 35212d3704..93c441141b 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Management.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Management.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Management.dll")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, UnmanagedCode=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace System.Management @@ -390,19 +390,19 @@ namespace System.Management { public ManagementPath() { } public ManagementPath(string path) { } - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string ClassName { get { throw null; } set { } } public static System.Management.ManagementPath DefaultPath { get { throw null; } set { } } public bool IsClass { get { throw null; } } public bool IsInstance { get { throw null; } } public bool IsSingleton { get { throw null; } } - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string NamespacePath { get { throw null; } set { } } - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string Path { get { throw null; } set { } } - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string RelativePath { get { throw null; } set { } } - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string Server { get { throw null; } set { } } public System.Management.ManagementPath Clone() { throw null; } public void SetAsClass() { } @@ -794,7 +794,7 @@ namespace System.Management } namespace System.Management.Instrumentation { - [System.Management.Instrumentation.InstrumentationClassAttribute((System.Management.Instrumentation.InstrumentationType)(1))] + [System.Management.Instrumentation.InstrumentationClassAttribute(System.Management.Instrumentation.InstrumentationType.Event)] public abstract partial class BaseEvent : System.Management.Instrumentation.IEvent { protected BaseEvent() { } @@ -808,7 +808,7 @@ namespace System.Management.Instrumentation { void Fire(); } - [System.AttributeUsageAttribute((System.AttributeTargets)(448))] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Property)] public partial class IgnoreMemberAttribute : System.Attribute { public IgnoreMemberAttribute() { } @@ -817,7 +817,7 @@ namespace System.Management.Instrumentation { bool Published { get; set; } } - [System.Management.Instrumentation.InstrumentationClassAttribute((System.Management.Instrumentation.InstrumentationType)(0))] + [System.Management.Instrumentation.InstrumentationClassAttribute(System.Management.Instrumentation.InstrumentationType.Instance)] public abstract partial class Instance : System.Management.Instrumentation.IInstance { protected Instance() { } @@ -834,7 +834,7 @@ namespace System.Management.Instrumentation public static void Revoke(object instanceData) { } public static void SetBatchSize(System.Type instrumentationClass, int batchSize) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(12))] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Struct)] public partial class InstrumentationClassAttribute : System.Attribute { public InstrumentationClassAttribute(System.Management.Instrumentation.InstrumentationType instrumentationType) { } @@ -848,7 +848,7 @@ namespace System.Management.Instrumentation Event = 1, Instance = 0, } - [System.AttributeUsageAttribute((System.AttributeTargets)(1))] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly)] public partial class InstrumentedAttribute : System.Attribute { public InstrumentedAttribute() { } @@ -857,7 +857,7 @@ namespace System.Management.Instrumentation public string NamespaceName { get { throw null; } } public string SecurityDescriptor { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(460))] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Property | System.AttributeTargets.Struct)] public partial class ManagedNameAttribute : System.Attribute { public ManagedNameAttribute(string name) { } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Messaging.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Messaging.cs index 306ab5cdfd..4b6c7f51c1 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Messaging.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Messaging.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Messaging.dll")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace System.Messaging { @@ -96,10 +96,10 @@ namespace System.Messaging { public BinaryMessageFormatter() { } public BinaryMessageFormatter(System.Runtime.Serialization.Formatters.FormatterAssemblyStyle topObjectFormat, System.Runtime.Serialization.Formatters.FormatterTypeStyle typeFormat) { } - [System.ComponentModel.DefaultValueAttribute((System.Runtime.Serialization.Formatters.FormatterAssemblyStyle)(0))] + [System.ComponentModel.DefaultValueAttribute(System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple)] [System.Messaging.MessagingDescriptionAttribute("MsgTopObjectFormat")] public System.Runtime.Serialization.Formatters.FormatterAssemblyStyle TopObjectFormat { get { throw null; } set { } } - [System.ComponentModel.DefaultValueAttribute((System.Runtime.Serialization.Formatters.FormatterTypeStyle)(0))] + [System.ComponentModel.DefaultValueAttribute(System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesWhenNeeded)] [System.Messaging.MessagingDescriptionAttribute("MsgTypeFormat")] public System.Runtime.Serialization.Formatters.FormatterTypeStyle TypeFormat { get { throw null; } set { } } public bool CanRead(System.Messaging.Message message) { throw null; } @@ -132,7 +132,7 @@ namespace System.Messaging public partial class DefaultPropertiesToSend { public DefaultPropertiesToSend() { } - [System.ComponentModel.DefaultValueAttribute((System.Messaging.AcknowledgeTypes)(0))] + [System.ComponentModel.DefaultValueAttribute(System.Messaging.AcknowledgeTypes.None)] [System.Messaging.MessagingDescriptionAttribute("MsgAcknowledgeType")] public System.Messaging.AcknowledgeTypes AcknowledgeType { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(null)] @@ -144,19 +144,19 @@ namespace System.Messaging [System.ComponentModel.DefaultValueAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgAttachSenderId")] public bool AttachSenderId { get { throw null; } set { } } - [System.ComponentModel.DefaultValueAttribute((System.Messaging.EncryptionAlgorithm)(26114))] + [System.ComponentModel.DefaultValueAttribute(System.Messaging.EncryptionAlgorithm.Rc2)] [System.Messaging.MessagingDescriptionAttribute("MsgEncryptionAlgorithm")] public System.Messaging.EncryptionAlgorithm EncryptionAlgorithm { get { throw null; } set { } } [System.ComponentModel.EditorAttribute("System.ComponentModel.Design.ArrayEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [System.Messaging.MessagingDescriptionAttribute("MsgExtension")] public byte[] Extension { get { throw null; } set { } } - [System.ComponentModel.DefaultValueAttribute((System.Messaging.HashAlgorithm)(32771))] + [System.ComponentModel.DefaultValueAttribute(System.Messaging.HashAlgorithm.Md5)] [System.Messaging.MessagingDescriptionAttribute("MsgHashAlgorithm")] public System.Messaging.HashAlgorithm HashAlgorithm { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute("")] [System.Messaging.MessagingDescriptionAttribute("MsgLabel")] public string Label { get { throw null; } set { } } - [System.ComponentModel.DefaultValueAttribute((System.Messaging.MessagePriority)(3))] + [System.ComponentModel.DefaultValueAttribute(System.Messaging.MessagePriority.Normal)] [System.Messaging.MessagingDescriptionAttribute("MsgPriority")] public System.Messaging.MessagePriority Priority { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(false)] @@ -237,171 +237,171 @@ namespace System.Messaging public Message() { } public Message(object body) { } public Message(object body, System.Messaging.IMessageFormatter formatter) { } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgAcknowledgeType")] public System.Messaging.AcknowledgeTypes AcknowledgeType { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgAcknowledgement")] public System.Messaging.Acknowledgment Acknowledgment { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgAdministrationQueue")] public System.Messaging.MessageQueue AdministrationQueue { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgAppSpecific")] public int AppSpecific { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MsgArrivedTime")] public System.DateTime ArrivedTime { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgAttachSenderId")] public bool AttachSenderId { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MsgAuthenticated")] public bool Authenticated { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgAuthenticationProviderName")] public string AuthenticationProviderName { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgAuthenticationProviderType")] public System.Messaging.CryptographicProviderType AuthenticationProviderType { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public object Body { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.EditorAttribute("System.ComponentModel.Design.BinaryEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgBodyStream")] public System.IO.Stream BodyStream { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgBodyType")] public int BodyType { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgConnectorType")] public System.Guid ConnectorType { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgCorrelationId")] public string CorrelationId { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MsgDestinationQueue")] public System.Messaging.MessageQueue DestinationQueue { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgDestinationSymmetricKey")] public byte[] DestinationSymmetricKey { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgDigitalSignature")] public byte[] DigitalSignature { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgEncryptionAlgorithm")] public System.Messaging.EncryptionAlgorithm EncryptionAlgorithm { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgExtension")] public byte[] Extension { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public System.Messaging.IMessageFormatter Formatter { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgHashAlgorithm")] public System.Messaging.HashAlgorithm HashAlgorithm { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgId")] public string Id { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MsgIsFirstInTransaction")] public bool IsFirstInTransaction { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MsgIsLastInTransaction")] public bool IsLastInTransaction { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgLabel")] public string Label { get { throw null; } set { } } public long LookupId { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MsgMessageType")] public System.Messaging.MessageType MessageType { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgPriority")] public System.Messaging.MessagePriority Priority { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgRecoverable")] public bool Recoverable { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgResponseQueue")] public System.Messaging.MessageQueue ResponseQueue { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] public System.Messaging.SecurityContext SecurityContext { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgSenderCertificate")] public byte[] SenderCertificate { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MsgSenderId")] public byte[] SenderId { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgSenderVersion")] public long SenderVersion { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgSentTime")] public System.DateTime SentTime { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MsgSourceMachine")] public string SourceMachine { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.ComponentModel.TypeConverterAttribute("System.Messaging.Design.TimeoutConverter")] [System.Messaging.MessagingDescriptionAttribute("MsgTimeToBeReceived")] public System.TimeSpan TimeToBeReceived { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.ComponentModel.TypeConverterAttribute("System.Messaging.Design.TimeoutConverter")] [System.Messaging.MessagingDescriptionAttribute("MsgTimeToReachQueue")] public System.TimeSpan TimeToReachQueue { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MsgTransactionId")] public string TransactionId { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgTransactionStatusQueue")] public System.Messaging.MessageQueue TransactionStatusQueue { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgUseAuthentication")] public bool UseAuthentication { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgUseDeadLetterQueue")] public bool UseDeadLetterQueue { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgUseEncryption")] public bool UseEncryption { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgUseJournalQueue")] public bool UseJournalQueue { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.Messaging.MessagingDescriptionAttribute("MsgUseTracing")] public bool UseTracing { get { throw null; } set { } } @@ -601,28 +601,28 @@ namespace System.Messaging public MessageQueue(string path, bool sharedModeDenyReceive, bool enableCache, System.Messaging.QueueAccessMode accessMode) { } public MessageQueue(string path, System.Messaging.QueueAccessMode accessMode) { } public System.Messaging.QueueAccessMode AccessMode { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_Authenticate")] public bool Authenticate { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_BasePriority")] public short BasePriority { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_CanRead")] public bool CanRead { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_CanWrite")] public bool CanWrite { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_Category")] public System.Guid Category { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_CreateTime")] public System.DateTime CreateTime { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(2))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)] [System.Messaging.MessagingDescriptionAttribute("MQ_DefaultPropertiesToSend")] public System.Messaging.DefaultPropertiesToSend DefaultPropertiesToSend { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] @@ -631,10 +631,10 @@ namespace System.Messaging public bool DenySharedReceive { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public static bool EnableConnectionCache { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_EncryptionRequired")] public System.Messaging.EncryptionRequired EncryptionRequired { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_FormatName")] public string FormatName { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] @@ -642,63 +642,63 @@ namespace System.Messaging [System.ComponentModel.TypeConverterAttribute("System.Messaging.Design.MessageFormatterConverter")] [System.Messaging.MessagingDescriptionAttribute("MQ_Formatter")] public System.Messaging.IMessageFormatter Formatter { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_GuidId")] public System.Guid Id { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_Label")] public string Label { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_LastModifyTime")] public System.DateTime LastModifyTime { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_MachineName")] public string MachineName { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.TypeConverterAttribute("System.Messaging.Design.SizeConverter")] [System.Messaging.MessagingDescriptionAttribute("MQ_MaximumJournalSize")] public long MaximumJournalSize { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.TypeConverterAttribute("System.Messaging.Design.SizeConverter")] [System.Messaging.MessagingDescriptionAttribute("MQ_MaximumQueueSize")] public long MaximumQueueSize { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(2))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)] [System.Messaging.MessagingDescriptionAttribute("MQ_MessageReadPropertyFilter")] public System.Messaging.MessagePropertyFilter MessageReadPropertyFilter { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute("")] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_MulticastAddress")] public string MulticastAddress { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DefaultValueAttribute("")] [System.ComponentModel.EditorAttribute("System.Messaging.Design.QueuePathEditor", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] - [System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] [System.ComponentModel.SettingsBindableAttribute(true)] [System.ComponentModel.TypeConverterAttribute("System.Diagnostics.Design.StringValueConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [System.Messaging.MessagingDescriptionAttribute("MQ_Path")] public string Path { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_QueueName")] public string QueueName { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_ReadHandle")] public System.IntPtr ReadHandle { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DefaultValueAttribute(null)] [System.Messaging.MessagingDescriptionAttribute("MQ_SynchronizingObject")] public System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_Transactional")] public bool Transactional { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_UseJournalQueue")] public bool UseJournalQueue { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("MQ_WriteHandle")] public System.IntPtr WriteHandle { get { throw null; } } [System.Messaging.MessagingDescriptionAttribute("MQ_PeekCompleted")] @@ -970,7 +970,7 @@ namespace System.Messaging public short BasePriority { get { throw null; } set { } } [System.ComponentModel.TypeConverterAttribute("System.ComponentModel.GuidConverter, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public System.Guid Category { get { throw null; } set { } } - [System.ComponentModel.DefaultValueAttribute((System.Messaging.EncryptionRequired)(1))] + [System.ComponentModel.DefaultValueAttribute(System.Messaging.EncryptionRequired.Optional)] public System.Messaging.EncryptionRequired EncryptionRequired { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute("")] public string Label { get { throw null; } set { } } @@ -985,11 +985,11 @@ namespace System.Messaging [System.ComponentModel.TypeConverterAttribute("System.Diagnostics.Design.StringValueConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public string Path { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public System.Messaging.AccessControlList Permissions { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(false)] public bool Transactional { get { throw null; } set { } } - [System.ComponentModel.DefaultValueAttribute((System.Configuration.Install.UninstallAction)(0))] + [System.ComponentModel.DefaultValueAttribute(System.Configuration.Install.UninstallAction.Remove)] public System.Configuration.Install.UninstallAction UninstallAction { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(false)] public bool UseJournalQueue { get { throw null; } set { } } @@ -1028,7 +1028,7 @@ namespace System.Messaging Receive = 26, Send = 6, } - [System.AttributeUsageAttribute((System.AttributeTargets)(621), AllowMultiple=true, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Event | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)] [System.SerializableAttribute] public partial class MessageQueuePermissionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute { @@ -1099,7 +1099,7 @@ namespace System.Messaging Normal = 2, Report = 3, } - [System.AttributeUsageAttribute((System.AttributeTargets)(32767))] + [System.AttributeUsageAttribute(System.AttributeTargets.All)] public partial class MessagingDescriptionAttribute : System.ComponentModel.DescriptionAttribute { public MessagingDescriptionAttribute(string description) { } @@ -1180,7 +1180,7 @@ namespace System.Messaging [System.Messaging.MessagingDescriptionAttribute("XmlMsgTargetTypeNames")] public string[] TargetTypeNames { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.Messaging.MessagingDescriptionAttribute("XmlMsgTargetTypes")] public System.Type[] TargetTypes { get { throw null; } set { } } public bool CanRead(System.Messaging.Message message) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Net.Http.WebRequest.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Net.Http.WebRequest.cs index 0f2ecbebc3..02c904363a 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Net.Http.WebRequest.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Net.Http.WebRequest.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Net.Http.WebRequest.dll")] @@ -19,9 +19,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace System.Net.Http { diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Net.Http.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Net.Http.cs index eff75b2c2d..8efe64ab3c 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Net.Http.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Net.Http.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.2.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Net.Http.dll")] @@ -19,9 +19,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace System.Net.Http { @@ -31,7 +31,7 @@ namespace System.Net.Http public ByteArrayContent(byte[] content, int offset, int count) { } protected override System.Threading.Tasks.Task CreateContentReadStreamAsync() { throw null; } protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; } - protected internal override bool TryComputeLength(out long length) { length = default(long); throw null; } + protected internal override bool TryComputeLength(out long length) { throw null; } } public enum ClientCertificateOption { @@ -233,7 +233,7 @@ namespace System.Net.Http public System.Collections.Generic.IEnumerator GetEnumerator() { throw null; } protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } - protected internal override bool TryComputeLength(out long length) { length = default(long); throw null; } + protected internal override bool TryComputeLength(out long length) { throw null; } } public partial class MultipartFormDataContent : System.Net.Http.MultipartContent { @@ -250,7 +250,7 @@ namespace System.Net.Http protected override System.Threading.Tasks.Task CreateContentReadStreamAsync() { throw null; } protected override void Dispose(bool disposing) { } protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; } - protected internal override bool TryComputeLength(out long length) { length = default(long); throw null; } + protected internal override bool TryComputeLength(out long length) { throw null; } } public partial class StringContent : System.Net.Http.ByteArrayContent { @@ -272,7 +272,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.AuthenticationHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.AuthenticationHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.AuthenticationHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.AuthenticationHeaderValue parsedValue) { throw null; } } public partial class CacheControlHeaderValue : System.ICloneable { @@ -298,7 +298,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.CacheControlHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.CacheControlHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.CacheControlHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.CacheControlHeaderValue parsedValue) { throw null; } } public partial class ContentDispositionHeaderValue : System.ICloneable { @@ -318,7 +318,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.ContentDispositionHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.ContentDispositionHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ContentDispositionHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.ContentDispositionHeaderValue parsedValue) { throw null; } } public partial class ContentRangeHeaderValue : System.ICloneable { @@ -336,7 +336,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.ContentRangeHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.ContentRangeHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ContentRangeHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.ContentRangeHeaderValue parsedValue) { throw null; } } public partial class EntityTagHeaderValue : System.ICloneable { @@ -350,7 +350,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.EntityTagHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.EntityTagHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.EntityTagHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.EntityTagHeaderValue parsedValue) { throw null; } } public sealed partial class HttpContentHeaders : System.Net.Http.Headers.HttpHeaders { @@ -381,7 +381,7 @@ namespace System.Net.Http.Headers public override string ToString() { throw null; } public bool TryAddWithoutValidation(string name, System.Collections.Generic.IEnumerable values) { throw null; } public bool TryAddWithoutValidation(string name, string value) { throw null; } - public bool TryGetValues(string name, out System.Collections.Generic.IEnumerable values) { values = default(System.Collections.Generic.IEnumerable); throw null; } + public bool TryGetValues(string name, out System.Collections.Generic.IEnumerable values) { throw null; } } public sealed partial class HttpHeaderValueCollection : System.Collections.Generic.ICollection, System.Collections.Generic.IEnumerable, System.Collections.IEnumerable where T : class { @@ -470,7 +470,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.MediaTypeHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.MediaTypeHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.MediaTypeHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.MediaTypeHeaderValue parsedValue) { throw null; } } public sealed partial class MediaTypeWithQualityHeaderValue : System.Net.Http.Headers.MediaTypeHeaderValue, System.ICloneable { @@ -479,7 +479,7 @@ namespace System.Net.Http.Headers public System.Nullable Quality { get { throw null; } set { } } public static new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.MediaTypeWithQualityHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.MediaTypeWithQualityHeaderValue parsedValue) { throw null; } } public partial class NameValueHeaderValue : System.ICloneable { @@ -493,7 +493,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.NameValueHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.NameValueHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.NameValueHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.NameValueHeaderValue parsedValue) { throw null; } } public partial class NameValueWithParametersHeaderValue : System.Net.Http.Headers.NameValueHeaderValue, System.ICloneable { @@ -506,7 +506,7 @@ namespace System.Net.Http.Headers public static new System.Net.Http.Headers.NameValueWithParametersHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.NameValueWithParametersHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.NameValueWithParametersHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.NameValueWithParametersHeaderValue parsedValue) { throw null; } } public partial class ProductHeaderValue : System.ICloneable { @@ -519,7 +519,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.ProductHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.ProductHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ProductHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.ProductHeaderValue parsedValue) { throw null; } } public partial class ProductInfoHeaderValue : System.ICloneable { @@ -533,7 +533,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.ProductInfoHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.ProductInfoHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ProductInfoHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.ProductInfoHeaderValue parsedValue) { throw null; } } public partial class RangeConditionHeaderValue : System.ICloneable { @@ -547,7 +547,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.RangeConditionHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.RangeConditionHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.RangeConditionHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.RangeConditionHeaderValue parsedValue) { throw null; } } public partial class RangeHeaderValue : System.ICloneable { @@ -560,7 +560,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.RangeHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.RangeHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.RangeHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.RangeHeaderValue parsedValue) { throw null; } } public partial class RangeItemHeaderValue : System.ICloneable { @@ -583,7 +583,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.RetryConditionHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.RetryConditionHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.RetryConditionHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.RetryConditionHeaderValue parsedValue) { throw null; } } public partial class StringWithQualityHeaderValue : System.ICloneable { @@ -596,7 +596,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.StringWithQualityHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.StringWithQualityHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.StringWithQualityHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.StringWithQualityHeaderValue parsedValue) { throw null; } } public partial class TransferCodingHeaderValue : System.ICloneable { @@ -609,7 +609,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.TransferCodingHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.TransferCodingHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.TransferCodingHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.TransferCodingHeaderValue parsedValue) { throw null; } } public sealed partial class TransferCodingWithQualityHeaderValue : System.Net.Http.Headers.TransferCodingHeaderValue, System.ICloneable { @@ -618,7 +618,7 @@ namespace System.Net.Http.Headers public System.Nullable Quality { get { throw null; } set { } } public static new System.Net.Http.Headers.TransferCodingWithQualityHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.TransferCodingWithQualityHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.TransferCodingWithQualityHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.TransferCodingWithQualityHeaderValue parsedValue) { throw null; } } public partial class ViaHeaderValue : System.ICloneable { @@ -634,7 +634,7 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.ViaHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.ViaHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ViaHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.ViaHeaderValue parsedValue) { throw null; } } public partial class WarningHeaderValue : System.ICloneable { @@ -649,6 +649,6 @@ namespace System.Net.Http.Headers public static System.Net.Http.Headers.WarningHeaderValue Parse(string input) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } - public static bool TryParse(string input, out System.Net.Http.Headers.WarningHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.WarningHeaderValue); throw null; } + public static bool TryParse(string input, out System.Net.Http.Headers.WarningHeaderValue parsedValue) { throw null; } } } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Net.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Net.cs index 6c251b902a..6ee24af8e1 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Net.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Net.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(263))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.Default | System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations | System.Diagnostics.DebuggableAttribute.DebuggingModes.EnableEditAndContinue | System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Net.dll")] @@ -19,10 +19,10 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] [assembly:System.Security.SecurityCriticalAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Execution=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.Cookie))] @@ -76,7 +76,7 @@ [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.WriteStreamClosedEventHandler))] namespace System.Net { - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public partial interface INetworkProgress { @@ -91,36 +91,36 @@ namespace System.Net protected override void InsertItem(int index, System.Net.IPEndPoint item) { } protected override void SetItem(int index, System.Net.IPEndPoint item) { } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public partial interface IUnsafeWebRequestCreate { - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] System.Net.WebRequest Create(System.Uri uri); } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public partial class NetworkProgressChangedEventArgs : System.ComponentModel.ProgressChangedEventArgs { - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public NetworkProgressChangedEventArgs(int percentage, int processedBytes, int totalBytes, object userState) : base (default(int), default(object)) { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public int ProcessedBytes { get { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public int TotalBytes { get { throw null; } } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public static partial class UiSynchronizationContext { - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public static System.Threading.SynchronizationContext Current { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public static int ManagedUiThreadId { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } } @@ -132,7 +132,7 @@ namespace System.Net.PeerToPeer { public static readonly System.Net.PeerToPeer.Cloud AllLinkLocal; public static readonly System.Net.PeerToPeer.Cloud Available; - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] protected Cloud(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public static System.Net.PeerToPeer.Cloud Global { get { throw null; } } public string Name { get { throw null; } } @@ -146,7 +146,7 @@ namespace System.Net.PeerToPeer [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, SerializationFormatter=true)] protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128), SerializationFormatter=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter, SerializationFormatter=true)] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } } @@ -160,7 +160,7 @@ namespace System.Net.PeerToPeer [System.SerializableAttribute] public partial class PeerName : System.IEquatable, System.Runtime.Serialization.ISerializable { - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] protected PeerName(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public PeerName(string remotePeerName) { } [System.Security.SecurityCriticalAttribute] @@ -179,7 +179,7 @@ namespace System.Net.PeerToPeer [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, SerializationFormatter=true)] protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128), SerializationFormatter=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter, SerializationFormatter=true)] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } } @@ -187,7 +187,7 @@ namespace System.Net.PeerToPeer public partial class PeerNameRecord : System.Runtime.Serialization.ISerializable { public PeerNameRecord() { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] protected PeerNameRecord(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public string Comment { get { throw null; } set { } } public byte[] Data { get { throw null; } set { } } @@ -196,7 +196,7 @@ namespace System.Net.PeerToPeer [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, SerializationFormatter=true)] protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128), SerializationFormatter=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter, SerializationFormatter=true)] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } [System.SerializableAttribute] @@ -212,7 +212,7 @@ namespace System.Net.PeerToPeer public PeerNameRegistration() { } public PeerNameRegistration(System.Net.PeerToPeer.PeerName name, int port) { } public PeerNameRegistration(System.Net.PeerToPeer.PeerName name, int port, System.Net.PeerToPeer.Cloud cloud) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] protected PeerNameRegistration(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public System.Net.PeerToPeer.Cloud Cloud { get { throw null; } set { } } public string Comment { get { throw null; } set { } } @@ -231,7 +231,7 @@ namespace System.Net.PeerToPeer [System.Security.SecurityCriticalAttribute] public void Stop() { } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128), SerializationFormatter=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter, SerializationFormatter=true)] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } [System.Security.SecurityCriticalAttribute] public void Update() { } @@ -269,15 +269,15 @@ namespace System.Net.PeerToPeer public partial class PeerToPeerException : System.Exception, System.Runtime.Serialization.ISerializable { public PeerToPeerException() { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] protected PeerToPeerException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public PeerToPeerException(string message) { } public PeerToPeerException(string message, System.Exception innerException) { } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } [System.SerializableAttribute] @@ -292,7 +292,7 @@ namespace System.Net.PeerToPeer public override System.Security.SecurityElement ToXml() { throw null; } public override System.Security.IPermission Union(System.Security.IPermission target) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(109), AllowMultiple=true, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)] [System.SerializableAttribute] public sealed partial class PnrpPermissionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute { @@ -386,7 +386,7 @@ namespace System.Net.PeerToPeer.Collaboration [System.SerializableAttribute] public abstract partial class Peer : System.IDisposable, System.IEquatable, System.Runtime.Serialization.ISerializable { - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] protected Peer(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public bool IsOnline { get { throw null; } } public virtual System.Net.PeerToPeer.Collaboration.PeerEndPointCollection PeerEndPoints { get { throw null; } } @@ -414,7 +414,7 @@ namespace System.Net.PeerToPeer.Collaboration public void InviteAsyncCancel(object userToken) { } protected virtual void OnInviteCompleted(System.Net.PeerToPeer.Collaboration.InviteCompletedEventArgs e) { } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128), SerializationFormatter=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter, SerializationFormatter=true)] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } } @@ -423,7 +423,7 @@ namespace System.Net.PeerToPeer.Collaboration { public PeerApplication() { } public PeerApplication(System.Guid id, string description, byte[] data, string path, string commandLineArgs, System.Net.PeerToPeer.Collaboration.PeerScope peerScope) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] protected PeerApplication(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public string CommandLineArgs { get { throw null; } set { } } public byte[] Data { get { throw null; } set { } } @@ -448,7 +448,7 @@ namespace System.Net.PeerToPeer.Collaboration protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } protected virtual void OnApplicationChanged(System.Net.PeerToPeer.Collaboration.ApplicationChangedEventArgs appChangedArgs) { } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128), SerializationFormatter=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter, SerializationFormatter=true)] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } } @@ -527,7 +527,7 @@ namespace System.Net.PeerToPeer.Collaboration public override System.Security.SecurityElement ToXml() { throw null; } public override System.Security.IPermission Union(System.Security.IPermission target) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(109), AllowMultiple=true, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)] [System.SerializableAttribute] public sealed partial class PeerCollaborationPermissionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute { @@ -596,7 +596,7 @@ namespace System.Net.PeerToPeer.Collaboration public virtual void Subscribe() { } public virtual void SubscribeAsync(object userToken) { } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128), SerializationFormatter=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter, SerializationFormatter=true)] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } [System.Security.SecurityCriticalAttribute] @@ -617,7 +617,7 @@ namespace System.Net.PeerToPeer.Collaboration public PeerEndPoint() { } public PeerEndPoint(System.Net.IPEndPoint endPoint) { } public PeerEndPoint(System.Net.IPEndPoint endPoint, string endPointName) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] protected PeerEndPoint(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public System.Net.IPEndPoint EndPoint { get { throw null; } set { } } public string Name { get { throw null; } set { } } @@ -638,7 +638,7 @@ namespace System.Net.PeerToPeer.Collaboration protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } protected void OnNameChanged(System.Net.PeerToPeer.Collaboration.NameChangedEventArgs nameChangedArgs) { } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128), SerializationFormatter=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter, SerializationFormatter=true)] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } } @@ -666,7 +666,7 @@ namespace System.Net.PeerToPeer.Collaboration public partial class PeerNearMe : System.Net.PeerToPeer.Collaboration.Peer, System.IEquatable, System.Runtime.Serialization.ISerializable { public PeerNearMe() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] protected PeerNearMe(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public string Nickname { get { throw null; } } public static event System.EventHandler PeerNearMeChanged { add { } remove { } } @@ -699,7 +699,7 @@ namespace System.Net.PeerToPeer.Collaboration [System.Security.SecurityCriticalAttribute] public void RefreshDataAsync(object userToken) { } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128), SerializationFormatter=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter, SerializationFormatter=true)] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } } @@ -722,7 +722,7 @@ namespace System.Net.PeerToPeer.Collaboration { public PeerObject() { } public PeerObject(System.Guid Id, byte[] data, System.Net.PeerToPeer.Collaboration.PeerScope peerScope) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] protected PeerObject(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public byte[] Data { get { throw null; } set { } } public System.Guid Id { get { throw null; } set { } } @@ -744,7 +744,7 @@ namespace System.Net.PeerToPeer.Collaboration protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } protected virtual void OnObjectChanged(System.Net.PeerToPeer.Collaboration.ObjectChangedEventArgs objChangedArgs) { } [System.Security.SecurityCriticalAttribute] - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128), SerializationFormatter=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter, SerializationFormatter=true)] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } } @@ -815,123 +815,123 @@ namespace System.Net.PeerToPeer.Collaboration } namespace System.Net.Sockets { - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public partial class HttpPolicyDownloaderProtocol { - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public HttpPolicyDownloaderProtocol(System.Uri appUri, System.Net.IPAddress address) { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public System.Net.Sockets.SocketPolicy Result { get { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public void Abort() { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public void BeginDownload(System.Net.Sockets.SecurityCriticalAction callback) { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public void DownloadCallback(System.IAsyncResult ar) { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public void ReadCallback(System.IAsyncResult ar) { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public static void RegisterUnsafeWebRequestCreator(System.Net.IUnsafeWebRequestCreate creator) { } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public delegate void SecurityCriticalAction(); - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public partial class SocketPolicy { public SocketPolicy() { } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public partial class UdpAnySourceMulticastClient : System.IDisposable { - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public UdpAnySourceMulticastClient(System.Net.IPAddress groupAddress, int localPort) { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public bool MulticastLoopback { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public int ReceiveBufferSize { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public int SendBufferSize { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public System.IAsyncResult BeginJoinGroup(System.AsyncCallback callback, object state) { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public System.IAsyncResult BeginReceiveFromGroup(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public System.IAsyncResult BeginSendTo(byte[] buffer, int offset, int count, System.Net.IPEndPoint remoteEndPoint, System.AsyncCallback callback, object state) { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public System.IAsyncResult BeginSendToGroup(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public void BlockSource(System.Net.IPAddress sourceAddress) { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public void Dispose() { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public void EndJoinGroup(System.IAsyncResult result) { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] - public int EndReceiveFromGroup(System.IAsyncResult result, out System.Net.IPEndPoint source) { source = default(System.Net.IPEndPoint); throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + public int EndReceiveFromGroup(System.IAsyncResult result, out System.Net.IPEndPoint source) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public void EndSendTo(System.IAsyncResult result) { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public void EndSendToGroup(System.IAsyncResult result) { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public void UnblockSource(System.Net.IPAddress sourceAddress) { } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public partial class UdpSingleSourceMulticastClient : System.IDisposable { - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public UdpSingleSourceMulticastClient(System.Net.IPAddress sourceAddress, System.Net.IPAddress groupAddress, int localPort) { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public int ReceiveBufferSize { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public int SendBufferSize { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public System.IAsyncResult BeginJoinGroup(System.AsyncCallback callback, object state) { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public System.IAsyncResult BeginReceiveFromSource(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public System.IAsyncResult BeginSendToSource(byte[] buffer, int offset, int count, int remotePort, System.AsyncCallback callback, object state) { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public void Dispose() { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public void EndJoinGroup(System.IAsyncResult result) { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] - public int EndReceiveFromSource(System.IAsyncResult result, out int sourcePort) { sourcePort = default(int); throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + public int EndReceiveFromSource(System.IAsyncResult result, out int sourcePort) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public void EndSendToSource(System.IAsyncResult result) { } } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Numerics.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Numerics.cs index 68963d1cca..4ab4ef98a7 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Numerics.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Numerics.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Numerics.dll")] @@ -19,9 +19,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace System.Numerics { @@ -29,17 +29,19 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BigInteger : System.IComparable, System.IComparable, System.IEquatable, System.IFormattable { + private object _dummy; + private int _dummyPrimitive; [System.CLSCompliantAttribute(false)] - public BigInteger(byte[] value) { throw null;} - public BigInteger(decimal value) { throw null;} - public BigInteger(double value) { throw null;} - public BigInteger(int value) { throw null;} - public BigInteger(long value) { throw null;} - public BigInteger(float value) { throw null;} + public BigInteger(byte[] value) { throw null; } + public BigInteger(decimal value) { throw null; } + public BigInteger(double value) { throw null; } + public BigInteger(int value) { throw null; } + public BigInteger(long value) { throw null; } + public BigInteger(float value) { throw null; } [System.CLSCompliantAttribute(false)] - public BigInteger(uint value) { throw null;} + public BigInteger(uint value) { throw null; } [System.CLSCompliantAttribute(false)] - public BigInteger(ulong value) { throw null;} + public BigInteger(ulong value) { throw null; } public bool IsEven { get { throw null; } } public bool IsOne { get { throw null; } } public bool IsPowerOfTwo { get { throw null; } } @@ -57,7 +59,7 @@ namespace System.Numerics [System.CLSCompliantAttribute(false)] public int CompareTo(ulong other) { throw null; } public static System.Numerics.BigInteger Divide(System.Numerics.BigInteger dividend, System.Numerics.BigInteger divisor) { throw null; } - public static System.Numerics.BigInteger DivRem(System.Numerics.BigInteger dividend, System.Numerics.BigInteger divisor, out System.Numerics.BigInteger remainder) { remainder = default(System.Numerics.BigInteger); throw null; } + public static System.Numerics.BigInteger DivRem(System.Numerics.BigInteger dividend, System.Numerics.BigInteger divisor, out System.Numerics.BigInteger remainder) { throw null; } public bool Equals(long other) { throw null; } public bool Equals(System.Numerics.BigInteger other) { throw null; } public override bool Equals(object obj) { throw null; } @@ -172,17 +174,18 @@ namespace System.Numerics public string ToString(System.IFormatProvider provider) { throw null; } public string ToString(string format) { throw null; } public string ToString(string format, System.IFormatProvider provider) { throw null; } - public static bool TryParse(string value, System.Globalization.NumberStyles style, System.IFormatProvider provider, out System.Numerics.BigInteger result) { result = default(System.Numerics.BigInteger); throw null; } - public static bool TryParse(string value, out System.Numerics.BigInteger result) { result = default(System.Numerics.BigInteger); throw null; } + public static bool TryParse(string value, System.Globalization.NumberStyles style, System.IFormatProvider provider, out System.Numerics.BigInteger result) { throw null; } + public static bool TryParse(string value, out System.Numerics.BigInteger result) { throw null; } } [System.SerializableAttribute] [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Complex : System.IEquatable, System.IFormattable { + private int _dummyPrimitive; public static readonly System.Numerics.Complex ImaginaryOne; public static readonly System.Numerics.Complex One; public static readonly System.Numerics.Complex Zero; - public Complex(double real, double imaginary) { throw null;} + public Complex(double real, double imaginary) { throw null; } public double Imaginary { get { throw null; } } public double Magnitude { get { throw null; } } public double Phase { get { throw null; } } @@ -252,7 +255,7 @@ namespace System.Numerics public float M22; public float M31; public float M32; - public Matrix3x2(float m11, float m12, float m21, float m22, float m31, float m32) { throw null;} + public Matrix3x2(float m11, float m12, float m21, float m22, float m31, float m32) { throw null; } public static System.Numerics.Matrix3x2 Identity { get { throw null; } } public bool IsIdentity { get { throw null; } } public System.Numerics.Vector2 Translation { get { throw null; } set { } } @@ -273,7 +276,7 @@ namespace System.Numerics public override bool Equals(object obj) { throw null; } public float GetDeterminant() { throw null; } public override int GetHashCode() { throw null; } - public static bool Invert(System.Numerics.Matrix3x2 matrix, out System.Numerics.Matrix3x2 result) { result = default(System.Numerics.Matrix3x2); throw null; } + public static bool Invert(System.Numerics.Matrix3x2 matrix, out System.Numerics.Matrix3x2 result) { throw null; } public static System.Numerics.Matrix3x2 Lerp(System.Numerics.Matrix3x2 matrix1, System.Numerics.Matrix3x2 matrix2, float amount) { throw null; } public static System.Numerics.Matrix3x2 Multiply(System.Numerics.Matrix3x2 value1, System.Numerics.Matrix3x2 value2) { throw null; } public static System.Numerics.Matrix3x2 Multiply(System.Numerics.Matrix3x2 value1, float value2) { throw null; } @@ -307,8 +310,8 @@ namespace System.Numerics public float M42; public float M43; public float M44; - public Matrix4x4(System.Numerics.Matrix3x2 value) { throw null;} - public Matrix4x4(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44) { throw null;} + public Matrix4x4(System.Numerics.Matrix3x2 value) { throw null; } + public Matrix4x4(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44) { throw null; } public static System.Numerics.Matrix4x4 Identity { get { throw null; } } public bool IsIdentity { get { throw null; } } public System.Numerics.Vector3 Translation { get { throw null; } set { } } @@ -342,12 +345,12 @@ namespace System.Numerics public static System.Numerics.Matrix4x4 CreateTranslation(float xPosition, float yPosition, float zPosition) { throw null; } public static System.Numerics.Matrix4x4 CreateWorld(System.Numerics.Vector3 position, System.Numerics.Vector3 forward, System.Numerics.Vector3 up) { throw null; } [System.Security.SecuritySafeCriticalAttribute] - public static bool Decompose(System.Numerics.Matrix4x4 matrix, out System.Numerics.Vector3 scale, out System.Numerics.Quaternion rotation, out System.Numerics.Vector3 translation) { scale = default(System.Numerics.Vector3); rotation = default(System.Numerics.Quaternion); translation = default(System.Numerics.Vector3); throw null; } + public static bool Decompose(System.Numerics.Matrix4x4 matrix, out System.Numerics.Vector3 scale, out System.Numerics.Quaternion rotation, out System.Numerics.Vector3 translation) { throw null; } public bool Equals(System.Numerics.Matrix4x4 other) { throw null; } public override bool Equals(object obj) { throw null; } public float GetDeterminant() { throw null; } public override int GetHashCode() { throw null; } - public static bool Invert(System.Numerics.Matrix4x4 matrix, out System.Numerics.Matrix4x4 result) { result = default(System.Numerics.Matrix4x4); throw null; } + public static bool Invert(System.Numerics.Matrix4x4 matrix, out System.Numerics.Matrix4x4 result) { throw null; } public static System.Numerics.Matrix4x4 Lerp(System.Numerics.Matrix4x4 matrix1, System.Numerics.Matrix4x4 matrix2, float amount) { throw null; } public static System.Numerics.Matrix4x4 Multiply(System.Numerics.Matrix4x4 value1, System.Numerics.Matrix4x4 value2) { throw null; } public static System.Numerics.Matrix4x4 Multiply(System.Numerics.Matrix4x4 value1, float value2) { throw null; } @@ -369,9 +372,9 @@ namespace System.Numerics { public float D; public System.Numerics.Vector3 Normal; - public Plane(System.Numerics.Vector3 normal, float d) { throw null;} - public Plane(System.Numerics.Vector4 value) { throw null;} - public Plane(float x, float y, float z, float d) { throw null;} + public Plane(System.Numerics.Vector3 normal, float d) { throw null; } + public Plane(System.Numerics.Vector4 value) { throw null; } + public Plane(float x, float y, float z, float d) { throw null; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]public static System.Numerics.Plane CreateFromVertices(System.Numerics.Vector3 point1, System.Numerics.Vector3 point2, System.Numerics.Vector3 point3) { throw null; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]public static float Dot(System.Numerics.Plane plane, System.Numerics.Vector4 value) { throw null; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]public static float DotCoordinate(System.Numerics.Plane plane, System.Numerics.Vector3 value) { throw null; } @@ -393,8 +396,8 @@ namespace System.Numerics public float X; public float Y; public float Z; - public Quaternion(System.Numerics.Vector3 vectorPart, float scalarPart) { throw null;} - public Quaternion(float x, float y, float z, float w) { throw null;} + public Quaternion(System.Numerics.Vector3 vectorPart, float scalarPart) { throw null; } + public Quaternion(float x, float y, float z, float w) { throw null; } public static System.Numerics.Quaternion Identity { get { throw null; } } public bool IsIdentity { get { throw null; } } public static System.Numerics.Quaternion Add(System.Numerics.Quaternion value1, System.Numerics.Quaternion value2) { throw null; } @@ -433,8 +436,8 @@ namespace System.Numerics { public float X; public float Y; - public Vector2(float value) { throw null;} - public Vector2(float x, float y) { throw null;} + public Vector2(float value) { throw null; } + public Vector2(float x, float y) { throw null; } public static System.Numerics.Vector2 One { get { throw null; } } public static System.Numerics.Vector2 UnitX { get { throw null; } } public static System.Numerics.Vector2 UnitY { get { throw null; } } @@ -490,9 +493,9 @@ namespace System.Numerics public float X; public float Y; public float Z; - public Vector3(System.Numerics.Vector2 value, float z) { throw null;} - public Vector3(float value) { throw null;} - public Vector3(float x, float y, float z) { throw null;} + public Vector3(System.Numerics.Vector2 value, float z) { throw null; } + public Vector3(float value) { throw null; } + public Vector3(float x, float y, float z) { throw null; } public static System.Numerics.Vector3 One { get { throw null; } } public static System.Numerics.Vector3 UnitX { get { throw null; } } public static System.Numerics.Vector3 UnitY { get { throw null; } } @@ -549,10 +552,10 @@ namespace System.Numerics public float X; public float Y; public float Z; - public Vector4(System.Numerics.Vector2 value, float z, float w) { throw null;} - public Vector4(System.Numerics.Vector3 value, float w) { throw null;} - public Vector4(float value) { throw null;} - public Vector4(float x, float y, float z, float w) { throw null;} + public Vector4(System.Numerics.Vector2 value, float z, float w) { throw null; } + public Vector4(System.Numerics.Vector3 value, float w) { throw null; } + public Vector4(float value) { throw null; } + public Vector4(float x, float y, float z, float w) { throw null; } public static System.Numerics.Vector4 One { get { throw null; } } public static System.Numerics.Vector4 UnitW { get { throw null; } } public static System.Numerics.Vector4 UnitX { get { throw null; } } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Reflection.Context.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Reflection.Context.cs index 96651d4acc..1f123839c6 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Reflection.Context.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Reflection.Context.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Reflection.Context.dll")] @@ -19,8 +19,8 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.SecurityTransparentAttribute] namespace System.Reflection.Context { diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Caching.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Caching.cs index f891b126ec..dae06b6c7b 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Caching.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Caching.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Runtime.Caching.dll")] @@ -19,9 +19,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Execution=true)] namespace System.Runtime.Caching { @@ -124,7 +124,7 @@ namespace System.Runtime.Caching } public partial class MemoryCache : System.Runtime.Caching.ObjectCache, System.Collections.IEnumerable, System.IDisposable { - public MemoryCache(string name, System.Collections.Specialized.NameValueCollection config=null) { } + public MemoryCache(string name, System.Collections.Specialized.NameValueCollection config = null) { } public MemoryCache(string name, System.Collections.Specialized.NameValueCollection config, bool ignoreConfigSection) { } public long CacheMemoryLimit { get { throw null; } } public static System.Runtime.Caching.MemoryCache Default { get { throw null; } } @@ -135,22 +135,22 @@ namespace System.Runtime.Caching public System.TimeSpan PollingInterval { get { throw null; } } public override bool Add(System.Runtime.Caching.CacheItem item, System.Runtime.Caching.CacheItemPolicy policy) { throw null; } public override System.Runtime.Caching.CacheItem AddOrGetExisting(System.Runtime.Caching.CacheItem item, System.Runtime.Caching.CacheItemPolicy policy) { throw null; } - public override object AddOrGetExisting(string key, object value, System.DateTimeOffset absoluteExpiration, string regionName=null) { throw null; } - public override object AddOrGetExisting(string key, object value, System.Runtime.Caching.CacheItemPolicy policy, string regionName=null) { throw null; } - public override bool Contains(string key, string regionName=null) { throw null; } - public override System.Runtime.Caching.CacheEntryChangeMonitor CreateCacheEntryChangeMonitor(System.Collections.Generic.IEnumerable keys, string regionName=null) { throw null; } + public override object AddOrGetExisting(string key, object value, System.DateTimeOffset absoluteExpiration, string regionName = null) { throw null; } + public override object AddOrGetExisting(string key, object value, System.Runtime.Caching.CacheItemPolicy policy, string regionName = null) { throw null; } + public override bool Contains(string key, string regionName = null) { throw null; } + public override System.Runtime.Caching.CacheEntryChangeMonitor CreateCacheEntryChangeMonitor(System.Collections.Generic.IEnumerable keys, string regionName = null) { throw null; } public void Dispose() { } - public override object Get(string key, string regionName=null) { throw null; } - public override System.Runtime.Caching.CacheItem GetCacheItem(string key, string regionName=null) { throw null; } - public override long GetCount(string regionName=null) { throw null; } + public override object Get(string key, string regionName = null) { throw null; } + public override System.Runtime.Caching.CacheItem GetCacheItem(string key, string regionName = null) { throw null; } + public override long GetCount(string regionName = null) { throw null; } protected override System.Collections.Generic.IEnumerator> GetEnumerator() { throw null; } - public long GetLastSize(string regionName=null) { throw null; } - public override System.Collections.Generic.IDictionary GetValues(System.Collections.Generic.IEnumerable keys, string regionName=null) { throw null; } - public object Remove(string key, System.Runtime.Caching.CacheEntryRemovedReason reason, string regionName=null) { throw null; } - public override object Remove(string key, string regionName=null) { throw null; } + public long GetLastSize(string regionName = null) { throw null; } + public override System.Collections.Generic.IDictionary GetValues(System.Collections.Generic.IEnumerable keys, string regionName = null) { throw null; } + public object Remove(string key, System.Runtime.Caching.CacheEntryRemovedReason reason, string regionName = null) { throw null; } + public override object Remove(string key, string regionName = null) { throw null; } public override void Set(System.Runtime.Caching.CacheItem item, System.Runtime.Caching.CacheItemPolicy policy) { } - public override void Set(string key, object value, System.DateTimeOffset absoluteExpiration, string regionName=null) { } - public override void Set(string key, object value, System.Runtime.Caching.CacheItemPolicy policy, string regionName=null) { } + public override void Set(string key, object value, System.DateTimeOffset absoluteExpiration, string regionName = null) { } + public override void Set(string key, object value, System.Runtime.Caching.CacheItemPolicy policy, string regionName = null) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public long Trim(int percent) { throw null; } } @@ -164,23 +164,23 @@ namespace System.Runtime.Caching public abstract object this[string key] { get; set; } public abstract string Name { get; } public virtual bool Add(System.Runtime.Caching.CacheItem item, System.Runtime.Caching.CacheItemPolicy policy) { throw null; } - public virtual bool Add(string key, object value, System.DateTimeOffset absoluteExpiration, string regionName=null) { throw null; } - public virtual bool Add(string key, object value, System.Runtime.Caching.CacheItemPolicy policy, string regionName=null) { throw null; } + public virtual bool Add(string key, object value, System.DateTimeOffset absoluteExpiration, string regionName = null) { throw null; } + public virtual bool Add(string key, object value, System.Runtime.Caching.CacheItemPolicy policy, string regionName = null) { throw null; } public abstract System.Runtime.Caching.CacheItem AddOrGetExisting(System.Runtime.Caching.CacheItem value, System.Runtime.Caching.CacheItemPolicy policy); - public abstract object AddOrGetExisting(string key, object value, System.DateTimeOffset absoluteExpiration, string regionName=null); - public abstract object AddOrGetExisting(string key, object value, System.Runtime.Caching.CacheItemPolicy policy, string regionName=null); - public abstract bool Contains(string key, string regionName=null); - public abstract System.Runtime.Caching.CacheEntryChangeMonitor CreateCacheEntryChangeMonitor(System.Collections.Generic.IEnumerable keys, string regionName=null); - public abstract object Get(string key, string regionName=null); - public abstract System.Runtime.Caching.CacheItem GetCacheItem(string key, string regionName=null); - public abstract long GetCount(string regionName=null); + public abstract object AddOrGetExisting(string key, object value, System.DateTimeOffset absoluteExpiration, string regionName = null); + public abstract object AddOrGetExisting(string key, object value, System.Runtime.Caching.CacheItemPolicy policy, string regionName = null); + public abstract bool Contains(string key, string regionName = null); + public abstract System.Runtime.Caching.CacheEntryChangeMonitor CreateCacheEntryChangeMonitor(System.Collections.Generic.IEnumerable keys, string regionName = null); + public abstract object Get(string key, string regionName = null); + public abstract System.Runtime.Caching.CacheItem GetCacheItem(string key, string regionName = null); + public abstract long GetCount(string regionName = null); protected abstract System.Collections.Generic.IEnumerator> GetEnumerator(); - public abstract System.Collections.Generic.IDictionary GetValues(System.Collections.Generic.IEnumerable keys, string regionName=null); + public abstract System.Collections.Generic.IDictionary GetValues(System.Collections.Generic.IEnumerable keys, string regionName = null); public virtual System.Collections.Generic.IDictionary GetValues(string regionName, params string[] keys) { throw null; } - public abstract object Remove(string key, string regionName=null); + public abstract object Remove(string key, string regionName = null); public abstract void Set(System.Runtime.Caching.CacheItem item, System.Runtime.Caching.CacheItemPolicy policy); - public abstract void Set(string key, object value, System.DateTimeOffset absoluteExpiration, string regionName=null); - public abstract void Set(string key, object value, System.Runtime.Caching.CacheItemPolicy policy, string regionName=null); + public abstract void Set(string key, object value, System.DateTimeOffset absoluteExpiration, string regionName = null); + public abstract void Set(string key, object value, System.Runtime.Caching.CacheItemPolicy policy, string regionName = null); System.Collections.Generic.IEnumerator> System.Collections.Generic.IEnumerable>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } @@ -225,7 +225,7 @@ namespace System.Runtime.Caching.Configuration public System.Runtime.Caching.Configuration.MemoryCacheSettingsCollection NamedCaches { get { throw null; } } protected override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } } } - [System.Configuration.ConfigurationCollectionAttribute(typeof(System.Runtime.Caching.Configuration.MemoryCacheElement), CollectionType=(System.Configuration.ConfigurationElementCollectionType)(1))] + [System.Configuration.ConfigurationCollectionAttribute(typeof(System.Runtime.Caching.Configuration.MemoryCacheElement), CollectionType=System.Configuration.ConfigurationElementCollectionType.AddRemoveClearMap)] public sealed partial class MemoryCacheSettingsCollection : System.Configuration.ConfigurationElementCollection { public MemoryCacheSettingsCollection() { } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.DurableInstancing.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.DurableInstancing.cs index 5374d023be..077daccbc2 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.DurableInstancing.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.DurableInstancing.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Runtime.DurableInstancing.dll")] @@ -19,10 +19,10 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Runtime.InteropServices.GuidAttribute("a9b8c4b5-b4a9-4800-8268-e8ec3b93d9ac")] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Execution=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] #if false // these are forwarded to System.ServiceModel.Internals.dll but this assembly doesn't actually exist in the .NET 4.7.2 reference assemblies ... diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Remoting.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Remoting.cs index 8a8662a86f..71288cd23f 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Remoting.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Remoting.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(false)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Runtime.Remoting.dll")] @@ -20,7 +20,7 @@ [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComCompatibleVersionAttribute(1, 0, 3300, 0)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Runtime.InteropServices.TypeLibVersionAttribute(4, 0)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace System.Runtime.Remoting.Channels @@ -28,43 +28,43 @@ namespace System.Runtime.Remoting.Channels public partial class BinaryClientFormatterSink : System.Runtime.Remoting.Channels.IChannelSinkBase, System.Runtime.Remoting.Channels.IClientChannelSink, System.Runtime.Remoting.Channels.IClientFormatterSink, System.Runtime.Remoting.Messaging.IMessageSink { public BinaryClientFormatterSink(System.Runtime.Remoting.Channels.IClientChannelSink nextSink) { } - public System.Runtime.Remoting.Channels.IClientChannelSink NextChannelSink { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public System.Runtime.Remoting.Messaging.IMessageSink NextSink { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public System.Collections.IDictionary Properties { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + public System.Runtime.Remoting.Channels.IClientChannelSink NextChannelSink { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public System.Runtime.Remoting.Messaging.IMessageSink NextSink { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public System.Collections.IDictionary Properties { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public System.Runtime.Remoting.Messaging.IMessageCtrl AsyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Messaging.IMessageSink replySink) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void AsyncProcessRequest(System.Runtime.Remoting.Channels.IClientChannelSinkStack sinkStack, System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders headers, System.IO.Stream stream) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void AsyncProcessResponse(System.Runtime.Remoting.Channels.IClientResponseChannelSinkStack sinkStack, object state, System.Runtime.Remoting.Channels.ITransportHeaders headers, System.IO.Stream stream) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public System.IO.Stream GetRequestStream(System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders headers) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public void ProcessMessage(System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders requestHeaders, System.IO.Stream requestStream, out System.Runtime.Remoting.Channels.ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { responseHeaders = default(System.Runtime.Remoting.Channels.ITransportHeaders); responseStream = default(System.IO.Stream); } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public void ProcessMessage(System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders requestHeaders, System.IO.Stream requestStream, out System.Runtime.Remoting.Channels.ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public System.Runtime.Remoting.Messaging.IMessage SyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage msg) { throw null; } } public partial class BinaryClientFormatterSinkProvider : System.Runtime.Remoting.Channels.IClientChannelSinkProvider, System.Runtime.Remoting.Channels.IClientFormatterSinkProvider { public BinaryClientFormatterSinkProvider() { } public BinaryClientFormatterSinkProvider(System.Collections.IDictionary properties, System.Collections.ICollection providerData) { } - public System.Runtime.Remoting.Channels.IClientChannelSinkProvider Next { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]set { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + public System.Runtime.Remoting.Channels.IClientChannelSinkProvider Next { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]set { } } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public System.Runtime.Remoting.Channels.IClientChannelSink CreateSink(System.Runtime.Remoting.Channels.IChannelSender channel, string url, object remoteChannelData) { throw null; } } public partial class BinaryServerFormatterSink : System.Runtime.Remoting.Channels.IChannelSinkBase, System.Runtime.Remoting.Channels.IServerChannelSink { public BinaryServerFormatterSink(System.Runtime.Remoting.Channels.BinaryServerFormatterSink.Protocol protocol, System.Runtime.Remoting.Channels.IServerChannelSink nextSink, System.Runtime.Remoting.Channels.IChannelReceiver receiver) { } - public System.Runtime.Remoting.Channels.IServerChannelSink NextChannelSink { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public System.Collections.IDictionary Properties { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } + public System.Runtime.Remoting.Channels.IServerChannelSink NextChannelSink { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public System.Collections.IDictionary Properties { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } [System.Runtime.InteropServices.ComVisibleAttribute(false)] public System.Runtime.Serialization.Formatters.TypeFilterLevel TypeFilterLevel { get { throw null; } set { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void AsyncProcessResponse(System.Runtime.Remoting.Channels.IServerResponseChannelSinkStack sinkStack, object state, System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders headers, System.IO.Stream stream) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public System.IO.Stream GetResponseStream(System.Runtime.Remoting.Channels.IServerResponseChannelSinkStack sinkStack, object state, System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders headers) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public System.Runtime.Remoting.Channels.ServerProcessing ProcessMessage(System.Runtime.Remoting.Channels.IServerChannelSinkStack sinkStack, System.Runtime.Remoting.Messaging.IMessage requestMsg, System.Runtime.Remoting.Channels.ITransportHeaders requestHeaders, System.IO.Stream requestStream, out System.Runtime.Remoting.Messaging.IMessage responseMsg, out System.Runtime.Remoting.Channels.ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { responseMsg = default(System.Runtime.Remoting.Messaging.IMessage); responseHeaders = default(System.Runtime.Remoting.Channels.ITransportHeaders); responseStream = default(System.IO.Stream); throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public System.Runtime.Remoting.Channels.ServerProcessing ProcessMessage(System.Runtime.Remoting.Channels.IServerChannelSinkStack sinkStack, System.Runtime.Remoting.Messaging.IMessage requestMsg, System.Runtime.Remoting.Channels.ITransportHeaders requestHeaders, System.IO.Stream requestStream, out System.Runtime.Remoting.Messaging.IMessage responseMsg, out System.Runtime.Remoting.Channels.ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { throw null; } [System.SerializableAttribute] public enum Protocol { @@ -76,12 +76,12 @@ namespace System.Runtime.Remoting.Channels { public BinaryServerFormatterSinkProvider() { } public BinaryServerFormatterSinkProvider(System.Collections.IDictionary properties, System.Collections.ICollection providerData) { } - public System.Runtime.Remoting.Channels.IServerChannelSinkProvider Next { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]set { } } + public System.Runtime.Remoting.Channels.IServerChannelSinkProvider Next { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]set { } } [System.Runtime.InteropServices.ComVisibleAttribute(false)] public System.Runtime.Serialization.Formatters.TypeFilterLevel TypeFilterLevel { get { throw null; } set { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public System.Runtime.Remoting.Channels.IServerChannelSink CreateSink(System.Runtime.Remoting.Channels.IChannelReceiver channel) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void GetChannelData(System.Runtime.Remoting.Channels.IChannelDataStore channelData) { } } public partial class CommonTransportKeys @@ -99,43 +99,43 @@ namespace System.Runtime.Remoting.Channels public partial class SoapClientFormatterSink : System.Runtime.Remoting.Channels.IChannelSinkBase, System.Runtime.Remoting.Channels.IClientChannelSink, System.Runtime.Remoting.Channels.IClientFormatterSink, System.Runtime.Remoting.Messaging.IMessageSink { public SoapClientFormatterSink(System.Runtime.Remoting.Channels.IClientChannelSink nextSink) { } - public System.Runtime.Remoting.Channels.IClientChannelSink NextChannelSink { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public System.Runtime.Remoting.Messaging.IMessageSink NextSink { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public System.Collections.IDictionary Properties { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + public System.Runtime.Remoting.Channels.IClientChannelSink NextChannelSink { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public System.Runtime.Remoting.Messaging.IMessageSink NextSink { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public System.Collections.IDictionary Properties { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public System.Runtime.Remoting.Messaging.IMessageCtrl AsyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Messaging.IMessageSink replySink) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void AsyncProcessRequest(System.Runtime.Remoting.Channels.IClientChannelSinkStack sinkStack, System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders headers, System.IO.Stream stream) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void AsyncProcessResponse(System.Runtime.Remoting.Channels.IClientResponseChannelSinkStack sinkStack, object state, System.Runtime.Remoting.Channels.ITransportHeaders headers, System.IO.Stream stream) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public System.IO.Stream GetRequestStream(System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders headers) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public void ProcessMessage(System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders requestHeaders, System.IO.Stream requestStream, out System.Runtime.Remoting.Channels.ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { responseHeaders = default(System.Runtime.Remoting.Channels.ITransportHeaders); responseStream = default(System.IO.Stream); } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public void ProcessMessage(System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders requestHeaders, System.IO.Stream requestStream, out System.Runtime.Remoting.Channels.ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public System.Runtime.Remoting.Messaging.IMessage SyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage msg) { throw null; } } public partial class SoapClientFormatterSinkProvider : System.Runtime.Remoting.Channels.IClientChannelSinkProvider, System.Runtime.Remoting.Channels.IClientFormatterSinkProvider { public SoapClientFormatterSinkProvider() { } public SoapClientFormatterSinkProvider(System.Collections.IDictionary properties, System.Collections.ICollection providerData) { } - public System.Runtime.Remoting.Channels.IClientChannelSinkProvider Next { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]set { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + public System.Runtime.Remoting.Channels.IClientChannelSinkProvider Next { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]set { } } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public System.Runtime.Remoting.Channels.IClientChannelSink CreateSink(System.Runtime.Remoting.Channels.IChannelSender channel, string url, object remoteChannelData) { throw null; } } public partial class SoapServerFormatterSink : System.Runtime.Remoting.Channels.IChannelSinkBase, System.Runtime.Remoting.Channels.IServerChannelSink { public SoapServerFormatterSink(System.Runtime.Remoting.Channels.SoapServerFormatterSink.Protocol protocol, System.Runtime.Remoting.Channels.IServerChannelSink nextSink, System.Runtime.Remoting.Channels.IChannelReceiver receiver) { } - public System.Runtime.Remoting.Channels.IServerChannelSink NextChannelSink { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public System.Collections.IDictionary Properties { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } + public System.Runtime.Remoting.Channels.IServerChannelSink NextChannelSink { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public System.Collections.IDictionary Properties { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } [System.Runtime.InteropServices.ComVisibleAttribute(false)] public System.Runtime.Serialization.Formatters.TypeFilterLevel TypeFilterLevel { get { throw null; } set { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void AsyncProcessResponse(System.Runtime.Remoting.Channels.IServerResponseChannelSinkStack sinkStack, object state, System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders headers, System.IO.Stream stream) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public System.IO.Stream GetResponseStream(System.Runtime.Remoting.Channels.IServerResponseChannelSinkStack sinkStack, object state, System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders headers) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public System.Runtime.Remoting.Channels.ServerProcessing ProcessMessage(System.Runtime.Remoting.Channels.IServerChannelSinkStack sinkStack, System.Runtime.Remoting.Messaging.IMessage requestMsg, System.Runtime.Remoting.Channels.ITransportHeaders requestHeaders, System.IO.Stream requestStream, out System.Runtime.Remoting.Messaging.IMessage responseMsg, out System.Runtime.Remoting.Channels.ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { responseMsg = default(System.Runtime.Remoting.Messaging.IMessage); responseHeaders = default(System.Runtime.Remoting.Channels.ITransportHeaders); responseStream = default(System.IO.Stream); throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public System.Runtime.Remoting.Channels.ServerProcessing ProcessMessage(System.Runtime.Remoting.Channels.IServerChannelSinkStack sinkStack, System.Runtime.Remoting.Messaging.IMessage requestMsg, System.Runtime.Remoting.Channels.ITransportHeaders requestHeaders, System.IO.Stream requestStream, out System.Runtime.Remoting.Messaging.IMessage responseMsg, out System.Runtime.Remoting.Channels.ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { throw null; } [System.SerializableAttribute] public enum Protocol { @@ -147,12 +147,12 @@ namespace System.Runtime.Remoting.Channels { public SoapServerFormatterSinkProvider() { } public SoapServerFormatterSinkProvider(System.Collections.IDictionary properties, System.Collections.ICollection providerData) { } - public System.Runtime.Remoting.Channels.IServerChannelSinkProvider Next { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]set { } } + public System.Runtime.Remoting.Channels.IServerChannelSinkProvider Next { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]set { } } [System.Runtime.InteropServices.ComVisibleAttribute(false)] public System.Runtime.Serialization.Formatters.TypeFilterLevel TypeFilterLevel { get { throw null; } set { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public System.Runtime.Remoting.Channels.IServerChannelSink CreateSink(System.Runtime.Remoting.Channels.IChannelReceiver channel) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void GetChannelData(System.Runtime.Remoting.Channels.IChannelDataStore channelData) { } } public enum SocketCachePolicy @@ -168,27 +168,27 @@ namespace System.Runtime.Remoting.Channels.Http public HttpChannel() { } public HttpChannel(System.Collections.IDictionary properties, System.Runtime.Remoting.Channels.IClientChannelSinkProvider clientSinkProvider, System.Runtime.Remoting.Channels.IServerChannelSinkProvider serverSinkProvider) { } public HttpChannel(int port) { } - public object ChannelData { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public string ChannelScheme { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public System.Runtime.Remoting.Channels.IServerChannelSink ChannelSinkChain { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]set { } } + public object ChannelData { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public string ChannelScheme { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public System.Runtime.Remoting.Channels.IServerChannelSink ChannelSinkChain { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]set { } } public override object this[object key] { get { throw null; } set { } } public override System.Collections.ICollection Keys { get { throw null; } } - public override System.Collections.IDictionary Properties { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public bool WantsToListen { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } set { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + public override System.Collections.IDictionary Properties { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public bool WantsToListen { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } set { } } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void AddHookChannelUri(string channelUri) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public System.Runtime.Remoting.Messaging.IMessageSink CreateMessageSink(string url, object remoteChannelData, out string objectURI) { objectURI = default(string); throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public System.Runtime.Remoting.Messaging.IMessageSink CreateMessageSink(string url, object remoteChannelData, out string objectURI) { throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public string[] GetUrlsForUri(string objectURI) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public string Parse(string url, out string objectURI) { objectURI = default(string); throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public string Parse(string url, out string objectURI) { throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void StartListening(object data) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void StopListening(object data) { } } public partial class HttpClientChannel : System.Runtime.Remoting.Channels.BaseChannelWithProperties, System.Runtime.Remoting.Channels.IChannel, System.Runtime.Remoting.Channels.IChannelSender, System.Runtime.Remoting.Channels.ISecurableChannel @@ -196,15 +196,15 @@ namespace System.Runtime.Remoting.Channels.Http public HttpClientChannel() { } public HttpClientChannel(System.Collections.IDictionary properties, System.Runtime.Remoting.Channels.IClientChannelSinkProvider sinkProvider) { } public HttpClientChannel(string name, System.Runtime.Remoting.Channels.IClientChannelSinkProvider sinkProvider) { } - public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]set { } } + public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]set { } } public override object this[object key] { get { throw null; } set { } } public override System.Collections.ICollection Keys { get { throw null; } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public virtual System.Runtime.Remoting.Messaging.IMessageSink CreateMessageSink(string url, object remoteChannelData, out string objectURI) { objectURI = default(string); throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public string Parse(string url, out string objectURI) { objectURI = default(string); throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public virtual System.Runtime.Remoting.Messaging.IMessageSink CreateMessageSink(string url, object remoteChannelData, out string objectURI) { throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public string Parse(string url, out string objectURI) { throw null; } } public partial class HttpRemotingHandler : System.Web.IHttpHandler { @@ -226,24 +226,24 @@ namespace System.Runtime.Remoting.Channels.Http public HttpServerChannel(int port) { } public HttpServerChannel(string name, int port) { } public HttpServerChannel(string name, int port, System.Runtime.Remoting.Channels.IServerChannelSinkProvider sinkProvider) { } - public object ChannelData { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public string ChannelScheme { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096))]get { throw null; } } - public System.Runtime.Remoting.Channels.IServerChannelSink ChannelSinkChain { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096))]get { throw null; } } + public object ChannelData { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public string ChannelScheme { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure)]get { throw null; } } + public System.Runtime.Remoting.Channels.IServerChannelSink ChannelSinkChain { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure)]get { throw null; } } public override object this[object key] { get { throw null; } set { } } public override System.Collections.ICollection Keys { get { throw null; } } - public bool WantsToListen { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } set { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + public bool WantsToListen { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } set { } } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void AddHookChannelUri(string channelUri) { } public string GetChannelUri() { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public virtual string[] GetUrlsForUri(string objectUri) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public string Parse(string url, out string objectURI) { objectURI = default(string); throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public string Parse(string url, out string objectURI) { throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void StartListening(object data) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void StopListening(object data) { } } } @@ -255,19 +255,19 @@ namespace System.Runtime.Remoting.Channels.Ipc public IpcChannel(System.Collections.IDictionary properties, System.Runtime.Remoting.Channels.IClientChannelSinkProvider clientSinkProvider, System.Runtime.Remoting.Channels.IServerChannelSinkProvider serverSinkProvider) { } public IpcChannel(System.Collections.IDictionary properties, System.Runtime.Remoting.Channels.IClientChannelSinkProvider clientSinkProvider, System.Runtime.Remoting.Channels.IServerChannelSinkProvider serverSinkProvider, System.Security.AccessControl.CommonSecurityDescriptor securityDescriptor) { } public IpcChannel(string portName) { } - public object ChannelData { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]set { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public System.Runtime.Remoting.Messaging.IMessageSink CreateMessageSink(string url, object remoteChannelData, out string objectURI) { objectURI = default(string); throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + public object ChannelData { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]set { } } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public System.Runtime.Remoting.Messaging.IMessageSink CreateMessageSink(string url, object remoteChannelData, out string objectURI) { throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public string[] GetUrlsForUri(string objectURI) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public string Parse(string url, out string objectURI) { objectURI = default(string); throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public string Parse(string url, out string objectURI) { throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void StartListening(object data) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void StopListening(object data) { } } public partial class IpcClientChannel : System.Runtime.Remoting.Channels.IChannel, System.Runtime.Remoting.Channels.IChannelSender, System.Runtime.Remoting.Channels.ISecurableChannel @@ -275,13 +275,13 @@ namespace System.Runtime.Remoting.Channels.Ipc public IpcClientChannel() { } public IpcClientChannel(System.Collections.IDictionary properties, System.Runtime.Remoting.Channels.IClientChannelSinkProvider sinkProvider) { } public IpcClientChannel(string name, System.Runtime.Remoting.Channels.IClientChannelSinkProvider sinkProvider) { } - public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]set { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public virtual System.Runtime.Remoting.Messaging.IMessageSink CreateMessageSink(string url, object remoteChannelData, out string objectURI) { objectURI = default(string); throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public string Parse(string url, out string objectURI) { objectURI = default(string); throw null; } + public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]set { } } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public virtual System.Runtime.Remoting.Messaging.IMessageSink CreateMessageSink(string url, object remoteChannelData, out string objectURI) { throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public string Parse(string url, out string objectURI) { throw null; } } public partial class IpcServerChannel : System.Runtime.Remoting.Channels.IChannel, System.Runtime.Remoting.Channels.IChannelReceiver, System.Runtime.Remoting.Channels.ISecurableChannel { @@ -290,18 +290,18 @@ namespace System.Runtime.Remoting.Channels.Ipc public IpcServerChannel(string portName) { } public IpcServerChannel(string name, string portName) { } public IpcServerChannel(string name, string portName, System.Runtime.Remoting.Channels.IServerChannelSinkProvider sinkProvider) { } - public object ChannelData { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]set { } } + public object ChannelData { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]set { } } public string GetChannelUri() { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public virtual string[] GetUrlsForUri(string objectUri) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public string Parse(string url, out string objectURI) { objectURI = default(string); throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public string Parse(string url, out string objectURI) { throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void StartListening(object data) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void StopListening(object data) { } } } @@ -312,19 +312,19 @@ namespace System.Runtime.Remoting.Channels.Tcp public TcpChannel() { } public TcpChannel(System.Collections.IDictionary properties, System.Runtime.Remoting.Channels.IClientChannelSinkProvider clientSinkProvider, System.Runtime.Remoting.Channels.IServerChannelSinkProvider serverSinkProvider) { } public TcpChannel(int port) { } - public object ChannelData { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]set { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public System.Runtime.Remoting.Messaging.IMessageSink CreateMessageSink(string url, object remoteChannelData, out string objectURI) { objectURI = default(string); throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + public object ChannelData { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]set { } } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public System.Runtime.Remoting.Messaging.IMessageSink CreateMessageSink(string url, object remoteChannelData, out string objectURI) { throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public string[] GetUrlsForUri(string objectURI) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public string Parse(string url, out string objectURI) { objectURI = default(string); throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public string Parse(string url, out string objectURI) { throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void StartListening(object data) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void StopListening(object data) { } } public partial class TcpClientChannel : System.Runtime.Remoting.Channels.IChannel, System.Runtime.Remoting.Channels.IChannelSender, System.Runtime.Remoting.Channels.ISecurableChannel @@ -332,13 +332,13 @@ namespace System.Runtime.Remoting.Channels.Tcp public TcpClientChannel() { } public TcpClientChannel(System.Collections.IDictionary properties, System.Runtime.Remoting.Channels.IClientChannelSinkProvider sinkProvider) { } public TcpClientChannel(string name, System.Runtime.Remoting.Channels.IClientChannelSinkProvider sinkProvider) { } - public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]set { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public virtual System.Runtime.Remoting.Messaging.IMessageSink CreateMessageSink(string url, object remoteChannelData, out string objectURI) { objectURI = default(string); throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public string Parse(string url, out string objectURI) { objectURI = default(string); throw null; } + public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]set { } } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public virtual System.Runtime.Remoting.Messaging.IMessageSink CreateMessageSink(string url, object remoteChannelData, out string objectURI) { throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public string Parse(string url, out string objectURI) { throw null; } } public partial class TcpServerChannel : System.Runtime.Remoting.Channels.IChannel, System.Runtime.Remoting.Channels.IChannelReceiver, System.Runtime.Remoting.Channels.ISecurableChannel { @@ -347,18 +347,18 @@ namespace System.Runtime.Remoting.Channels.Tcp public TcpServerChannel(int port) { } public TcpServerChannel(string name, int port) { } public TcpServerChannel(string name, int port, System.Runtime.Remoting.Channels.IServerChannelSinkProvider sinkProvider) { } - public object ChannelData { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]set { } } + public object ChannelData { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public string ChannelName { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public int ChannelPriority { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public bool IsSecured { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]set { } } public string GetChannelUri() { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public virtual string[] GetUrlsForUri(string objectUri) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public string Parse(string url, out string objectURI) { objectURI = default(string); throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public string Parse(string url, out string objectURI) { throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void StartListening(object data) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void StopListening(object data) { } } } @@ -383,23 +383,23 @@ namespace System.Runtime.Remoting.MetadataServices public partial class SdlChannelSink : System.Runtime.Remoting.Channels.IChannelSinkBase, System.Runtime.Remoting.Channels.IServerChannelSink { public SdlChannelSink(System.Runtime.Remoting.Channels.IChannelReceiver receiver, System.Runtime.Remoting.Channels.IServerChannelSink nextSink) { } - public System.Runtime.Remoting.Channels.IServerChannelSink NextChannelSink { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - public System.Collections.IDictionary Properties { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + public System.Runtime.Remoting.Channels.IServerChannelSink NextChannelSink { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + public System.Collections.IDictionary Properties { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void AsyncProcessResponse(System.Runtime.Remoting.Channels.IServerResponseChannelSinkStack sinkStack, object state, System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders headers, System.IO.Stream stream) { } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public System.IO.Stream GetResponseStream(System.Runtime.Remoting.Channels.IServerResponseChannelSinkStack sinkStack, object state, System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Channels.ITransportHeaders headers) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] - public System.Runtime.Remoting.Channels.ServerProcessing ProcessMessage(System.Runtime.Remoting.Channels.IServerChannelSinkStack sinkStack, System.Runtime.Remoting.Messaging.IMessage requestMsg, System.Runtime.Remoting.Channels.ITransportHeaders requestHeaders, System.IO.Stream requestStream, out System.Runtime.Remoting.Messaging.IMessage responseMsg, out System.Runtime.Remoting.Channels.ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { responseMsg = default(System.Runtime.Remoting.Messaging.IMessage); responseHeaders = default(System.Runtime.Remoting.Channels.ITransportHeaders); responseStream = default(System.IO.Stream); throw null; } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] + public System.Runtime.Remoting.Channels.ServerProcessing ProcessMessage(System.Runtime.Remoting.Channels.IServerChannelSinkStack sinkStack, System.Runtime.Remoting.Messaging.IMessage requestMsg, System.Runtime.Remoting.Channels.ITransportHeaders requestHeaders, System.IO.Stream requestStream, out System.Runtime.Remoting.Messaging.IMessage responseMsg, out System.Runtime.Remoting.Channels.ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { throw null; } } public partial class SdlChannelSinkProvider : System.Runtime.Remoting.Channels.IServerChannelSinkProvider { public SdlChannelSinkProvider() { } public SdlChannelSinkProvider(System.Collections.IDictionary properties, System.Collections.ICollection providerData) { } - public System.Runtime.Remoting.Channels.IServerChannelSinkProvider Next { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)]set { } } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + public System.Runtime.Remoting.Channels.IServerChannelSinkProvider Next { [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]get { throw null; } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)]set { } } + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public System.Runtime.Remoting.Channels.IServerChannelSink CreateSink(System.Runtime.Remoting.Channels.IChannelReceiver channel) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(4096), Infrastructure=true)] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void GetChannelData(System.Runtime.Remoting.Channels.IChannelDataStore localChannelData) { } } [System.SerializableAttribute] diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Serialization.Formatters.Soap.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Serialization.Formatters.Soap.cs index 47c78d706c..4ef2b538b1 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Serialization.Formatters.Soap.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Serialization.Formatters.Soap.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Runtime.Serialization.Formatters.Soap.dll")] @@ -20,7 +20,7 @@ [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComCompatibleVersionAttribute(1, 0, 3300, 0)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(true)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] namespace System.Runtime.Serialization.Formatters.Soap { public sealed partial class SoapFormatter : System.Runtime.Remoting.Messaging.IRemotingFormatter, System.Runtime.Serialization.IFormatter diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Serialization.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Serialization.cs index b40c8e9713..41e1161f6f 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Serialization.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Runtime.Serialization.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Runtime.Serialization.dll")] @@ -20,14 +20,14 @@ [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComCompatibleVersionAttribute(1, 0, 3300, 0)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] [assembly:System.Security.SecurityCriticalAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1))] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace System.Runtime.Serialization { - [System.AttributeUsageAttribute((System.AttributeTargets)(12), Inherited=false, AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Struct, Inherited=false, AllowMultiple=false)] public sealed partial class CollectionDataContractAttribute : System.Attribute { public CollectionDataContractAttribute() { } @@ -44,14 +44,14 @@ namespace System.Runtime.Serialization public string Namespace { get { throw null; } set { } } public string ValueName { get { throw null; } set { } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(3), Inherited=false, AllowMultiple=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly | System.AttributeTargets.Module, Inherited=false, AllowMultiple=true)] public sealed partial class ContractNamespaceAttribute : System.Attribute { public ContractNamespaceAttribute(string contractNamespace) { } public string ClrNamespace { get { throw null; } set { } } public string ContractNamespace { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(28), Inherited=false, AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Struct, Inherited=false, AllowMultiple=false)] public sealed partial class DataContractAttribute : System.Attribute { public DataContractAttribute() { } @@ -105,12 +105,12 @@ namespace System.Runtime.Serialization public override void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object graph) { } public override void WriteStartObject(System.Xml.XmlWriter writer, object graph) { } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static partial class DataContractSerializerExtensions { - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Runtime.Serialization.ISerializationSurrogateProvider GetSerializationSurrogateProvider(this System.Runtime.Serialization.DataContractSerializer serializer) { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void SetSerializationSurrogateProvider(this System.Runtime.Serialization.DataContractSerializer serializer, System.Runtime.Serialization.ISerializationSurrogateProvider provider) { } } public partial class DataContractSerializerSettings @@ -126,7 +126,7 @@ namespace System.Runtime.Serialization public System.Xml.XmlDictionaryString RootNamespace { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public bool SerializeReadOnlyTypes { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), Inherited=false, AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, Inherited=false, AllowMultiple=false)] public sealed partial class DataMemberAttribute : System.Attribute { public DataMemberAttribute() { } @@ -150,7 +150,7 @@ namespace System.Runtime.Serialization AsNeeded = 0, Never = 2, } - [System.AttributeUsageAttribute((System.AttributeTargets)(256), Inherited=false, AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field, Inherited=false, AllowMultiple=false)] public sealed partial class EnumMemberAttribute : System.Attribute { public EnumMemberAttribute() { } @@ -182,7 +182,7 @@ namespace System.Runtime.Serialization { System.Runtime.Serialization.ExtensionDataObject ExtensionData { get; set; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(384), Inherited=false, AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, Inherited=false, AllowMultiple=false)] public sealed partial class IgnoreDataMemberAttribute : System.Attribute { public IgnoreDataMemberAttribute() { } @@ -214,7 +214,7 @@ namespace System.Runtime.Serialization object GetObjectToSerialize(object obj, System.Type targetType); System.Type GetSurrogateType(System.Type type); } - [System.AttributeUsageAttribute((System.AttributeTargets)(12), Inherited=true, AllowMultiple=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Struct, Inherited=true, AllowMultiple=true)] public sealed partial class KnownTypeAttribute : System.Attribute { public KnownTypeAttribute(string methodName) { } @@ -280,8 +280,8 @@ namespace System.Runtime.Serialization } public static partial class XPathQueryGenerator { - public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, System.Text.StringBuilder rootElementXpath, out System.Xml.XmlNamespaceManager namespaces) { namespaces = default(System.Xml.XmlNamespaceManager); throw null; } - public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, out System.Xml.XmlNamespaceManager namespaces) { namespaces = default(System.Xml.XmlNamespaceManager); throw null; } + public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, System.Text.StringBuilder rootElementXpath, out System.Xml.XmlNamespaceManager namespaces) { throw null; } + public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, out System.Xml.XmlNamespaceManager namespaces) { throw null; } } public partial class XsdDataContractExporter { @@ -331,10 +331,10 @@ namespace System.Runtime.Serialization.Configuration { public DeclaredTypeElement() { } public DeclaredTypeElement(string typeName) { } - [System.Configuration.ConfigurationPropertyAttribute("", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(1))] + [System.Configuration.ConfigurationPropertyAttribute("", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.IsDefaultCollection)] public System.Runtime.Serialization.Configuration.TypeElementCollection KnownTypes { get { throw null; } } protected override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } } - [System.Configuration.ConfigurationPropertyAttribute("type", DefaultValue="", Options=(System.Configuration.ConfigurationPropertyOptions)(4))] + [System.Configuration.ConfigurationPropertyAttribute("type", DefaultValue="", Options=System.Configuration.ConfigurationPropertyOptions.IsKey)] public string Type { get { throw null; } set { } } [System.Security.SecuritySafeCriticalAttribute] protected override void PostDeserialize() { } @@ -370,7 +370,7 @@ namespace System.Runtime.Serialization.Configuration [System.Configuration.ConfigurationPropertyAttribute("index", DefaultValue=0)] [System.Configuration.IntegerValidatorAttribute(MinValue=0)] public int Index { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(1))] + [System.Configuration.ConfigurationPropertyAttribute("", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.IsDefaultCollection)] public System.Runtime.Serialization.Configuration.ParameterElementCollection Parameters { get { throw null; } } protected override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } } [System.Configuration.ConfigurationPropertyAttribute("type", DefaultValue="")] @@ -379,7 +379,7 @@ namespace System.Runtime.Serialization.Configuration protected override void PostDeserialize() { } protected override void PreSerialize(System.Xml.XmlWriter writer) { } } - [System.Configuration.ConfigurationCollectionAttribute(typeof(System.Runtime.Serialization.Configuration.ParameterElement), AddItemName="parameter", CollectionType=(System.Configuration.ConfigurationElementCollectionType)(0))] + [System.Configuration.ConfigurationCollectionAttribute(typeof(System.Runtime.Serialization.Configuration.ParameterElement), AddItemName="parameter", CollectionType=System.Configuration.ConfigurationElementCollectionType.BasicMap)] public sealed partial class ParameterElementCollection : System.Configuration.ConfigurationElementCollection { public ParameterElementCollection() { } @@ -409,7 +409,7 @@ namespace System.Runtime.Serialization.Configuration [System.Configuration.ConfigurationPropertyAttribute("index", DefaultValue=0)] [System.Configuration.IntegerValidatorAttribute(MinValue=0)] public int Index { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(1))] + [System.Configuration.ConfigurationPropertyAttribute("", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.IsDefaultCollection)] public System.Runtime.Serialization.Configuration.ParameterElementCollection Parameters { get { throw null; } } protected override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } } [System.Configuration.ConfigurationPropertyAttribute("type", DefaultValue="")] @@ -417,7 +417,7 @@ namespace System.Runtime.Serialization.Configuration public string Type { get { throw null; } set { } } protected override void Reset(System.Configuration.ConfigurationElement parentElement) { } } - [System.Configuration.ConfigurationCollectionAttribute(typeof(System.Runtime.Serialization.Configuration.TypeElement), CollectionType=(System.Configuration.ConfigurationElementCollectionType)(0))] + [System.Configuration.ConfigurationCollectionAttribute(typeof(System.Runtime.Serialization.Configuration.TypeElement), CollectionType=System.Configuration.ConfigurationElementCollectionType.BasicMap)] public sealed partial class TypeElementCollection : System.Configuration.ConfigurationElementCollection { public TypeElementCollection() { } @@ -583,22 +583,22 @@ namespace System.Xml public override string ToString() { throw null; } [System.Security.SecuritySafeCriticalAttribute] public bool TryGetGuid(byte[] buffer, int offset) { throw null; } - public bool TryGetGuid(out System.Guid guid) { guid = default(System.Guid); throw null; } + public bool TryGetGuid(out System.Guid guid) { throw null; } } public partial class XmlBinaryReaderSession : System.Xml.IXmlDictionary { public XmlBinaryReaderSession() { } public System.Xml.XmlDictionaryString Add(int id, string value) { throw null; } public void Clear() { } - public bool TryLookup(int key, out System.Xml.XmlDictionaryString result) { result = default(System.Xml.XmlDictionaryString); throw null; } - public bool TryLookup(string value, out System.Xml.XmlDictionaryString result) { result = default(System.Xml.XmlDictionaryString); throw null; } - public bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result) { result = default(System.Xml.XmlDictionaryString); throw null; } + public bool TryLookup(int key, out System.Xml.XmlDictionaryString result) { throw null; } + public bool TryLookup(string value, out System.Xml.XmlDictionaryString result) { throw null; } + public bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result) { throw null; } } public partial class XmlBinaryWriterSession { public XmlBinaryWriterSession() { } public void Reset() { } - public virtual bool TryAdd(System.Xml.XmlDictionaryString value, out int key) { key = default(int); throw null; } + public virtual bool TryAdd(System.Xml.XmlDictionaryString value, out int key) { throw null; } } public partial class XmlDictionary : System.Xml.IXmlDictionary { @@ -606,9 +606,9 @@ namespace System.Xml public XmlDictionary(int capacity) { } public static System.Xml.IXmlDictionary Empty { get { throw null; } } public virtual System.Xml.XmlDictionaryString Add(string value) { throw null; } - public virtual bool TryLookup(int key, out System.Xml.XmlDictionaryString result) { result = default(System.Xml.XmlDictionaryString); throw null; } - public virtual bool TryLookup(string value, out System.Xml.XmlDictionaryString result) { result = default(System.Xml.XmlDictionaryString); throw null; } - public virtual bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result) { result = default(System.Xml.XmlDictionaryString); throw null; } + public virtual bool TryLookup(int key, out System.Xml.XmlDictionaryString result) { throw null; } + public virtual bool TryLookup(string value, out System.Xml.XmlDictionaryString result) { throw null; } + public virtual bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result) { throw null; } } public abstract partial class XmlDictionaryReader : System.Xml.XmlReader { @@ -640,14 +640,14 @@ namespace System.Xml public static System.Xml.XmlDictionaryReader CreateTextReader(System.IO.Stream stream, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; } public virtual void EndCanonicalization() { } public virtual string GetAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } - public virtual void GetNonAtomizedNames(out string localName, out string namespaceUri) { localName = default(string); namespaceUri = default(string); } + public virtual void GetNonAtomizedNames(out string localName, out string namespaceUri) { throw null; } public virtual int IndexOfLocalName(string[] localNames, string namespaceUri) { throw null; } public virtual int IndexOfLocalName(System.Xml.XmlDictionaryString[] localNames, System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual bool IsLocalName(string localName) { throw null; } public virtual bool IsLocalName(System.Xml.XmlDictionaryString localName) { throw null; } public virtual bool IsNamespaceUri(string namespaceUri) { throw null; } public virtual bool IsNamespaceUri(System.Xml.XmlDictionaryString namespaceUri) { throw null; } - public virtual bool IsStartArray(out System.Type type) { type = default(System.Type); throw null; } + public virtual bool IsStartArray(out System.Type type) { throw null; } public virtual bool IsStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } protected bool IsTextNode(System.Xml.XmlNodeType nodeType) { throw null; } public virtual void MoveToStartElement() { } @@ -684,11 +684,11 @@ namespace System.Xml public override decimal ReadContentAsDecimal() { throw null; } public override float ReadContentAsFloat() { throw null; } public virtual System.Guid ReadContentAsGuid() { throw null; } - public virtual void ReadContentAsQualifiedName(out string localName, out string namespaceUri) { localName = default(string); namespaceUri = default(string); } + public virtual void ReadContentAsQualifiedName(out string localName, out string namespaceUri) { throw null; } public override string ReadContentAsString() { throw null; } protected string ReadContentAsString(int maxStringContentLength) { throw null; } - public virtual string ReadContentAsString(string[] strings, out int index) { index = default(int); throw null; } - public virtual string ReadContentAsString(System.Xml.XmlDictionaryString[] strings, out int index) { index = default(int); throw null; } + public virtual string ReadContentAsString(string[] strings, out int index) { throw null; } + public virtual string ReadContentAsString(System.Xml.XmlDictionaryString[] strings, out int index) { throw null; } public virtual System.TimeSpan ReadContentAsTimeSpan() { throw null; } public virtual System.Xml.UniqueId ReadContentAsUniqueId() { throw null; } public virtual System.DateTime[] ReadDateTimeArray(string localName, string namespaceUri) { throw null; } @@ -731,11 +731,11 @@ namespace System.Xml public virtual System.TimeSpan[] ReadTimeSpanArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; } public virtual int ReadValueAsBase64(byte[] buffer, int offset, int count) { throw null; } public virtual void StartCanonicalization(System.IO.Stream stream, bool includeComments, string[] inclusivePrefixes) { } - public virtual bool TryGetArrayLength(out int count) { count = default(int); throw null; } - public virtual bool TryGetBase64ContentLength(out int length) { length = default(int); throw null; } - public virtual bool TryGetLocalNameAsDictionaryString(out System.Xml.XmlDictionaryString localName) { localName = default(System.Xml.XmlDictionaryString); throw null; } - public virtual bool TryGetNamespaceUriAsDictionaryString(out System.Xml.XmlDictionaryString namespaceUri) { namespaceUri = default(System.Xml.XmlDictionaryString); throw null; } - public virtual bool TryGetValueAsDictionaryString(out System.Xml.XmlDictionaryString value) { value = default(System.Xml.XmlDictionaryString); throw null; } + public virtual bool TryGetArrayLength(out int count) { throw null; } + public virtual bool TryGetBase64ContentLength(out int length) { throw null; } + public virtual bool TryGetLocalNameAsDictionaryString(out System.Xml.XmlDictionaryString localName) { throw null; } + public virtual bool TryGetNamespaceUriAsDictionaryString(out System.Xml.XmlDictionaryString namespaceUri) { throw null; } + public virtual bool TryGetValueAsDictionaryString(out System.Xml.XmlDictionaryString value) { throw null; } } public sealed partial class XmlDictionaryReaderQuotas { diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Security.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Security.cs index ec34edfb4c..33f0613a31 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Security.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Security.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Security.dll")] @@ -19,9 +19,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace System.Security.Cryptography { @@ -895,7 +895,7 @@ namespace System.Security.Cryptography.Xml [System.Runtime.InteropServices.ComVisibleAttribute(false)] [System.Security.SecuritySafeCriticalAttribute] public bool CheckSignature(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, bool verifySignatureOnly) { throw null; } - public bool CheckSignatureReturningKey(out System.Security.Cryptography.AsymmetricAlgorithm signingKey) { signingKey = default(System.Security.Cryptography.AsymmetricAlgorithm); throw null; } + public bool CheckSignatureReturningKey(out System.Security.Cryptography.AsymmetricAlgorithm signingKey) { throw null; } public void ComputeSignature() { } public void ComputeSignature(System.Security.Cryptography.KeyedHashAlgorithm macAlg) { } public virtual System.Xml.XmlElement GetIdElement(System.Xml.XmlDocument document, string idValue) { throw null; } @@ -938,6 +938,7 @@ namespace System.Security.Cryptography.Xml [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct X509IssuerSerial { + private object _dummy; public string IssuerName { get { throw null; } set { } } public string SerialNumber { get { throw null; } set { } } } @@ -1079,7 +1080,7 @@ namespace System.Security.Permissions public override System.Security.SecurityElement ToXml() { throw null; } public override System.Security.IPermission Union(System.Security.IPermission target) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(109), AllowMultiple=true, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)] [System.Security.Permissions.HostProtectionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, MayLeakOnAbort=true)] [System.SerializableAttribute] public sealed partial class DataProtectionPermissionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Activation.cs b/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Activation.cs index 7f55f60c2c..dbffc5e6b8 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Activation.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Activation.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.ServiceModel.Activation.dll")] @@ -19,9 +19,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Execution=true)] namespace System.ServiceModel { @@ -30,7 +30,7 @@ namespace System.ServiceModel { public static bool AspNetCompatibilityEnabled { get { throw null; } } public static bool MultipleSiteBindingsEnabled { get { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void EnsureInitialized() { } public static void EnsureServiceAvailable(string virtualPath) { } } @@ -43,28 +43,28 @@ namespace System.ServiceModel.Activation protected HostedTransportConfiguration() { } public abstract System.Uri[] GetBaseAddresses(string virtualPath); } - [System.AttributeUsageAttribute((System.AttributeTargets)(4))] + [System.AttributeUsageAttribute(System.AttributeTargets.Class)] public sealed partial class ServiceActivationBuildProviderAttribute : System.Attribute { public ServiceActivationBuildProviderAttribute() { } } - [System.Security.SecurityCriticalAttribute((System.Security.SecurityCriticalScope)(1))] + [System.Security.SecurityCriticalAttribute(System.Security.SecurityCriticalScope.Everything)] #if SERVICEMODEL_DEP [System.ServiceModel.Activation.ServiceActivationBuildProviderAttribute] #endif #if WEB_DEP - [System.Web.Compilation.BuildProviderAppliesToAttribute((System.Web.Compilation.BuildProviderAppliesTo)(1))] + [System.Web.Compilation.BuildProviderAppliesToAttribute(System.Web.Compilation.BuildProviderAppliesTo.Web)] public sealed partial class ServiceBuildProvider : System.Web.Compilation.BuildProvider #else public sealed partial class ServiceBuildProvider #endif { - public ServiceBuildProvider() { } #if WEB_DEP + public ServiceBuildProvider() { } public override System.Web.Compilation.CompilerType CodeCompilerType { get { throw null; } } public override System.Collections.ICollection VirtualPathDependencies { get { throw null; } } public override void GenerateCode(System.Web.Compilation.AssemblyBuilder assemblyBuilder) { } - protected override System.CodeDom.CodeCompileUnit GetCodeCompileUnit(out System.Collections.IDictionary linePragmasTable) { linePragmasTable = default(System.Collections.IDictionary); throw null; } + protected override System.CodeDom.CodeCompileUnit GetCodeCompileUnit(out System.Collections.IDictionary linePragmasTable) { throw null; } public override string GetCustomString(System.CodeDom.Compiler.CompilerResults results) { throw null; } public override System.Web.Compilation.BuildProviderResultFlags GetResultFlags(System.CodeDom.Compiler.CompilerResults results) { throw null; } #endif @@ -83,7 +83,7 @@ namespace System.ServiceModel.Activation #endif } #if SERVICEMODEL_DEP - public partial class ServiceRoute : System.Web.Routing.Route + public partial class ServiceRoute : System.Web.Routing.Route #else public partial class ServiceRoute #endif @@ -96,7 +96,7 @@ namespace System.ServiceModel.Activation namespace System.ServiceModel.Activities.Activation { #if WORKFLOW_DEP - public partial class WorkflowServiceHostFactory : System.ServiceModel.Activation.ServiceHostFactoryBase + public partial class WorkflowServiceHostFactory : System.ServiceModel.Activation.ServiceHostFactoryBase #else public partial class WorkflowServiceHostFactory #endif diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Discovery.cs b/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Discovery.cs index 500b0e0c0a..ae668743ce 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Discovery.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Discovery.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.ServiceModel.Discovery.dll")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Execution=true)] namespace System.ServiceModel.Discovery { @@ -83,7 +83,7 @@ namespace System.ServiceModel.Discovery public System.ServiceModel.Discovery.EndpointDiscoveryMetadata EndpointDiscoveryMetadata { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public System.ServiceModel.Discovery.DiscoveryMessageSequence MessageSequence { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } - [System.ServiceModel.ServiceBehaviorAttribute(InstanceContextMode=(System.ServiceModel.InstanceContextMode)(2), ConcurrencyMode=(System.ServiceModel.ConcurrencyMode)(2))] + [System.ServiceModel.ServiceBehaviorAttribute(InstanceContextMode=System.ServiceModel.InstanceContextMode.Single, ConcurrencyMode=System.ServiceModel.ConcurrencyMode.Multiple)] public partial class AnnouncementService { public AnnouncementService() { } @@ -206,8 +206,8 @@ namespace System.ServiceModel.Discovery protected DiscoveryProxy(System.ServiceModel.Discovery.DiscoveryMessageSequenceGenerator messageSequenceGenerator, int duplicateMessageHistoryLength) { } protected virtual System.IAsyncResult BeginShouldRedirectFind(System.ServiceModel.Discovery.FindCriteria resolveCriteria, System.AsyncCallback callback, object state) { throw null; } protected virtual System.IAsyncResult BeginShouldRedirectResolve(System.ServiceModel.Discovery.ResolveCriteria findCriteria, System.AsyncCallback callback, object state) { throw null; } - protected virtual bool EndShouldRedirectFind(System.IAsyncResult result, out System.Collections.ObjectModel.Collection redirectionEndpoints) { redirectionEndpoints = default(System.Collections.ObjectModel.Collection); throw null; } - protected virtual bool EndShouldRedirectResolve(System.IAsyncResult result, out System.Collections.ObjectModel.Collection redirectionEndpoints) { redirectionEndpoints = default(System.Collections.ObjectModel.Collection); throw null; } + protected virtual bool EndShouldRedirectFind(System.IAsyncResult result, out System.Collections.ObjectModel.Collection redirectionEndpoints) { throw null; } + protected virtual bool EndShouldRedirectResolve(System.IAsyncResult result, out System.Collections.ObjectModel.Collection redirectionEndpoints) { throw null; } protected abstract System.IAsyncResult OnBeginFind(System.ServiceModel.Discovery.FindRequestContext findRequestContext, System.AsyncCallback callback, object state); protected abstract System.IAsyncResult OnBeginOfflineAnnouncement(System.ServiceModel.Discovery.DiscoveryMessageSequence messageSequence, System.ServiceModel.Discovery.EndpointDiscoveryMetadata endpointDiscoveryMetadata, System.AsyncCallback callback, object state); protected abstract System.IAsyncResult OnBeginOnlineAnnouncement(System.ServiceModel.Discovery.DiscoveryMessageSequence messageSequence, System.ServiceModel.Discovery.EndpointDiscoveryMetadata endpointDiscoveryMetadata, System.AsyncCallback callback, object state); @@ -430,10 +430,10 @@ namespace System.ServiceModel.Discovery.Configuration { public ContractTypeNameElement() { } public ContractTypeNameElement(string name, string ns) { } - [System.Configuration.ConfigurationPropertyAttribute("name", Options=(System.Configuration.ConfigurationPropertyOptions)(6))] + [System.Configuration.ConfigurationPropertyAttribute("name", Options=System.Configuration.ConfigurationPropertyOptions.IsKey | System.Configuration.ConfigurationPropertyOptions.IsRequired)] [System.Configuration.StringValidatorAttribute(MinLength=1)] public string Name { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("namespace", DefaultValue="http://tempuri.org/", Options=(System.Configuration.ConfigurationPropertyOptions)(4))] + [System.Configuration.ConfigurationPropertyAttribute("namespace", DefaultValue="http://tempuri.org/", Options=System.Configuration.ConfigurationPropertyOptions.IsKey)] public string Namespace { get { throw null; } set { } } protected override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } } } @@ -473,7 +473,7 @@ namespace System.ServiceModel.Discovery.Configuration public partial class DiscoveryEndpointElement : System.ServiceModel.Configuration.StandardEndpointElement { public DiscoveryEndpointElement() { } - [System.Configuration.ConfigurationPropertyAttribute("discoveryMode", DefaultValue=(System.ServiceModel.Discovery.ServiceDiscoveryMode)(1))] + [System.Configuration.ConfigurationPropertyAttribute("discoveryMode", DefaultValue=System.ServiceModel.Discovery.ServiceDiscoveryMode.Managed)] public System.ServiceModel.Discovery.ServiceDiscoveryMode DiscoveryMode { get { throw null; } set { } } [System.ComponentModel.TypeConverterAttribute(typeof(System.ServiceModel.Discovery.Configuration.DiscoveryVersionConverter))] [System.Configuration.ConfigurationPropertyAttribute("discoveryVersion", DefaultValue="WSDiscovery11")] @@ -554,7 +554,7 @@ namespace System.ServiceModel.Discovery.Configuration public ScopeElement() { } protected override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } } [System.Configuration.CallbackValidatorAttribute(CallbackMethodName="ScopeValidatorCallback", Type=typeof(System.ServiceModel.Discovery.Configuration.ScopeElement))] - [System.Configuration.ConfigurationPropertyAttribute("scope", Options=(System.Configuration.ConfigurationPropertyOptions)(6))] + [System.Configuration.ConfigurationPropertyAttribute("scope", Options=System.Configuration.ConfigurationPropertyOptions.IsKey | System.Configuration.ConfigurationPropertyOptions.IsRequired)] public System.Uri Scope { get { throw null; } set { } } } [System.Configuration.ConfigurationCollectionAttribute(typeof(System.ServiceModel.Discovery.Configuration.ScopeElement))] @@ -602,7 +602,7 @@ namespace System.ServiceModel.Discovery.Configuration public partial class UdpDiscoveryEndpointElement : System.ServiceModel.Discovery.Configuration.DiscoveryEndpointElement { public UdpDiscoveryEndpointElement() { } - [System.Configuration.ConfigurationPropertyAttribute("discoveryMode", DefaultValue=(System.ServiceModel.Discovery.ServiceDiscoveryMode)(0))] + [System.Configuration.ConfigurationPropertyAttribute("discoveryMode", DefaultValue=System.ServiceModel.Discovery.ServiceDiscoveryMode.Adhoc)] public new System.ServiceModel.Discovery.ServiceDiscoveryMode DiscoveryMode { get { throw null; } set { } } protected internal override System.Type EndpointType { get { throw null; } } [System.ComponentModel.TypeConverterAttribute("System.ServiceModel.Configuration.TimeSpanOrInfiniteConverter")] diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Routing.cs b/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Routing.cs index d269d3c5b0..96ebf51c75 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Routing.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Routing.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.ServiceModel.Routing.dll")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Execution=true)] namespace System.ServiceModel.Dispatcher { @@ -39,28 +39,28 @@ namespace System.ServiceModel.Dispatcher } namespace System.ServiceModel.Routing { - [System.ServiceModel.ServiceContractAttribute(Namespace="http://schemas.microsoft.com/netfx/2009/05/routing", SessionMode=(System.ServiceModel.SessionMode)(1), CallbackContract=typeof(System.ServiceModel.Routing.IDuplexRouterCallback))] + [System.ServiceModel.ServiceContractAttribute(Namespace="http://schemas.microsoft.com/netfx/2009/05/routing", SessionMode=System.ServiceModel.SessionMode.Required, CallbackContract=typeof(System.ServiceModel.Routing.IDuplexRouterCallback))] public partial interface IDuplexSessionRouter { [System.ServiceModel.OperationContractAttribute(AsyncPattern=true, IsOneWay=true, Action="*")] System.IAsyncResult BeginProcessMessage(System.ServiceModel.Channels.Message message, System.AsyncCallback callback, object state); void EndProcessMessage(System.IAsyncResult result); } - [System.ServiceModel.ServiceContractAttribute(Namespace="http://schemas.microsoft.com/netfx/2009/05/routing", SessionMode=(System.ServiceModel.SessionMode)(0))] + [System.ServiceModel.ServiceContractAttribute(Namespace="http://schemas.microsoft.com/netfx/2009/05/routing", SessionMode=System.ServiceModel.SessionMode.Allowed)] public partial interface IRequestReplyRouter { [System.ServiceModel.OperationContractAttribute(AsyncPattern=true, IsOneWay=false, Action="*", ReplyAction="*")] System.IAsyncResult BeginProcessRequest(System.ServiceModel.Channels.Message message, System.AsyncCallback callback, object state); System.ServiceModel.Channels.Message EndProcessRequest(System.IAsyncResult result); } - [System.ServiceModel.ServiceContractAttribute(Namespace="http://schemas.microsoft.com/netfx/2009/05/routing", SessionMode=(System.ServiceModel.SessionMode)(0))] + [System.ServiceModel.ServiceContractAttribute(Namespace="http://schemas.microsoft.com/netfx/2009/05/routing", SessionMode=System.ServiceModel.SessionMode.Allowed)] public partial interface ISimplexDatagramRouter { [System.ServiceModel.OperationContractAttribute(AsyncPattern=true, IsOneWay=true, Action="*")] System.IAsyncResult BeginProcessMessage(System.ServiceModel.Channels.Message message, System.AsyncCallback callback, object state); void EndProcessMessage(System.IAsyncResult result); } - [System.ServiceModel.ServiceContractAttribute(Namespace="http://schemas.microsoft.com/netfx/2009/05/routing", SessionMode=(System.ServiceModel.SessionMode)(1))] + [System.ServiceModel.ServiceContractAttribute(Namespace="http://schemas.microsoft.com/netfx/2009/05/routing", SessionMode=System.ServiceModel.SessionMode.Required)] public partial interface ISimplexSessionRouter { [System.ServiceModel.OperationContractAttribute(AsyncPattern=true, IsOneWay=true, Action="*")] @@ -91,22 +91,22 @@ namespace System.ServiceModel.Routing void System.ServiceModel.IExtension.Attach(System.ServiceModel.ServiceHostBase owner) { } void System.ServiceModel.IExtension.Detach(System.ServiceModel.ServiceHostBase owner) { } } - [System.ServiceModel.Activation.AspNetCompatibilityRequirementsAttribute(RequirementsMode=(System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode)(1))] - [System.ServiceModel.ServiceBehaviorAttribute(AddressFilterMode=(System.ServiceModel.AddressFilterMode)(2), InstanceContextMode=(System.ServiceModel.InstanceContextMode)(0), UseSynchronizationContext=false, ValidateMustUnderstand=false)] + [System.ServiceModel.Activation.AspNetCompatibilityRequirementsAttribute(RequirementsMode=System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Allowed)] + [System.ServiceModel.ServiceBehaviorAttribute(AddressFilterMode=System.ServiceModel.AddressFilterMode.Any, InstanceContextMode=System.ServiceModel.InstanceContextMode.PerSession, UseSynchronizationContext=false, ValidateMustUnderstand=false)] public sealed partial class RoutingService : System.IDisposable, System.ServiceModel.Routing.IDuplexSessionRouter, System.ServiceModel.Routing.IRequestReplyRouter, System.ServiceModel.Routing.ISimplexDatagramRouter, System.ServiceModel.Routing.ISimplexSessionRouter { internal RoutingService() { } void System.IDisposable.Dispose() { } - [System.ServiceModel.OperationBehaviorAttribute(Impersonation=(System.ServiceModel.ImpersonationOption)(1))] + [System.ServiceModel.OperationBehaviorAttribute(Impersonation=System.ServiceModel.ImpersonationOption.Allowed)] System.IAsyncResult System.ServiceModel.Routing.IDuplexSessionRouter.BeginProcessMessage(System.ServiceModel.Channels.Message message, System.AsyncCallback callback, object state) { throw null; } void System.ServiceModel.Routing.IDuplexSessionRouter.EndProcessMessage(System.IAsyncResult result) { } - [System.ServiceModel.OperationBehaviorAttribute(Impersonation=(System.ServiceModel.ImpersonationOption)(1))] + [System.ServiceModel.OperationBehaviorAttribute(Impersonation=System.ServiceModel.ImpersonationOption.Allowed)] System.IAsyncResult System.ServiceModel.Routing.IRequestReplyRouter.BeginProcessRequest(System.ServiceModel.Channels.Message message, System.AsyncCallback callback, object state) { throw null; } System.ServiceModel.Channels.Message System.ServiceModel.Routing.IRequestReplyRouter.EndProcessRequest(System.IAsyncResult result) { throw null; } - [System.ServiceModel.OperationBehaviorAttribute(Impersonation=(System.ServiceModel.ImpersonationOption)(1))] + [System.ServiceModel.OperationBehaviorAttribute(Impersonation=System.ServiceModel.ImpersonationOption.Allowed)] System.IAsyncResult System.ServiceModel.Routing.ISimplexDatagramRouter.BeginProcessMessage(System.ServiceModel.Channels.Message message, System.AsyncCallback callback, object state) { throw null; } void System.ServiceModel.Routing.ISimplexDatagramRouter.EndProcessMessage(System.IAsyncResult result) { } - [System.ServiceModel.OperationBehaviorAttribute(Impersonation=(System.ServiceModel.ImpersonationOption)(1))] + [System.ServiceModel.OperationBehaviorAttribute(Impersonation=System.ServiceModel.ImpersonationOption.Allowed)] System.IAsyncResult System.ServiceModel.Routing.ISimplexSessionRouter.BeginProcessMessage(System.ServiceModel.Channels.Message message, System.AsyncCallback callback, object state) { throw null; } void System.ServiceModel.Routing.ISimplexSessionRouter.EndProcessMessage(System.IAsyncResult result) { } } @@ -126,7 +126,7 @@ namespace System.ServiceModel.Routing.Configuration public partial class BackupEndpointCollection : System.Configuration.ConfigurationElementCollection { public BackupEndpointCollection() { } - [System.Configuration.ConfigurationPropertyAttribute("name", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(6))] + [System.Configuration.ConfigurationPropertyAttribute("name", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.IsKey | System.Configuration.ConfigurationPropertyOptions.IsRequired)] public string Name { get { throw null; } set { } } public void Add(System.ServiceModel.Routing.Configuration.BackupEndpointElement element) { } public void Clear() { } @@ -137,7 +137,7 @@ namespace System.ServiceModel.Routing.Configuration public partial class BackupEndpointElement : System.Configuration.ConfigurationElement { public BackupEndpointElement() { } - [System.Configuration.ConfigurationPropertyAttribute("endpointName", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(2))] + [System.Configuration.ConfigurationPropertyAttribute("endpointName", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.IsRequired)] public string EndpointName { get { throw null; } set { } } } [System.Configuration.ConfigurationCollectionAttribute(typeof(System.ServiceModel.Routing.Configuration.BackupEndpointCollection), AddItemName="backupList")] @@ -154,17 +154,17 @@ namespace System.ServiceModel.Routing.Configuration public partial class FilterElement : System.Configuration.ConfigurationElement { public FilterElement() { } - [System.Configuration.ConfigurationPropertyAttribute("customType", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(0))] + [System.Configuration.ConfigurationPropertyAttribute("customType", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.None)] public string CustomType { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("filter1", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(0))] + [System.Configuration.ConfigurationPropertyAttribute("filter1", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.None)] public string Filter1 { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("filter2", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(0))] + [System.Configuration.ConfigurationPropertyAttribute("filter2", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.None)] public string Filter2 { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("filterData", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(0))] + [System.Configuration.ConfigurationPropertyAttribute("filterData", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.None)] public string FilterData { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("filterType", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(2))] + [System.Configuration.ConfigurationPropertyAttribute("filterType", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.IsRequired)] public System.ServiceModel.Routing.Configuration.FilterType FilterType { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("name", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(6))] + [System.Configuration.ConfigurationPropertyAttribute("name", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.IsKey | System.Configuration.ConfigurationPropertyOptions.IsRequired)] public string Name { get { throw null; } set { } } } [System.Configuration.ConfigurationCollectionAttribute(typeof(System.ServiceModel.Routing.Configuration.FilterElement), AddItemName="filter")] @@ -196,7 +196,7 @@ namespace System.ServiceModel.Routing.Configuration public partial class FilterTableEntryCollection : System.Configuration.ConfigurationElementCollection { public FilterTableEntryCollection() { } - [System.Configuration.ConfigurationPropertyAttribute("name", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(6))] + [System.Configuration.ConfigurationPropertyAttribute("name", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.IsKey | System.Configuration.ConfigurationPropertyOptions.IsRequired)] public string Name { get { throw null; } set { } } public void Add(System.ServiceModel.Routing.Configuration.FilterTableEntryElement element) { } public void Clear() { } @@ -207,13 +207,13 @@ namespace System.ServiceModel.Routing.Configuration public partial class FilterTableEntryElement : System.Configuration.ConfigurationElement { public FilterTableEntryElement() { } - [System.Configuration.ConfigurationPropertyAttribute("backupList", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(0))] + [System.Configuration.ConfigurationPropertyAttribute("backupList", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.None)] public string BackupList { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("endpointName", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(6))] + [System.Configuration.ConfigurationPropertyAttribute("endpointName", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.IsKey | System.Configuration.ConfigurationPropertyOptions.IsRequired)] public string EndpointName { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("filterName", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(6))] + [System.Configuration.ConfigurationPropertyAttribute("filterName", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.IsKey | System.Configuration.ConfigurationPropertyOptions.IsRequired)] public string FilterName { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("priority", DefaultValue=0, Options=(System.Configuration.ConfigurationPropertyOptions)(0))] + [System.Configuration.ConfigurationPropertyAttribute("priority", DefaultValue=0, Options=System.Configuration.ConfigurationPropertyOptions.None)] public int Priority { get { throw null; } set { } } } public enum FilterType @@ -230,9 +230,9 @@ namespace System.ServiceModel.Routing.Configuration public partial class NamespaceElement : System.Configuration.ConfigurationElement { public NamespaceElement() { } - [System.Configuration.ConfigurationPropertyAttribute("namespace", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(2))] + [System.Configuration.ConfigurationPropertyAttribute("namespace", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.IsRequired)] public string Namespace { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("prefix", DefaultValue=null, Options=(System.Configuration.ConfigurationPropertyOptions)(6))] + [System.Configuration.ConfigurationPropertyAttribute("prefix", DefaultValue=null, Options=System.Configuration.ConfigurationPropertyOptions.IsKey | System.Configuration.ConfigurationPropertyOptions.IsRequired)] public string Prefix { get { throw null; } set { } } } [System.Configuration.ConfigurationCollectionAttribute(typeof(System.ServiceModel.Routing.Configuration.NamespaceElement))] @@ -255,7 +255,7 @@ namespace System.ServiceModel.Routing.Configuration public bool EnsureOrderedDispatch { get { throw null; } set { } } [System.Configuration.ConfigurationPropertyAttribute("filterTableName", DefaultValue=null)] public string FilterTableName { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("routeOnHeadersOnly", DefaultValue=true, Options=(System.Configuration.ConfigurationPropertyOptions)(0))] + [System.Configuration.ConfigurationPropertyAttribute("routeOnHeadersOnly", DefaultValue=true, Options=System.Configuration.ConfigurationPropertyOptions.None)] public bool RouteOnHeadersOnly { get { throw null; } set { } } [System.Configuration.ConfigurationPropertyAttribute("soapProcessingEnabled", DefaultValue=true)] public bool SoapProcessingEnabled { get { throw null; } set { } } @@ -264,13 +264,13 @@ namespace System.ServiceModel.Routing.Configuration public partial class RoutingSection : System.Configuration.ConfigurationSection { public RoutingSection() { } - [System.Configuration.ConfigurationPropertyAttribute("backupLists", Options=(System.Configuration.ConfigurationPropertyOptions)(0))] + [System.Configuration.ConfigurationPropertyAttribute("backupLists", Options=System.Configuration.ConfigurationPropertyOptions.None)] public System.ServiceModel.Routing.Configuration.BackupListCollection BackupLists { get { throw null; } } - [System.Configuration.ConfigurationPropertyAttribute("filters", Options=(System.Configuration.ConfigurationPropertyOptions)(0))] + [System.Configuration.ConfigurationPropertyAttribute("filters", Options=System.Configuration.ConfigurationPropertyOptions.None)] public System.ServiceModel.Routing.Configuration.FilterElementCollection Filters { get { throw null; } } - [System.Configuration.ConfigurationPropertyAttribute("filterTables", Options=(System.Configuration.ConfigurationPropertyOptions)(0))] + [System.Configuration.ConfigurationPropertyAttribute("filterTables", Options=System.Configuration.ConfigurationPropertyOptions.None)] public System.ServiceModel.Routing.Configuration.FilterTableCollection FilterTables { get { throw null; } } - [System.Configuration.ConfigurationPropertyAttribute("namespaceTable", Options=(System.Configuration.ConfigurationPropertyOptions)(0))] + [System.Configuration.ConfigurationPropertyAttribute("namespaceTable", Options=System.Configuration.ConfigurationPropertyOptions.None)] public System.ServiceModel.Routing.Configuration.NamespaceElementCollection NamespaceTable { get { throw null; } } public static System.ServiceModel.Dispatcher.MessageFilterTable> CreateFilterTable(string name) { throw null; } } @@ -278,7 +278,7 @@ namespace System.ServiceModel.Routing.Configuration { public SoapProcessingExtensionElement() { } public override System.Type BehaviorType { get { throw null; } } - [System.Configuration.ConfigurationPropertyAttribute("processMessages", DefaultValue=true, Options=(System.Configuration.ConfigurationPropertyOptions)(0))] + [System.Configuration.ConfigurationPropertyAttribute("processMessages", DefaultValue=true, Options=System.Configuration.ConfigurationPropertyOptions.None)] public bool ProcessMessages { get { throw null; } set { } } protected internal override object CreateBehavior() { throw null; } } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Web.cs b/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Web.cs index 80e4c49af0..de8f27f49a 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Web.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.Web.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.ServiceModel.Web.dll")] @@ -19,10 +19,10 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] [assembly:System.Security.SecurityCriticalAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Execution=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Runtime.Serialization.Json.DataContractJsonSerializer))] @@ -82,7 +82,7 @@ namespace System.ServiceModel public System.ServiceModel.Channels.WebContentTypeMapper ContentTypeMapper { get { throw null; } set { } } public bool CrossDomainScriptAccessEnabled { get { throw null; } set { } } public System.ServiceModel.EnvelopeVersion EnvelopeVersion { get { throw null; } } - [System.ComponentModel.DefaultValueAttribute((System.ServiceModel.HostNameComparisonMode)(0))] + [System.ComponentModel.DefaultValueAttribute(System.ServiceModel.HostNameComparisonMode.StrongWildcard)] public System.ServiceModel.HostNameComparisonMode HostNameComparisonMode { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute((long)524288)] public long MaxBufferPoolSize { get { throw null; } set { } } @@ -96,7 +96,7 @@ namespace System.ServiceModel public override string Scheme { get { throw null; } } public System.ServiceModel.WebHttpSecurity Security { get { throw null; } set { } } bool System.ServiceModel.Channels.IBindingRuntimePreferences.ReceiveSynchronously { get { throw null; } } - [System.ComponentModel.DefaultValueAttribute((System.ServiceModel.TransferMode)(0))] + [System.ComponentModel.DefaultValueAttribute(System.ServiceModel.TransferMode.Buffered)] public System.ServiceModel.TransferMode TransferMode { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(true)] public bool UseDefaultWebProxy { get { throw null; } set { } } @@ -104,11 +104,11 @@ namespace System.ServiceModel public System.Text.Encoding WriteEncoding { get { throw null; } set { } } public override System.ServiceModel.Channels.IChannelFactory BuildChannelFactory(System.ServiceModel.Channels.BindingParameterCollection parameters) { throw null; } public override System.ServiceModel.Channels.BindingElementCollection CreateBindingElements() { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public bool ShouldSerializeReaderQuotas() { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public bool ShouldSerializeSecurity() { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public bool ShouldSerializeWriteEncoding() { throw null; } } public sealed partial class WebHttpSecurity @@ -116,9 +116,9 @@ namespace System.ServiceModel public WebHttpSecurity() { } public System.ServiceModel.WebHttpSecurityMode Mode { get { throw null; } set { } } public System.ServiceModel.HttpTransportSecurity Transport { get { throw null; } set { } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public bool ShouldSerializeMode() { throw null; } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public bool ShouldSerializeTransport() { throw null; } } public enum WebHttpSecurityMode @@ -219,7 +219,7 @@ namespace System.ServiceModel.Configuration public string ContentTypeMapper { get { throw null; } set { } } [System.Configuration.ConfigurationPropertyAttribute("crossDomainScriptAccessEnabled", DefaultValue=false)] public bool CrossDomainScriptAccessEnabled { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("hostNameComparisonMode", DefaultValue=(System.ServiceModel.HostNameComparisonMode)(0))] + [System.Configuration.ConfigurationPropertyAttribute("hostNameComparisonMode", DefaultValue=System.ServiceModel.HostNameComparisonMode.StrongWildcard)] public System.ServiceModel.HostNameComparisonMode HostNameComparisonMode { get { throw null; } set { } } [System.Configuration.ConfigurationPropertyAttribute("maxBufferPoolSize", DefaultValue=(long)524288)] [System.Configuration.LongValidatorAttribute(MinValue=(long)0)] @@ -237,7 +237,7 @@ namespace System.ServiceModel.Configuration public System.ServiceModel.Configuration.XmlDictionaryReaderQuotasElement ReaderQuotas { get { throw null; } } [System.Configuration.ConfigurationPropertyAttribute("security")] public System.ServiceModel.Configuration.WebHttpSecurityElement Security { get { throw null; } } - [System.Configuration.ConfigurationPropertyAttribute("transferMode", DefaultValue=(System.ServiceModel.TransferMode)(0))] + [System.Configuration.ConfigurationPropertyAttribute("transferMode", DefaultValue=System.ServiceModel.TransferMode.Buffered)] public System.ServiceModel.TransferMode TransferMode { get { throw null; } set { } } [System.Configuration.ConfigurationPropertyAttribute("useDefaultWebProxy", DefaultValue=true)] public bool UseDefaultWebProxy { get { throw null; } set { } } @@ -278,14 +278,14 @@ namespace System.ServiceModel.Configuration public string ContentTypeMapper { get { throw null; } set { } } [System.Configuration.ConfigurationPropertyAttribute("crossDomainScriptAccessEnabled", DefaultValue=false)] public bool CrossDomainScriptAccessEnabled { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("defaultOutgoingResponseFormat", DefaultValue=(System.ServiceModel.Web.WebMessageFormat)(0))] + [System.Configuration.ConfigurationPropertyAttribute("defaultOutgoingResponseFormat", DefaultValue=System.ServiceModel.Web.WebMessageFormat.Xml)] public System.ServiceModel.Web.WebMessageFormat DefaultOutgoingResponseFormat { get { throw null; } set { } } protected internal override System.Type EndpointType { get { throw null; } } [System.Configuration.ConfigurationPropertyAttribute("faultExceptionEnabled", DefaultValue=false)] public bool FaultExceptionEnabled { get { throw null; } set { } } [System.Configuration.ConfigurationPropertyAttribute("helpEnabled", DefaultValue=false)] public bool HelpEnabled { get { throw null; } set { } } - [System.Configuration.ConfigurationPropertyAttribute("hostNameComparisonMode", DefaultValue=(System.ServiceModel.HostNameComparisonMode)(0))] + [System.Configuration.ConfigurationPropertyAttribute("hostNameComparisonMode", DefaultValue=System.ServiceModel.HostNameComparisonMode.StrongWildcard)] public System.ServiceModel.HostNameComparisonMode HostNameComparisonMode { get { throw null; } set { } } [System.Configuration.ConfigurationPropertyAttribute("maxBufferPoolSize", DefaultValue=(long)524288)] [System.Configuration.LongValidatorAttribute(MinValue=(long)0)] @@ -301,7 +301,7 @@ namespace System.ServiceModel.Configuration public System.ServiceModel.Configuration.XmlDictionaryReaderQuotasElement ReaderQuotas { get { throw null; } } [System.Configuration.ConfigurationPropertyAttribute("security")] public System.ServiceModel.Configuration.WebHttpSecurityElement Security { get { throw null; } } - [System.Configuration.ConfigurationPropertyAttribute("transferMode", DefaultValue=(System.ServiceModel.TransferMode)(0))] + [System.Configuration.ConfigurationPropertyAttribute("transferMode", DefaultValue=System.ServiceModel.TransferMode.Buffered)] public System.ServiceModel.TransferMode TransferMode { get { throw null; } set { } } [System.ComponentModel.TypeConverterAttribute("System.ServiceModel.Configuration.EncodingConverter")] [System.Configuration.ConfigurationPropertyAttribute("writeEncoding", DefaultValue="utf-8")] @@ -315,7 +315,7 @@ namespace System.ServiceModel.Configuration public sealed partial class WebHttpSecurityElement : System.ServiceModel.Configuration.ServiceModelConfigurationElement { public WebHttpSecurityElement() { } - [System.Configuration.ConfigurationPropertyAttribute("mode", DefaultValue=(System.ServiceModel.WebHttpSecurityMode)(0))] + [System.Configuration.ConfigurationPropertyAttribute("mode", DefaultValue=System.ServiceModel.WebHttpSecurityMode.None)] public System.ServiceModel.WebHttpSecurityMode Mode { get { throw null; } set { } } protected override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } } [System.Configuration.ConfigurationPropertyAttribute("transport")] @@ -362,7 +362,7 @@ namespace System.ServiceModel.Configuration [System.Configuration.ConfigurationPropertyAttribute("crossDomainScriptAccessEnabled", DefaultValue=false)] public bool CrossDomainScriptAccessEnabled { get { throw null; } set { } } protected internal override System.Type EndpointType { get { throw null; } } - [System.Configuration.ConfigurationPropertyAttribute("hostNameComparisonMode", DefaultValue=(System.ServiceModel.HostNameComparisonMode)(0))] + [System.Configuration.ConfigurationPropertyAttribute("hostNameComparisonMode", DefaultValue=System.ServiceModel.HostNameComparisonMode.StrongWildcard)] public System.ServiceModel.HostNameComparisonMode HostNameComparisonMode { get { throw null; } set { } } [System.Configuration.ConfigurationPropertyAttribute("maxBufferPoolSize", DefaultValue=(long)524288)] [System.Configuration.LongValidatorAttribute(MinValue=(long)0)] @@ -378,7 +378,7 @@ namespace System.ServiceModel.Configuration public System.ServiceModel.Configuration.XmlDictionaryReaderQuotasElement ReaderQuotas { get { throw null; } } [System.Configuration.ConfigurationPropertyAttribute("security")] public System.ServiceModel.Configuration.WebHttpSecurityElement Security { get { throw null; } } - [System.Configuration.ConfigurationPropertyAttribute("transferMode", DefaultValue=(System.ServiceModel.TransferMode)(0))] + [System.Configuration.ConfigurationPropertyAttribute("transferMode", DefaultValue=System.ServiceModel.TransferMode.Buffered)] public System.ServiceModel.TransferMode TransferMode { get { throw null; } set { } } [System.ComponentModel.TypeConverterAttribute("System.ServiceModel.Configuration.EncodingConverter")] [System.Configuration.ConfigurationPropertyAttribute("writeEncoding", DefaultValue="utf-8")] @@ -505,12 +505,12 @@ namespace System.ServiceModel.Dispatcher public WebHttpDispatchOperationSelector(System.ServiceModel.Description.ServiceEndpoint endpoint) { } public virtual System.UriTemplate GetUriTemplate(string operationName) { throw null; } public string SelectOperation(ref System.ServiceModel.Channels.Message message) { throw null; } - protected virtual string SelectOperation(ref System.ServiceModel.Channels.Message message, out bool uriMatched) { uriMatched = default(bool); throw null; } + protected virtual string SelectOperation(ref System.ServiceModel.Channels.Message message, out bool uriMatched) { throw null; } } } namespace System.ServiceModel.Web { - [System.AttributeUsageAttribute((System.AttributeTargets)(64))] + [System.AttributeUsageAttribute(System.AttributeTargets.Method)] public sealed partial class AspNetCacheProfileAttribute : System.Attribute, System.ServiceModel.Description.IOperationBehavior { public AspNetCacheProfileAttribute(string cacheProfileName) { } @@ -556,7 +556,7 @@ namespace System.ServiceModel.Web public System.Net.HttpStatusCode StatusCode { get { throw null; } } public string StatusDescription { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] public sealed partial class JavascriptCallbackBehaviorAttribute : System.Attribute, System.ServiceModel.Description.IContractBehavior { public JavascriptCallbackBehaviorAttribute() { } @@ -636,7 +636,7 @@ namespace System.ServiceModel.Web [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, SerializationFormatter=true)] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(64))] + [System.AttributeUsageAttribute(System.AttributeTargets.Method)] public sealed partial class WebGetAttribute : System.Attribute, System.ServiceModel.Description.IOperationBehavior { public WebGetAttribute() { } @@ -652,7 +652,7 @@ namespace System.ServiceModel.Web void System.ServiceModel.Description.IOperationBehavior.ApplyDispatchBehavior(System.ServiceModel.Description.OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation) { } void System.ServiceModel.Description.IOperationBehavior.Validate(System.ServiceModel.Description.OperationDescription operationDescription) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(64))] + [System.AttributeUsageAttribute(System.AttributeTargets.Method)] public sealed partial class WebInvokeAttribute : System.Attribute, System.ServiceModel.Description.IOperationBehavior { public WebInvokeAttribute() { } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.cs.REMOVED.git-id index f9addf3cfd..b191c3a54a 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.ServiceModel.cs.REMOVED.git-id @@ -1 +1 @@ -5d01b24ff59b0a7b37cefec29de80b4828bbbf83 \ No newline at end of file +4af041ea483f330afad9969623e2032f16d1c287 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.ServiceProcess.cs b/external/binary-reference-assemblies/src/v4.7.2/System.ServiceProcess.cs index b0c18f41a9..43179349cb 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.ServiceProcess.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.ServiceProcess.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.ServiceProcess.dll")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] namespace System.ServiceProcess { @@ -62,11 +62,11 @@ namespace System.ServiceProcess [System.ComponentModel.DefaultValueAttribute(true)] public bool CanStop { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual System.Diagnostics.EventLog EventLog { get { throw null; } } [System.Runtime.InteropServices.ComVisibleAttribute(false)] public int ExitCode { get { throw null; } set { } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(2))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] protected System.IntPtr ServiceHandle { get { throw null; } } [System.ComponentModel.TypeConverterAttribute("System.Diagnostics.Design.StringValueConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [System.ServiceProcess.ServiceProcessDescriptionAttribute("SBServiceName")] @@ -84,7 +84,7 @@ namespace System.ServiceProcess public void RequestAdditionalTime(int milliseconds) { } public static void Run(System.ServiceProcess.ServiceBase service) { } public static void Run(System.ServiceProcess.ServiceBase[] services) { } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Runtime.InteropServices.ComVisibleAttribute(false)] public void ServiceMainCallback(int argCount, System.IntPtr argPointer) { } public void Stop() { } @@ -96,19 +96,19 @@ namespace System.ServiceProcess public ServiceController() { } public ServiceController(string name) { } public ServiceController(string name, string machineName) { } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ServiceProcess.ServiceProcessDescriptionAttribute("SPCanPauseAndContinue")] public bool CanPauseAndContinue { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ServiceProcess.ServiceProcessDescriptionAttribute("SPCanShutdown")] public bool CanShutdown { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ServiceProcess.ServiceProcessDescriptionAttribute("SPCanStop")] public bool CanStop { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ServiceProcess.ServiceProcessDescriptionAttribute("SPDependentServices")] public System.ServiceProcess.ServiceController[] DependentServices { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.ReadOnlyAttribute(true)] [System.ServiceProcess.ServiceProcessDescriptionAttribute("SPDisplayName")] public string DisplayName { get { throw null; } set { } } @@ -118,7 +118,7 @@ namespace System.ServiceProcess [System.ServiceProcess.ServiceProcessDescriptionAttribute("SPMachineName")] public string MachineName { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public System.Runtime.InteropServices.SafeHandle ServiceHandle { get { throw null; } } [System.ComponentModel.DefaultValueAttribute("")] [System.ComponentModel.ReadOnlyAttribute(true)] @@ -126,16 +126,16 @@ namespace System.ServiceProcess [System.ComponentModel.TypeConverterAttribute("System.ServiceProcess.Design.ServiceNameConverter")] [System.ServiceProcess.ServiceProcessDescriptionAttribute("SPServiceName")] public string ServiceName { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ServiceProcess.ServiceProcessDescriptionAttribute("SPServicesDependedOn")] public System.ServiceProcess.ServiceController[] ServicesDependedOn { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ServiceProcess.ServiceProcessDescriptionAttribute("SPServiceType")] public System.ServiceProcess.ServiceType ServiceType { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ServiceProcess.ServiceProcessDescriptionAttribute("SPStartType")] public System.ServiceProcess.ServiceStartMode StartType { get { throw null; } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ServiceProcess.ServiceProcessDescriptionAttribute("SPStatus")] public System.ServiceProcess.ServiceControllerStatus Status { get { throw null; } } public void Close() { } @@ -170,7 +170,7 @@ namespace System.ServiceProcess Control = 6, None = 0, } - [System.AttributeUsageAttribute((System.AttributeTargets)(621), AllowMultiple=true, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Event | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)] [System.SerializableAttribute] public partial class ServiceControllerPermissionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute { @@ -236,7 +236,7 @@ namespace System.ServiceProcess public string ServiceName { get { throw null; } set { } } [System.ServiceProcess.ServiceProcessDescriptionAttribute("ServiceInstallerServicesDependedOn")] public string[] ServicesDependedOn { get { throw null; } set { } } - [System.ComponentModel.DefaultValueAttribute((System.ServiceProcess.ServiceStartMode)(3))] + [System.ComponentModel.DefaultValueAttribute(System.ServiceProcess.ServiceStartMode.Manual)] [System.ServiceProcess.ServiceProcessDescriptionAttribute("ServiceInstallerStartType")] public System.ServiceProcess.ServiceStartMode StartType { get { throw null; } set { } } public override void CopyFromComponent(System.ComponentModel.IComponent component) { } @@ -245,7 +245,7 @@ namespace System.ServiceProcess public override void Rollback(System.Collections.IDictionary savedState) { } public override void Uninstall(System.Collections.IDictionary savedState) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(32767))] + [System.AttributeUsageAttribute(System.AttributeTargets.All)] public partial class ServiceProcessDescriptionAttribute : System.ComponentModel.DescriptionAttribute { public ServiceProcessDescriptionAttribute(string description) { } @@ -254,7 +254,7 @@ namespace System.ServiceProcess public partial class ServiceProcessInstaller : System.Configuration.Install.ComponentInstaller { public ServiceProcessInstaller() { } - [System.ComponentModel.DefaultValueAttribute((System.ServiceProcess.ServiceAccount)(3))] + [System.ComponentModel.DefaultValueAttribute(System.ServiceProcess.ServiceAccount.User)] [System.ServiceProcess.ServiceProcessDescriptionAttribute("ServiceProcessInstallerAccount")] public System.ServiceProcess.ServiceAccount Account { get { throw null; } set { } } public override string HelpText { get { throw null; } } @@ -289,6 +289,7 @@ namespace System.ServiceProcess [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct SessionChangeDescription { + private int _dummyPrimitive; public System.ServiceProcess.SessionChangeReason Reason { get { throw null; } } public int SessionId { get { throw null; } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Transactions.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Transactions.cs index c1b36b3458..baeb4ae041 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Transactions.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Transactions.cs @@ -19,9 +19,9 @@ [assembly:System.Runtime.InteropServices.BestFitMappingAttribute(false)] [assembly:System.Runtime.InteropServices.ComCompatibleVersionAttribute(1, 0, 3300, 0)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum)] namespace System.Transactions { @@ -62,7 +62,7 @@ namespace System.Transactions public override System.Security.SecurityElement ToXml() { throw null; } public override System.Security.IPermission Union(System.Security.IPermission target) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(32767), AllowMultiple=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.All, AllowMultiple=true)] public sealed partial class DistributedTransactionPermissionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute { public DistributedTransactionPermissionAttribute(System.Security.Permissions.SecurityAction action) : base (default(System.Security.Permissions.SecurityAction)) { } @@ -88,7 +88,7 @@ namespace System.Transactions } public delegate System.Transactions.Transaction HostCurrentTransactionCallback(); [System.Runtime.InteropServices.GuidAttribute("0fb15084-af41-11ce-bd2b-204c4f4f5020")] - [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))] + [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface IDtcTransaction { void Abort(System.IntPtr reason, int retaining, int async); @@ -261,6 +261,7 @@ namespace System.Transactions [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct TransactionOptions { + private int _dummyPrimitive; public System.Transactions.IsolationLevel IsolationLevel { get { throw null; } set { } } public System.TimeSpan Timeout { get { throw null; } set { } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Web.Abstractions.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Web.Abstractions.cs index c25a207ffa..6ecac805b8 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Web.Abstractions.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Web.Abstractions.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Web.Abstractions.dll")] @@ -19,9 +19,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] -[assembly:System.Security.AllowPartiallyTrustedCallersAttribute(PartialTrustVisibilityLevel=(System.Security.PartialTrustVisibilityLevel)(1))] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] +[assembly:System.Security.AllowPartiallyTrustedCallersAttribute(PartialTrustVisibilityLevel=System.Security.PartialTrustVisibilityLevel.NotVisibleByDefault)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Execution=true)] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Web.HttpApplicationStateBase))] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Web.HttpApplicationStateWrapper))] diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Web.ApplicationServices.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Web.ApplicationServices.cs index 90a0f951a6..2c2937dd35 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Web.ApplicationServices.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Web.ApplicationServices.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Web.ApplicationServices.dll")] @@ -19,9 +19,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] -[assembly:System.Security.AllowPartiallyTrustedCallersAttribute(PartialTrustVisibilityLevel=(System.Security.PartialTrustVisibilityLevel)(1))] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] +[assembly:System.Security.AllowPartiallyTrustedCallersAttribute(PartialTrustVisibilityLevel=System.Security.PartialTrustVisibilityLevel.NotVisibleByDefault)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] namespace System.Web.Configuration { public enum MembershipPasswordCompatibilityMode @@ -32,7 +32,7 @@ namespace System.Web.Configuration } namespace System.Web.Hosting { - [System.AttributeUsageAttribute((System.AttributeTargets)(1), AllowMultiple=false, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly, AllowMultiple=false, Inherited=false)] public sealed partial class CustomLoaderAttribute : System.Attribute { public CustomLoaderAttribute(System.Type customLoaderType) { } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Web.DynamicData.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Web.DynamicData.cs index 9bdd9ef4f4..0a712856a6 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Web.DynamicData.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Web.DynamicData.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Drawing.BitmapSuffixInSatelliteAssemblyAttribute] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] @@ -20,9 +20,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] -[assembly:System.Security.AllowPartiallyTrustedCallersAttribute(PartialTrustVisibilityLevel=(System.Security.PartialTrustVisibilityLevel)(1))] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] +[assembly:System.Security.AllowPartiallyTrustedCallersAttribute(PartialTrustVisibilityLevel=System.Security.PartialTrustVisibilityLevel.NotVisibleByDefault)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.SecurityTransparentAttribute] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Execution=true)] namespace System.Web.DynamicData @@ -104,7 +104,7 @@ namespace System.Web.DynamicData [System.ComponentModel.DefaultValueAttribute(true)] public bool HtmlEncode { get { throw null; } set { } } [System.ComponentModel.CategoryAttribute("Behavior")] - [System.ComponentModel.DefaultValueAttribute((System.Web.UI.WebControls.DataBoundControlMode)(0))] + [System.ComponentModel.DefaultValueAttribute(System.Web.UI.WebControls.DataBoundControlMode.ReadOnly)] public System.Web.UI.WebControls.DataBoundControlMode Mode { get { throw null; } set { } } [System.ComponentModel.CategoryAttribute("Behavior")] [System.ComponentModel.DefaultValueAttribute("")] @@ -154,8 +154,8 @@ namespace System.Web.DynamicData public static void SetMetaTable(this System.Web.UI.INamingContainer control, System.Web.DynamicData.MetaTable table) { } public static void SetMetaTable(this System.Web.UI.INamingContainer control, System.Web.DynamicData.MetaTable table, System.Collections.Generic.IDictionary defaultValues) { } public static void SetMetaTable(this System.Web.UI.INamingContainer control, System.Web.DynamicData.MetaTable table, object defaultValues) { } - public static bool TryGetMetaTable(this System.Web.UI.IDataSource dataSource, out System.Web.DynamicData.MetaTable table) { table = default(System.Web.DynamicData.MetaTable); throw null; } - public static bool TryGetMetaTable(this System.Web.UI.INamingContainer control, out System.Web.DynamicData.MetaTable table) { table = default(System.Web.DynamicData.MetaTable); throw null; } + public static bool TryGetMetaTable(this System.Web.UI.IDataSource dataSource, out System.Web.DynamicData.MetaTable table) { throw null; } + public static bool TryGetMetaTable(this System.Web.UI.INamingContainer control, out System.Web.DynamicData.MetaTable table) { throw null; } } [System.ComponentModel.DesignerAttribute("System.Web.DynamicData.Design.DynamicDataManagerDesigner, System.Web.DynamicData.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] [System.Drawing.ToolboxBitmapAttribute(typeof(System.Web.DynamicData.DynamicDataManager), "DynamicDataManager.bmp")] @@ -169,21 +169,21 @@ namespace System.Web.DynamicData [System.ComponentModel.DefaultValueAttribute(false)] public bool AutoLoadForeignKeys { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ClientID { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override System.Web.UI.ClientIDMode ClientIDMode { get { throw null; } set { } } [System.ComponentModel.CategoryAttribute("Behavior")] [System.ComponentModel.DefaultValueAttribute(null)] [System.ComponentModel.MergablePropertyAttribute(false)] - [System.Web.UI.PersistenceModeAttribute((System.Web.UI.PersistenceMode)(1))] + [System.Web.UI.PersistenceModeAttribute(System.Web.UI.PersistenceMode.InnerProperty)] public System.Web.DynamicData.DataControlReferenceCollection DataControls { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Visible { get { throw null; } set { } } protected override void OnInit(System.EventArgs e) { } protected override void OnLoad(System.EventArgs e) { } @@ -220,7 +220,7 @@ namespace System.Web.DynamicData { public DynamicEntity() { } [System.ComponentModel.CategoryAttribute("Behavior")] - [System.ComponentModel.DefaultValueAttribute((System.Web.UI.WebControls.DataBoundControlMode)(0))] + [System.ComponentModel.DefaultValueAttribute(System.Web.UI.WebControls.DataBoundControlMode.ReadOnly)] public System.Web.UI.WebControls.DataBoundControlMode Mode { get { throw null; } set { } } [System.ComponentModel.CategoryAttribute("Behavior")] [System.ComponentModel.DefaultValueAttribute("")] @@ -264,7 +264,7 @@ namespace System.Web.DynamicData [System.ComponentModel.DefaultValueAttribute("")] public virtual string UIHint { get { throw null; } set { } } [System.ComponentModel.CategoryAttribute("Behavior")] - [System.ComponentModel.DefaultValueAttribute((System.Web.UI.ValidateRequestMode)(0))] + [System.ComponentModel.DefaultValueAttribute(System.Web.UI.ValidateRequestMode.Inherit)] public new System.Web.UI.ValidateRequestMode ValidateRequestMode { get { throw null; } set { } } [System.ComponentModel.CategoryAttribute("Behavior")] [System.ComponentModel.DefaultValueAttribute("")] @@ -286,7 +286,7 @@ namespace System.Web.DynamicData [System.ComponentModel.DefaultValueAttribute("")] public string DataField { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public System.Web.UI.Control FilterTemplate { get { throw null; } } [System.ComponentModel.CategoryAttribute("Behavior")] [System.ComponentModel.DefaultValueAttribute("")] @@ -363,7 +363,7 @@ namespace System.Web.DynamicData public EntityTemplate() { } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DefaultValueAttribute(null)] - [System.Web.UI.PersistenceModeAttribute((System.Web.UI.PersistenceMode)(1))] + [System.Web.UI.PersistenceModeAttribute(System.Web.UI.PersistenceMode.InnerProperty)] [System.Web.UI.TemplateContainerAttribute(typeof(System.Web.UI.INamingContainer))] public virtual System.Web.UI.ITemplate ItemTemplate { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } } @@ -630,8 +630,8 @@ namespace System.Web.DynamicData public void RegisterContext(System.Web.DynamicData.ModelProviders.DataModelProvider dataModelProvider) { } public virtual void RegisterContext(System.Web.DynamicData.ModelProviders.DataModelProvider dataModelProvider, System.Web.DynamicData.ContextConfiguration configuration) { } public static void ResetRegistrationException() { } - public bool TryGetTable(string uniqueTableName, out System.Web.DynamicData.MetaTable table) { table = default(System.Web.DynamicData.MetaTable); throw null; } - public bool TryGetTable(System.Type entityType, out System.Web.DynamicData.MetaTable table) { table = default(System.Web.DynamicData.MetaTable); throw null; } + public bool TryGetTable(string uniqueTableName, out System.Web.DynamicData.MetaTable table) { throw null; } + public bool TryGetTable(System.Type entityType, out System.Web.DynamicData.MetaTable table) { throw null; } } public partial class MetaTable { @@ -688,8 +688,8 @@ namespace System.Web.DynamicData protected internal virtual void Initialize() { } public void ResetMetadata() { } public override string ToString() { throw null; } - public bool TryGetColumn(string columnName, out System.Web.DynamicData.MetaColumn column) { column = default(System.Web.DynamicData.MetaColumn); throw null; } - public static bool TryGetTable(System.Type entityType, out System.Web.DynamicData.MetaTable table) { table = default(System.Web.DynamicData.MetaTable); throw null; } + public bool TryGetColumn(string columnName, out System.Web.DynamicData.MetaColumn column) { throw null; } + public static bool TryGetTable(System.Type entityType, out System.Web.DynamicData.MetaTable table) { throw null; } } public static partial class PageAction { @@ -710,7 +710,7 @@ namespace System.Web.DynamicData public string DynamicFilterContainerId { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DefaultValueAttribute(null)] - [System.Web.UI.PersistenceModeAttribute((System.Web.UI.PersistenceMode)(1))] + [System.Web.UI.PersistenceModeAttribute(System.Web.UI.PersistenceMode.InnerProperty)] [System.Web.UI.TemplateContainerAttribute(typeof(System.Web.UI.INamingContainer))] public virtual System.Web.UI.ITemplate ItemTemplate { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } protected override void OnPreRender(System.EventArgs e) { } @@ -730,7 +730,7 @@ namespace System.Web.DynamicData protected void OnFilterChanged() { } public void PopulateListControl(System.Web.UI.WebControls.ListControl listControl) { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] public sealed partial class TableNameAttribute : System.Attribute { public TableNameAttribute(string name) { } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Web.Extensions.Design.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Web.Extensions.Design.cs index 365e47cc7c..d31ab098ec 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Web.Extensions.Design.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Web.Extensions.Design.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Drawing.BitmapSuffixInSatelliteAssemblyAttribute] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] @@ -20,7 +20,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Web.UI.WebResourceAttribute("System.Web.Resources.Design.Background.gif", "image/gif")] namespace System.Web.UI.Design { @@ -170,7 +170,7 @@ namespace System.Web.UI.Design.WebControls public string ContextTypeName { get { throw null; } set { } } [System.ComponentModel.CategoryAttribute("Data")] [System.ComponentModel.DefaultValueAttribute(null)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.MergablePropertyAttribute(false)] [System.ComponentModel.TypeConverterAttribute("System.Web.UI.Design.WebControls.LinqDataSourceInsertUpdateDeleteStatementConverter")] public string Delete { get { throw null; } set { } } @@ -183,7 +183,7 @@ namespace System.Web.UI.Design.WebControls public string GroupBy { get { throw null; } set { } } [System.ComponentModel.CategoryAttribute("Data")] [System.ComponentModel.DefaultValueAttribute(null)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.MergablePropertyAttribute(false)] [System.ComponentModel.TypeConverterAttribute("System.Web.UI.Design.WebControls.LinqDataSourceInsertUpdateDeleteStatementConverter")] public string Insert { get { throw null; } set { } } @@ -207,7 +207,7 @@ namespace System.Web.UI.Design.WebControls public string TableName { get { throw null; } set { } } [System.ComponentModel.CategoryAttribute("Data")] [System.ComponentModel.DefaultValueAttribute(null)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [System.ComponentModel.MergablePropertyAttribute(false)] [System.ComponentModel.TypeConverterAttribute("System.Web.UI.Design.WebControls.LinqDataSourceInsertUpdateDeleteStatementConverter")] public string Update { get { throw null; } set { } } @@ -233,7 +233,7 @@ namespace System.Web.UI.Design.WebControls public bool IsDataContext { get { throw null; } } public bool IsTableTypeTable { get { throw null; } } public override System.Web.UI.Design.IDataSourceViewSchema Schema { get { throw null; } } - public override System.Collections.IEnumerable GetDesignTimeData(int minimumRows, out bool isSampleData) { isSampleData = default(bool); throw null; } + public override System.Collections.IEnumerable GetDesignTimeData(int minimumRows, out bool isSampleData) { throw null; } } public partial class ListViewDesigner : System.Web.UI.Design.WebControls.DataBoundControlDesigner { diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Web.Extensions.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.Web.Extensions.cs.REMOVED.git-id index 0cb2b75279..0b390ad59e 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Web.Extensions.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Web.Extensions.cs.REMOVED.git-id @@ -1 +1 @@ -32b3036e03fe3a73582a1c22df8aadeba3599362 \ No newline at end of file +22883bb2bcdb864cf1ae08787f722a7927d3f32e \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Web.Mobile.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Web.Mobile.cs index 0ddefe646e..0ff4fc62f3 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Web.Mobile.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Web.Mobile.cs @@ -4,13 +4,13 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Web.Mobile.dll")] [assembly:System.Reflection.AssemblyDescriptionAttribute("System.Web.Mobile.dll")] -[assembly:System.Reflection.AssemblyFileVersionAttribute("4.7.2558.0")] -[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.7.2558.0")] +[assembly:System.Reflection.AssemblyFileVersionAttribute("4.7.3062.0")] +[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.7.3062.0")] [assembly:System.Reflection.AssemblyProductAttribute("Mono Common Language Infrastructure")] [assembly:System.Reflection.AssemblyTitleAttribute("System.Web.Mobile.dll")] [assembly:System.Resources.NeutralResourcesLanguageAttribute("en-US")] @@ -19,6 +19,6 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Web.RegularExpressions.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Web.RegularExpressions.cs index 84ecfd4037..02c58ee05b 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Web.RegularExpressions.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Web.RegularExpressions.cs @@ -18,8 +18,8 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.SecurityTransparentAttribute] namespace System.Web.RegularExpressions { diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Web.Routing.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Web.Routing.cs index 1af8314574..4b8a233733 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Web.Routing.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Web.Routing.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Web.Routing.dll")] @@ -19,9 +19,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] -[assembly:System.Security.AllowPartiallyTrustedCallersAttribute(PartialTrustVisibilityLevel=(System.Security.PartialTrustVisibilityLevel)(1))] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] +[assembly:System.Security.AllowPartiallyTrustedCallersAttribute(PartialTrustVisibilityLevel=System.Security.PartialTrustVisibilityLevel.NotVisibleByDefault)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Security.SecurityTransparentAttribute] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Execution=true)] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Web.Routing.HttpMethodConstraint))] diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Web.Services.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.Web.Services.cs.REMOVED.git-id index 0d8c40341c..48b91772fb 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Web.Services.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Web.Services.cs.REMOVED.git-id @@ -1 +1 @@ -02589ecdb065b3670fb87c820f88a851496156ea \ No newline at end of file +1518146629f0249fcc04dafc61d21735eb1d78c6 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Web.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.Web.cs.REMOVED.git-id index 0119e725b1..c7a00e4770 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Web.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Web.cs.REMOVED.git-id @@ -1 +1 @@ -362e6367f2d6f1eec01369224034a684bde8b52c \ No newline at end of file +a55fbabb5222683ba50f4524c26bf3d785b7910b \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Windows.Forms.DataVisualization.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.Windows.Forms.DataVisualization.cs.REMOVED.git-id index 923d96f29a..204ac54206 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Windows.Forms.DataVisualization.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Windows.Forms.DataVisualization.cs.REMOVED.git-id @@ -1 +1 @@ -db4ebbff29afe2ca0772b5e1bc32ecd09ab8b5d8 \ No newline at end of file +df6a9ef1c6c8b4e58805304a041136b8bddc9b71 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Windows.Forms.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.Windows.Forms.cs.REMOVED.git-id index e45fbdc2b6..caf44ff36b 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Windows.Forms.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Windows.Forms.cs.REMOVED.git-id @@ -1 +1 @@ -475846a23eba2cafd545a49242827317c5c865bb \ No newline at end of file +6fbe7e8658fb1ff09615242713b1f38da6ea1b26 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Windows.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Windows.cs index 50c91a82ff..6c9ffbbe35 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Windows.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Windows.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Windows.dll")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Collections.ObjectModel.ObservableCollection<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Collections.ObjectModel.ReadOnlyObservableCollection<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Collections.Specialized.INotifyCollectionChanged))] diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Workflow.Activities.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Workflow.Activities.cs index 6fe4083fa9..1022f3b983 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Workflow.Activities.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Workflow.Activities.cs @@ -4,13 +4,13 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Workflow.Activities.dll")] [assembly:System.Reflection.AssemblyDescriptionAttribute("System.Workflow.Activities.dll")] -[assembly:System.Reflection.AssemblyFileVersionAttribute("4.7.2558.0")] -[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.7.2558.0")] +[assembly:System.Reflection.AssemblyFileVersionAttribute("4.7.3062.0")] +[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.7.3062.0")] [assembly:System.Reflection.AssemblyProductAttribute("Mono Common Language Infrastructure")] [assembly:System.Reflection.AssemblyTitleAttribute("System.Workflow.Activities.dll")] [assembly:System.Resources.NeutralResourcesLanguageAttribute("en-US")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] #if false [assembly:System.Workflow.ComponentModel.Serialization.XmlnsDefinitionAttribute("http://schemas.microsoft.com/winfx/2006/xaml/workflow", "System.Workflow.Activities")] [assembly:System.Workflow.ComponentModel.Serialization.XmlnsDefinitionAttribute("http://schemas.microsoft.com/winfx/2006/xaml/workflow", "System.Workflow.Activities.Rules")] diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Workflow.ComponentModel.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Workflow.ComponentModel.cs index 57e1221fbc..db09fc4d0b 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Workflow.ComponentModel.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Workflow.ComponentModel.cs @@ -4,13 +4,13 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Workflow.ComponentModel.dll")] [assembly:System.Reflection.AssemblyDescriptionAttribute("System.Workflow.ComponentModel.dll")] -[assembly:System.Reflection.AssemblyFileVersionAttribute("4.7.2558.0")] -[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.7.2558.0")] +[assembly:System.Reflection.AssemblyFileVersionAttribute("4.7.3062.0")] +[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.7.3062.0")] [assembly:System.Reflection.AssemblyProductAttribute("Mono Common Language Infrastructure")] [assembly:System.Reflection.AssemblyTitleAttribute("System.Workflow.ComponentModel.dll")] [assembly:System.Resources.NeutralResourcesLanguageAttribute("en-US")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] #if false [assembly:System.Workflow.ComponentModel.Serialization.XmlnsDefinitionAttribute("http://schemas.microsoft.com/winfx/2006/xaml", "System.Workflow.ComponentModel.Serialization")] [assembly:System.Workflow.ComponentModel.Serialization.XmlnsDefinitionAttribute("http://schemas.microsoft.com/winfx/2006/xaml/workflow", "System.Workflow.ComponentModel")] @@ -27,4 +27,4 @@ [assembly:System.Workflow.ComponentModel.Serialization.XmlnsDefinitionAttribute("http://schemas.microsoft.com/winfx/2006/xaml/workflow", "System.Workflow.ComponentModel.Design")] [assembly:System.Workflow.ComponentModel.Serialization.XmlnsPrefixAttribute("http://schemas.microsoft.com/winfx/2006/xaml", "x")] [assembly:System.Workflow.ComponentModel.Serialization.XmlnsPrefixAttribute("http://schemas.microsoft.com/winfx/2006/xaml/workflow", "wf")] -#endif +#endif \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Workflow.Runtime.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Workflow.Runtime.cs index 7b1543e36d..39935091d6 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Workflow.Runtime.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Workflow.Runtime.cs @@ -4,13 +4,13 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Workflow.Runtime.dll")] [assembly:System.Reflection.AssemblyDescriptionAttribute("System.Workflow.Runtime.dll")] -[assembly:System.Reflection.AssemblyFileVersionAttribute("4.7.2558.0")] -[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.7.2558.0")] +[assembly:System.Reflection.AssemblyFileVersionAttribute("4.7.3062.0")] +[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.7.3062.0")] [assembly:System.Reflection.AssemblyProductAttribute("Mono Common Language Infrastructure")] [assembly:System.Reflection.AssemblyTitleAttribute("System.Workflow.Runtime.dll")] [assembly:System.Resources.NeutralResourcesLanguageAttribute("en-US")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] #if false [assembly:System.Workflow.ComponentModel.Serialization.XmlnsDefinitionAttribute("http://schemas.microsoft.com/winfx/2006/xaml/workflow", "System.Workflow.Runtime")] [assembly:System.Workflow.ComponentModel.Serialization.XmlnsDefinitionAttribute("http://schemas.microsoft.com/winfx/2006/xaml/workflow", "System.Workflow.Runtime.Configuration")] @@ -27,5 +27,5 @@ [assembly:System.Workflow.ComponentModel.Serialization.XmlnsDefinitionAttribute("http://schemas.microsoft.com/winfx/2006/xaml/workflow", "System.Workflow.Runtime.Tracking")] [assembly:System.Workflow.ComponentModel.Serialization.XmlnsPrefixAttribute("http://schemas.microsoft.com/winfx/2006/xaml/workflow", "wf")] #endif -[assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Flags=(System.Security.Permissions.SecurityPermissionFlag)(136))] +[assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Flags=System.Security.Permissions.SecurityPermissionFlag.Execution | System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Xaml.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Xaml.cs index ad3db1a200..5210f96178 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Xaml.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Xaml.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Xaml.dll")] @@ -19,23 +19,23 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(2), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] [assembly:System.Windows.Markup.XmlnsDefinitionAttribute("http://schemas.microsoft.com/winfx/2006/xaml", "System.Windows.Markup")] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, Execution=true)] [assembly:System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum, SkipVerification=true)] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Windows.Markup.ValueSerializerAttribute))] namespace System.Windows.Markup { - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=true, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true, Inherited=true)] [System.ObsoleteAttribute("This is not used by the XAML parser. Please look at XamlSetMarkupExtensionAttribute.")] public partial class AcceptedMarkupExtensionExpressionTypeAttribute : System.Attribute { public AcceptedMarkupExtensionExpressionTypeAttribute(System.Type type) { } public System.Type Type { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(196), Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Method | System.AttributeTargets.Property, Inherited=true)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class AmbientAttribute : System.Attribute { @@ -49,7 +49,7 @@ namespace System.Windows.Markup public ArrayExtension() { } public ArrayExtension(System.Array elements) { } public ArrayExtension(System.Type arrayType) { } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(2))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)] public System.Collections.IList Items { get { throw null; } } [System.Windows.Markup.ConstructorArgumentAttribute("type")] public System.Type Type { get { throw null; } set { } } @@ -57,14 +57,14 @@ namespace System.Windows.Markup public void AddText(string text) { } public override object ProvideValue(System.IServiceProvider serviceProvider) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(128), AllowMultiple=false, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class ConstructorArgumentAttribute : System.Attribute { public ConstructorArgumentAttribute(string argumentName) { } public string ArgumentName { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class ContentPropertyAttribute : System.Attribute { @@ -72,7 +72,7 @@ namespace System.Windows.Markup public ContentPropertyAttribute(string name) { } public string Name { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=true, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true, Inherited=true)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class ContentWrapperAttribute : System.Attribute { @@ -91,7 +91,7 @@ namespace System.Windows.Markup public override object ConvertFromString(string value, System.Windows.Markup.IValueSerializerContext context) { throw null; } public override string ConvertToString(object value, System.Windows.Markup.IValueSerializerContext context) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(192), AllowMultiple=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Method | System.AttributeTargets.Property, AllowMultiple=true)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class DependsOnAttribute : System.Attribute { @@ -99,7 +99,7 @@ namespace System.Windows.Markup public string Name { get { throw null; } } public override object TypeId { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class DictionaryKeyPropertyAttribute : System.Attribute { @@ -154,14 +154,14 @@ namespace System.Windows.Markup protected MarkupExtension() { } public abstract object ProvideValue(System.IServiceProvider serviceProvider); } - [System.AttributeUsageAttribute((System.AttributeTargets)(128), AllowMultiple=true, Inherited=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=true, Inherited=false)] public sealed partial class MarkupExtensionBracketCharactersAttribute : System.Attribute { public MarkupExtensionBracketCharactersAttribute(char openingBracket, char closingBracket) { } public char ClosingBracket { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public char OpeningBracket { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed partial class MarkupExtensionReturnTypeAttribute : System.Attribute { public MarkupExtensionReturnTypeAttribute() { } @@ -185,7 +185,7 @@ namespace System.Windows.Markup public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { throw null; } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class NameScopePropertyAttribute : System.Attribute { @@ -220,14 +220,14 @@ namespace System.Windows.Markup public string Name { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public override object ProvideValue(System.IServiceProvider serviceProvider) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(1))] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class RootNamespaceAttribute : System.Attribute { public RootNamespaceAttribute(string nameSpace) { } public string Namespace { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4))] + [System.AttributeUsageAttribute(System.AttributeTargets.Class)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class RuntimeNamePropertyAttribute : System.Attribute { @@ -247,7 +247,7 @@ namespace System.Windows.Markup public System.Type MemberType { get { throw null; } set { } } public override object ProvideValue(System.IServiceProvider serviceProvider) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class TrimSurroundingWhitespaceAttribute : System.Attribute { @@ -264,18 +264,18 @@ namespace System.Windows.Markup [System.ComponentModel.DefaultValueAttribute(null)] [System.Windows.Markup.ConstructorArgumentAttribute("type")] public System.Type Type { get { throw null; } set { } } - [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] + [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public string TypeName { get { throw null; } set { } } public override object ProvideValue(System.IServiceProvider serviceProvider) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class UidPropertyAttribute : System.Attribute { public UidPropertyAttribute(string name) { } public string Name { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed partial class UsableDuringInitializationAttribute : System.Attribute { public UsableDuringInitializationAttribute(bool usable) { } @@ -297,13 +297,13 @@ namespace System.Windows.Markup public static System.Windows.Markup.ValueSerializer GetSerializerFor(System.Type type, System.Windows.Markup.IValueSerializerContext context) { throw null; } public virtual System.Collections.Generic.IEnumerable TypeReferences(object value, System.Windows.Markup.IValueSerializerContext context) { throw null; } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class WhitespaceSignificantCollectionAttribute : System.Attribute { public WhitespaceSignificantCollectionAttribute() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(132), AllowMultiple=false, Inherited=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)] public sealed partial class XamlDeferLoadAttribute : System.Attribute { public XamlDeferLoadAttribute(string loaderType, string contentType) { } @@ -313,7 +313,7 @@ namespace System.Windows.Markup public System.Type LoaderType { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public string LoaderTypeName { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true, AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true, AllowMultiple=false)] public sealed partial class XamlSetMarkupExtensionAttribute : System.Attribute { public XamlSetMarkupExtensionAttribute(string xamlSetMarkupExtensionHandler) { } @@ -326,7 +326,7 @@ namespace System.Windows.Markup public System.IServiceProvider ServiceProvider { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public override void CallBase() { } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=true, AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true, AllowMultiple=false)] public sealed partial class XamlSetTypeConverterAttribute : System.Attribute { public XamlSetTypeConverterAttribute(string xamlSetTypeConverterHandler) { } @@ -355,14 +355,14 @@ namespace System.Windows.Markup public string Text { get { throw null; } set { } } public object XmlReader { get { throw null; } set { } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false)] + [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class XmlLangPropertyAttribute : System.Attribute { public XmlLangPropertyAttribute(string name) { } public string Name { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(1), AllowMultiple=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly, AllowMultiple=true)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class XmlnsCompatibleWithAttribute : System.Attribute { @@ -370,7 +370,7 @@ namespace System.Windows.Markup public string NewNamespace { get { throw null; } } public string OldNamespace { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(1), AllowMultiple=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly, AllowMultiple=true)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class XmlnsDefinitionAttribute : System.Attribute { @@ -379,7 +379,7 @@ namespace System.Windows.Markup public string ClrNamespace { get { throw null; } } public string XmlNamespace { get { throw null; } } } - [System.AttributeUsageAttribute((System.AttributeTargets)(1), AllowMultiple=true)] + [System.AttributeUsageAttribute(System.AttributeTargets.Assembly, AllowMultiple=true)] [System.Runtime.CompilerServices.TypeForwardedFromAttribute("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed partial class XmlnsPrefixAttribute : System.Attribute { @@ -414,8 +414,8 @@ namespace System.Xaml public static int GetAttachedPropertyCount(object instance) { throw null; } public static bool RemoveProperty(object instance, System.Xaml.AttachableMemberIdentifier name) { throw null; } public static void SetProperty(object instance, System.Xaml.AttachableMemberIdentifier name, object value) { } - public static bool TryGetProperty(object instance, System.Xaml.AttachableMemberIdentifier name, out object value) { value = default(object); throw null; } - public static bool TryGetProperty(object instance, System.Xaml.AttachableMemberIdentifier name, out T value) { value = default(T); throw null; } + public static bool TryGetProperty(object instance, System.Xaml.AttachableMemberIdentifier name, out object value) { throw null; } + public static bool TryGetProperty(object instance, System.Xaml.AttachableMemberIdentifier name, out T value) { throw null; } } public partial interface IAmbientProvider { @@ -868,7 +868,7 @@ namespace System.Xaml public virtual System.Xaml.XamlType GetXamlType(System.Type type) { throw null; } public System.Xaml.XamlType GetXamlType(System.Xaml.Schema.XamlTypeName xamlTypeName) { throw null; } protected internal virtual System.Reflection.Assembly OnAssemblyResolve(string assemblyName) { throw null; } - public virtual bool TryGetCompatibleXamlNamespace(string xamlNamespace, out string compatibleNamespace) { compatibleNamespace = default(string); throw null; } + public virtual bool TryGetCompatibleXamlNamespace(string xamlNamespace, out string compatibleNamespace) { throw null; } } public partial class XamlSchemaContextSettings { @@ -1180,8 +1180,8 @@ namespace System.Xaml.Schema public override string ToString() { throw null; } public static string ToString(System.Collections.Generic.IList typeNameList, System.Xaml.INamespacePrefixLookup prefixLookup) { throw null; } public string ToString(System.Xaml.INamespacePrefixLookup prefixLookup) { throw null; } - public static bool TryParse(string typeName, System.Xaml.IXamlNamespaceResolver namespaceResolver, out System.Xaml.Schema.XamlTypeName result) { result = default(System.Xaml.Schema.XamlTypeName); throw null; } - public static bool TryParseList(string typeNameList, System.Xaml.IXamlNamespaceResolver namespaceResolver, out System.Collections.Generic.IList result) { result = default(System.Collections.Generic.IList); throw null; } + public static bool TryParse(string typeName, System.Xaml.IXamlNamespaceResolver namespaceResolver, out System.Xaml.Schema.XamlTypeName result) { throw null; } + public static bool TryParseList(string typeNameList, System.Xaml.IXamlNamespaceResolver namespaceResolver, out System.Collections.Generic.IList result) { throw null; } } public partial class XamlTypeTypeConverter : System.ComponentModel.TypeConverter { diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Xml.Linq.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Xml.Linq.cs index 8e06855863..7e904e5c91 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Xml.Linq.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Xml.Linq.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Xml.Linq.dll")] @@ -19,9 +19,9 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Security.AllowPartiallyTrustedCallersAttribute] -[assembly:System.Security.SecurityRulesAttribute((System.Security.SecurityRuleSet)(1), SkipVerificationInFullTrust=true)] +[assembly:System.Security.SecurityRulesAttribute(System.Security.SecurityRuleSet.Level1, SkipVerificationInFullTrust=true)] namespace System.Xml.Linq { public static partial class Extensions @@ -343,7 +343,7 @@ namespace System.Xml.Linq public static implicit operator System.Xml.Linq.XName (string expandedName) { throw null; } public static bool operator !=(System.Xml.Linq.XName left, System.Xml.Linq.XName right) { throw null; } bool System.IEquatable.Equals(System.Xml.Linq.XName other) { throw null; } - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } } @@ -512,10 +512,10 @@ namespace System.Xml.XPath public static System.Collections.Generic.IEnumerable XPathSelectElements(this System.Xml.Linq.XNode node, string expression) { throw null; } public static System.Collections.Generic.IEnumerable XPathSelectElements(this System.Xml.Linq.XNode node, string expression, System.Xml.IXmlNamespaceResolver resolver) { throw null; } } - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static partial class XDocumentExtensions { - [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Xml.XPath.IXPathNavigable ToXPathNavigable(this System.Xml.Linq.XNode node) { throw null; } } } diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Xml.Serialization.cs b/external/binary-reference-assemblies/src/v4.7.2/System.Xml.Serialization.cs index dbabad7cf1..a4b17b4597 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Xml.Serialization.cs +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Xml.Serialization.cs @@ -4,7 +4,7 @@ [assembly:System.Reflection.AssemblyVersionAttribute("4.0.0.0")] [assembly:System.CLSCompliantAttribute(true)] -[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] +[assembly:System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly:System.Reflection.AssemblyCompanyAttribute("Mono development team")] [assembly:System.Reflection.AssemblyCopyrightAttribute("(c) Various Mono authors")] [assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Xml.Serialization.dll")] @@ -19,7 +19,7 @@ [assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] -[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute((System.Runtime.InteropServices.DllImportSearchPath)(2050))] +[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.ServiceModel.XmlSerializerFormatAttribute))] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Xml.Serialization.IXmlSerializable))] [assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Xml.Serialization.XmlAnyAttributeAttribute))] diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.Xml.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.Xml.cs.REMOVED.git-id index e3461de681..6b943fb08f 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.Xml.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.Xml.cs.REMOVED.git-id @@ -1 +1 @@ -4c110c77dd5c1f873b6386838d9978c617d7b331 \ No newline at end of file +d4ffeaa1d177f8adbb593ff725818b571fee34b8 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/System.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/System.cs.REMOVED.git-id index b039601e1c..6527b8ebde 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/System.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/System.cs.REMOVED.git-id @@ -1 +1 @@ -d92259cafd8a981c91d4f6c63d021f930fc9f9e8 \ No newline at end of file +57ed6d9929412c413994ef90cc64217750705736 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/WindowsBase.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/WindowsBase.cs.REMOVED.git-id index 264c3c7d96..7cd7044a9e 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/WindowsBase.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/WindowsBase.cs.REMOVED.git-id @@ -1 +1 @@ -3daf568695dc95110c526d79b88b519ba45f6b04 \ No newline at end of file +93c267163c20176dc63db81c827139a2bafd837e \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7.2/mscorlib.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7.2/mscorlib.cs.REMOVED.git-id index cf9c9e0393..f0be045b32 100644 --- a/external/binary-reference-assemblies/src/v4.7.2/mscorlib.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7.2/mscorlib.cs.REMOVED.git-id @@ -1 +1 @@ -64eba1d90031311c97e88916621477cf646f6c82 \ No newline at end of file +2ff2d350df052a548a5f413a99bad2370d332d0e \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7/Microsoft.Build.Framework.cs b/external/binary-reference-assemblies/src/v4.7/Microsoft.Build.Framework.cs index 8ecd0251fc..f0c47ac06d 100644 --- a/external/binary-reference-assemblies/src/v4.7/Microsoft.Build.Framework.cs +++ b/external/binary-reference-assemblies/src/v4.7/Microsoft.Build.Framework.cs @@ -29,6 +29,8 @@ namespace Microsoft.Build.Framework [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BuildEngineResult { + private object _dummy; + private int _dummyPrimitive; public BuildEngineResult(bool result, System.Collections.Generic.List> targetOutputsPerProject) { throw null;} public bool Result { get { throw null; } } public System.Collections.Generic.IList> TargetOutputsPerProject { get { throw null; } } diff --git a/external/binary-reference-assemblies/src/v4.7/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id index a6d8144ebd..2a47fb1cc1 100644 --- a/external/binary-reference-assemblies/src/v4.7/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7/Microsoft.Build.Tasks.v4.0.cs.REMOVED.git-id @@ -1 +1 @@ -0e4b76d79ddf28d8ae6e2f267192773ba4b28008 \ No newline at end of file +915b3c4fc0f8b2ba9a0dfeb5a71fd4b9b48e11c5 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7/Microsoft.Build.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7/Microsoft.Build.cs.REMOVED.git-id index d37824e8c8..a0a64bc9ae 100644 --- a/external/binary-reference-assemblies/src/v4.7/Microsoft.Build.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7/Microsoft.Build.cs.REMOVED.git-id @@ -1 +1 @@ -6e3d91482ed3f3afd5eac919a930eda7cba06e43 \ No newline at end of file +865287818969d5bc6c6e6ceb0436577e96f7d10d \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7/System.ComponentModel.Composition.cs b/external/binary-reference-assemblies/src/v4.7/System.ComponentModel.Composition.cs index e12c46764d..548563271a 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.ComponentModel.Composition.cs +++ b/external/binary-reference-assemblies/src/v4.7/System.ComponentModel.Composition.cs @@ -657,6 +657,8 @@ namespace System.ComponentModel.Composition.ReflectionModel [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct LazyMemberInfo { + private object _dummy; + private int _dummyPrimitive; public LazyMemberInfo(System.Reflection.MemberInfo member) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, System.Func accessorsCreator) { throw null;} public LazyMemberInfo(System.Reflection.MemberTypes memberType, params System.Reflection.MemberInfo[] accessors) { throw null;} diff --git a/external/binary-reference-assemblies/src/v4.7/System.Core.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7/System.Core.cs.REMOVED.git-id index b0b060ca16..b3a5598489 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.Core.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7/System.Core.cs.REMOVED.git-id @@ -1 +1 @@ -6a7b4a3d33b8cff8a74179bcaf9b1383f9be7c49 \ No newline at end of file +c8e2d84423685b382bdb86279db5647a0be7c85a \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7/System.Data.Entity.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7/System.Data.Entity.cs.REMOVED.git-id index 72ec74a6c7..b24f4b4c97 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.Data.Entity.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7/System.Data.Entity.cs.REMOVED.git-id @@ -1 +1 @@ -bdd6390b3a7a0f31f20b4e8a622c06f4a96d667c \ No newline at end of file +bb1ba2f36239869c45a82b8e4f97c108252a2e28 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7/System.Data.Linq.cs b/external/binary-reference-assemblies/src/v4.7/System.Data.Linq.cs index 21609f5792..cf5db54146 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.Data.Linq.cs +++ b/external/binary-reference-assemblies/src/v4.7/System.Data.Linq.cs @@ -173,6 +173,8 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EntityRef where TEntity : class { + private TEntity entity; + private object _dummy; public EntityRef(System.Collections.Generic.IEnumerable source) { throw null;} public EntityRef(System.Data.Linq.EntityRef entityRef) { throw null;} public EntityRef(TEntity entity) { throw null;} @@ -265,6 +267,9 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Link { + private T underlyingValue; + private object _dummy; + private int _dummyPrimitive; public Link(System.Collections.Generic.IEnumerable source) { throw null;} public Link(System.Data.Linq.Link link) { throw null;} public Link(T value) { throw null;} @@ -287,6 +292,7 @@ namespace System.Data.Linq [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ModifiedMemberInfo { + private object _dummy; public object CurrentValue { get { throw null; } } public System.Reflection.MemberInfo Member { get { throw null; } } public object OriginalValue { get { throw null; } } diff --git a/external/binary-reference-assemblies/src/v4.7/System.Data.OracleClient.cs b/external/binary-reference-assemblies/src/v4.7/System.Data.OracleClient.cs index a83c4ecf72..b305262551 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.Data.OracleClient.cs +++ b/external/binary-reference-assemblies/src/v4.7/System.Data.OracleClient.cs @@ -54,6 +54,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBinary : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleBinary Null; public OracleBinary(byte[] b) { throw null;} public bool IsNull { get { throw null; } } @@ -83,6 +84,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleBoolean : System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleBoolean False; public static readonly System.Data.OracleClient.OracleBoolean Null; public static readonly System.Data.OracleClient.OracleBoolean One; @@ -416,6 +418,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack=1)] public partial struct OracleDateTime : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleDateTime MaxValue; public static readonly System.Data.OracleClient.OracleDateTime MinValue; public static readonly System.Data.OracleClient.OracleDateTime Null; @@ -516,6 +519,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack=1)] public partial struct OracleMonthSpan : System.Data.SqlTypes.INullable, System.IComparable { + private int _dummyPrimitive; public static readonly System.Data.OracleClient.OracleMonthSpan MaxValue; public static readonly System.Data.OracleClient.OracleMonthSpan MinValue; public static readonly System.Data.OracleClient.OracleMonthSpan Null; @@ -547,6 +551,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack=1)] public partial struct OracleNumber : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleNumber E; public static readonly int MaxPrecision; public static readonly int MaxScale; @@ -765,6 +770,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OracleString : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleString Empty; public static readonly System.Data.OracleClient.OracleString Null; public OracleString(string s) { throw null;} @@ -796,6 +802,7 @@ namespace System.Data.OracleClient [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack=1)] public partial struct OracleTimeSpan : System.Data.SqlTypes.INullable, System.IComparable { + private object _dummy; public static readonly System.Data.OracleClient.OracleTimeSpan MaxValue; public static readonly System.Data.OracleClient.OracleTimeSpan MinValue; public static readonly System.Data.OracleClient.OracleTimeSpan Null; diff --git a/external/binary-reference-assemblies/src/v4.7/System.Data.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7/System.Data.cs.REMOVED.git-id index bc5dbd4977..203ed337f8 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.Data.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7/System.Data.cs.REMOVED.git-id @@ -1 +1 @@ -60394488d2a25a3d50e9f8d5f010f5b845ea3601 \ No newline at end of file +5cf8ea7e23a3e524ffb2d1bd79340bf08ebf4cf9 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7/System.Drawing.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7/System.Drawing.cs.REMOVED.git-id index c74a1ae50b..af6f214982 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.Drawing.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7/System.Drawing.cs.REMOVED.git-id @@ -1 +1 @@ -ecf64e1810e42ebd1ad158d60507282a5b12f757 \ No newline at end of file +4907a4af641be092f594012f2188193e9f8e4f65 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7/System.Numerics.cs b/external/binary-reference-assemblies/src/v4.7/System.Numerics.cs index db212c7a19..9344acffa2 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.Numerics.cs +++ b/external/binary-reference-assemblies/src/v4.7/System.Numerics.cs @@ -29,6 +29,8 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BigInteger : System.IComparable, System.IComparable, System.IEquatable, System.IFormattable { + private object _dummy; + private int _dummyPrimitive; [System.CLSCompliantAttribute(false)] public BigInteger(byte[] value) { throw null;} public BigInteger(decimal value) { throw null;} @@ -179,6 +181,7 @@ namespace System.Numerics [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Complex : System.IEquatable, System.IFormattable { + private int _dummyPrimitive; public static readonly System.Numerics.Complex ImaginaryOne; public static readonly System.Numerics.Complex One; public static readonly System.Numerics.Complex Zero; diff --git a/external/binary-reference-assemblies/src/v4.7/System.Security.cs b/external/binary-reference-assemblies/src/v4.7/System.Security.cs index 7642116bb0..ce2a6509a0 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.Security.cs +++ b/external/binary-reference-assemblies/src/v4.7/System.Security.cs @@ -935,6 +935,7 @@ namespace System.Security.Cryptography.Xml [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct X509IssuerSerial { + private object _dummy; public string IssuerName { get { throw null; } set { } } public string SerialNumber { get { throw null; } set { } } } diff --git a/external/binary-reference-assemblies/src/v4.7/System.ServiceProcess.cs b/external/binary-reference-assemblies/src/v4.7/System.ServiceProcess.cs index 0d3b6d3194..6ed9c7a763 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.ServiceProcess.cs +++ b/external/binary-reference-assemblies/src/v4.7/System.ServiceProcess.cs @@ -289,6 +289,7 @@ namespace System.ServiceProcess [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct SessionChangeDescription { + private int _dummyPrimitive; public System.ServiceProcess.SessionChangeReason Reason { get { throw null; } } public int SessionId { get { throw null; } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.7/System.Transactions.cs b/external/binary-reference-assemblies/src/v4.7/System.Transactions.cs index 106d2a520f..d4ad9de43f 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.Transactions.cs +++ b/external/binary-reference-assemblies/src/v4.7/System.Transactions.cs @@ -261,6 +261,7 @@ namespace System.Transactions [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct TransactionOptions { + private int _dummyPrimitive; public System.Transactions.IsolationLevel IsolationLevel { get { throw null; } set { } } public System.TimeSpan Timeout { get { throw null; } set { } } public override bool Equals(object obj) { throw null; } diff --git a/external/binary-reference-assemblies/src/v4.7/System.Web.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7/System.Web.cs.REMOVED.git-id index 96d8ee16a0..b4b44b3f88 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.Web.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7/System.Web.cs.REMOVED.git-id @@ -1 +1 @@ -dd7d2aa726b5783b24db2eadb2ab77af2410187c \ No newline at end of file +7be5a31ec5bd10142d633964f65c6e2a5a851b16 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7/System.Windows.Forms.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7/System.Windows.Forms.cs.REMOVED.git-id index 72ed0d7943..d30f990950 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.Windows.Forms.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7/System.Windows.Forms.cs.REMOVED.git-id @@ -1 +1 @@ -9dc9072e290fdf9ecf2b17133147863b686d895e \ No newline at end of file +e953b3eabc3819a60bf3835f0d24faeb5b9591ed \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7/System.Xml.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7/System.Xml.cs.REMOVED.git-id index 695c0ffcef..944f187f19 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.Xml.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7/System.Xml.cs.REMOVED.git-id @@ -1 +1 @@ -d687fa6c0344ad18bcaacb72ba5a270e08903ec6 \ No newline at end of file +5fb57f865ad7d5b9d6e4735af26747a3b265f6f7 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7/System.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7/System.cs.REMOVED.git-id index e61b69ae58..070dc0af5c 100644 --- a/external/binary-reference-assemblies/src/v4.7/System.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7/System.cs.REMOVED.git-id @@ -1 +1 @@ -258334d7654d584297c6ffec7a4a1c00343e654a \ No newline at end of file +a3ce181b7935c4d488552f9e714fb6a94e4d19cd \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7/WindowsBase.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7/WindowsBase.cs.REMOVED.git-id index 3a5941301b..88cd4ae289 100644 --- a/external/binary-reference-assemblies/src/v4.7/WindowsBase.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7/WindowsBase.cs.REMOVED.git-id @@ -1 +1 @@ -b9722e6c32abac68b4a2d58716ab5b24b87580ed \ No newline at end of file +6d17c4453875d5f8dba6e63f02f5679832e90144 \ No newline at end of file diff --git a/external/binary-reference-assemblies/src/v4.7/mscorlib.cs.REMOVED.git-id b/external/binary-reference-assemblies/src/v4.7/mscorlib.cs.REMOVED.git-id index 586b5d6ded..783f8e07a4 100644 --- a/external/binary-reference-assemblies/src/v4.7/mscorlib.cs.REMOVED.git-id +++ b/external/binary-reference-assemblies/src/v4.7/mscorlib.cs.REMOVED.git-id @@ -1 +1 @@ -387b22f3013324f6afd37ce19e985be9b24885d0 \ No newline at end of file +38a5b0321786a743168b24f010a5605a6bf48ad8 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.1/Microsoft.Build.Framework.dll b/external/binary-reference-assemblies/v4.5.1/Microsoft.Build.Framework.dll index f6cf4839c0..1e4c533409 100644 Binary files a/external/binary-reference-assemblies/v4.5.1/Microsoft.Build.Framework.dll and b/external/binary-reference-assemblies/v4.5.1/Microsoft.Build.Framework.dll differ diff --git a/external/binary-reference-assemblies/v4.5.1/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.1/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id index 12ef57cea8..520dc77caf 100644 --- a/external/binary-reference-assemblies/v4.5.1/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.1/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id @@ -1 +1 @@ -49c32525f5c1d1a6e28cd1faf36340aae892f8de \ No newline at end of file +1ed403fd5614bed6fa297719f42cec58c1507079 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.1/Microsoft.Build.dll b/external/binary-reference-assemblies/v4.5.1/Microsoft.Build.dll index 5aef2f6402..cb0cba6c60 100644 Binary files a/external/binary-reference-assemblies/v4.5.1/Microsoft.Build.dll and b/external/binary-reference-assemblies/v4.5.1/Microsoft.Build.dll differ diff --git a/external/binary-reference-assemblies/v4.5.1/System.ComponentModel.Composition.dll b/external/binary-reference-assemblies/v4.5.1/System.ComponentModel.Composition.dll index 12991f3443..c79192f610 100644 Binary files a/external/binary-reference-assemblies/v4.5.1/System.ComponentModel.Composition.dll and b/external/binary-reference-assemblies/v4.5.1/System.ComponentModel.Composition.dll differ diff --git a/external/binary-reference-assemblies/v4.5.1/System.Core.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.1/System.Core.dll.REMOVED.git-id index aa3c9fc600..7539a151a9 100644 --- a/external/binary-reference-assemblies/v4.5.1/System.Core.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.1/System.Core.dll.REMOVED.git-id @@ -1 +1 @@ -bd07ea4ab5abd4c8ae1ad78ab2da87821c9a83d2 \ No newline at end of file +dcc8755d3b789dd1746bfc154cd4815fe4188561 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.1/System.Data.Entity.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.1/System.Data.Entity.dll.REMOVED.git-id index 444c9a3bc0..c6dbc739ee 100644 --- a/external/binary-reference-assemblies/v4.5.1/System.Data.Entity.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.1/System.Data.Entity.dll.REMOVED.git-id @@ -1 +1 @@ -56cbfb21084b43e3633a286128cb3e25d31e2471 \ No newline at end of file +c9c8604d68f8944be2b422d26f48018c2d66b75a \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.1/System.Data.Linq.dll b/external/binary-reference-assemblies/v4.5.1/System.Data.Linq.dll index 12a17e4354..14cdf54bfb 100644 Binary files a/external/binary-reference-assemblies/v4.5.1/System.Data.Linq.dll and b/external/binary-reference-assemblies/v4.5.1/System.Data.Linq.dll differ diff --git a/external/binary-reference-assemblies/v4.5.1/System.Data.OracleClient.dll b/external/binary-reference-assemblies/v4.5.1/System.Data.OracleClient.dll index fccd0beda7..ce29684928 100644 Binary files a/external/binary-reference-assemblies/v4.5.1/System.Data.OracleClient.dll and b/external/binary-reference-assemblies/v4.5.1/System.Data.OracleClient.dll differ diff --git a/external/binary-reference-assemblies/v4.5.1/System.Data.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.1/System.Data.dll.REMOVED.git-id index edf9f81987..b7aa44f3e6 100644 --- a/external/binary-reference-assemblies/v4.5.1/System.Data.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.1/System.Data.dll.REMOVED.git-id @@ -1 +1 @@ -dfa9154a37a4dbfc07dbc08dec77c87c510296a8 \ No newline at end of file +2abf024af4aeaf82b4eeb5d654832109087b5ae8 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.1/System.Drawing.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.1/System.Drawing.dll.REMOVED.git-id index 5907ebfa52..602a15e70a 100644 --- a/external/binary-reference-assemblies/v4.5.1/System.Drawing.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.1/System.Drawing.dll.REMOVED.git-id @@ -1 +1 @@ -b505cff1bf7ee307902654c3b0b69b411197144a \ No newline at end of file +f14b985f3bd9bcd1478a65787efed05db3c0df34 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.1/System.Numerics.dll b/external/binary-reference-assemblies/v4.5.1/System.Numerics.dll index c4beb6b79e..449823e7fa 100644 Binary files a/external/binary-reference-assemblies/v4.5.1/System.Numerics.dll and b/external/binary-reference-assemblies/v4.5.1/System.Numerics.dll differ diff --git a/external/binary-reference-assemblies/v4.5.1/System.Security.dll b/external/binary-reference-assemblies/v4.5.1/System.Security.dll index cf9841c56c..1cdc8e384b 100644 Binary files a/external/binary-reference-assemblies/v4.5.1/System.Security.dll and b/external/binary-reference-assemblies/v4.5.1/System.Security.dll differ diff --git a/external/binary-reference-assemblies/v4.5.1/System.ServiceProcess.dll b/external/binary-reference-assemblies/v4.5.1/System.ServiceProcess.dll index e8cea607e3..d4229a8df3 100644 Binary files a/external/binary-reference-assemblies/v4.5.1/System.ServiceProcess.dll and b/external/binary-reference-assemblies/v4.5.1/System.ServiceProcess.dll differ diff --git a/external/binary-reference-assemblies/v4.5.1/System.Transactions.dll b/external/binary-reference-assemblies/v4.5.1/System.Transactions.dll index c3833ae3ac..4e57377665 100644 Binary files a/external/binary-reference-assemblies/v4.5.1/System.Transactions.dll and b/external/binary-reference-assemblies/v4.5.1/System.Transactions.dll differ diff --git a/external/binary-reference-assemblies/v4.5.1/System.Web.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.1/System.Web.dll.REMOVED.git-id index 6f733f5c3d..221bb6481d 100644 --- a/external/binary-reference-assemblies/v4.5.1/System.Web.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.1/System.Web.dll.REMOVED.git-id @@ -1 +1 @@ -3d669fb5d8c96b5de8debff246a29aad6d66ec39 \ No newline at end of file +12cd1bc0cd26528a211762c97eca2d3cbfc28e92 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.1/System.Windows.Forms.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.1/System.Windows.Forms.dll.REMOVED.git-id index 4b72d7e179..3d386aff50 100644 --- a/external/binary-reference-assemblies/v4.5.1/System.Windows.Forms.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.1/System.Windows.Forms.dll.REMOVED.git-id @@ -1 +1 @@ -4380852aa38070618e2a48b43ce64d249985ab02 \ No newline at end of file +497498c2cd16323229f65731a6e4b8009c4dde8b \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.1/System.Xml.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.1/System.Xml.dll.REMOVED.git-id index 8934c1c86f..42fe3ae813 100644 --- a/external/binary-reference-assemblies/v4.5.1/System.Xml.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.1/System.Xml.dll.REMOVED.git-id @@ -1 +1 @@ -b040218dcfb6fa185b5ceea6921092c4991b164b \ No newline at end of file +6ce573c980783797fe8a15d0b0ef5cf661cdfa15 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.1/System.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.1/System.dll.REMOVED.git-id index 88ce91b63e..49a2956fce 100644 --- a/external/binary-reference-assemblies/v4.5.1/System.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.1/System.dll.REMOVED.git-id @@ -1 +1 @@ -4d1079b06765c5434c59f9a8a6a0585c404a32b3 \ No newline at end of file +550bd72f71fa405c4d982af70d1409f903ce5086 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.1/WindowsBase.dll b/external/binary-reference-assemblies/v4.5.1/WindowsBase.dll index 08bdc74bed..18e88dcd65 100644 Binary files a/external/binary-reference-assemblies/v4.5.1/WindowsBase.dll and b/external/binary-reference-assemblies/v4.5.1/WindowsBase.dll differ diff --git a/external/binary-reference-assemblies/v4.5.1/mscorlib.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.1/mscorlib.dll.REMOVED.git-id index 2f855036c9..6f5d80405a 100644 --- a/external/binary-reference-assemblies/v4.5.1/mscorlib.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.1/mscorlib.dll.REMOVED.git-id @@ -1 +1 @@ -6b4649826d61e7a01f57c531406eba70b6d956e0 \ No newline at end of file +1d99bbc945d479eb3d3210b7f1af958b94b89b59 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.2/Microsoft.Build.Framework.dll b/external/binary-reference-assemblies/v4.5.2/Microsoft.Build.Framework.dll index f6cf4839c0..1e4c533409 100644 Binary files a/external/binary-reference-assemblies/v4.5.2/Microsoft.Build.Framework.dll and b/external/binary-reference-assemblies/v4.5.2/Microsoft.Build.Framework.dll differ diff --git a/external/binary-reference-assemblies/v4.5.2/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.2/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id index 12ef57cea8..520dc77caf 100644 --- a/external/binary-reference-assemblies/v4.5.2/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.2/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id @@ -1 +1 @@ -49c32525f5c1d1a6e28cd1faf36340aae892f8de \ No newline at end of file +1ed403fd5614bed6fa297719f42cec58c1507079 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.2/Microsoft.Build.dll b/external/binary-reference-assemblies/v4.5.2/Microsoft.Build.dll index 5aef2f6402..cb0cba6c60 100644 Binary files a/external/binary-reference-assemblies/v4.5.2/Microsoft.Build.dll and b/external/binary-reference-assemblies/v4.5.2/Microsoft.Build.dll differ diff --git a/external/binary-reference-assemblies/v4.5.2/System.ComponentModel.Composition.dll b/external/binary-reference-assemblies/v4.5.2/System.ComponentModel.Composition.dll index 12991f3443..c79192f610 100644 Binary files a/external/binary-reference-assemblies/v4.5.2/System.ComponentModel.Composition.dll and b/external/binary-reference-assemblies/v4.5.2/System.ComponentModel.Composition.dll differ diff --git a/external/binary-reference-assemblies/v4.5.2/System.Core.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.2/System.Core.dll.REMOVED.git-id index aa3c9fc600..7539a151a9 100644 --- a/external/binary-reference-assemblies/v4.5.2/System.Core.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.2/System.Core.dll.REMOVED.git-id @@ -1 +1 @@ -bd07ea4ab5abd4c8ae1ad78ab2da87821c9a83d2 \ No newline at end of file +dcc8755d3b789dd1746bfc154cd4815fe4188561 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.2/System.Data.Entity.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.2/System.Data.Entity.dll.REMOVED.git-id index 444c9a3bc0..c6dbc739ee 100644 --- a/external/binary-reference-assemblies/v4.5.2/System.Data.Entity.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.2/System.Data.Entity.dll.REMOVED.git-id @@ -1 +1 @@ -56cbfb21084b43e3633a286128cb3e25d31e2471 \ No newline at end of file +c9c8604d68f8944be2b422d26f48018c2d66b75a \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.2/System.Data.Linq.dll b/external/binary-reference-assemblies/v4.5.2/System.Data.Linq.dll index 12a17e4354..14cdf54bfb 100644 Binary files a/external/binary-reference-assemblies/v4.5.2/System.Data.Linq.dll and b/external/binary-reference-assemblies/v4.5.2/System.Data.Linq.dll differ diff --git a/external/binary-reference-assemblies/v4.5.2/System.Data.OracleClient.dll b/external/binary-reference-assemblies/v4.5.2/System.Data.OracleClient.dll index fccd0beda7..ce29684928 100644 Binary files a/external/binary-reference-assemblies/v4.5.2/System.Data.OracleClient.dll and b/external/binary-reference-assemblies/v4.5.2/System.Data.OracleClient.dll differ diff --git a/external/binary-reference-assemblies/v4.5.2/System.Data.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.2/System.Data.dll.REMOVED.git-id index edf9f81987..b7aa44f3e6 100644 --- a/external/binary-reference-assemblies/v4.5.2/System.Data.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.2/System.Data.dll.REMOVED.git-id @@ -1 +1 @@ -dfa9154a37a4dbfc07dbc08dec77c87c510296a8 \ No newline at end of file +2abf024af4aeaf82b4eeb5d654832109087b5ae8 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.2/System.Drawing.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.2/System.Drawing.dll.REMOVED.git-id index 5907ebfa52..602a15e70a 100644 --- a/external/binary-reference-assemblies/v4.5.2/System.Drawing.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.2/System.Drawing.dll.REMOVED.git-id @@ -1 +1 @@ -b505cff1bf7ee307902654c3b0b69b411197144a \ No newline at end of file +f14b985f3bd9bcd1478a65787efed05db3c0df34 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.2/System.Numerics.dll b/external/binary-reference-assemblies/v4.5.2/System.Numerics.dll index c4beb6b79e..449823e7fa 100644 Binary files a/external/binary-reference-assemblies/v4.5.2/System.Numerics.dll and b/external/binary-reference-assemblies/v4.5.2/System.Numerics.dll differ diff --git a/external/binary-reference-assemblies/v4.5.2/System.Security.dll b/external/binary-reference-assemblies/v4.5.2/System.Security.dll index cf9841c56c..1cdc8e384b 100644 Binary files a/external/binary-reference-assemblies/v4.5.2/System.Security.dll and b/external/binary-reference-assemblies/v4.5.2/System.Security.dll differ diff --git a/external/binary-reference-assemblies/v4.5.2/System.ServiceProcess.dll b/external/binary-reference-assemblies/v4.5.2/System.ServiceProcess.dll index e8cea607e3..d4229a8df3 100644 Binary files a/external/binary-reference-assemblies/v4.5.2/System.ServiceProcess.dll and b/external/binary-reference-assemblies/v4.5.2/System.ServiceProcess.dll differ diff --git a/external/binary-reference-assemblies/v4.5.2/System.Transactions.dll b/external/binary-reference-assemblies/v4.5.2/System.Transactions.dll index 672ec65b55..6011b36f87 100644 Binary files a/external/binary-reference-assemblies/v4.5.2/System.Transactions.dll and b/external/binary-reference-assemblies/v4.5.2/System.Transactions.dll differ diff --git a/external/binary-reference-assemblies/v4.5.2/System.Web.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.2/System.Web.dll.REMOVED.git-id index 388ebb7a31..382553f782 100644 --- a/external/binary-reference-assemblies/v4.5.2/System.Web.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.2/System.Web.dll.REMOVED.git-id @@ -1 +1 @@ -de3e952156ff6cfca31b47062a63169565fae5ad \ No newline at end of file +6bec325e763ab80a0c0b39b5c9139b6e7c54a755 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.2/System.Windows.Forms.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.2/System.Windows.Forms.dll.REMOVED.git-id index 4b50acb063..7fe4e51cdd 100644 --- a/external/binary-reference-assemblies/v4.5.2/System.Windows.Forms.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.2/System.Windows.Forms.dll.REMOVED.git-id @@ -1 +1 @@ -943ee937d21220472d5066c69f34525354242e6c \ No newline at end of file +a19f532414b4a790d097cde5c7a9c49468910d19 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.2/System.Xml.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.2/System.Xml.dll.REMOVED.git-id index 8934c1c86f..42fe3ae813 100644 --- a/external/binary-reference-assemblies/v4.5.2/System.Xml.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.2/System.Xml.dll.REMOVED.git-id @@ -1 +1 @@ -b040218dcfb6fa185b5ceea6921092c4991b164b \ No newline at end of file +6ce573c980783797fe8a15d0b0ef5cf661cdfa15 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.2/System.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.2/System.dll.REMOVED.git-id index 88ce91b63e..49a2956fce 100644 --- a/external/binary-reference-assemblies/v4.5.2/System.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.2/System.dll.REMOVED.git-id @@ -1 +1 @@ -4d1079b06765c5434c59f9a8a6a0585c404a32b3 \ No newline at end of file +550bd72f71fa405c4d982af70d1409f903ce5086 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5.2/WindowsBase.dll b/external/binary-reference-assemblies/v4.5.2/WindowsBase.dll index 08bdc74bed..18e88dcd65 100644 Binary files a/external/binary-reference-assemblies/v4.5.2/WindowsBase.dll and b/external/binary-reference-assemblies/v4.5.2/WindowsBase.dll differ diff --git a/external/binary-reference-assemblies/v4.5.2/mscorlib.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5.2/mscorlib.dll.REMOVED.git-id index bdb7c71737..c4629d5fe1 100644 --- a/external/binary-reference-assemblies/v4.5.2/mscorlib.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5.2/mscorlib.dll.REMOVED.git-id @@ -1 +1 @@ -eb713f28515871a001340769063ce2a264c4068e \ No newline at end of file +7a59d19271f8977b79cbb272932e645aaa291bfd \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5/Microsoft.Build.Framework.dll b/external/binary-reference-assemblies/v4.5/Microsoft.Build.Framework.dll index f6cf4839c0..1e4c533409 100644 Binary files a/external/binary-reference-assemblies/v4.5/Microsoft.Build.Framework.dll and b/external/binary-reference-assemblies/v4.5/Microsoft.Build.Framework.dll differ diff --git a/external/binary-reference-assemblies/v4.5/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id index 12ef57cea8..520dc77caf 100644 --- a/external/binary-reference-assemblies/v4.5/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id @@ -1 +1 @@ -49c32525f5c1d1a6e28cd1faf36340aae892f8de \ No newline at end of file +1ed403fd5614bed6fa297719f42cec58c1507079 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5/Microsoft.Build.dll b/external/binary-reference-assemblies/v4.5/Microsoft.Build.dll index 5aef2f6402..cb0cba6c60 100644 Binary files a/external/binary-reference-assemblies/v4.5/Microsoft.Build.dll and b/external/binary-reference-assemblies/v4.5/Microsoft.Build.dll differ diff --git a/external/binary-reference-assemblies/v4.5/System.ComponentModel.Composition.dll b/external/binary-reference-assemblies/v4.5/System.ComponentModel.Composition.dll index 12991f3443..c79192f610 100644 Binary files a/external/binary-reference-assemblies/v4.5/System.ComponentModel.Composition.dll and b/external/binary-reference-assemblies/v4.5/System.ComponentModel.Composition.dll differ diff --git a/external/binary-reference-assemblies/v4.5/System.Core.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5/System.Core.dll.REMOVED.git-id index 3b0b624e78..42f850d59e 100644 --- a/external/binary-reference-assemblies/v4.5/System.Core.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5/System.Core.dll.REMOVED.git-id @@ -1 +1 @@ -21c4c068088dcf4cc7c0c592cd80b9e645c8ea38 \ No newline at end of file +13ccaccfb9277476713c75afa1db2655e85da667 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5/System.Data.Entity.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5/System.Data.Entity.dll.REMOVED.git-id index 444c9a3bc0..c6dbc739ee 100644 --- a/external/binary-reference-assemblies/v4.5/System.Data.Entity.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5/System.Data.Entity.dll.REMOVED.git-id @@ -1 +1 @@ -56cbfb21084b43e3633a286128cb3e25d31e2471 \ No newline at end of file +c9c8604d68f8944be2b422d26f48018c2d66b75a \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5/System.Data.Linq.dll b/external/binary-reference-assemblies/v4.5/System.Data.Linq.dll index 12a17e4354..14cdf54bfb 100644 Binary files a/external/binary-reference-assemblies/v4.5/System.Data.Linq.dll and b/external/binary-reference-assemblies/v4.5/System.Data.Linq.dll differ diff --git a/external/binary-reference-assemblies/v4.5/System.Data.OracleClient.dll b/external/binary-reference-assemblies/v4.5/System.Data.OracleClient.dll index fccd0beda7..ce29684928 100644 Binary files a/external/binary-reference-assemblies/v4.5/System.Data.OracleClient.dll and b/external/binary-reference-assemblies/v4.5/System.Data.OracleClient.dll differ diff --git a/external/binary-reference-assemblies/v4.5/System.Data.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5/System.Data.dll.REMOVED.git-id index a4b100bace..ad05bf4e73 100644 --- a/external/binary-reference-assemblies/v4.5/System.Data.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5/System.Data.dll.REMOVED.git-id @@ -1 +1 @@ -aff97615be676582899823d7f592c89591fcc92a \ No newline at end of file +9a85ec364249a64f9f6dbf4c7247603e093e87f6 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5/System.Drawing.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5/System.Drawing.dll.REMOVED.git-id index 5907ebfa52..602a15e70a 100644 --- a/external/binary-reference-assemblies/v4.5/System.Drawing.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5/System.Drawing.dll.REMOVED.git-id @@ -1 +1 @@ -b505cff1bf7ee307902654c3b0b69b411197144a \ No newline at end of file +f14b985f3bd9bcd1478a65787efed05db3c0df34 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5/System.Numerics.dll b/external/binary-reference-assemblies/v4.5/System.Numerics.dll index c4beb6b79e..449823e7fa 100644 Binary files a/external/binary-reference-assemblies/v4.5/System.Numerics.dll and b/external/binary-reference-assemblies/v4.5/System.Numerics.dll differ diff --git a/external/binary-reference-assemblies/v4.5/System.Security.dll b/external/binary-reference-assemblies/v4.5/System.Security.dll index bc069719e7..fe69711b7e 100644 Binary files a/external/binary-reference-assemblies/v4.5/System.Security.dll and b/external/binary-reference-assemblies/v4.5/System.Security.dll differ diff --git a/external/binary-reference-assemblies/v4.5/System.ServiceProcess.dll b/external/binary-reference-assemblies/v4.5/System.ServiceProcess.dll index e8cea607e3..d4229a8df3 100644 Binary files a/external/binary-reference-assemblies/v4.5/System.ServiceProcess.dll and b/external/binary-reference-assemblies/v4.5/System.ServiceProcess.dll differ diff --git a/external/binary-reference-assemblies/v4.5/System.Transactions.dll b/external/binary-reference-assemblies/v4.5/System.Transactions.dll index 76046dfb37..67d644a539 100644 Binary files a/external/binary-reference-assemblies/v4.5/System.Transactions.dll and b/external/binary-reference-assemblies/v4.5/System.Transactions.dll differ diff --git a/external/binary-reference-assemblies/v4.5/System.Web.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5/System.Web.dll.REMOVED.git-id index def32ab9d2..2fddb4d9d8 100644 --- a/external/binary-reference-assemblies/v4.5/System.Web.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5/System.Web.dll.REMOVED.git-id @@ -1 +1 @@ -f53f2b0d0dcbf743adc915e8baaa8681fcf6c67a \ No newline at end of file +3037f5f61d94d57bb5a9739519ae7b2f54db39fa \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5/System.Windows.Forms.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5/System.Windows.Forms.dll.REMOVED.git-id index 4b72d7e179..3d386aff50 100644 --- a/external/binary-reference-assemblies/v4.5/System.Windows.Forms.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5/System.Windows.Forms.dll.REMOVED.git-id @@ -1 +1 @@ -4380852aa38070618e2a48b43ce64d249985ab02 \ No newline at end of file +497498c2cd16323229f65731a6e4b8009c4dde8b \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5/System.Xml.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5/System.Xml.dll.REMOVED.git-id index 8934c1c86f..42fe3ae813 100644 --- a/external/binary-reference-assemblies/v4.5/System.Xml.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5/System.Xml.dll.REMOVED.git-id @@ -1 +1 @@ -b040218dcfb6fa185b5ceea6921092c4991b164b \ No newline at end of file +6ce573c980783797fe8a15d0b0ef5cf661cdfa15 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5/System.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5/System.dll.REMOVED.git-id index 88ce91b63e..49a2956fce 100644 --- a/external/binary-reference-assemblies/v4.5/System.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5/System.dll.REMOVED.git-id @@ -1 +1 @@ -4d1079b06765c5434c59f9a8a6a0585c404a32b3 \ No newline at end of file +550bd72f71fa405c4d982af70d1409f903ce5086 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.5/WindowsBase.dll b/external/binary-reference-assemblies/v4.5/WindowsBase.dll index 08bdc74bed..18e88dcd65 100644 Binary files a/external/binary-reference-assemblies/v4.5/WindowsBase.dll and b/external/binary-reference-assemblies/v4.5/WindowsBase.dll differ diff --git a/external/binary-reference-assemblies/v4.5/mscorlib.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.5/mscorlib.dll.REMOVED.git-id index 631ac7cde2..fa16c5aefe 100644 --- a/external/binary-reference-assemblies/v4.5/mscorlib.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.5/mscorlib.dll.REMOVED.git-id @@ -1 +1 @@ -a1f479e9506cba5c8139c97eb28560b67e092e73 \ No newline at end of file +942bc6c47bda699270097ff8c86a2863f04b9213 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.1/Microsoft.Build.Framework.dll b/external/binary-reference-assemblies/v4.6.1/Microsoft.Build.Framework.dll index 84e7d57de3..01f6786306 100644 Binary files a/external/binary-reference-assemblies/v4.6.1/Microsoft.Build.Framework.dll and b/external/binary-reference-assemblies/v4.6.1/Microsoft.Build.Framework.dll differ diff --git a/external/binary-reference-assemblies/v4.6.1/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.1/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id index f7586e7be5..aeffeaee5b 100644 --- a/external/binary-reference-assemblies/v4.6.1/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.1/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id @@ -1 +1 @@ -6e7264fc3986a0f7fdcca293cc17f711ab3cd23c \ No newline at end of file +d4586082f34e034f4adafd1e6cb54b4831cad7d1 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.1/Microsoft.Build.dll b/external/binary-reference-assemblies/v4.6.1/Microsoft.Build.dll index de66d900b7..35063c3abd 100644 Binary files a/external/binary-reference-assemblies/v4.6.1/Microsoft.Build.dll and b/external/binary-reference-assemblies/v4.6.1/Microsoft.Build.dll differ diff --git a/external/binary-reference-assemblies/v4.6.1/System.ComponentModel.Composition.dll b/external/binary-reference-assemblies/v4.6.1/System.ComponentModel.Composition.dll index 26dc4a9b02..3ced6bef75 100644 Binary files a/external/binary-reference-assemblies/v4.6.1/System.ComponentModel.Composition.dll and b/external/binary-reference-assemblies/v4.6.1/System.ComponentModel.Composition.dll differ diff --git a/external/binary-reference-assemblies/v4.6.1/System.Core.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.1/System.Core.dll.REMOVED.git-id index ea8fbac7c1..2b37174289 100644 --- a/external/binary-reference-assemblies/v4.6.1/System.Core.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.1/System.Core.dll.REMOVED.git-id @@ -1 +1 @@ -365bbedd02ebc76023960b160a855564766d8069 \ No newline at end of file +cb75282eacb364688fb988eae6a152efe85d3c78 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.1/System.Data.Entity.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.1/System.Data.Entity.dll.REMOVED.git-id index 328fd0fd1f..f7468814fa 100644 --- a/external/binary-reference-assemblies/v4.6.1/System.Data.Entity.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.1/System.Data.Entity.dll.REMOVED.git-id @@ -1 +1 @@ -4d5b9221bb53c8b1a5ae7e6cf12ffe2ed7bcb64f \ No newline at end of file +25b0875ffa191b1c34e1f6d0100b6d41e83c1cf0 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.1/System.Data.Linq.dll b/external/binary-reference-assemblies/v4.6.1/System.Data.Linq.dll index f355bd9dec..f83512d807 100644 Binary files a/external/binary-reference-assemblies/v4.6.1/System.Data.Linq.dll and b/external/binary-reference-assemblies/v4.6.1/System.Data.Linq.dll differ diff --git a/external/binary-reference-assemblies/v4.6.1/System.Data.OracleClient.dll b/external/binary-reference-assemblies/v4.6.1/System.Data.OracleClient.dll index 10f97f6850..edbf9b4ef5 100644 Binary files a/external/binary-reference-assemblies/v4.6.1/System.Data.OracleClient.dll and b/external/binary-reference-assemblies/v4.6.1/System.Data.OracleClient.dll differ diff --git a/external/binary-reference-assemblies/v4.6.1/System.Data.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.1/System.Data.dll.REMOVED.git-id index 1702402d85..f94bf845e5 100644 --- a/external/binary-reference-assemblies/v4.6.1/System.Data.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.1/System.Data.dll.REMOVED.git-id @@ -1 +1 @@ -173243810f07ef5e7507a8b121148025fd5152e3 \ No newline at end of file +9fd9502b611c7c70a022131b63e3b79fb887e9a2 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.1/System.Drawing.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.1/System.Drawing.dll.REMOVED.git-id index d146f33d84..bfd14327d7 100644 --- a/external/binary-reference-assemblies/v4.6.1/System.Drawing.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.1/System.Drawing.dll.REMOVED.git-id @@ -1 +1 @@ -f7f7ee6989ae152f4842b321531df9383a41b79d \ No newline at end of file +54a1fc9b9be10dd758595ff0a4b90b2e546f6159 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.1/System.Numerics.dll b/external/binary-reference-assemblies/v4.6.1/System.Numerics.dll index 90fdc21400..302ec072f6 100644 Binary files a/external/binary-reference-assemblies/v4.6.1/System.Numerics.dll and b/external/binary-reference-assemblies/v4.6.1/System.Numerics.dll differ diff --git a/external/binary-reference-assemblies/v4.6.1/System.Security.dll b/external/binary-reference-assemblies/v4.6.1/System.Security.dll index 565fe8a7c5..07d56b822c 100644 Binary files a/external/binary-reference-assemblies/v4.6.1/System.Security.dll and b/external/binary-reference-assemblies/v4.6.1/System.Security.dll differ diff --git a/external/binary-reference-assemblies/v4.6.1/System.ServiceProcess.dll b/external/binary-reference-assemblies/v4.6.1/System.ServiceProcess.dll index a3223491d1..28bf3b045c 100644 Binary files a/external/binary-reference-assemblies/v4.6.1/System.ServiceProcess.dll and b/external/binary-reference-assemblies/v4.6.1/System.ServiceProcess.dll differ diff --git a/external/binary-reference-assemblies/v4.6.1/System.Transactions.dll b/external/binary-reference-assemblies/v4.6.1/System.Transactions.dll index d3eb54641a..16d0d2ed1e 100644 Binary files a/external/binary-reference-assemblies/v4.6.1/System.Transactions.dll and b/external/binary-reference-assemblies/v4.6.1/System.Transactions.dll differ diff --git a/external/binary-reference-assemblies/v4.6.1/System.Web.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.1/System.Web.dll.REMOVED.git-id index ea8510eb29..8bc4255374 100644 --- a/external/binary-reference-assemblies/v4.6.1/System.Web.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.1/System.Web.dll.REMOVED.git-id @@ -1 +1 @@ -54785d4e2608c5e6d572ca2658d6c922900ccb16 \ No newline at end of file +8d74da10676910b13e81bba16a7e09d99490ef1f \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.1/System.Windows.Forms.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.1/System.Windows.Forms.dll.REMOVED.git-id index bc7afe789a..f18c77acfb 100644 --- a/external/binary-reference-assemblies/v4.6.1/System.Windows.Forms.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.1/System.Windows.Forms.dll.REMOVED.git-id @@ -1 +1 @@ -5fc16a5c3ebca4b00826479977b99590a80f7077 \ No newline at end of file +dc9344c4112c75dcd01e8298c5b73de2fc491f09 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.1/System.Xml.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.1/System.Xml.dll.REMOVED.git-id index b2c623098e..ac84d52b1a 100644 --- a/external/binary-reference-assemblies/v4.6.1/System.Xml.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.1/System.Xml.dll.REMOVED.git-id @@ -1 +1 @@ -de2bf8b94eb1120ce825ec32a8b02d03c0199699 \ No newline at end of file +410d80e2d1348d4b8a7b18a018a7687760611eb9 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.1/System.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.1/System.dll.REMOVED.git-id index 192d833561..c6bf34d610 100644 --- a/external/binary-reference-assemblies/v4.6.1/System.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.1/System.dll.REMOVED.git-id @@ -1 +1 @@ -8394fcc8263dd977c2dc936e664f764a8d4937de \ No newline at end of file +43d3c1e5cbc6a9c63183cc6930ddebd8c89d7f86 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.1/WindowsBase.dll b/external/binary-reference-assemblies/v4.6.1/WindowsBase.dll index 24a2c39ea1..7a31b3f40f 100644 Binary files a/external/binary-reference-assemblies/v4.6.1/WindowsBase.dll and b/external/binary-reference-assemblies/v4.6.1/WindowsBase.dll differ diff --git a/external/binary-reference-assemblies/v4.6.1/mscorlib.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.1/mscorlib.dll.REMOVED.git-id index 10fcb9ac3d..275bab93c4 100644 --- a/external/binary-reference-assemblies/v4.6.1/mscorlib.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.1/mscorlib.dll.REMOVED.git-id @@ -1 +1 @@ -7706e7266bd3c6e7ed85c3bb94e7dc0e23084fa7 \ No newline at end of file +657241801ec92cd84c443c6bc527c7cdbc4fbd99 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.2/Microsoft.Build.Framework.dll b/external/binary-reference-assemblies/v4.6.2/Microsoft.Build.Framework.dll index 84e7d57de3..01f6786306 100644 Binary files a/external/binary-reference-assemblies/v4.6.2/Microsoft.Build.Framework.dll and b/external/binary-reference-assemblies/v4.6.2/Microsoft.Build.Framework.dll differ diff --git a/external/binary-reference-assemblies/v4.6.2/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.2/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id index f7586e7be5..aeffeaee5b 100644 --- a/external/binary-reference-assemblies/v4.6.2/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.2/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id @@ -1 +1 @@ -6e7264fc3986a0f7fdcca293cc17f711ab3cd23c \ No newline at end of file +d4586082f34e034f4adafd1e6cb54b4831cad7d1 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.2/Microsoft.Build.dll b/external/binary-reference-assemblies/v4.6.2/Microsoft.Build.dll index de66d900b7..35063c3abd 100644 Binary files a/external/binary-reference-assemblies/v4.6.2/Microsoft.Build.dll and b/external/binary-reference-assemblies/v4.6.2/Microsoft.Build.dll differ diff --git a/external/binary-reference-assemblies/v4.6.2/System.ComponentModel.Composition.dll b/external/binary-reference-assemblies/v4.6.2/System.ComponentModel.Composition.dll index 26dc4a9b02..3ced6bef75 100644 Binary files a/external/binary-reference-assemblies/v4.6.2/System.ComponentModel.Composition.dll and b/external/binary-reference-assemblies/v4.6.2/System.ComponentModel.Composition.dll differ diff --git a/external/binary-reference-assemblies/v4.6.2/System.Core.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.2/System.Core.dll.REMOVED.git-id index e0b52d8166..6329bb8dc0 100644 --- a/external/binary-reference-assemblies/v4.6.2/System.Core.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.2/System.Core.dll.REMOVED.git-id @@ -1 +1 @@ -c5bc6eb723e00c4cf7a14f5fb374065c4030944b \ No newline at end of file +c8f0b449ef0ff76e29810d010a0b2f5a496fd7c2 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.2/System.Data.Entity.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.2/System.Data.Entity.dll.REMOVED.git-id index 328fd0fd1f..f7468814fa 100644 --- a/external/binary-reference-assemblies/v4.6.2/System.Data.Entity.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.2/System.Data.Entity.dll.REMOVED.git-id @@ -1 +1 @@ -4d5b9221bb53c8b1a5ae7e6cf12ffe2ed7bcb64f \ No newline at end of file +25b0875ffa191b1c34e1f6d0100b6d41e83c1cf0 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.2/System.Data.Linq.dll b/external/binary-reference-assemblies/v4.6.2/System.Data.Linq.dll index f355bd9dec..f83512d807 100644 Binary files a/external/binary-reference-assemblies/v4.6.2/System.Data.Linq.dll and b/external/binary-reference-assemblies/v4.6.2/System.Data.Linq.dll differ diff --git a/external/binary-reference-assemblies/v4.6.2/System.Data.OracleClient.dll b/external/binary-reference-assemblies/v4.6.2/System.Data.OracleClient.dll index 10f97f6850..edbf9b4ef5 100644 Binary files a/external/binary-reference-assemblies/v4.6.2/System.Data.OracleClient.dll and b/external/binary-reference-assemblies/v4.6.2/System.Data.OracleClient.dll differ diff --git a/external/binary-reference-assemblies/v4.6.2/System.Data.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.2/System.Data.dll.REMOVED.git-id index b73ebe60f6..0defe5d7c0 100644 --- a/external/binary-reference-assemblies/v4.6.2/System.Data.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.2/System.Data.dll.REMOVED.git-id @@ -1 +1 @@ -e59bf5e76441db29e6c505accf6599e975f2c56c \ No newline at end of file +95f58cb87202cac2d45a729ebf5ea6737ccf745c \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.2/System.Drawing.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.2/System.Drawing.dll.REMOVED.git-id index d146f33d84..bfd14327d7 100644 --- a/external/binary-reference-assemblies/v4.6.2/System.Drawing.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.2/System.Drawing.dll.REMOVED.git-id @@ -1 +1 @@ -f7f7ee6989ae152f4842b321531df9383a41b79d \ No newline at end of file +54a1fc9b9be10dd758595ff0a4b90b2e546f6159 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.2/System.Numerics.dll b/external/binary-reference-assemblies/v4.6.2/System.Numerics.dll index 90fdc21400..302ec072f6 100644 Binary files a/external/binary-reference-assemblies/v4.6.2/System.Numerics.dll and b/external/binary-reference-assemblies/v4.6.2/System.Numerics.dll differ diff --git a/external/binary-reference-assemblies/v4.6.2/System.Security.dll b/external/binary-reference-assemblies/v4.6.2/System.Security.dll index 4a72dea8cf..e55e8952a5 100644 Binary files a/external/binary-reference-assemblies/v4.6.2/System.Security.dll and b/external/binary-reference-assemblies/v4.6.2/System.Security.dll differ diff --git a/external/binary-reference-assemblies/v4.6.2/System.ServiceProcess.dll b/external/binary-reference-assemblies/v4.6.2/System.ServiceProcess.dll index a3223491d1..28bf3b045c 100644 Binary files a/external/binary-reference-assemblies/v4.6.2/System.ServiceProcess.dll and b/external/binary-reference-assemblies/v4.6.2/System.ServiceProcess.dll differ diff --git a/external/binary-reference-assemblies/v4.6.2/System.Transactions.dll b/external/binary-reference-assemblies/v4.6.2/System.Transactions.dll index d3eb54641a..16d0d2ed1e 100644 Binary files a/external/binary-reference-assemblies/v4.6.2/System.Transactions.dll and b/external/binary-reference-assemblies/v4.6.2/System.Transactions.dll differ diff --git a/external/binary-reference-assemblies/v4.6.2/System.Web.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.2/System.Web.dll.REMOVED.git-id index 6418217006..e8fe1e2938 100644 --- a/external/binary-reference-assemblies/v4.6.2/System.Web.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.2/System.Web.dll.REMOVED.git-id @@ -1 +1 @@ -730b2add8f051a5811b78c9021f46ff68526d90b \ No newline at end of file +595933a8a2073b8c0e3da2d3e8e25ea0ea45d367 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.2/System.Windows.Forms.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.2/System.Windows.Forms.dll.REMOVED.git-id index bc7afe789a..f18c77acfb 100644 --- a/external/binary-reference-assemblies/v4.6.2/System.Windows.Forms.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.2/System.Windows.Forms.dll.REMOVED.git-id @@ -1 +1 @@ -5fc16a5c3ebca4b00826479977b99590a80f7077 \ No newline at end of file +dc9344c4112c75dcd01e8298c5b73de2fc491f09 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.2/System.Xml.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.2/System.Xml.dll.REMOVED.git-id index b2c623098e..ac84d52b1a 100644 --- a/external/binary-reference-assemblies/v4.6.2/System.Xml.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.2/System.Xml.dll.REMOVED.git-id @@ -1 +1 @@ -de2bf8b94eb1120ce825ec32a8b02d03c0199699 \ No newline at end of file +410d80e2d1348d4b8a7b18a018a7687760611eb9 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.2/System.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.2/System.dll.REMOVED.git-id index 192d833561..c6bf34d610 100644 --- a/external/binary-reference-assemblies/v4.6.2/System.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.2/System.dll.REMOVED.git-id @@ -1 +1 @@ -8394fcc8263dd977c2dc936e664f764a8d4937de \ No newline at end of file +43d3c1e5cbc6a9c63183cc6930ddebd8c89d7f86 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6.2/WindowsBase.dll b/external/binary-reference-assemblies/v4.6.2/WindowsBase.dll index 3f6def428d..3382ed2846 100644 Binary files a/external/binary-reference-assemblies/v4.6.2/WindowsBase.dll and b/external/binary-reference-assemblies/v4.6.2/WindowsBase.dll differ diff --git a/external/binary-reference-assemblies/v4.6.2/mscorlib.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6.2/mscorlib.dll.REMOVED.git-id index 8f9612f6b9..c7c9ed1b24 100644 --- a/external/binary-reference-assemblies/v4.6.2/mscorlib.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6.2/mscorlib.dll.REMOVED.git-id @@ -1 +1 @@ -cdcde6afc2e87860927f6d2b491b1beba7fdf448 \ No newline at end of file +02630e820d95788942acfaf4286a4d3a29fa228a \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6/Microsoft.Build.Framework.dll b/external/binary-reference-assemblies/v4.6/Microsoft.Build.Framework.dll index 84e7d57de3..01f6786306 100644 Binary files a/external/binary-reference-assemblies/v4.6/Microsoft.Build.Framework.dll and b/external/binary-reference-assemblies/v4.6/Microsoft.Build.Framework.dll differ diff --git a/external/binary-reference-assemblies/v4.6/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id index f7586e7be5..aeffeaee5b 100644 --- a/external/binary-reference-assemblies/v4.6/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id @@ -1 +1 @@ -6e7264fc3986a0f7fdcca293cc17f711ab3cd23c \ No newline at end of file +d4586082f34e034f4adafd1e6cb54b4831cad7d1 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6/Microsoft.Build.dll b/external/binary-reference-assemblies/v4.6/Microsoft.Build.dll index de66d900b7..35063c3abd 100644 Binary files a/external/binary-reference-assemblies/v4.6/Microsoft.Build.dll and b/external/binary-reference-assemblies/v4.6/Microsoft.Build.dll differ diff --git a/external/binary-reference-assemblies/v4.6/System.ComponentModel.Composition.dll b/external/binary-reference-assemblies/v4.6/System.ComponentModel.Composition.dll index 26dc4a9b02..3ced6bef75 100644 Binary files a/external/binary-reference-assemblies/v4.6/System.ComponentModel.Composition.dll and b/external/binary-reference-assemblies/v4.6/System.ComponentModel.Composition.dll differ diff --git a/external/binary-reference-assemblies/v4.6/System.Core.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6/System.Core.dll.REMOVED.git-id index 45ebf81002..43e322fa8c 100644 --- a/external/binary-reference-assemblies/v4.6/System.Core.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6/System.Core.dll.REMOVED.git-id @@ -1 +1 @@ -603817ebf24972ac0388f1fb6d4d17f22f81fb35 \ No newline at end of file +8639c4317705686e9ec4118123985763357212eb \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6/System.Data.Entity.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6/System.Data.Entity.dll.REMOVED.git-id index 328fd0fd1f..f7468814fa 100644 --- a/external/binary-reference-assemblies/v4.6/System.Data.Entity.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6/System.Data.Entity.dll.REMOVED.git-id @@ -1 +1 @@ -4d5b9221bb53c8b1a5ae7e6cf12ffe2ed7bcb64f \ No newline at end of file +25b0875ffa191b1c34e1f6d0100b6d41e83c1cf0 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6/System.Data.Linq.dll b/external/binary-reference-assemblies/v4.6/System.Data.Linq.dll index f355bd9dec..f83512d807 100644 Binary files a/external/binary-reference-assemblies/v4.6/System.Data.Linq.dll and b/external/binary-reference-assemblies/v4.6/System.Data.Linq.dll differ diff --git a/external/binary-reference-assemblies/v4.6/System.Data.OracleClient.dll b/external/binary-reference-assemblies/v4.6/System.Data.OracleClient.dll index 10f97f6850..edbf9b4ef5 100644 Binary files a/external/binary-reference-assemblies/v4.6/System.Data.OracleClient.dll and b/external/binary-reference-assemblies/v4.6/System.Data.OracleClient.dll differ diff --git a/external/binary-reference-assemblies/v4.6/System.Data.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6/System.Data.dll.REMOVED.git-id index b7b74b548c..1ea6decef8 100644 --- a/external/binary-reference-assemblies/v4.6/System.Data.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6/System.Data.dll.REMOVED.git-id @@ -1 +1 @@ -3b97f9e20449e59db0e0e712326e9967567154d7 \ No newline at end of file +b80787054dfe057597f2798ab78d08eff0dea8f7 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6/System.Drawing.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6/System.Drawing.dll.REMOVED.git-id index 9b50bfb43c..2b90012393 100644 --- a/external/binary-reference-assemblies/v4.6/System.Drawing.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6/System.Drawing.dll.REMOVED.git-id @@ -1 +1 @@ -87d25464c403c5d1e04669368f14e9cbda91f907 \ No newline at end of file +938799f64801c29e02bf7454c99517edc3c3f75e \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6/System.Numerics.dll b/external/binary-reference-assemblies/v4.6/System.Numerics.dll index 90fdc21400..302ec072f6 100644 Binary files a/external/binary-reference-assemblies/v4.6/System.Numerics.dll and b/external/binary-reference-assemblies/v4.6/System.Numerics.dll differ diff --git a/external/binary-reference-assemblies/v4.6/System.Security.dll b/external/binary-reference-assemblies/v4.6/System.Security.dll index 565fe8a7c5..07d56b822c 100644 Binary files a/external/binary-reference-assemblies/v4.6/System.Security.dll and b/external/binary-reference-assemblies/v4.6/System.Security.dll differ diff --git a/external/binary-reference-assemblies/v4.6/System.ServiceProcess.dll b/external/binary-reference-assemblies/v4.6/System.ServiceProcess.dll index b584d5dbd6..f20ba5a532 100644 Binary files a/external/binary-reference-assemblies/v4.6/System.ServiceProcess.dll and b/external/binary-reference-assemblies/v4.6/System.ServiceProcess.dll differ diff --git a/external/binary-reference-assemblies/v4.6/System.Transactions.dll b/external/binary-reference-assemblies/v4.6/System.Transactions.dll index 9b934b43c9..d39585961d 100644 Binary files a/external/binary-reference-assemblies/v4.6/System.Transactions.dll and b/external/binary-reference-assemblies/v4.6/System.Transactions.dll differ diff --git a/external/binary-reference-assemblies/v4.6/System.Web.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6/System.Web.dll.REMOVED.git-id index fd51d0718d..7007a0d198 100644 --- a/external/binary-reference-assemblies/v4.6/System.Web.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6/System.Web.dll.REMOVED.git-id @@ -1 +1 @@ -490c2b97607bcebebea45ffe58f952a0f6444306 \ No newline at end of file +4ecbe376ba8d1d962238b18977b0dbfbf0adbea4 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6/System.Windows.Forms.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6/System.Windows.Forms.dll.REMOVED.git-id index a3456ab832..2732041006 100644 --- a/external/binary-reference-assemblies/v4.6/System.Windows.Forms.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6/System.Windows.Forms.dll.REMOVED.git-id @@ -1 +1 @@ -2da9bb43c910a5b3c733385b13df3460fb741898 \ No newline at end of file +b67c5b2e0915f9ed6544c405c75880952d10b843 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6/System.Xml.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6/System.Xml.dll.REMOVED.git-id index b2c623098e..ac84d52b1a 100644 --- a/external/binary-reference-assemblies/v4.6/System.Xml.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6/System.Xml.dll.REMOVED.git-id @@ -1 +1 @@ -de2bf8b94eb1120ce825ec32a8b02d03c0199699 \ No newline at end of file +410d80e2d1348d4b8a7b18a018a7687760611eb9 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6/System.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6/System.dll.REMOVED.git-id index d2976d4176..e9e168081b 100644 --- a/external/binary-reference-assemblies/v4.6/System.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6/System.dll.REMOVED.git-id @@ -1 +1 @@ -8e4d6a7a5182ab0227c542a4a748b127d2169805 \ No newline at end of file +f420cc943b0ee7291bb351daaf9feee1aed1e5a4 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.6/WindowsBase.dll b/external/binary-reference-assemblies/v4.6/WindowsBase.dll index 24a2c39ea1..7a31b3f40f 100644 Binary files a/external/binary-reference-assemblies/v4.6/WindowsBase.dll and b/external/binary-reference-assemblies/v4.6/WindowsBase.dll differ diff --git a/external/binary-reference-assemblies/v4.6/mscorlib.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.6/mscorlib.dll.REMOVED.git-id index 10fcb9ac3d..275bab93c4 100644 --- a/external/binary-reference-assemblies/v4.6/mscorlib.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.6/mscorlib.dll.REMOVED.git-id @@ -1 +1 @@ -7706e7266bd3c6e7ed85c3bb94e7dc0e23084fa7 \ No newline at end of file +657241801ec92cd84c443c6bc527c7cdbc4fbd99 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.1/Microsoft.Build.Framework.dll b/external/binary-reference-assemblies/v4.7.1/Microsoft.Build.Framework.dll index 44f081c36c..19d23ae040 100644 Binary files a/external/binary-reference-assemblies/v4.7.1/Microsoft.Build.Framework.dll and b/external/binary-reference-assemblies/v4.7.1/Microsoft.Build.Framework.dll differ diff --git a/external/binary-reference-assemblies/v4.7.1/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.1/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id index d0a803c905..cd6b39b579 100644 --- a/external/binary-reference-assemblies/v4.7.1/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.1/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id @@ -1 +1 @@ -48a489d6a78a7df567985f79be83987716da4da5 \ No newline at end of file +ec5f617a0eba2a97401e423e434408843030f399 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.1/Microsoft.Build.dll b/external/binary-reference-assemblies/v4.7.1/Microsoft.Build.dll index 08796e380d..230c08ef30 100644 Binary files a/external/binary-reference-assemblies/v4.7.1/Microsoft.Build.dll and b/external/binary-reference-assemblies/v4.7.1/Microsoft.Build.dll differ diff --git a/external/binary-reference-assemblies/v4.7.1/System.ComponentModel.Composition.dll b/external/binary-reference-assemblies/v4.7.1/System.ComponentModel.Composition.dll index d719c9ba7a..550e7dad10 100644 Binary files a/external/binary-reference-assemblies/v4.7.1/System.ComponentModel.Composition.dll and b/external/binary-reference-assemblies/v4.7.1/System.ComponentModel.Composition.dll differ diff --git a/external/binary-reference-assemblies/v4.7.1/System.Core.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.1/System.Core.dll.REMOVED.git-id index 8a08bb53cc..a177f6b827 100644 --- a/external/binary-reference-assemblies/v4.7.1/System.Core.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.1/System.Core.dll.REMOVED.git-id @@ -1 +1 @@ -7eee6c1bcdceb41196eb7f1d975cf201347d5946 \ No newline at end of file +a72a2e1e54e64b49b0e3da9bbed3e5b1dac3df77 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.1/System.Data.Entity.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.1/System.Data.Entity.dll.REMOVED.git-id index fc66735029..f8be5d5296 100644 --- a/external/binary-reference-assemblies/v4.7.1/System.Data.Entity.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.1/System.Data.Entity.dll.REMOVED.git-id @@ -1 +1 @@ -86528ac3b19364d3baa5911a4fe3139f4fb33446 \ No newline at end of file +e903b79d211d2f824ab4577af88641eaec44c294 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.1/System.Data.Linq.dll b/external/binary-reference-assemblies/v4.7.1/System.Data.Linq.dll index 509ee78475..140e1c934c 100644 Binary files a/external/binary-reference-assemblies/v4.7.1/System.Data.Linq.dll and b/external/binary-reference-assemblies/v4.7.1/System.Data.Linq.dll differ diff --git a/external/binary-reference-assemblies/v4.7.1/System.Data.OracleClient.dll b/external/binary-reference-assemblies/v4.7.1/System.Data.OracleClient.dll index b117c38d51..a14a74a202 100644 Binary files a/external/binary-reference-assemblies/v4.7.1/System.Data.OracleClient.dll and b/external/binary-reference-assemblies/v4.7.1/System.Data.OracleClient.dll differ diff --git a/external/binary-reference-assemblies/v4.7.1/System.Data.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.1/System.Data.dll.REMOVED.git-id index 7b7d38c5d6..3fd647c905 100644 --- a/external/binary-reference-assemblies/v4.7.1/System.Data.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.1/System.Data.dll.REMOVED.git-id @@ -1 +1 @@ -33b714b7adc8c96386cec07ab1d4a4ab277441bf \ No newline at end of file +519acb138fd45b21719bd55d6ecd2b2c883a078f \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.1/System.Drawing.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.1/System.Drawing.dll.REMOVED.git-id index 845f77bb44..4cdb5af544 100644 --- a/external/binary-reference-assemblies/v4.7.1/System.Drawing.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.1/System.Drawing.dll.REMOVED.git-id @@ -1 +1 @@ -201d85b0cae38c07eaf738f62e4f37b317683db4 \ No newline at end of file +89ba1f5b5e8e3273f5e75bcd634feda7d1af3e63 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.1/System.Numerics.dll b/external/binary-reference-assemblies/v4.7.1/System.Numerics.dll index 65077629e0..5f7f519851 100644 Binary files a/external/binary-reference-assemblies/v4.7.1/System.Numerics.dll and b/external/binary-reference-assemblies/v4.7.1/System.Numerics.dll differ diff --git a/external/binary-reference-assemblies/v4.7.1/System.Security.dll b/external/binary-reference-assemblies/v4.7.1/System.Security.dll index 517eb3ebd3..cc1fd867dd 100644 Binary files a/external/binary-reference-assemblies/v4.7.1/System.Security.dll and b/external/binary-reference-assemblies/v4.7.1/System.Security.dll differ diff --git a/external/binary-reference-assemblies/v4.7.1/System.ServiceProcess.dll b/external/binary-reference-assemblies/v4.7.1/System.ServiceProcess.dll index 317b735011..cd6a23812f 100644 Binary files a/external/binary-reference-assemblies/v4.7.1/System.ServiceProcess.dll and b/external/binary-reference-assemblies/v4.7.1/System.ServiceProcess.dll differ diff --git a/external/binary-reference-assemblies/v4.7.1/System.Transactions.dll b/external/binary-reference-assemblies/v4.7.1/System.Transactions.dll index 032824074a..345fb2a4db 100644 Binary files a/external/binary-reference-assemblies/v4.7.1/System.Transactions.dll and b/external/binary-reference-assemblies/v4.7.1/System.Transactions.dll differ diff --git a/external/binary-reference-assemblies/v4.7.1/System.Web.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.1/System.Web.dll.REMOVED.git-id index 67d5d2f074..3cb429af5a 100644 --- a/external/binary-reference-assemblies/v4.7.1/System.Web.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.1/System.Web.dll.REMOVED.git-id @@ -1 +1 @@ -f6a91fe656f6a99a464e7b4a50b0dfd8a8b79d6f \ No newline at end of file +ca68a71e097d143daff5f2ce9d279d7e850cb40b \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.1/System.Windows.Forms.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.1/System.Windows.Forms.dll.REMOVED.git-id index e600684ce1..e29c95cce4 100644 --- a/external/binary-reference-assemblies/v4.7.1/System.Windows.Forms.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.1/System.Windows.Forms.dll.REMOVED.git-id @@ -1 +1 @@ -43dada0d23b3441989831f46ace0dc3fa0b0d26a \ No newline at end of file +0587d73003ec3add94641ac4ae13a18260d368e2 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.1/System.Xml.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.1/System.Xml.dll.REMOVED.git-id index 2c39af363d..d78fca5413 100644 --- a/external/binary-reference-assemblies/v4.7.1/System.Xml.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.1/System.Xml.dll.REMOVED.git-id @@ -1 +1 @@ -55ac5245bdeeea66fe42d1004653707cfa6876c3 \ No newline at end of file +93d857748d4091818ade69b8c2e70454df01cd51 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.1/System.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.1/System.dll.REMOVED.git-id index 7d06f83249..53ab2d5665 100644 --- a/external/binary-reference-assemblies/v4.7.1/System.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.1/System.dll.REMOVED.git-id @@ -1 +1 @@ -ea33a272ed6642fd300e619349eab0546fec86e1 \ No newline at end of file +7b114dd8258fe0bde446588547c0de323f89849e \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.1/WindowsBase.dll b/external/binary-reference-assemblies/v4.7.1/WindowsBase.dll index bf729e4454..723a6b6df3 100644 Binary files a/external/binary-reference-assemblies/v4.7.1/WindowsBase.dll and b/external/binary-reference-assemblies/v4.7.1/WindowsBase.dll differ diff --git a/external/binary-reference-assemblies/v4.7.1/mscorlib.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.1/mscorlib.dll.REMOVED.git-id index 42c3767a11..a13793534c 100644 --- a/external/binary-reference-assemblies/v4.7.1/mscorlib.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.1/mscorlib.dll.REMOVED.git-id @@ -1 +1 @@ -3b49735dd3b9800ff990ce156dc26b94ed4920e7 \ No newline at end of file +5b18b45eb6b006bab87cf46c29f124a1d8e8388c \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.2/Accessibility.dll b/external/binary-reference-assemblies/v4.7.2/Accessibility.dll index fdd9dd7a03..c0407ff677 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/Accessibility.dll and b/external/binary-reference-assemblies/v4.7.2/Accessibility.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.Framework.dll b/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.Framework.dll index ad9e902851..a596529353 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.Framework.dll and b/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.Framework.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id index 0c963c3f41..63c2c1b0aa 100644 --- a/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id @@ -1 +1 @@ -e20db0a392f47c3fb67b684787719bc3997739ac \ No newline at end of file +562d49bd1d364f357cd998a00a73e2dcac1efd3f \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.Utilities.v4.0.dll b/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.Utilities.v4.0.dll index 02e5a3a81c..043e661bf6 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.Utilities.v4.0.dll and b/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.Utilities.v4.0.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.dll b/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.dll index 3eec4f27fb..ab71e9778a 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.dll and b/external/binary-reference-assemblies/v4.7.2/Microsoft.Build.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/Microsoft.VisualC.dll b/external/binary-reference-assemblies/v4.7.2/Microsoft.VisualC.dll index 2546b2b11f..7afc277dfc 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/Microsoft.VisualC.dll and b/external/binary-reference-assemblies/v4.7.2/Microsoft.VisualC.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.ComponentModel.Composition.dll b/external/binary-reference-assemblies/v4.7.2/System.ComponentModel.Composition.dll index 8b88c1c116..2bd8aa8d42 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.ComponentModel.Composition.dll and b/external/binary-reference-assemblies/v4.7.2/System.ComponentModel.Composition.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Configuration.dll b/external/binary-reference-assemblies/v4.7.2/System.Configuration.dll index f56096aa79..61bde2a17b 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Configuration.dll and b/external/binary-reference-assemblies/v4.7.2/System.Configuration.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Core.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.2/System.Core.dll.REMOVED.git-id index 9683165bd0..641c677105 100644 --- a/external/binary-reference-assemblies/v4.7.2/System.Core.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.2/System.Core.dll.REMOVED.git-id @@ -1 +1 @@ -5e205b854543133ce4674ed5dd1dea6a4468bb2c \ No newline at end of file +b6008cffd6022987863dc0f86354db18371d191b \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.2/System.Data.Entity.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.2/System.Data.Entity.dll.REMOVED.git-id index a990eddb27..e38fbeab0d 100644 --- a/external/binary-reference-assemblies/v4.7.2/System.Data.Entity.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.2/System.Data.Entity.dll.REMOVED.git-id @@ -1 +1 @@ -31adaaae4a0c5bf1a13d43a7111934ad3bae3c26 \ No newline at end of file +486ae2880f113f7a0b196dfbbfb4ec6d006311b9 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.2/System.Data.Linq.dll b/external/binary-reference-assemblies/v4.7.2/System.Data.Linq.dll index 509ee78475..b5c64af4ea 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Data.Linq.dll and b/external/binary-reference-assemblies/v4.7.2/System.Data.Linq.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Data.OracleClient.dll b/external/binary-reference-assemblies/v4.7.2/System.Data.OracleClient.dll index 4b80362aee..1849fc5833 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Data.OracleClient.dll and b/external/binary-reference-assemblies/v4.7.2/System.Data.OracleClient.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Data.Services.Client.dll b/external/binary-reference-assemblies/v4.7.2/System.Data.Services.Client.dll index 5a3a564cb4..eaa15af90e 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Data.Services.Client.dll and b/external/binary-reference-assemblies/v4.7.2/System.Data.Services.Client.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Data.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.2/System.Data.dll.REMOVED.git-id index 9ab9f00d22..398e47f3db 100644 --- a/external/binary-reference-assemblies/v4.7.2/System.Data.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.2/System.Data.dll.REMOVED.git-id @@ -1 +1 @@ -4816c8177afc283710b5186f3f8416ccb9d95f4a \ No newline at end of file +ae3aba494e3e43b006184644b0721463d02fb92b \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.2/System.Deployment.dll b/external/binary-reference-assemblies/v4.7.2/System.Deployment.dll index 1b42a76d91..16d3f38bde 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Deployment.dll and b/external/binary-reference-assemblies/v4.7.2/System.Deployment.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Design.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.2/System.Design.dll.REMOVED.git-id index 87dbc94050..27a9e03540 100644 --- a/external/binary-reference-assemblies/v4.7.2/System.Design.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.2/System.Design.dll.REMOVED.git-id @@ -1 +1 @@ -e5ae48b87281e12d32ee6f079b850574c513dc3f \ No newline at end of file +16a513a017aa6719904ebc9131c372feeee815e3 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.2/System.DirectoryServices.dll b/external/binary-reference-assemblies/v4.7.2/System.DirectoryServices.dll index 11c43d8d36..eda4dcd0d6 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.DirectoryServices.dll and b/external/binary-reference-assemblies/v4.7.2/System.DirectoryServices.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Drawing.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.2/System.Drawing.dll.REMOVED.git-id index 9d0a3726b3..7ba4cf2ed8 100644 --- a/external/binary-reference-assemblies/v4.7.2/System.Drawing.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.2/System.Drawing.dll.REMOVED.git-id @@ -1 +1 @@ -dff2aeca782c81983775b1307e4a6c4785dfe8d6 \ No newline at end of file +63d3706daaf7d9e48af19e41b6ae391481345840 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.2/System.EnterpriseServices.dll b/external/binary-reference-assemblies/v4.7.2/System.EnterpriseServices.dll index 416f4b043c..58b4183db1 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.EnterpriseServices.dll and b/external/binary-reference-assemblies/v4.7.2/System.EnterpriseServices.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.IdentityModel.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.2/System.IdentityModel.dll.REMOVED.git-id index c0c4675204..4622cd8e14 100644 --- a/external/binary-reference-assemblies/v4.7.2/System.IdentityModel.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.2/System.IdentityModel.dll.REMOVED.git-id @@ -1 +1 @@ -1f41b7c254694a14a9cdfb6a8dd30040cd33bebe \ No newline at end of file +c8d9a14c10f7b7960c9e32f0f865341ed69839ec \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.2/System.Net.Http.dll b/external/binary-reference-assemblies/v4.7.2/System.Net.Http.dll index 9b0863b305..aacfe53c30 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Net.Http.dll and b/external/binary-reference-assemblies/v4.7.2/System.Net.Http.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Net.dll b/external/binary-reference-assemblies/v4.7.2/System.Net.dll index 88baf215d6..e0ca19e0a5 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Net.dll and b/external/binary-reference-assemblies/v4.7.2/System.Net.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Numerics.dll b/external/binary-reference-assemblies/v4.7.2/System.Numerics.dll index 6b81e41dc9..bcdcf56262 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Numerics.dll and b/external/binary-reference-assemblies/v4.7.2/System.Numerics.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Runtime.Remoting.dll b/external/binary-reference-assemblies/v4.7.2/System.Runtime.Remoting.dll index e3db03e754..07a92bee65 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Runtime.Remoting.dll and b/external/binary-reference-assemblies/v4.7.2/System.Runtime.Remoting.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Runtime.Serialization.dll b/external/binary-reference-assemblies/v4.7.2/System.Runtime.Serialization.dll index 9233f7c84c..8ae73005c0 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Runtime.Serialization.dll and b/external/binary-reference-assemblies/v4.7.2/System.Runtime.Serialization.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Security.dll b/external/binary-reference-assemblies/v4.7.2/System.Security.dll index 4bfdb77ce6..150177baae 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Security.dll and b/external/binary-reference-assemblies/v4.7.2/System.Security.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.Activation.dll b/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.Activation.dll index 25855b0cd4..50e734fe8c 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.Activation.dll and b/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.Activation.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.Discovery.dll b/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.Discovery.dll index cc900efcde..f8b5c5f2af 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.Discovery.dll and b/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.Discovery.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.Web.dll b/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.Web.dll index f31863f420..3d0f580158 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.Web.dll and b/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.Web.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.dll.REMOVED.git-id index 9057956ffd..1bf474a03c 100644 --- a/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.2/System.ServiceModel.dll.REMOVED.git-id @@ -1 +1 @@ -1c15ef420512ff9f660f541c8f2f9aea686b0a8f \ No newline at end of file +33ed74333f24770d48a362b4ae0d2de2d8f9a922 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.2/System.ServiceProcess.dll b/external/binary-reference-assemblies/v4.7.2/System.ServiceProcess.dll index 1a06227e64..7654896285 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.ServiceProcess.dll and b/external/binary-reference-assemblies/v4.7.2/System.ServiceProcess.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Transactions.dll b/external/binary-reference-assemblies/v4.7.2/System.Transactions.dll index 2f2f33928e..a54d0a36aa 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Transactions.dll and b/external/binary-reference-assemblies/v4.7.2/System.Transactions.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Web.DynamicData.dll b/external/binary-reference-assemblies/v4.7.2/System.Web.DynamicData.dll index df7cde49a3..2f63ff60c1 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Web.DynamicData.dll and b/external/binary-reference-assemblies/v4.7.2/System.Web.DynamicData.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Web.Extensions.Design.dll b/external/binary-reference-assemblies/v4.7.2/System.Web.Extensions.Design.dll index 3f1d17b579..2d57802126 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Web.Extensions.Design.dll and b/external/binary-reference-assemblies/v4.7.2/System.Web.Extensions.Design.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Web.Extensions.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.2/System.Web.Extensions.dll.REMOVED.git-id index ea13348bd3..5aac196a9d 100644 --- a/external/binary-reference-assemblies/v4.7.2/System.Web.Extensions.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.2/System.Web.Extensions.dll.REMOVED.git-id @@ -1 +1 @@ -f594c98ef88ced94eb5d3d3c869a5798ed444efe \ No newline at end of file +f693985fa2246c4c536668fd36ba0ff5353acca2 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.2/System.Web.Mobile.dll b/external/binary-reference-assemblies/v4.7.2/System.Web.Mobile.dll index a6ef8c7986..0317cfb1b9 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Web.Mobile.dll and b/external/binary-reference-assemblies/v4.7.2/System.Web.Mobile.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Web.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.2/System.Web.dll.REMOVED.git-id index 3262f34576..ecd38251b2 100644 --- a/external/binary-reference-assemblies/v4.7.2/System.Web.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.2/System.Web.dll.REMOVED.git-id @@ -1 +1 @@ -9958da4135a08d59cfe0f8e036a5e584a4051b50 \ No newline at end of file +70e9d9cbf8c625bf0a99d54e08bc0467c5dbe7ca \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.2/System.Windows.Forms.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.2/System.Windows.Forms.dll.REMOVED.git-id index 6d8a260726..c47cd380d6 100644 --- a/external/binary-reference-assemblies/v4.7.2/System.Windows.Forms.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.2/System.Windows.Forms.dll.REMOVED.git-id @@ -1 +1 @@ -e115bf981a00a39b67d1ac0e1ed403948ff491ec \ No newline at end of file +ab7cd320b8fb9ccd3b067cb6bee9fde1192bed9f \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.2/System.Workflow.Activities.dll b/external/binary-reference-assemblies/v4.7.2/System.Workflow.Activities.dll index e264df948b..31d378cca5 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Workflow.Activities.dll and b/external/binary-reference-assemblies/v4.7.2/System.Workflow.Activities.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Workflow.ComponentModel.dll b/external/binary-reference-assemblies/v4.7.2/System.Workflow.ComponentModel.dll index 789e41cd07..d306989b15 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Workflow.ComponentModel.dll and b/external/binary-reference-assemblies/v4.7.2/System.Workflow.ComponentModel.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Workflow.Runtime.dll b/external/binary-reference-assemblies/v4.7.2/System.Workflow.Runtime.dll index fe1141bb04..7db9b61d47 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Workflow.Runtime.dll and b/external/binary-reference-assemblies/v4.7.2/System.Workflow.Runtime.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Xaml.dll b/external/binary-reference-assemblies/v4.7.2/System.Xaml.dll index 78e5dddaab..c8b6abff55 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/System.Xaml.dll and b/external/binary-reference-assemblies/v4.7.2/System.Xaml.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/System.Xml.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.2/System.Xml.dll.REMOVED.git-id index 89f3e5f29d..d70b21d520 100644 --- a/external/binary-reference-assemblies/v4.7.2/System.Xml.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.2/System.Xml.dll.REMOVED.git-id @@ -1 +1 @@ -6d7b235f6706ad626601c2ace546081d30ae6319 \ No newline at end of file +0ca33e2a5b039299b3c8571866ccc1893374af5f \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.2/System.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.2/System.dll.REMOVED.git-id index 9044bc13fb..6038c4205e 100644 --- a/external/binary-reference-assemblies/v4.7.2/System.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.2/System.dll.REMOVED.git-id @@ -1 +1 @@ -62ad4ff30da4cec662488287076947c0fcd73301 \ No newline at end of file +ca4bfc7bf2230ccc0e6dd4c7e4d23be46dcade9e \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7.2/WindowsBase.dll b/external/binary-reference-assemblies/v4.7.2/WindowsBase.dll index cbc8ba77f9..c5eefa37f0 100644 Binary files a/external/binary-reference-assemblies/v4.7.2/WindowsBase.dll and b/external/binary-reference-assemblies/v4.7.2/WindowsBase.dll differ diff --git a/external/binary-reference-assemblies/v4.7.2/mscorlib.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7.2/mscorlib.dll.REMOVED.git-id index aadce6a818..841fdced72 100644 --- a/external/binary-reference-assemblies/v4.7.2/mscorlib.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7.2/mscorlib.dll.REMOVED.git-id @@ -1 +1 @@ -6ce213fcfab5937b8366e2f5c853c5441d105ac5 \ No newline at end of file +e2470c6fb5beee9013ca1b9d645a0c47073af860 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7/Microsoft.Build.Framework.dll b/external/binary-reference-assemblies/v4.7/Microsoft.Build.Framework.dll index 1efb74dc6a..f26331e793 100644 Binary files a/external/binary-reference-assemblies/v4.7/Microsoft.Build.Framework.dll and b/external/binary-reference-assemblies/v4.7/Microsoft.Build.Framework.dll differ diff --git a/external/binary-reference-assemblies/v4.7/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id index 5f19fe37df..d53f85f71c 100644 --- a/external/binary-reference-assemblies/v4.7/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7/Microsoft.Build.Tasks.v4.0.dll.REMOVED.git-id @@ -1 +1 @@ -c54ef6c604c374956fd33058d092a81a8be18881 \ No newline at end of file +da71ff9866798c520f7bab1c48eafeffb6e360da \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7/Microsoft.Build.dll b/external/binary-reference-assemblies/v4.7/Microsoft.Build.dll index 32cee628a0..6e4541a826 100644 Binary files a/external/binary-reference-assemblies/v4.7/Microsoft.Build.dll and b/external/binary-reference-assemblies/v4.7/Microsoft.Build.dll differ diff --git a/external/binary-reference-assemblies/v4.7/System.ComponentModel.Composition.dll b/external/binary-reference-assemblies/v4.7/System.ComponentModel.Composition.dll index 850c1a3b60..66f63294ce 100644 Binary files a/external/binary-reference-assemblies/v4.7/System.ComponentModel.Composition.dll and b/external/binary-reference-assemblies/v4.7/System.ComponentModel.Composition.dll differ diff --git a/external/binary-reference-assemblies/v4.7/System.Core.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7/System.Core.dll.REMOVED.git-id index 28ca6f9644..abe4e6ce70 100644 --- a/external/binary-reference-assemblies/v4.7/System.Core.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7/System.Core.dll.REMOVED.git-id @@ -1 +1 @@ -d5f118840ca37b6281659ae21eaf0573724f64b4 \ No newline at end of file +5e702fca68396ccfc70d559989706d14d1bd99fa \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7/System.Data.Entity.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7/System.Data.Entity.dll.REMOVED.git-id index 049c58ddd2..1698820744 100644 --- a/external/binary-reference-assemblies/v4.7/System.Data.Entity.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7/System.Data.Entity.dll.REMOVED.git-id @@ -1 +1 @@ -22bead91a9e736c7be82479449968bd291d33876 \ No newline at end of file +ff8f0f85e234409b27005cecbcd356a43ae16804 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7/System.Data.Linq.dll b/external/binary-reference-assemblies/v4.7/System.Data.Linq.dll index 1f8a9eccd9..bd4a240628 100644 Binary files a/external/binary-reference-assemblies/v4.7/System.Data.Linq.dll and b/external/binary-reference-assemblies/v4.7/System.Data.Linq.dll differ diff --git a/external/binary-reference-assemblies/v4.7/System.Data.OracleClient.dll b/external/binary-reference-assemblies/v4.7/System.Data.OracleClient.dll index bc8588eecb..e29c0da6d6 100644 Binary files a/external/binary-reference-assemblies/v4.7/System.Data.OracleClient.dll and b/external/binary-reference-assemblies/v4.7/System.Data.OracleClient.dll differ diff --git a/external/binary-reference-assemblies/v4.7/System.Data.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7/System.Data.dll.REMOVED.git-id index d3afb231cf..c176ba723c 100644 --- a/external/binary-reference-assemblies/v4.7/System.Data.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7/System.Data.dll.REMOVED.git-id @@ -1 +1 @@ -070caaa81f33de941a876f4e9eb1ca0b1dd614b6 \ No newline at end of file +e2d6a671afb0f17c7e6e4f059490ad5ce474b7e7 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7/System.Drawing.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7/System.Drawing.dll.REMOVED.git-id index 4eaaaf5189..f9363864e5 100644 --- a/external/binary-reference-assemblies/v4.7/System.Drawing.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7/System.Drawing.dll.REMOVED.git-id @@ -1 +1 @@ -fd90e4993ff65e78bfb83393339f41bbf239d8b4 \ No newline at end of file +a8193b9e3db00a1ab19fb31c105c12f96c72a952 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7/System.Numerics.dll b/external/binary-reference-assemblies/v4.7/System.Numerics.dll index 4dec7fb370..28e2ef421f 100644 Binary files a/external/binary-reference-assemblies/v4.7/System.Numerics.dll and b/external/binary-reference-assemblies/v4.7/System.Numerics.dll differ diff --git a/external/binary-reference-assemblies/v4.7/System.Security.dll b/external/binary-reference-assemblies/v4.7/System.Security.dll index 100450f67b..a4a2f712fe 100644 Binary files a/external/binary-reference-assemblies/v4.7/System.Security.dll and b/external/binary-reference-assemblies/v4.7/System.Security.dll differ diff --git a/external/binary-reference-assemblies/v4.7/System.ServiceProcess.dll b/external/binary-reference-assemblies/v4.7/System.ServiceProcess.dll index 8cc4a2783e..72b0e5f085 100644 Binary files a/external/binary-reference-assemblies/v4.7/System.ServiceProcess.dll and b/external/binary-reference-assemblies/v4.7/System.ServiceProcess.dll differ diff --git a/external/binary-reference-assemblies/v4.7/System.Transactions.dll b/external/binary-reference-assemblies/v4.7/System.Transactions.dll index 6ae5828193..e3a761e216 100644 Binary files a/external/binary-reference-assemblies/v4.7/System.Transactions.dll and b/external/binary-reference-assemblies/v4.7/System.Transactions.dll differ diff --git a/external/binary-reference-assemblies/v4.7/System.Web.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7/System.Web.dll.REMOVED.git-id index e26b8eff7a..7fdb2c9ccc 100644 --- a/external/binary-reference-assemblies/v4.7/System.Web.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7/System.Web.dll.REMOVED.git-id @@ -1 +1 @@ -4f01d9f39227503021dd862f42aa7212181de8ae \ No newline at end of file +e208da576b8a081a25a8552e4f44a18e41cd84f7 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7/System.Windows.Forms.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7/System.Windows.Forms.dll.REMOVED.git-id index ee8dc08296..78ebd13878 100644 --- a/external/binary-reference-assemblies/v4.7/System.Windows.Forms.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7/System.Windows.Forms.dll.REMOVED.git-id @@ -1 +1 @@ -13c15912daf9cd7d0ae7976471d90b7bfd89b24d \ No newline at end of file +e26a922ac939c9fc4c452fb0add233f0533c35bd \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7/System.Xml.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7/System.Xml.dll.REMOVED.git-id index d17e3a4f8b..6a5da5db74 100644 --- a/external/binary-reference-assemblies/v4.7/System.Xml.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7/System.Xml.dll.REMOVED.git-id @@ -1 +1 @@ -619064649dac0b0cba7d7f75d3eb9d7646d36036 \ No newline at end of file +dfdd5e61ad4791ad1836083ec2ed4a80be99af85 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7/System.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7/System.dll.REMOVED.git-id index 476e91b497..92f21bbf0a 100644 --- a/external/binary-reference-assemblies/v4.7/System.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7/System.dll.REMOVED.git-id @@ -1 +1 @@ -62d188c9b51634d8481fa5218167b6834076d09f \ No newline at end of file +ea125013b883115e482769a9aab55f0f1d694f52 \ No newline at end of file diff --git a/external/binary-reference-assemblies/v4.7/WindowsBase.dll b/external/binary-reference-assemblies/v4.7/WindowsBase.dll index ab704b1485..b8ff8c8a2a 100644 Binary files a/external/binary-reference-assemblies/v4.7/WindowsBase.dll and b/external/binary-reference-assemblies/v4.7/WindowsBase.dll differ diff --git a/external/binary-reference-assemblies/v4.7/mscorlib.dll.REMOVED.git-id b/external/binary-reference-assemblies/v4.7/mscorlib.dll.REMOVED.git-id index 54c7d03317..b8f5dda260 100644 --- a/external/binary-reference-assemblies/v4.7/mscorlib.dll.REMOVED.git-id +++ b/external/binary-reference-assemblies/v4.7/mscorlib.dll.REMOVED.git-id @@ -1 +1 @@ -3fce1453163152b542d5a901167f4392328eb997 \ No newline at end of file +c6b68521f68ca852fd4a275caed13d30cfa3d484 \ No newline at end of file diff --git a/external/bockbuild/packages/libtiff.py b/external/bockbuild/packages/libtiff.py index 26eb691f36..2cadcc64da 100644 --- a/external/bockbuild/packages/libtiff.py +++ b/external/bockbuild/packages/libtiff.py @@ -1,7 +1,7 @@ class LibTiffPackage (Package): def __init__(self): - Package.__init__(self, 'tiff', '4.0.8', + Package.__init__(self, 'tiff', '4.0.9', configure_flags=[ ], sources=[ diff --git a/external/cecil/.gitignore b/external/cecil/.gitignore index 08c8509f51..b369ea1f92 100644 --- a/external/cecil/.gitignore +++ b/external/cecil/.gitignore @@ -13,3 +13,4 @@ Mono.Cecil.sln.ide* TestResults project.lock.json .vs/ +.idea/ diff --git a/external/cecil/.travis.yml b/external/cecil/.travis.yml deleted file mode 100644 index 0f102833a3..0000000000 --- a/external/cecil/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: csharp -solution: Mono.Cecil.sln -install: - - nuget restore Mono.Cecil.sln - - nuget install NUnit.Runners -Version 2.6.4 -OutputDirectory testrunner -script: - - xbuild /p:Configuration=net_4_0_Debug Mono.Cecil.sln - - mono ./testrunner/NUnit.Runners.2.6.4/tools/nunit-console.exe Mono.Cecil.nunit diff --git a/external/cecil/Mono.Cecil.Cil/PortablePdb.cs b/external/cecil/Mono.Cecil.Cil/PortablePdb.cs index a7883e71d1..5d0555fbcc 100644 --- a/external/cecil/Mono.Cecil.Cil/PortablePdb.cs +++ b/external/cecil/Mono.Cecil.Cil/PortablePdb.cs @@ -158,7 +158,6 @@ namespace Mono.Cecil.Cil { public ISymbolReader GetSymbolReader (ModuleDefinition module, string fileName) { Mixin.CheckModule (module); - Mixin.CheckFileName (fileName); var header = module.GetDebugHeader (); var entry = header.GetEmbeddedPortablePdbEntry (); @@ -451,6 +450,8 @@ namespace Mono.Cecil.Cil { var directory = new ImageDebugDirectory { Type = ImageDebugType.EmbeddedPortablePdb, + MajorVersion = 0x0100, + MinorVersion = 0x0100, }; var data = new MemoryStream (); diff --git a/external/cecil/Mono.Cecil.Cil/Symbols.cs b/external/cecil/Mono.Cecil.Cil/Symbols.cs index ef40547c46..fc734ceb3a 100644 --- a/external/cecil/Mono.Cecil.Cil/Symbols.cs +++ b/external/cecil/Mono.Cecil.Cil/Symbols.cs @@ -16,6 +16,7 @@ using SR = System.Reflection; using Mono.Collections.Generic; using Mono.Cecil.Cil; +using Mono.Cecil.PE; namespace Mono.Cecil.Cil { @@ -855,7 +856,69 @@ namespace Mono.Cecil.Cil { public ISymbolReader GetSymbolReader (ModuleDefinition module, Stream symbolStream) { - throw new NotSupportedException (); + if (module.Image.HasDebugTables ()) + return null; + + if (module.HasDebugHeader) { + var header = module.GetDebugHeader (); + var entry = header.GetEmbeddedPortablePdbEntry (); + if (entry != null) + return new EmbeddedPortablePdbReaderProvider ().GetSymbolReader (module, ""); + } + + Mixin.CheckStream (symbolStream); + Mixin.CheckReadSeek (symbolStream); + + var position = symbolStream.Position; + + const int portablePdbHeader = 0x424a5342; + + var reader = new BinaryStreamReader (symbolStream); + var intHeader = reader.ReadInt32 (); + symbolStream.Position = position; + + if (intHeader == portablePdbHeader) { + return new PortablePdbReaderProvider ().GetSymbolReader (module, symbolStream); + } + + const string nativePdbHeader = "Microsoft C/C++ MSF 7.00"; + + var bytesHeader = reader.ReadBytes (nativePdbHeader.Length); + symbolStream.Position = position; + var isNativePdb = true; + + for (var i = 0; i < bytesHeader.Length; i++) { + if (bytesHeader [i] != (byte) nativePdbHeader [i]) { + isNativePdb = false; + break; + } + } + + if (isNativePdb) { + try { + return SymbolProvider.GetReaderProvider (SymbolKind.NativePdb).GetSymbolReader (module, symbolStream); + } catch (Exception) { + // We might not include support for native pdbs. + } + } + + const long mdbHeader = 0x45e82623fd7fa614; + + var longHeader = reader.ReadInt64 (); + symbolStream.Position = position; + + if (longHeader == mdbHeader) { + try { + return SymbolProvider.GetReaderProvider (SymbolKind.Mdb).GetSymbolReader (module, symbolStream); + } catch (Exception) { + // We might not include support for mdbs. + } + } + + if (throw_if_no_symbol) + throw new SymbolsNotFoundException (string.Format ("No symbols found in stream")); + + return null; } } diff --git a/external/cecil/Mono.Cecil.Tests.props b/external/cecil/Mono.Cecil.Tests.props index 49c1a386f1..284408a56e 100644 --- a/external/cecil/Mono.Cecil.Tests.props +++ b/external/cecil/Mono.Cecil.Tests.props @@ -13,13 +13,13 @@ - 3.7.1 + 3.10.1 - 15.3.0 + 15.8.0 - 3.8.0 + 3.10.0 diff --git a/external/cecil/Mono.Cecil.nuspec b/external/cecil/Mono.Cecil.nuspec index ab1d991834..6432e14ab3 100644 --- a/external/cecil/Mono.Cecil.nuspec +++ b/external/cecil/Mono.Cecil.nuspec @@ -2,7 +2,7 @@ Mono.Cecil - 0.10.0.0 + 0.10.1.0 Mono.Cecil Jb Evain Jb Evain diff --git a/external/cecil/Mono.Cecil.props b/external/cecil/Mono.Cecil.props index aef3a98a3f..bc3bd30cb5 100644 --- a/external/cecil/Mono.Cecil.props +++ b/external/cecil/Mono.Cecil.props @@ -43,6 +43,10 @@ v4.0 $(DefineConstants);NET_4_0; + + v4.6.2 + $(DefineConstants);NET_4_0; + netcoreapp2.0 netstandard1.3 @@ -62,6 +66,10 @@ + + + + diff --git a/external/cecil/Mono.Cecil.sln b/external/cecil/Mono.Cecil.sln index a8c436f342..1c64c2dec7 100644 --- a/external/cecil/Mono.Cecil.sln +++ b/external/cecil/Mono.Cecil.sln @@ -37,6 +37,10 @@ Global net_4_0_Debug|Any CPU = net_4_0_Debug|Any CPU net_4_0_Release_ReadOnly|Any CPU = net_4_0_Release_ReadOnly|Any CPU net_4_0_Release|Any CPU = net_4_0_Release|Any CPU + net_462_Debug_ReadOnly|Any CPU = net_462_Debug_ReadOnly|Any CPU + net_462_Debug|Any CPU = net_462_Debug|Any CPU + net_462_Release_ReadOnly|Any CPU = net_462_Release_ReadOnly|Any CPU + net_462_Release|Any CPU = net_462_Release|Any CPU netstandard_Debug_ReadOnly|Any CPU = netstandard_Debug_ReadOnly|Any CPU netstandard_Debug|Any CPU = netstandard_Debug|Any CPU netstandard_Release_ReadOnly|Any CPU = netstandard_Release_ReadOnly|Any CPU @@ -59,6 +63,14 @@ Global {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_0_Release_ReadOnly|Any CPU.Build.0 = net_4_0_Release_ReadOnly|Any CPU {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU + {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_462_Debug_ReadOnly|Any CPU.ActiveCfg = net_462_Debug_ReadOnly|Any CPU + {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_462_Debug_ReadOnly|Any CPU.Build.0 = net_462_Debug_ReadOnly|Any CPU + {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_462_Debug|Any CPU.ActiveCfg = net_462_Debug|Any CPU + {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_462_Debug|Any CPU.Build.0 = net_462_Debug|Any CPU + {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_462_Release_ReadOnly|Any CPU.ActiveCfg = net_462_Release_ReadOnly|Any CPU + {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_462_Release_ReadOnly|Any CPU.Build.0 = net_462_Release_ReadOnly|Any CPU + {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_462_Release|Any CPU.ActiveCfg = net_462_Release|Any CPU + {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_462_Release|Any CPU.Build.0 = net_462_Release|Any CPU {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.netstandard_Debug_ReadOnly|Any CPU.ActiveCfg = netstandard_Debug_ReadOnly|Any CPU {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.netstandard_Debug_ReadOnly|Any CPU.Build.0 = netstandard_Debug_ReadOnly|Any CPU {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.netstandard_Debug|Any CPU.ActiveCfg = netstandard_Debug|Any CPU @@ -83,6 +95,14 @@ Global {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_4_0_Release_ReadOnly|Any CPU.Build.0 = net_4_0_Release_ReadOnly|Any CPU {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU + {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_462_Debug_ReadOnly|Any CPU.ActiveCfg = net_462_Debug_ReadOnly|Any CPU + {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_462_Debug_ReadOnly|Any CPU.Build.0 = net_462_Debug_ReadOnly|Any CPU + {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_462_Debug|Any CPU.ActiveCfg = net_462_Debug|Any CPU + {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_462_Debug|Any CPU.Build.0 = net_462_Debug|Any CPU + {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_462_Release_ReadOnly|Any CPU.ActiveCfg = net_462_Release_ReadOnly|Any CPU + {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_462_Release_ReadOnly|Any CPU.Build.0 = net_462_Release_ReadOnly|Any CPU + {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_462_Release|Any CPU.ActiveCfg = net_462_Release|Any CPU + {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_462_Release|Any CPU.Build.0 = net_462_Release|Any CPU {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.netstandard_Debug_ReadOnly|Any CPU.ActiveCfg = netstandard_Debug_ReadOnly|Any CPU {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.netstandard_Debug_ReadOnly|Any CPU.Build.0 = netstandard_Debug_ReadOnly|Any CPU {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.netstandard_Debug|Any CPU.ActiveCfg = netstandard_Debug|Any CPU @@ -107,6 +127,14 @@ Global {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_4_0_Release_ReadOnly|Any CPU.Build.0 = net_4_0_Release_ReadOnly|Any CPU {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU + {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_462_Debug_ReadOnly|Any CPU.ActiveCfg = net_462_Debug_ReadOnly|Any CPU + {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_462_Debug_ReadOnly|Any CPU.Build.0 = net_462_Debug_ReadOnly|Any CPU + {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_462_Debug|Any CPU.ActiveCfg = net_462_Debug|Any CPU + {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_462_Debug|Any CPU.Build.0 = net_462_Debug|Any CPU + {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_462_Release_ReadOnly|Any CPU.ActiveCfg = net_462_Release_ReadOnly|Any CPU + {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_462_Release_ReadOnly|Any CPU.Build.0 = net_462_Release_ReadOnly|Any CPU + {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_462_Release|Any CPU.ActiveCfg = net_462_Release|Any CPU + {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_462_Release|Any CPU.Build.0 = net_462_Release|Any CPU {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.netstandard_Debug_ReadOnly|Any CPU.ActiveCfg = netstandard_Debug_ReadOnly|Any CPU {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.netstandard_Debug_ReadOnly|Any CPU.Build.0 = netstandard_Debug_ReadOnly|Any CPU {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.netstandard_Debug|Any CPU.ActiveCfg = netstandard_Debug|Any CPU @@ -131,6 +159,14 @@ Global {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_4_0_Release_ReadOnly|Any CPU.Build.0 = net_4_0_Release_ReadOnly|Any CPU {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU + {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_462_Debug_ReadOnly|Any CPU.ActiveCfg = net_462_Debug_ReadOnly|Any CPU + {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_462_Debug_ReadOnly|Any CPU.Build.0 = net_462_Debug_ReadOnly|Any CPU + {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_462_Debug|Any CPU.ActiveCfg = net_462_Debug|Any CPU + {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_462_Debug|Any CPU.Build.0 = net_462_Debug|Any CPU + {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_462_Release_ReadOnly|Any CPU.ActiveCfg = net_462_Release_ReadOnly|Any CPU + {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_462_Release_ReadOnly|Any CPU.Build.0 = net_462_Release_ReadOnly|Any CPU + {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_462_Release|Any CPU.ActiveCfg = net_462_Release|Any CPU + {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_462_Release|Any CPU.Build.0 = net_462_Release|Any CPU {AC71DF9C-99FA-4A63-990A-66C8010355A6}.netstandard_Debug_ReadOnly|Any CPU.ActiveCfg = netstandard_Debug_ReadOnly|Any CPU {AC71DF9C-99FA-4A63-990A-66C8010355A6}.netstandard_Debug|Any CPU.ActiveCfg = netstandard_Debug|Any CPU {AC71DF9C-99FA-4A63-990A-66C8010355A6}.netstandard_Release_ReadOnly|Any CPU.ActiveCfg = netstandard_Release_ReadOnly|Any CPU @@ -151,6 +187,14 @@ Global {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_4_0_Release_ReadOnly|Any CPU.Build.0 = net_4_0_Release_ReadOnly|Any CPU {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU + {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_462_Debug_ReadOnly|Any CPU.ActiveCfg = net_462_Debug_ReadOnly|Any CPU + {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_462_Debug_ReadOnly|Any CPU.Build.0 = net_462_Debug_ReadOnly|Any CPU + {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_462_Debug|Any CPU.ActiveCfg = net_462_Debug|Any CPU + {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_462_Debug|Any CPU.Build.0 = net_462_Debug|Any CPU + {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_462_Release_ReadOnly|Any CPU.ActiveCfg = net_462_Release_ReadOnly|Any CPU + {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_462_Release_ReadOnly|Any CPU.Build.0 = net_462_Release_ReadOnly|Any CPU + {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_462_Release|Any CPU.ActiveCfg = net_462_Release|Any CPU + {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_462_Release|Any CPU.Build.0 = net_462_Release|Any CPU {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.netstandard_Debug_ReadOnly|Any CPU.ActiveCfg = netstandard_Debug_ReadOnly|Any CPU {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.netstandard_Debug_ReadOnly|Any CPU.Build.0 = netstandard_Debug_ReadOnly|Any CPU {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.netstandard_Debug|Any CPU.ActiveCfg = netstandard_Debug|Any CPU @@ -175,6 +219,14 @@ Global {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_4_0_Release_ReadOnly|Any CPU.Build.0 = net_4_0_Release_ReadOnly|Any CPU {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU + {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_462_Debug_ReadOnly|Any CPU.ActiveCfg = net_462_Debug_ReadOnly|Any CPU + {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_462_Debug_ReadOnly|Any CPU.Build.0 = net_462_Debug_ReadOnly|Any CPU + {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_462_Debug|Any CPU.ActiveCfg = net_462_Debug|Any CPU + {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_462_Debug|Any CPU.Build.0 = net_462_Debug|Any CPU + {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_462_Release_ReadOnly|Any CPU.ActiveCfg = net_462_Release_ReadOnly|Any CPU + {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_462_Release_ReadOnly|Any CPU.Build.0 = net_462_Release_ReadOnly|Any CPU + {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_462_Release|Any CPU.ActiveCfg = net_462_Release|Any CPU + {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_462_Release|Any CPU.Build.0 = net_462_Release|Any CPU {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.netstandard_Debug_ReadOnly|Any CPU.ActiveCfg = netstandard_Debug_ReadOnly|Any CPU {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.netstandard_Debug|Any CPU.ActiveCfg = netstandard_Debug|Any CPU {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.netstandard_Release_ReadOnly|Any CPU.ActiveCfg = netstandard_Release_ReadOnly|Any CPU @@ -195,6 +247,14 @@ Global {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_4_0_Release_ReadOnly|Any CPU.Build.0 = net_4_0_Release_ReadOnly|Any CPU {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU + {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_462_Debug_ReadOnly|Any CPU.ActiveCfg = net_462_Debug_ReadOnly|Any CPU + {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_462_Debug_ReadOnly|Any CPU.Build.0 = net_462_Debug_ReadOnly|Any CPU + {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_462_Debug|Any CPU.ActiveCfg = net_462_Debug|Any CPU + {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_462_Debug|Any CPU.Build.0 = net_462_Debug|Any CPU + {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_462_Release_ReadOnly|Any CPU.ActiveCfg = net_462_Release_ReadOnly|Any CPU + {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_462_Release_ReadOnly|Any CPU.Build.0 = net_462_Release_ReadOnly|Any CPU + {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_462_Release|Any CPU.ActiveCfg = net_462_Release|Any CPU + {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_462_Release|Any CPU.Build.0 = net_462_Release|Any CPU {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.netstandard_Debug_ReadOnly|Any CPU.ActiveCfg = netstandard_Debug_ReadOnly|Any CPU {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.netstandard_Debug|Any CPU.ActiveCfg = netstandard_Debug|Any CPU {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.netstandard_Release_ReadOnly|Any CPU.ActiveCfg = netstandard_Release_ReadOnly|Any CPU @@ -215,6 +275,14 @@ Global {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_4_0_Release_ReadOnly|Any CPU.Build.0 = net_4_0_Release_ReadOnly|Any CPU {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU + {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_462_Debug_ReadOnly|Any CPU.ActiveCfg = net_462_Debug_ReadOnly|Any CPU + {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_462_Debug_ReadOnly|Any CPU.Build.0 = net_462_Debug_ReadOnly|Any CPU + {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_462_Debug|Any CPU.ActiveCfg = net_462_Debug|Any CPU + {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_462_Debug|Any CPU.Build.0 = net_462_Debug|Any CPU + {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_462_Release_ReadOnly|Any CPU.ActiveCfg = net_462_Release_ReadOnly|Any CPU + {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_462_Release_ReadOnly|Any CPU.Build.0 = net_462_Release_ReadOnly|Any CPU + {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_462_Release|Any CPU.ActiveCfg = net_462_Release|Any CPU + {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_462_Release|Any CPU.Build.0 = net_462_Release|Any CPU {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.netstandard_Debug_ReadOnly|Any CPU.ActiveCfg = netstandard_Debug_ReadOnly|Any CPU {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.netstandard_Debug_ReadOnly|Any CPU.Build.0 = netstandard_Debug_ReadOnly|Any CPU {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.netstandard_Debug|Any CPU.ActiveCfg = netstandard_Debug|Any CPU diff --git a/external/cecil/Mono.Cecil/AssemblyReader.cs b/external/cecil/Mono.Cecil/AssemblyReader.cs index db98f448e0..7954e9701f 100644 --- a/external/cecil/Mono.Cecil/AssemblyReader.cs +++ b/external/cecil/Mono.Cecil/AssemblyReader.cs @@ -2406,6 +2406,9 @@ namespace Mono.Cecil { if (token.TokenType != TokenType.Signature) throw new NotSupportedException (); + if (token.RID == 0) + return null; + if (!MoveTo (Table.StandAloneSig, token.RID)) return null; @@ -3763,8 +3766,10 @@ namespace Mono.Cecil { if (length == 0) return string.Empty; - var @string = Encoding.UTF8.GetString (buffer, position, - buffer [position + length - 1] == 0 ? length - 1 : length); + if (position + length >= buffer.Length) + return string.Empty; + + var @string = Encoding.UTF8.GetString (buffer, position, length); position += length; return @string; diff --git a/external/cecil/Mono.Cecil/AssemblyWriter.cs b/external/cecil/Mono.Cecil/AssemblyWriter.cs index 7b3710e2fd..1bccd027c4 100644 --- a/external/cecil/Mono.Cecil/AssemblyWriter.cs +++ b/external/cecil/Mono.Cecil/AssemblyWriter.cs @@ -1445,8 +1445,7 @@ namespace Mono.Cecil { if (type.HasInterfaces) AddInterfaces (type); - if (type.HasLayoutInfo) - AddLayoutInfo (type); + AddLayoutInfo (type); if (type.HasFields) AddFields (type); @@ -1557,12 +1556,36 @@ namespace Mono.Cecil { void AddLayoutInfo (TypeDefinition type) { - var table = GetTable (Table.ClassLayout); + if (type.HasLayoutInfo) { + var table = GetTable (Table.ClassLayout); - table.AddRow (new ClassLayoutRow ( - (ushort) type.PackingSize, - (uint) type.ClassSize, - type.token.RID)); + table.AddRow (new ClassLayoutRow ( + (ushort) type.PackingSize, + (uint) type.ClassSize, + type.token.RID)); + + return; + } + + if (type.IsValueType && HasNoInstanceField (type)) { + var table = GetTable (Table.ClassLayout); + + table.AddRow (new ClassLayoutRow (0, 1, type.token.RID)); + } + } + + static bool HasNoInstanceField (TypeDefinition type) + { + if (!type.HasFields) + return true; + + var fields = type.Fields; + + for (int i = 0; i < fields.Count; i++) + if (!fields [i].IsStatic) + return false; + + return true; } void AddNestedTypes (TypeDefinition type) @@ -3162,7 +3185,7 @@ namespace Mono.Cecil { void WriteTypeReference (TypeReference type) { - WriteUTF8String (TypeParser.ToParseable (type)); + WriteUTF8String (TypeParser.ToParseable (type, top_level: false)); } public void WriteMarshalInfo (MarshalInfo marshal_info) diff --git a/external/cecil/Mono.Cecil/MetadataResolver.cs b/external/cecil/Mono.Cecil/MetadataResolver.cs index 26c4e16d79..630ec8a7cd 100644 --- a/external/cecil/Mono.Cecil/MetadataResolver.cs +++ b/external/cecil/Mono.Cecil/MetadataResolver.cs @@ -59,6 +59,15 @@ namespace Mono.Cecil { this.member = member; } + public ResolutionException (MemberReference member, Exception innerException) + : base ("Failed to resolve " + member.FullName, innerException) + { + if (member == null) + throw new ArgumentNullException ("member"); + + this.member = member; + } + #if !NET_CORE ResolutionException ( System.Runtime.Serialization.SerializationInfo info, diff --git a/external/cecil/Mono.Cecil/TypeParser.cs b/external/cecil/Mono.Cecil/TypeParser.cs index d7c6aab1b0..07854cd6ed 100644 --- a/external/cecil/Mono.Cecil/TypeParser.cs +++ b/external/cecil/Mono.Cecil/TypeParser.cs @@ -402,13 +402,13 @@ namespace Mono.Cecil { return false; } - public static string ToParseable (TypeReference type) + public static string ToParseable (TypeReference type, bool top_level = true) { if (type == null) return null; var name = new StringBuilder (); - AppendType (type, name, true, true); + AppendType (type, name, true, top_level); return name.ToString (); } diff --git a/external/cecil/ProjectInfo.cs b/external/cecil/ProjectInfo.cs index a2a550d442..750118bbae 100644 --- a/external/cecil/ProjectInfo.cs +++ b/external/cecil/ProjectInfo.cs @@ -15,6 +15,6 @@ using System.Runtime.InteropServices; [assembly: ComVisible (false)] -[assembly: AssemblyVersion ("0.10.0.0")] -[assembly: AssemblyFileVersion ("0.10.0.0")] -[assembly: AssemblyInformationalVersion ("0.10.0.0")] +[assembly: AssemblyVersion ("0.10.1.0")] +[assembly: AssemblyFileVersion ("0.10.1.0")] +[assembly: AssemblyInformationalVersion ("0.10.1.0")] diff --git a/external/cecil/Test/Mono.Cecil.Tests/BaseTestFixture.cs b/external/cecil/Test/Mono.Cecil.Tests/BaseTestFixture.cs index c49880edae..476e17bbac 100644 --- a/external/cecil/Test/Mono.Cecil.Tests/BaseTestFixture.cs +++ b/external/cecil/Test/Mono.Cecil.Tests/BaseTestFixture.cs @@ -51,6 +51,11 @@ namespace Mono.Cecil.Tests { return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, GetType ().Assembly), new ReaderParameters (mode)); } + public Stream GetResourceStream (string name) + { + return new FileStream (GetAssemblyResourcePath (name, GetType ().Assembly), FileMode.Open, FileAccess.Read); + } + internal Image GetResourceImage (string name) { var file = new FileStream (GetAssemblyResourcePath (name, GetType ().Assembly), FileMode.Open, FileAccess.Read); diff --git a/external/cecil/Test/Mono.Cecil.Tests/CustomAttributesTests.cs b/external/cecil/Test/Mono.Cecil.Tests/CustomAttributesTests.cs index 8ec02705a3..db28ab5c18 100644 --- a/external/cecil/Test/Mono.Cecil.Tests/CustomAttributesTests.cs +++ b/external/cecil/Test/Mono.Cecil.Tests/CustomAttributesTests.cs @@ -449,6 +449,21 @@ namespace Mono.Cecil.Tests { }); } + [Test] + public void NullCharInString () + { + TestCSharp ("CustomAttributes.cs", module => { + var type = module.GetType ("NullCharInString"); + var attributes = type.CustomAttributes; + Assert.AreEqual (1, attributes.Count); + var attribute = attributes [0]; + Assert.AreEqual (1, attribute.ConstructorArguments.Count); + var value = (string) attribute.ConstructorArguments [0].Value; + Assert.AreEqual (8, value.Length); + Assert.AreEqual ('\0', value [7]); + }); + } + #if !READ_ONLY [Test] public void DefineCustomAttributeFromBlob () diff --git a/external/cecil/Test/Mono.Cecil.Tests/PortablePdbTests.cs b/external/cecil/Test/Mono.Cecil.Tests/PortablePdbTests.cs index 25ee2d1994..964c2accfa 100644 --- a/external/cecil/Test/Mono.Cecil.Tests/PortablePdbTests.cs +++ b/external/cecil/Test/Mono.Cecil.Tests/PortablePdbTests.cs @@ -364,6 +364,8 @@ namespace Mono.Cecil.Tests { var eppdb = header.Entries [1]; Assert.AreEqual (ImageDebugType.EmbeddedPortablePdb, eppdb.Directory.Type); + Assert.AreEqual (0x0100, eppdb.Directory.MajorVersion); + Assert.AreEqual (0x0100, eppdb.Directory.MinorVersion); }, symbolReaderProvider: typeof (EmbeddedPortablePdbReaderProvider), symbolWriterProvider: typeof (EmbeddedPortablePdbWriterProvider)); } diff --git a/external/cecil/Test/Mono.Cecil.Tests/SymbolTests.cs b/external/cecil/Test/Mono.Cecil.Tests/SymbolTests.cs index d1f239e3fe..b453bcc983 100644 --- a/external/cecil/Test/Mono.Cecil.Tests/SymbolTests.cs +++ b/external/cecil/Test/Mono.Cecil.Tests/SymbolTests.cs @@ -80,6 +80,58 @@ namespace Mono.Cecil.Tests { Assert.IsFalse (module.HasSymbols); } } + + [Test] + public void DefaultPortablePdbStream () + { + using (var symbolStream = GetResourceStream ("PdbTarget.pdb")) { + var parameters = new ReaderParameters { + SymbolReaderProvider = new PortablePdbReaderProvider (), + SymbolStream = symbolStream, + }; + + using (var module = GetResourceModule ("PdbTarget.exe", parameters)) { + Assert.IsNotNull (module.SymbolReader); + Assert.IsTrue (module.HasSymbols); + Assert.AreEqual (typeof (PortablePdbReader), module.SymbolReader.GetType ()); + } + } + } + + [Test] + public void DefaultPdbStream () + { + using (var symbolStream = GetResourceStream ("libpdb.pdb")) { + var parameters = new ReaderParameters { + SymbolReaderProvider = new NativePdbReaderProvider (), + SymbolStream = symbolStream, + }; + + using (var module = GetResourceModule ("libpdb.dll", parameters)) { + Assert.IsNotNull (module.SymbolReader); + Assert.IsTrue (module.HasSymbols); + Assert.AreEqual (typeof (NativePdbReader), module.SymbolReader.GetType ()); + } + } + } + + [Test] + public void DefaultMdbStream () + { + using (var symbolStream = GetResourceStream ("libmdb.dll.mdb")) { + var parameters = new ReaderParameters { + SymbolReaderProvider = new MdbReaderProvider (), + SymbolStream = symbolStream, + }; + + using (var module = GetResourceModule ("libmdb.dll", parameters)) { + Assert.IsNotNull (module.SymbolReader); + Assert.IsTrue (module.HasSymbols); + Assert.AreEqual (typeof (MdbReader), module.SymbolReader.GetType ()); + } + } + } } } -#endif \ No newline at end of file + +#endif diff --git a/external/cecil/Test/Mono.Cecil.Tests/TypeTests.cs b/external/cecil/Test/Mono.Cecil.Tests/TypeTests.cs index d378042095..a18e4a1884 100644 --- a/external/cecil/Test/Mono.Cecil.Tests/TypeTests.cs +++ b/external/cecil/Test/Mono.Cecil.Tests/TypeTests.cs @@ -30,6 +30,19 @@ namespace Mono.Cecil.Tests { }); } + [Test] + public void EmptyStructLayout () + { + TestModule ("hello.exe", module => + { + var foo = new TypeDefinition ("", "Foo", + TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit | TypeAttributes.SequentialLayout, + module.ImportReference (typeof (ValueType))) ; + + module.Types.Add (foo) ; + }) ; + } + [Test] public void SimpleInterfaces () { diff --git a/external/cecil/Test/Resources/cs/CustomAttributes.cs b/external/cecil/Test/Resources/cs/CustomAttributes.cs index dc2839b77d..11939ed200 100644 --- a/external/cecil/Test/Resources/cs/CustomAttributes.cs +++ b/external/cecil/Test/Resources/cs/CustomAttributes.cs @@ -156,3 +156,7 @@ class Parent { public class Child { } } + +[Foo ("Foo\0Bar\0")] +class NullCharInString { +} diff --git a/external/cecil/rocks/Mono.Cecil.Rocks/DocCommentId.cs b/external/cecil/rocks/Mono.Cecil.Rocks/DocCommentId.cs index 30740df673..da74bedee4 100644 --- a/external/cecil/rocks/Mono.Cecil.Rocks/DocCommentId.cs +++ b/external/cecil/rocks/Mono.Cecil.Rocks/DocCommentId.cs @@ -222,7 +222,7 @@ namespace Mono.Cecil.Rocks { void WriteItemName (string name) { - id.Append (name.Replace ('.', '#')); + id.Append (name.Replace ('.', '#').Replace('<', '{').Replace('>', '}')); } public override string ToString () diff --git a/external/cecil/rocks/Test/Mono.Cecil.Rocks.Tests.csproj b/external/cecil/rocks/Test/Mono.Cecil.Rocks.Tests.csproj index 4019977632..7c1946c5cf 100644 --- a/external/cecil/rocks/Test/Mono.Cecil.Rocks.Tests.csproj +++ b/external/cecil/rocks/Test/Mono.Cecil.Rocks.Tests.csproj @@ -1,5 +1,6 @@  + {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52} Mono.Cecil.Rocks.Tests @@ -25,6 +26,5 @@ - - + \ No newline at end of file diff --git a/external/cecil/rocks/Test/Mono.Cecil.Tests/DocCommentIdTests.cs b/external/cecil/rocks/Test/Mono.Cecil.Tests/DocCommentIdTests.cs index b18824c613..244d5ae92e 100644 --- a/external/cecil/rocks/Test/Mono.Cecil.Tests/DocCommentIdTests.cs +++ b/external/cecil/rocks/Test/Mono.Cecil.Tests/DocCommentIdTests.cs @@ -8,10 +8,11 @@ using Mono.Cecil.Rocks; namespace N { + /// /// ID string generated is "T:N.X". /// - public class X + public class X : IX> { /// /// ID string generated is "M:N.X.#ctor". @@ -102,7 +103,19 @@ namespace N public static void Linq (IEnumerable enumerable, Func selector) { } + + /// + /// ID string generated is "M:N.X.N#IX{N#KVP{System#String,System#Int32}}#IXA(N.KVP{System.String,System.Int32})" + /// + void IX>.IXA (KVP k) { } } + + public interface IX + { + void IXA (K k); + } + + public class KVP { } } namespace Mono.Cecil.Tests { @@ -251,6 +264,15 @@ namespace Mono.Cecil.Tests { AssertDocumentID ("M:N.X.Linq(System.Collections.Generic.IEnumerable{System.String},System.Func{System.String})", method); } + [Test] + public void EII () + { + var type = GetTestType (); + var method = type.Methods.Where (m => m.Name.Contains("IXA")).First (); + + AssertDocumentID ("M:N.X.N#IX{N#KVP{System#String,System#Int32}}#IXA(N.KVP{System.String,System.Int32})", method); + } + TypeDefinition GetTestType () { return typeof (N.X).ToDefinition (); diff --git a/external/cecil/symbols/mdb/Test/Mono.Cecil.Mdb.Tests.csproj b/external/cecil/symbols/mdb/Test/Mono.Cecil.Mdb.Tests.csproj index 9b899ed4dc..81cfc63eca 100644 --- a/external/cecil/symbols/mdb/Test/Mono.Cecil.Mdb.Tests.csproj +++ b/external/cecil/symbols/mdb/Test/Mono.Cecil.Mdb.Tests.csproj @@ -1,5 +1,6 @@  + {AC71DF9C-99FA-4A63-990A-66C8010355A6} Mono.Cecil.Mdb.Tests @@ -25,6 +26,5 @@ - - + \ No newline at end of file diff --git a/external/cecil/symbols/pdb/Mono.Cecil.Pdb/NativePdbReader.cs b/external/cecil/symbols/pdb/Mono.Cecil.Pdb/NativePdbReader.cs index da0cd36e95..49c509a59c 100644 --- a/external/cecil/symbols/pdb/Mono.Cecil.Pdb/NativePdbReader.cs +++ b/external/cecil/symbols/pdb/Mono.Cecil.Pdb/NativePdbReader.cs @@ -61,8 +61,6 @@ namespace Mono.Cecil.Pdb { if (directory.Type != ImageDebugType.CodeView) return false; - if (directory.MajorVersion != 0 || directory.MinorVersion != 0) - return false; var data = entry.Data; diff --git a/external/cecil/symbols/pdb/Test/Mono.Cecil.Pdb.Tests.csproj b/external/cecil/symbols/pdb/Test/Mono.Cecil.Pdb.Tests.csproj index 2b03651a9e..54fccb03e4 100644 --- a/external/cecil/symbols/pdb/Test/Mono.Cecil.Pdb.Tests.csproj +++ b/external/cecil/symbols/pdb/Test/Mono.Cecil.Pdb.Tests.csproj @@ -1,5 +1,6 @@  + {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA} Mono.Cecil.Pdb.Tests @@ -25,6 +26,5 @@ - - + \ No newline at end of file diff --git a/external/corefx/src/Common/src/CoreLib/System/BitConverter.cs b/external/corefx/src/Common/src/CoreLib/System/BitConverter.cs index e3cf20eb6a..a5553f13c3 100644 --- a/external/corefx/src/Common/src/CoreLib/System/BitConverter.cs +++ b/external/corefx/src/Common/src/CoreLib/System/BitConverter.cs @@ -14,15 +14,17 @@ namespace System // converting an array of bytes to one of the base data // types, as well as for converting a base data type to an // array of bytes. - public static class BitConverter + public static partial class BitConverter { // This field indicates the "endianess" of the architecture. // The value is set to true if the architecture is // little endian; false if it is big endian. +#if !MONO #if BIGENDIAN public static readonly bool IsLittleEndian /* = false */; #else public static readonly bool IsLittleEndian = true; +#endif #endif // Converts a Boolean into an array of bytes with length one. @@ -380,6 +382,22 @@ namespace System throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3))); } +#if __MonoCS__ //use old impl for mcs + const string HexValues = "0123456789ABCDEF"; + int chArrayLength = length * 3; + + char[] chArray = new char[chArrayLength]; + int i = 0; + int index = startIndex; + for (i = 0; i < chArrayLength; i += 3) + { + byte b = value[index++]; + chArray[i] = HexValues[b >> 4]; + chArray[i + 1] = HexValues[b & 0xF]; + chArray[i + 2] = '-'; + } + return new String(chArray, 0, chArray.Length - 1); +#else return string.Create(length * 3 - 1, (value, startIndex, length), (dst, state) => { const string HexValues = "0123456789ABCDEF"; @@ -401,6 +419,7 @@ namespace System dst[j++] = HexValues[b & 0xF]; } }); +#endif } // Converts an array of bytes into a String. diff --git a/external/corefx/src/Common/src/CoreLib/System/ComponentModel/DefaultValueAttribute.cs b/external/corefx/src/Common/src/CoreLib/System/ComponentModel/DefaultValueAttribute.cs index 3cdc907297..f65f1efdd8 100644 --- a/external/corefx/src/Common/src/CoreLib/System/ComponentModel/DefaultValueAttribute.cs +++ b/external/corefx/src/Common/src/CoreLib/System/ComponentModel/DefaultValueAttribute.cs @@ -2,11 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.ComponentModel; -using System.Diagnostics; using System.Globalization; -using System.Runtime.InteropServices; +using System.Threading; namespace System.ComponentModel { @@ -23,6 +20,9 @@ namespace System.ComponentModel /// private object _value; + // Delegate ad hoc created 'TypeDescriptor.ConvertFromInvariantString' reflection object cache + static object s_convertFromInvariantString; + /// /// Initializes a new instance of the class, converting the /// specified value to the @@ -36,7 +36,24 @@ namespace System.ComponentModel // load an otherwise normal class. try { - if (type.IsSubclassOf(typeof(Enum))) +#if __MonoCS__ + // lazy init reflection objects + if (s_convertFromInvariantString == null) + { + Type typeDescriptorType = Type.GetType("System.ComponentModel.TypeDescriptor, System.ComponentModel.TypeConverter", throwOnError: false); + Volatile.Write(ref s_convertFromInvariantString, typeDescriptorType == null ? new object() : Delegate.CreateDelegate(typeof(Func), typeDescriptorType, "ConvertFromInvariantString", ignoreCase: false)); + } + if (s_convertFromInvariantString is Func convertFromInvariantString) + { + _value = convertFromInvariantString(type, value); + } +#else + if (TryConvertFromInvariantString(type, value, out object convertedValue)) + { + _value = convertedValue; + } +#endif + else if (type.IsSubclassOf(typeof(Enum))) { _value = Enum.Parse(type, value, true); } @@ -48,6 +65,29 @@ namespace System.ComponentModel { _value = Convert.ChangeType(value, type, CultureInfo.InvariantCulture); } + + return; +#if !__MonoCS__ + // Looking for ad hoc created TypeDescriptor.ConvertFromInvariantString(Type, string) + bool TryConvertFromInvariantString(Type typeToConvert, string stringValue, out object conversionResult) + { + conversionResult = null; + + // lazy init reflection objects + if (s_convertFromInvariantString == null) + { + Type typeDescriptorType = Type.GetType("System.ComponentModel.TypeDescriptor, System.ComponentModel.TypeConverter", throwOnError: false); + Volatile.Write(ref s_convertFromInvariantString, typeDescriptorType == null ? new object() : Delegate.CreateDelegate(typeof(Func), typeDescriptorType, "ConvertFromInvariantString", ignoreCase: false)); + } + + if (!(s_convertFromInvariantString is Func convertFromInvariantString)) + return false; + + conversionResult = convertFromInvariantString(typeToConvert, stringValue); + + return true; + } +#endif } catch { diff --git a/external/corefx/src/Common/src/CoreLib/System/CurrentSystemTimeZone.cs b/external/corefx/src/Common/src/CoreLib/System/CurrentSystemTimeZone.cs index bab6a92bf5..607b5570b1 100644 --- a/external/corefx/src/Common/src/CoreLib/System/CurrentSystemTimeZone.cs +++ b/external/corefx/src/Common/src/CoreLib/System/CurrentSystemTimeZone.cs @@ -26,6 +26,9 @@ using System.Runtime.Versioning; namespace System { +#if MONO + [Serializable] +#endif [Obsolete("System.CurrentSystemTimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo.Local instead.")] internal partial class CurrentSystemTimeZone : TimeZone { diff --git a/external/corefx/src/Common/src/CoreLib/System/DateTime.cs b/external/corefx/src/Common/src/CoreLib/System/DateTime.cs index 9c3b3989e4..f4fd380631 100644 --- a/external/corefx/src/Common/src/CoreLib/System/DateTime.cs +++ b/external/corefx/src/Common/src/CoreLib/System/DateTime.cs @@ -52,7 +52,9 @@ namespace System // [StructLayout(LayoutKind.Auto)] [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public readonly partial struct DateTime : IComparable, IFormattable, IConvertible, IComparable, IEquatable, ISerializable, ISpanFormattable { // Number of 100ns ticks per time unit diff --git a/external/corefx/src/Common/src/CoreLib/System/DateTimeOffset.cs b/external/corefx/src/Common/src/CoreLib/System/DateTimeOffset.cs index 3c3f3f42a2..52b97f048f 100644 --- a/external/corefx/src/Common/src/CoreLib/System/DateTimeOffset.cs +++ b/external/corefx/src/Common/src/CoreLib/System/DateTimeOffset.cs @@ -30,7 +30,9 @@ namespace System [StructLayout(LayoutKind.Auto)] [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public struct DateTimeOffset : IComparable, IFormattable, IComparable, IEquatable, ISerializable, IDeserializationCallback, ISpanFormattable { // Constants diff --git a/external/corefx/src/Common/src/CoreLib/System/Globalization/DateTimeFormat.cs b/external/corefx/src/Common/src/CoreLib/System/Globalization/DateTimeFormat.cs index 092ad0365d..2b34d34485 100644 --- a/external/corefx/src/Common/src/CoreLib/System/Globalization/DateTimeFormat.cs +++ b/external/corefx/src/Common/src/CoreLib/System/Globalization/DateTimeFormat.cs @@ -461,7 +461,7 @@ namespace System } // This is a flag to indicate if we are format the dates using Hebrew calendar. - bool isHebrewCalendar = (cal.ID == CalendarId.HEBREW); + bool isHebrewCalendar = ((CalendarId)cal.ID == CalendarId.HEBREW); // This is a flag to indicate if we are formating hour/minute/second only. bool bTimeOnly = true; @@ -657,7 +657,7 @@ namespace System { FormatDigits(result, year, tokenLen <= 2 ? tokenLen : 2); } - else if (cal.ID == CalendarId.HEBREW) + else if ((CalendarId)cal.ID == CalendarId.HEBREW) { HebrewFormatDigits(result, year); } @@ -1085,7 +1085,7 @@ namespace System // thrown when we try to get the Japanese year for Gregorian year 0001. // Therefore, the workaround allows them to call ToString() for time of day from a DateTime by // formatting as ISO 8601 format. - switch (dtfi.Calendar.ID) + switch ((CalendarId)dtfi.Calendar.ID) { case CalendarId.JAPAN: case CalendarId.TAIWAN: diff --git a/external/corefx/src/Common/src/CoreLib/System/Globalization/DateTimeFormatInfo.cs.REMOVED.git-id b/external/corefx/src/Common/src/CoreLib/System/Globalization/DateTimeFormatInfo.cs.REMOVED.git-id index 1c8fb1eade..185397554c 100644 --- a/external/corefx/src/Common/src/CoreLib/System/Globalization/DateTimeFormatInfo.cs.REMOVED.git-id +++ b/external/corefx/src/Common/src/CoreLib/System/Globalization/DateTimeFormatInfo.cs.REMOVED.git-id @@ -1 +1 @@ -edec75ac85bbf13b7caaceabd789b69a9d4aadf5 \ No newline at end of file +69bc2d672d3fa08d33dac7ed1dd7328169f5d16d \ No newline at end of file diff --git a/external/corefx/src/Common/src/CoreLib/System/Globalization/DateTimeParse.cs.REMOVED.git-id b/external/corefx/src/Common/src/CoreLib/System/Globalization/DateTimeParse.cs.REMOVED.git-id index ffc4070332..01ba88f451 100644 --- a/external/corefx/src/Common/src/CoreLib/System/Globalization/DateTimeParse.cs.REMOVED.git-id +++ b/external/corefx/src/Common/src/CoreLib/System/Globalization/DateTimeParse.cs.REMOVED.git-id @@ -1 +1 @@ -970d1765bb32a4d94bf196a4494ce22b095e4f1c \ No newline at end of file +840ef7d4d277306043f86562f9cd7df1ea63583b \ No newline at end of file diff --git a/external/corefx/src/Common/src/CoreLib/System/IO/FileLoadException.cs b/external/corefx/src/Common/src/CoreLib/System/IO/FileLoadException.cs index 8c31244e1d..fdba20f48d 100644 --- a/external/corefx/src/Common/src/CoreLib/System/IO/FileLoadException.cs +++ b/external/corefx/src/Common/src/CoreLib/System/IO/FileLoadException.cs @@ -7,7 +7,9 @@ using System.Runtime.Serialization; namespace System.IO { [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public partial class FileLoadException : IOException { public FileLoadException() diff --git a/external/corefx/src/Common/src/CoreLib/System/IO/IOException.cs b/external/corefx/src/Common/src/CoreLib/System/IO/IOException.cs index 89b25d5142..de6c910f21 100644 --- a/external/corefx/src/Common/src/CoreLib/System/IO/IOException.cs +++ b/external/corefx/src/Common/src/CoreLib/System/IO/IOException.cs @@ -8,7 +8,9 @@ using System.Runtime.Serialization; namespace System.IO { [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public class IOException : SystemException { public IOException() diff --git a/external/corefx/src/Common/src/CoreLib/System/IO/MemoryStream.cs b/external/corefx/src/Common/src/CoreLib/System/IO/MemoryStream.cs index fb319de7c2..6b5fe8a9bd 100644 --- a/external/corefx/src/Common/src/CoreLib/System/IO/MemoryStream.cs +++ b/external/corefx/src/Common/src/CoreLib/System/IO/MemoryStream.cs @@ -18,6 +18,9 @@ namespace System.IO // from an unsigned byte array, or you can create an empty one. Empty // memory streams are resizable, while ones created with a byte array provide // a stream "view" of the data. +#if MONO + [Serializable] +#endif public class MemoryStream : Stream { private byte[] _buffer; // Either allocated internally or externally. @@ -32,6 +35,9 @@ namespace System.IO private bool _exposable; // Whether the array can be returned to the user. private bool _isOpen; // Is this stream open or closed? +#if MONO + [NonSerialized] +#endif private Task _lastReadTask; // The last successful task returned from ReadAsync private const int MemStreamMaxLength = int.MaxValue; @@ -165,10 +171,18 @@ namespace System.IO // We want to expand the array up to Array.MaxByteArrayLength // And we want to give the user the value that they asked for + +#if MONO //in Mono we don't want to add additional fields to Array + if ((uint)(_capacity * 2) > Array_ReferenceSources.MaxByteArrayLength) + { + newCapacity = value > Array_ReferenceSources.MaxByteArrayLength ? value : Array_ReferenceSources.MaxByteArrayLength; + } +#else if ((uint)(_capacity * 2) > Array.MaxByteArrayLength) { newCapacity = value > Array.MaxByteArrayLength ? value : Array.MaxByteArrayLength; } +#endif Capacity = newCapacity; return true; @@ -223,6 +237,14 @@ namespace System.IO { return _buffer; } +#if MONO // Mono's ResourceWriter from referencesource still uses this method + internal void InternalGetOriginAndLength(out int origin, out int length) + { + if (!_isOpen) __Error.StreamIsClosed(); + origin = _origin; + length = _length; + } +#endif // PERF: True cursor position, we don't need _origin for direct access internal int InternalGetPosition() diff --git a/external/corefx/src/Common/src/CoreLib/System/IO/StreamReader.cs b/external/corefx/src/Common/src/CoreLib/System/IO/StreamReader.cs index 46729af793..e6f17ba195 100644 --- a/external/corefx/src/Common/src/CoreLib/System/IO/StreamReader.cs +++ b/external/corefx/src/Common/src/CoreLib/System/IO/StreamReader.cs @@ -1018,7 +1018,11 @@ namespace System.IO CheckAsyncTaskInProgress(); +#if !__MonoCS__ Task task = ReadAsyncInternal(new Memory(buffer, index, count), default).AsTask(); +#else + Task task = ReadAsyncInternal(new Memory(buffer, index, count), default); +#endif _asyncReadTask = task; return task; @@ -1044,10 +1048,18 @@ namespace System.IO return new ValueTask(Task.FromCanceled(cancellationToken)); } +#if !__MonoCS__ return ReadAsyncInternal(buffer, cancellationToken); +#else + return new ValueTask(ReadAsyncInternal(buffer, cancellationToken)); +#endif } +#if !__MonoCS__ internal override async ValueTask ReadAsyncInternal(Memory buffer, CancellationToken cancellationToken) +#else + internal override async Task ReadAsyncInternal(Memory buffer, CancellationToken cancellationToken) +#endif { if (_charPos == _charLen && (await ReadBufferAsync().ConfigureAwait(false)) == 0) { @@ -1276,7 +1288,11 @@ namespace System.IO return new ValueTask(Task.FromCanceled(cancellationToken)); } +#if !__MonoCS__ ValueTask vt = ReadBlockAsyncInternal(buffer, cancellationToken); +#else + ValueTask vt = new ValueTask (ReadBlockAsyncInternal(buffer, cancellationToken)); +#endif if (vt.IsCompletedSuccessfully) { return vt; @@ -1419,5 +1435,15 @@ namespace System.IO return 0; } } +#if MONO + // + // Used internally by our console, as it previously depended on Peek() being a + // routine that would not block. + // + internal bool DataAvailable () + { + return _charPos < _charLen; + } +#endif } } diff --git a/external/corefx/src/Common/src/CoreLib/System/IO/TextReader.cs b/external/corefx/src/Common/src/CoreLib/System/IO/TextReader.cs index d4d7e54a18..7c4e686c16 100644 --- a/external/corefx/src/Common/src/CoreLib/System/IO/TextReader.cs +++ b/external/corefx/src/Common/src/CoreLib/System/IO/TextReader.cs @@ -249,7 +249,11 @@ namespace System.IO throw new ArgumentException(SR.Argument_InvalidOffLen); } +#if !__MonoCS__ return ReadAsyncInternal(new Memory(buffer, index, count), default).AsTask(); +#else + return ReadAsyncInternal(new Memory(buffer, index, count), default); +#endif } public virtual ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default(CancellationToken)) => @@ -261,15 +265,29 @@ namespace System.IO return t.Item1.Read(t.Item2.Span); }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); +#if !__MonoCS__ internal virtual ValueTask ReadAsyncInternal(Memory buffer, CancellationToken cancellationToken) +#else + internal virtual Task ReadAsyncInternal(Memory buffer, CancellationToken cancellationToken) +#endif { var tuple = new Tuple>(this, buffer); +#if !__MonoCS__ return new ValueTask(Task.Factory.StartNew(state => { var t = (Tuple>)state; return t.Item1.Read(t.Item2.Span); }, tuple, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); +#else + return Task.Factory.StartNew(state => + { + var t = (Tuple>)state; + return t.Item1.Read(t.Item2.Span); + }, + tuple, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); +#endif + } public virtual Task ReadBlockAsync(char[] buffer, int index, int count) @@ -287,7 +305,11 @@ namespace System.IO throw new ArgumentException(SR.Argument_InvalidOffLen); } +#if !__MonoCS__ return ReadBlockAsyncInternal(new Memory(buffer, index, count), default).AsTask(); +#else + return ReadBlockAsyncInternal(new Memory(buffer, index, count), default); +#endif } public virtual ValueTask ReadBlockAsync(Memory buffer, CancellationToken cancellationToken = default(CancellationToken)) => @@ -299,7 +321,11 @@ namespace System.IO return t.Item1.ReadBlock(t.Item2.Span); }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); +#if !__MonoCS__ internal async ValueTask ReadBlockAsyncInternal(Memory buffer, CancellationToken cancellationToken) +#else + internal async Task ReadBlockAsyncInternal(Memory buffer, CancellationToken cancellationToken) +#endif { int n = 0, i; do diff --git a/external/corefx/src/Common/src/CoreLib/System/IO/UnmanagedMemoryStream.cs b/external/corefx/src/Common/src/CoreLib/System/IO/UnmanagedMemoryStream.cs index 2bcb16f24e..20fd42b154 100644 --- a/external/corefx/src/Common/src/CoreLib/System/IO/UnmanagedMemoryStream.cs +++ b/external/corefx/src/Common/src/CoreLib/System/IO/UnmanagedMemoryStream.cs @@ -46,7 +46,11 @@ namespace System.IO private long _position; private long _offset; private FileAccess _access; +#if MONO // Mono's HGlobalUnmanagedMemoryStream class uses this field + internal bool _isOpen; +#else private bool _isOpen; +#endif private Task _lastReadTask; // The last successful task returned from ReadAsync /// diff --git a/external/corefx/src/Common/src/CoreLib/System/InvalidTimeZoneException.cs b/external/corefx/src/Common/src/CoreLib/System/InvalidTimeZoneException.cs index 3a7e41c843..f88c96cd74 100644 --- a/external/corefx/src/Common/src/CoreLib/System/InvalidTimeZoneException.cs +++ b/external/corefx/src/Common/src/CoreLib/System/InvalidTimeZoneException.cs @@ -7,7 +7,7 @@ using System.Runtime.Serialization; namespace System { [Serializable] -#if MONO +#if MONO && MOBILE [System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e")] #else [System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] diff --git a/external/corefx/src/Common/src/CoreLib/System/Math.cs b/external/corefx/src/Common/src/CoreLib/System/Math.cs index a175103f81..27ef7752de 100644 --- a/external/corefx/src/Common/src/CoreLib/System/Math.cs +++ b/external/corefx/src/Common/src/CoreLib/System/Math.cs @@ -644,6 +644,7 @@ namespace System return decimal.Round(d, decimals, mode); } +#if !MONO [Intrinsic] public static double Round(double a) { @@ -672,6 +673,10 @@ namespace System return copysign(flrTempVal, a); } +#else + [MethodImplAttribute(MethodImplOptions.InternalCall)] + public static extern double Round(double a); +#endif [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Round(double value, int digits) diff --git a/external/corefx/src/Common/src/CoreLib/System/Reflection/ConstructorInfo.cs b/external/corefx/src/Common/src/CoreLib/System/Reflection/ConstructorInfo.cs index 3ee1dbf855..b823f24bb6 100644 --- a/external/corefx/src/Common/src/CoreLib/System/Reflection/ConstructorInfo.cs +++ b/external/corefx/src/Common/src/CoreLib/System/Reflection/ConstructorInfo.cs @@ -7,6 +7,9 @@ using System.Globalization; namespace System.Reflection { +#if MONO + [Serializable] +#endif public abstract partial class ConstructorInfo : MethodBase { protected ConstructorInfo() { } @@ -15,7 +18,11 @@ namespace System.Reflection [DebuggerHidden] [DebuggerStepThrough] +#if MONO + public object Invoke(object[] parameters) => Invoke(BindingFlags.CreateInstance, binder: null, parameters: parameters, culture: null); +#else public object Invoke(object[] parameters) => Invoke(BindingFlags.Default, binder: null, parameters: parameters, culture: null); +#endif public abstract object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture); public override bool Equals(object obj) => base.Equals(obj); diff --git a/external/corefx/src/Common/src/CoreLib/System/Reflection/EventInfo.cs b/external/corefx/src/Common/src/CoreLib/System/Reflection/EventInfo.cs index ccd9acf648..3f3c51cf32 100644 --- a/external/corefx/src/Common/src/CoreLib/System/Reflection/EventInfo.cs +++ b/external/corefx/src/Common/src/CoreLib/System/Reflection/EventInfo.cs @@ -10,7 +10,7 @@ using EventRegistrationToken = System.Runtime.InteropServices.WindowsRuntime.Eve namespace System.Reflection { - public abstract class EventInfo : MemberInfo + public abstract partial class EventInfo : MemberInfo { protected EventInfo() { } @@ -49,7 +49,12 @@ namespace System.Reflection get { MethodInfo m = GetAddMethod(true); +#if MONO + ParameterInfo[] p = m.GetParametersInternal (); +#else ParameterInfo[] p = m.GetParametersNoCopy(); +#endif + Type del = typeof(Delegate); for (int i = 0; i < p.Length; i++) { @@ -61,6 +66,7 @@ namespace System.Reflection } } +#if !MONO [DebuggerHidden] [DebuggerStepThrough] public virtual void AddEventHandler(object target, Delegate handler) @@ -77,6 +83,7 @@ namespace System.Reflection addMethod.Invoke(target, new object[] { handler }); } +#endif [DebuggerHidden] [DebuggerStepThrough] diff --git a/external/corefx/src/Common/src/CoreLib/System/Reflection/Module.cs b/external/corefx/src/Common/src/CoreLib/System/Reflection/Module.cs index 56f83c40d9..a2d3aa3bbb 100644 --- a/external/corefx/src/Common/src/CoreLib/System/Reflection/Module.cs +++ b/external/corefx/src/Common/src/CoreLib/System/Reflection/Module.cs @@ -7,7 +7,7 @@ using System.Runtime.Serialization; namespace System.Reflection { - public abstract class Module : ICustomAttributeProvider, ISerializable + public abstract partial class Module : ICustomAttributeProvider, ISerializable { protected Module() { } diff --git a/external/corefx/src/Common/src/CoreLib/System/Reflection/ParameterInfo.cs b/external/corefx/src/Common/src/CoreLib/System/Reflection/ParameterInfo.cs index 94bfffaa53..eaad967bb2 100644 --- a/external/corefx/src/Common/src/CoreLib/System/Reflection/ParameterInfo.cs +++ b/external/corefx/src/Common/src/CoreLib/System/Reflection/ParameterInfo.cs @@ -4,9 +4,16 @@ using System.Collections.Generic; using System.Runtime.Serialization; +#if MONO +using System.Runtime.InteropServices; +#endif namespace System.Reflection { +#if MONO + [Serializable] + [StructLayout (LayoutKind.Sequential)] +#endif public class ParameterInfo : ICustomAttributeProvider, IObjectReference { protected ParameterInfo() { } diff --git a/external/corefx/src/Common/src/CoreLib/System/String.cs b/external/corefx/src/Common/src/CoreLib/System/String.cs index 4ea8ce81b6..00aec0515a 100644 --- a/external/corefx/src/Common/src/CoreLib/System/String.cs +++ b/external/corefx/src/Common/src/CoreLib/System/String.cs @@ -30,7 +30,7 @@ namespace System // declared constructors. [MethodImplAttribute(MethodImplOptions.InternalCall)] - [PreserveDependency("System.String.CreateString(System.Char[])")] + [PreserveDependency("CreateString(System.Char[])", "System.String")] public extern String(char[] value); #if PROJECTN @@ -54,7 +54,7 @@ namespace System } [MethodImplAttribute(MethodImplOptions.InternalCall)] - [PreserveDependency("System.String.CreateString(System.Char[], System.Int32, System.Int32)")] + [PreserveDependency("CreateString(System.Char[], System.Int32, System.Int32)", "System.String")] public extern String(char[] value, int startIndex, int length); #if PROJECTN @@ -91,7 +91,7 @@ namespace System [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.InternalCall)] - [PreserveDependency("System.String.CreateString(System.Char*)")] + [PreserveDependency("CreateString(System.Char*)", "System.String")] public extern unsafe String(char* value); #if PROJECTN @@ -117,7 +117,7 @@ namespace System [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.InternalCall)] - [PreserveDependency("System.String.CreateString(System.Char*, System.Int32, System.Int32)")] + [PreserveDependency("CreateString(System.Char*, System.Int32, System.Int32)", "System.String")] public extern unsafe String(char* value, int startIndex, int length); #if PROJECTN @@ -154,7 +154,7 @@ namespace System [CLSCompliant(false)] [MethodImpl(MethodImplOptions.InternalCall)] - [PreserveDependency("System.String.CreateString(System.SByte*)")] + [PreserveDependency("CreateString(System.SByte*)", "System.String")] public extern unsafe String(sbyte* value); #if PROJECTN @@ -180,7 +180,7 @@ namespace System [CLSCompliant(false)] [MethodImpl(MethodImplOptions.InternalCall)] - [PreserveDependency("System.String.CreateString(System.SByte*, System.Int32, System.Int32)")] + [PreserveDependency("CreateString(System.SByte*, System.Int32, System.Int32)", "System.String")] public extern unsafe String(sbyte* value, int startIndex, int length); #if PROJECTN @@ -243,7 +243,7 @@ namespace System [CLSCompliant(false)] [MethodImpl(MethodImplOptions.InternalCall)] - [PreserveDependency("System.String.CreateString(System.SByte*, System.Int32, System.Int32, System.Text.Encoding)")] + [PreserveDependency("CreateString(System.SByte*, System.Int32, System.Int32, System.Text.Encoding)", "System.String")] public extern unsafe String(sbyte* value, int startIndex, int length, Encoding enc); #if PROJECTN @@ -281,7 +281,7 @@ namespace System } [MethodImplAttribute(MethodImplOptions.InternalCall)] - [PreserveDependency("System.String.CreateString(System.Char, System.Int32)")] + [PreserveDependency("CreateString(System.Char, System.Int32)", "System.String")] public extern String(char c, int count); #if PROJECTN @@ -334,7 +334,7 @@ namespace System } [MethodImplAttribute(MethodImplOptions.InternalCall)] - [PreserveDependency("System.String.CreateString(System.ReadOnlySpan`1)")] + [PreserveDependency("CreateString(System.ReadOnlySpan`1)", "System.String")] public extern String(ReadOnlySpan value); #if PROJECTN diff --git a/external/corefx/src/Common/src/CoreLib/System/StringComparer.cs b/external/corefx/src/Common/src/CoreLib/System/StringComparer.cs index cb2d32fccb..043c455fdf 100644 --- a/external/corefx/src/Common/src/CoreLib/System/StringComparer.cs +++ b/external/corefx/src/Common/src/CoreLib/System/StringComparer.cs @@ -10,7 +10,9 @@ using System.Runtime.Serialization; namespace System { [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public abstract class StringComparer : IComparer, IEqualityComparer, IComparer, IEqualityComparer { private static readonly CultureAwareComparer s_invariantCulture = new CultureAwareComparer(CultureInfo.InvariantCulture, CompareOptions.None); @@ -171,7 +173,9 @@ namespace System } [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public sealed class CultureAwareComparer : StringComparer, ISerializable { private const CompareOptions ValidCompareMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort); @@ -253,7 +257,9 @@ namespace System } [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public class OrdinalComparer : StringComparer { private readonly bool _ignoreCase; // Do not rename (binary serialization) diff --git a/external/corefx/src/Common/src/CoreLib/System/Text/Encoding.cs b/external/corefx/src/Common/src/CoreLib/System/Text/Encoding.cs index e191ce14fd..64b457ff8a 100644 --- a/external/corefx/src/Common/src/CoreLib/System/Text/Encoding.cs +++ b/external/corefx/src/Common/src/CoreLib/System/Text/Encoding.cs @@ -77,8 +77,11 @@ namespace System.Text public abstract class Encoding : ICloneable { // For netcore we use UTF8 as default encoding since ANSI isn't available +#if MONO_HYBRID_ENCODING_SUPPORT + private static readonly Encoding s_defaultEncoding = EncodingHelper.GetDefaultEncoding (); +#else private static readonly UTF8Encoding.UTF8EncodingSealed s_defaultEncoding = new UTF8Encoding.UTF8EncodingSealed(encoderShouldEmitUTF8Identifier: false); - +#endif // Returns an encoding for the system's current ANSI code page. public static Encoding Default => s_defaultEncoding; @@ -301,7 +304,14 @@ namespace System.Text SR.Format(SR.NotSupported_NoCodepageData, codepage)); } +#if MONO_HYBRID_ENCODING_SUPPORT + result = (Encoding)(EncodingHelper.InvokeI18N ("GetEncoding", codepage)); + if (result == null) + throw new NotSupportedException(string.Format("Encoding {0} data could not be found. Make sure you have correct international codeset assembly installed and enabled.", codepage)); + return result; +#else return UTF8; +#endif } public static Encoding GetEncoding(int codepage, @@ -621,6 +631,13 @@ namespace System.Text } } +#if MONO_HYBRID_ENCODING_SUPPORT + internal void setReadOnly (bool value = true) + { + _isReadOnly = value; + } +#endif + // Returns an encoding for the ASCII character set. The returned encoding // will be an instance of the ASCIIEncoding class. diff --git a/external/corefx/src/Common/src/CoreLib/System/Threading/LockRecursionException.cs b/external/corefx/src/Common/src/CoreLib/System/Threading/LockRecursionException.cs index c07fe484ab..3f4a5669b2 100644 --- a/external/corefx/src/Common/src/CoreLib/System/Threading/LockRecursionException.cs +++ b/external/corefx/src/Common/src/CoreLib/System/Threading/LockRecursionException.cs @@ -8,7 +8,7 @@ using System.Runtime.Serialization; namespace System.Threading { [Serializable] -#if !MONO +#if !MONO && !MOBILE [System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] #endif public class LockRecursionException : System.Exception diff --git a/external/corefx/src/Common/src/CoreLib/System/Threading/SemaphoreFullException.cs b/external/corefx/src/Common/src/CoreLib/System/Threading/SemaphoreFullException.cs index 18558b19e0..641770a740 100644 --- a/external/corefx/src/Common/src/CoreLib/System/Threading/SemaphoreFullException.cs +++ b/external/corefx/src/Common/src/CoreLib/System/Threading/SemaphoreFullException.cs @@ -8,7 +8,9 @@ using System.Runtime.Serialization; namespace System.Threading { [Serializable] +#if !MOBILE [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public class SemaphoreFullException : SystemException { public SemaphoreFullException() : base(SR.Threading_SemaphoreFullException) diff --git a/external/corefx/src/Common/src/CoreLib/System/Threading/ThreadStartException.cs b/external/corefx/src/Common/src/CoreLib/System/Threading/ThreadStartException.cs index 5172555418..ecc35aa1ea 100644 --- a/external/corefx/src/Common/src/CoreLib/System/Threading/ThreadStartException.cs +++ b/external/corefx/src/Common/src/CoreLib/System/Threading/ThreadStartException.cs @@ -7,7 +7,9 @@ using System.Runtime.Serialization; namespace System.Threading { [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public sealed class ThreadStartException : SystemException { internal ThreadStartException() diff --git a/external/corefx/src/Common/src/CoreLib/System/TimeZone.cs b/external/corefx/src/Common/src/CoreLib/System/TimeZone.cs index d4059babfc..1475e504d4 100644 --- a/external/corefx/src/Common/src/CoreLib/System/TimeZone.cs +++ b/external/corefx/src/Common/src/CoreLib/System/TimeZone.cs @@ -27,7 +27,7 @@ using System.Globalization; namespace System { [Obsolete("System.TimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo instead.")] - public abstract class TimeZone + public abstract partial class TimeZone { private static volatile TimeZone currentTimeZone = null; diff --git a/external/corefx/src/Common/src/CoreLib/System/TimeZoneInfo.Unix.cs b/external/corefx/src/Common/src/CoreLib/System/TimeZoneInfo.Unix.cs index cc386a111f..9c81535f40 100644 --- a/external/corefx/src/Common/src/CoreLib/System/TimeZoneInfo.Unix.cs +++ b/external/corefx/src/Common/src/CoreLib/System/TimeZoneInfo.Unix.cs @@ -10,7 +10,9 @@ using System.Text; using System.Threading; using System.Security; +#if !MONO using Internal.IO; +#endif namespace System { @@ -76,9 +78,12 @@ namespace System } _displayName = _standardDisplayName; +#if !MONO + // .NET Core uses ICU to get nicer names for timezones, Mono doesn't use ICU so names from tzdata are enough GetDisplayName(Interop.Globalization.TimeZoneDisplayNameType.Generic, ref _displayName); GetDisplayName(Interop.Globalization.TimeZoneDisplayNameType.Standard, ref _standardDisplayName); GetDisplayName(Interop.Globalization.TimeZoneDisplayNameType.DaylightSavings, ref _daylightDisplayName); +#endif // TZif supports seconds-level granularity with offsets but TimeZoneInfo only supports minutes since it aligns // with DateTimeOffset, SQL Server, and the W3C XML Specification @@ -96,6 +101,7 @@ namespace System ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime); } +#if !MONO private void GetDisplayName(Interop.Globalization.TimeZoneDisplayNameType nameType, ref string displayName) { if (GlobalizationMode.Invariant) @@ -124,6 +130,7 @@ namespace System displayName = timeZoneDisplayName; } } +#endif /// /// Returns a cloned array of AdjustmentRule objects @@ -608,6 +615,9 @@ namespace System private static string GetTimeZoneDirectory() { +#if MONO && MOBILE + return GetTimeZoneDirectoryMobile(); +#else string tzDirectory = Environment.GetEnvironmentVariable(TimeZoneDirectoryEnvironmentVariable); if (tzDirectory == null) @@ -620,6 +630,7 @@ namespace System } return tzDirectory; +#endif } /// diff --git a/external/corefx/src/Common/src/CoreLib/System/TimeZoneInfo.cs b/external/corefx/src/Common/src/CoreLib/System/TimeZoneInfo.cs index 6e27376b68..930c43fe0f 100644 --- a/external/corefx/src/Common/src/CoreLib/System/TimeZoneInfo.cs +++ b/external/corefx/src/Common/src/CoreLib/System/TimeZoneInfo.cs @@ -28,7 +28,11 @@ namespace System }; [Serializable] +#if MONO && MOBILE + [System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e")] +#else [System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public sealed partial class TimeZoneInfo : IEquatable, ISerializable, IDeserializationCallback { private enum TimeZoneInfoResult diff --git a/external/corefx/src/Common/src/CoreLib/System/TimeZoneNotFoundException.cs b/external/corefx/src/Common/src/CoreLib/System/TimeZoneNotFoundException.cs index 36c3d7ef08..770865d5d6 100644 --- a/external/corefx/src/Common/src/CoreLib/System/TimeZoneNotFoundException.cs +++ b/external/corefx/src/Common/src/CoreLib/System/TimeZoneNotFoundException.cs @@ -7,7 +7,7 @@ using System.Runtime.Serialization; namespace System { [Serializable] -#if MONO +#if MONO && MOBILE [System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e")] #else [System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] diff --git a/external/corefx/src/Common/src/CoreLib/System/Version.cs b/external/corefx/src/Common/src/CoreLib/System/Version.cs index fe086be512..d6ce32a0b5 100644 --- a/external/corefx/src/Common/src/CoreLib/System/Version.cs +++ b/external/corefx/src/Common/src/CoreLib/System/Version.cs @@ -15,7 +15,9 @@ namespace System // specified component. [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public sealed class Version : ICloneable, IComparable, IComparable, IEquatable, ISpanFormattable { // AssemblyName depends on the order staying the same diff --git a/external/corefx/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs b/external/corefx/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs index 4671358822..95d159256a 100644 --- a/external/corefx/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs +++ b/external/corefx/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs @@ -12,6 +12,7 @@ internal static partial class Interop { internal static partial class NetSecurityNative { +#if ENABLE_GSS [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ReleaseGssBuffer")] internal static extern void ReleaseGssBuffer( IntPtr bufferPtr, @@ -144,6 +145,112 @@ internal static partial class Interop return Unwrap(out minorStatus, contextHandle, inputBytes, offset, count, ref outBuffer); } +#else + internal static void ReleaseGssBuffer ( + IntPtr bufferPtr, + UInt64 length) => throw new NotSupportedException (); + + internal static Status DisplayMinorStatus ( + out Status minorStatus, + Status statusValue, + ref GssBuffer buffer) => throw new NotSupportedException (); + + internal static Status DisplayMajorStatus ( + out Status minorStatus, + Status statusValue, + ref GssBuffer buffer) => throw new NotSupportedException (); + + internal static Status ImportUserName ( + out Status minorStatus, + string inputName, + int inputNameByteCount, + out SafeGssNameHandle outputName) => throw new NotSupportedException (); + + internal static Status ImportPrincipalName ( + out Status minorStatus, + string inputName, + int inputNameByteCount, + out SafeGssNameHandle outputName) => throw new NotSupportedException (); + + internal static Status ReleaseName ( + out Status minorStatus, + ref IntPtr inputName) => throw new NotSupportedException (); + + internal static Status InitiateCredSpNego ( + out Status minorStatus, + SafeGssNameHandle desiredName, + out SafeGssCredHandle outputCredHandle) => throw new NotSupportedException (); + + internal static Status InitiateCredWithPassword ( + out Status minorStatus, + bool isNtlm, + SafeGssNameHandle desiredName, + string password, + int passwordLen, + out SafeGssCredHandle outputCredHandle) => throw new NotSupportedException (); + + internal static Status ReleaseCred ( + out Status minorStatus, + ref IntPtr credHandle) => throw new NotSupportedException (); + + internal static Status InitSecContext ( + out Status minorStatus, + SafeGssCredHandle initiatorCredHandle, + ref SafeGssContextHandle contextHandle, + bool isNtlmOnly, + SafeGssNameHandle targetName, + uint reqFlags, + byte[] inputBytes, + int inputLength, + ref GssBuffer token, + out uint retFlags, + out int isNtlmUsed) => throw new NotSupportedException (); + + internal static Status AcceptSecContext ( + out Status minorStatus, + ref SafeGssContextHandle acceptContextHandle, + byte[] inputBytes, + int inputLength, + ref GssBuffer token) => throw new NotSupportedException (); + + internal static Status DeleteSecContext ( + out Status minorStatus, + ref IntPtr contextHandle) => throw new NotSupportedException (); + + static Status Wrap( + out Status minorStatus, + SafeGssContextHandle contextHandle, + bool isEncrypt, + byte[] inputBytes, + int offset, + int count, + ref GssBuffer outBuffer) => throw new NotSupportedException (); + + static Status Unwrap ( + out Status minorStatus, + SafeGssContextHandle contextHandle, + byte[] inputBytes, + int offset, + int count, + ref GssBuffer outBuffer) => throw new NotSupportedException (); + + internal static Status WrapBuffer ( + out Status minorStatus, + SafeGssContextHandle contextHandle, + bool isEncrypt, + byte[] inputBytes, + int offset, + int count, + ref GssBuffer outBuffer) => throw new NotSupportedException (); + + internal static Status UnwrapBuffer ( + out Status minorStatus, + SafeGssContextHandle contextHandle, + byte[] inputBytes, + int offset, + int count, + ref GssBuffer outBuffer) => throw new NotSupportedException (); +#endif internal enum Status : uint { diff --git a/external/corefx/src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs b/external/corefx/src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs index c0f441909d..8ec603ace7 100644 --- a/external/corefx/src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs +++ b/external/corefx/src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs @@ -263,7 +263,7 @@ namespace System.Collections.Generic T[] buffer = GetBuffer(row); int copied = #if __MonoCS__ - CopyToCore(buffer, column, array, arrayIndex, count); + CopyToCore(buffer, column, array, ref arrayIndex, ref count); #else CopyToCore(buffer, column); #endif @@ -278,7 +278,7 @@ namespace System.Collections.Generic buffer = GetBuffer(++row); copied = #if __MonoCS__ - CopyToCore(buffer, 0, array, arrayIndex, count); + CopyToCore(buffer, 0, array, ref arrayIndex, ref count); #else CopyToCore(buffer, 0); #endif @@ -289,7 +289,7 @@ namespace System.Collections.Generic #if __MonoCS__ } - static int CopyToCore(T[] sourceBuffer, int sourceIndex, T[] array, int arrayIndex, int count) + static int CopyToCore(T[] sourceBuffer, int sourceIndex, T[] array, ref int arrayIndex, ref int count) #else int CopyToCore(T[] sourceBuffer, int sourceIndex) #endif diff --git a/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs b/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs index a54881fe63..7e92772196 100644 --- a/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs +++ b/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs @@ -13,7 +13,7 @@ namespace Microsoft.Win32 #else internal #endif - static class Registry + static partial class Registry { /// Current User Key. This key should be used as the root for all user specific settings. public static readonly RegistryKey CurrentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default); diff --git a/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryHive.cs b/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryHive.cs index 14d360de69..b82cf49b5a 100644 --- a/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryHive.cs +++ b/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryHive.cs @@ -22,5 +22,8 @@ namespace Microsoft.Win32 Users = unchecked((int)0x80000003), PerformanceData = unchecked((int)0x80000004), CurrentConfig = unchecked((int)0x80000005), +#if MONO + DynData = unchecked((int)0x80000006) +#endif } } diff --git a/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs b/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs index 578c732952..31a01d12c7 100644 --- a/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs +++ b/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs @@ -22,12 +22,22 @@ namespace Microsoft.Win32 #endif sealed partial class RegistryKey : MarshalByRefObject, IDisposable { +#if MONO + internal static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000)); + internal static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001)); + internal static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002)); + internal static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003)); + internal static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004)); + internal static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005)); + internal static readonly IntPtr HKEY_DYN_DATA = new IntPtr(unchecked((int)0x80000006)); +#else private static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000)); private static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001)); private static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002)); private static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003)); private static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004)); private static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005)); +#endif /// Names of keys. This array must be in the same order as the HKEY values listed above. private static readonly string[] s_hkeyNames = new string[] @@ -37,7 +47,10 @@ namespace Microsoft.Win32 "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_PERFORMANCE_DATA", - "HKEY_CURRENT_CONFIG" + "HKEY_CURRENT_CONFIG", +#if MONO + "HKEY_DYN_DATA" +#endif }; // MSDN defines the following limits for registry key names & values: @@ -98,8 +111,15 @@ namespace Microsoft.Win32 FlushCore(); } +#if MONO + partial void CloseCore(); +#endif + public void Close() { +#if MONO + CloseCore(); +#endif Dispose(); } diff --git a/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKeyPermissionCheck.cs b/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKeyPermissionCheck.cs index d18b9f481a..b632477f21 100644 --- a/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKeyPermissionCheck.cs +++ b/external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKeyPermissionCheck.cs @@ -6,7 +6,6 @@ using System; namespace Microsoft.Win32 { - [Flags] #if REGISTRY_ASSEMBLY public #else diff --git a/external/corefx/src/Native/Unix/Common/pal_config.h.in b/external/corefx/src/Native/Unix/Common/pal_config.h.in index 2501a6a31d..c76d309940 100644 --- a/external/corefx/src/Native/Unix/Common/pal_config.h.in +++ b/external/corefx/src/Native/Unix/Common/pal_config.h.in @@ -9,6 +9,7 @@ #cmakedefine01 HAVE_F_DUPFD_CLOEXEC #cmakedefine01 HAVE_O_CLOEXEC #cmakedefine01 HAVE_GETIFADDRS +#cmakedefine01 HAVE_UTSNAME_DOMAINNAME #cmakedefine01 HAVE_STAT64 #cmakedefine01 HAVE_PIPE2 #cmakedefine01 HAVE_STAT_BIRTHTIME @@ -31,11 +32,12 @@ #cmakedefine01 HAVE_TIOCGWINSZ #cmakedefine01 HAVE_SCHED_GETAFFINITY #cmakedefine01 HAVE_SCHED_SETAFFINITY -#cmakedefine01 HAVE_ARC4RANDOM +#cmakedefine01 HAVE_ARC4RANDOM_BUF #cmakedefine01 KEVENT_HAS_VOID_UDATA #cmakedefine01 HAVE_FDS_BITS #cmakedefine01 HAVE_PRIVATE_FDS_BITS #cmakedefine01 HAVE_STATFS +#cmakedefine01 HAVE_SYS_SOCKIO_H #cmakedefine01 HAVE_SYS_POLL_H #cmakedefine01 HAVE_EPOLL #cmakedefine01 HAVE_ACCEPT4 diff --git a/external/corefx/src/Native/Unix/Common/pal_utilities.h b/external/corefx/src/Native/Unix/Common/pal_utilities.h index ff12d33af5..3b58dcac5f 100644 --- a/external/corefx/src/Native/Unix/Common/pal_utilities.h +++ b/external/corefx/src/Native/Unix/Common/pal_utilities.h @@ -118,11 +118,15 @@ template char(&_ArraySizeHelper(T(&array)[N]))[N]; #define ARRAY_SIZE(array) (sizeof(_ArraySizeHelper(array))) +#else // __cplusplus +#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0])) +#endif // __cplusplus + /** * Abstraction helper method to safely copy strings using strlcpy or strcpy_s * or a different safe copy method, depending on the current platform. */ -inline void SafeStringCopy(char* destination, size_t destinationSize, const char* source) +inline static void SafeStringCopy(char* destination, size_t destinationSize, const char* source) { #if HAVE_STRCPY_S strcpy_s(destination, destinationSize, source); @@ -133,24 +137,6 @@ inline void SafeStringCopy(char* destination, size_t destinationSize, const char #endif } -/** - * Overload of SafeStringCopy that takes a signed int32_t as buffer - * size. Asserts that its positive, but defensively treats the size - * as 0 (no-op) if it's negative. - */ -inline void SafeStringCopy(char* destination, int32_t destinationSize, const char* source) -{ - assert(destinationSize >= 0); - - if (destinationSize > 0) - { - size_t unsignedSize = UnsignedCast(destinationSize); - SafeStringCopy(destination, unsignedSize, source); - } -} - -#endif // __cplusplus - /** * Converts an intptr_t to a file descriptor. * intptr_t is the type used to marshal file descriptors so we can use SafeHandles effectively. @@ -187,6 +173,13 @@ static inline bool CheckInterrupted(TInt result) return result < 0 && errno == EINTR; } +#else + +static inline bool CheckInterrupted(ssize_t result) +{ + return result < 0 && errno == EINTR; +} + #endif // __cplusplus inline static uint32_t Int32ToUint32(int32_t value) @@ -206,3 +199,9 @@ inline static int32_t Uint32ToInt32(uint32_t value) assert(value <= INT_MAX); return (int32_t)value; } + +inline static int32_t SizeTToInt32(size_t value) +{ + assert(value <= INT_MAX); + return (int32_t)value; +} diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_errno.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_errno.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_errno.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_io.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_io.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_io.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_maphardwaretype.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_maphardwaretype.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_maphardwaretype.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_memory.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_memory.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_memory.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_networking.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_networking.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_networking.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_networkstatistics.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_networkstatistics.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_networkstatistics.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_random.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_random.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_random.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_tcpstate.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_tcpstate.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_compat_la-pal_tcpstate.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_errno.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_errno.Plo similarity index 98% rename from external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_errno.Plo rename to external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_errno.Plo index d6209a6aed..38943d78a0 100644 --- a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_errno.Plo +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_errno.Plo @@ -1,4 +1,4 @@ -../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_errno.lo: \ +../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_errno.lo: \ ../../external/corefx/src/Native/Unix/System.Native/pal_errno.c \ /usr/include/stdc-predef.h pal_config.h ../../config.h \ ../../external/corefx/src/Native/Unix/System.Native/pal_errno.h \ diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_io.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_io.Plo similarity index 99% rename from external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_io.Plo rename to external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_io.Plo index 34cf899e22..3c9dfdd27d 100644 --- a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_io.Plo +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_io.Plo @@ -1,4 +1,4 @@ -../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_io.lo: \ +../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_io.lo: \ ../../external/corefx/src/Native/Unix/System.Native/pal_io.c \ /usr/include/stdc-predef.h \ /mnt/jenkins/workspace/release-tarball-mono/external/corefx/src/Native/Unix/Common/pal_compiler.h \ diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_maphardwaretype.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_maphardwaretype.Plo similarity index 98% rename from external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_maphardwaretype.Plo rename to external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_maphardwaretype.Plo index 5702117ee8..d4728efd3d 100644 --- a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_maphardwaretype.Plo +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_maphardwaretype.Plo @@ -1,4 +1,4 @@ -../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_maphardwaretype.lo: \ +../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_maphardwaretype.lo: \ ../../external/corefx/src/Native/Unix/System.Native/pal_maphardwaretype.c \ /usr/include/stdc-predef.h pal_config.h ../../config.h \ ../../external/corefx/src/Native/Unix/System.Native/pal_maphardwaretype.h \ diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_memory.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_memory.Plo similarity index 96% rename from external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_memory.Plo rename to external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_memory.Plo index 7000dcf6c2..4e42cacec5 100644 --- a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_memory.Plo +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_memory.Plo @@ -1,4 +1,4 @@ -../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_memory.lo: \ +../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_memory.lo: \ ../../external/corefx/src/Native/Unix/System.Native/pal_memory.c \ /usr/include/stdc-predef.h \ ../../external/corefx/src/Native/Unix/System.Native/pal_memory.h \ diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_networking.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_networking.Plo similarity index 98% rename from external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_networking.Plo rename to external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_networking.Plo index 8b21bac27d..1016214adb 100644 --- a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_networking.Plo +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_networking.Plo @@ -1,4 +1,4 @@ -../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networking.lo: \ +../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networking.lo: \ ../../external/corefx/src/Native/Unix/System.Native/pal_networking.c \ /usr/include/stdc-predef.h pal_config.h ../../config.h \ ../../external/corefx/src/Native/Unix/System.Native/pal_networking.h \ @@ -76,6 +76,7 @@ /usr/include/asm-generic/sockios.h \ /usr/include/x86_64-linux-gnu/bits/socket2.h \ /usr/include/x86_64-linux-gnu/bits/in.h \ + /usr/include/x86_64-linux-gnu/sys/time.h \ /usr/include/x86_64-linux-gnu/sys/epoll.h \ /usr/include/x86_64-linux-gnu/bits/epoll.h /usr/include/netdb.h \ /usr/include/rpc/netdb.h /usr/include/x86_64-linux-gnu/bits/siginfo.h \ @@ -297,6 +298,8 @@ pal_config.h: /usr/include/x86_64-linux-gnu/bits/in.h: +/usr/include/x86_64-linux-gnu/sys/time.h: + /usr/include/x86_64-linux-gnu/sys/epoll.h: /usr/include/x86_64-linux-gnu/bits/epoll.h: diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_networkstatistics.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_networkstatistics.Plo similarity index 65% rename from external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_networkstatistics.Plo rename to external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_networkstatistics.Plo index c55e604615..918f02e852 100644 --- a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_networkstatistics.Plo +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_networkstatistics.Plo @@ -1,4 +1,4 @@ -../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networkstatistics.lo: \ +../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networkstatistics.lo: \ ../../external/corefx/src/Native/Unix/System.Native/pal_networkstatistics.c \ /usr/include/stdc-predef.h pal_config.h ../../config.h diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_random.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_random.Plo similarity index 98% rename from external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_random.Plo rename to external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_random.Plo index 123c072ec9..46fb965b2f 100644 --- a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_random.Plo +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_random.Plo @@ -1,4 +1,4 @@ -../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_random.lo: \ +../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_random.lo: \ ../../external/corefx/src/Native/Unix/System.Native/pal_random.c \ /usr/include/stdc-predef.h /usr/include/stdlib.h /usr/include/features.h \ /usr/include/x86_64-linux-gnu/sys/cdefs.h \ diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_tcpstate.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_tcpstate.Plo similarity index 97% rename from external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_tcpstate.Plo rename to external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_tcpstate.Plo index 2b3a6c88c6..676f582953 100644 --- a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_system_native_la-pal_tcpstate.Plo +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_la-pal_tcpstate.Plo @@ -1,4 +1,4 @@ -../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_tcpstate.lo: \ +../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_tcpstate.lo: \ ../../external/corefx/src/Native/Unix/System.Native/pal_tcpstate.c \ /usr/include/stdc-predef.h pal_config.h ../../config.h \ /mnt/jenkins/workspace/release-tarball-mono/external/corefx/src/Native/Unix/Common/pal_types.h \ diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_errno.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_errno.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_errno.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_io.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_io.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_io.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_maphardwaretype.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_maphardwaretype.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_maphardwaretype.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_memory.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_memory.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_memory.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_networking.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_networking.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_networking.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_networkstatistics.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_networkstatistics.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_networkstatistics.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_random.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_random.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_random.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_tcpstate.Plo b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_tcpstate.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.deps/libmono_native_unified_la-pal_tcpstate.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_errno.o b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_errno.o similarity index 67% rename from external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_errno.o rename to external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_errno.o index a3ee39e528..a53c33caba 100644 Binary files a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_errno.o and b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_errno.o differ diff --git a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_io.o.REMOVED.git-id b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_io.o.REMOVED.git-id new file mode 100644 index 0000000000..b1d1aff323 --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_io.o.REMOVED.git-id @@ -0,0 +1 @@ +df99021e1f9d29842410c9074e797c6149149d9c \ No newline at end of file diff --git a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_maphardwaretype.o b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_maphardwaretype.o new file mode 100644 index 0000000000..1074779193 Binary files /dev/null and b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_maphardwaretype.o differ diff --git a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_memory.o b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_memory.o new file mode 100644 index 0000000000..58891c2e34 Binary files /dev/null and b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_memory.o differ diff --git a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_networking.o.REMOVED.git-id b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_networking.o.REMOVED.git-id new file mode 100644 index 0000000000..2c6c9cf67a --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_networking.o.REMOVED.git-id @@ -0,0 +1 @@ +c1e2d534c3f65b1f852ab4f374e977c8f2686282 \ No newline at end of file diff --git a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_networkstatistics.o b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_networkstatistics.o similarity index 100% rename from external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_networkstatistics.o rename to external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_networkstatistics.o diff --git a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_random.o b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_random.o similarity index 72% rename from external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_random.o rename to external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_random.o index 42f6ae3d4a..dae7de4fb9 100644 Binary files a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_random.o and b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_random.o differ diff --git a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_tcpstate.o b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_tcpstate.o new file mode 100644 index 0000000000..334318e7f7 Binary files /dev/null and b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_native_la-pal_tcpstate.o differ diff --git a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_io.o.REMOVED.git-id b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_io.o.REMOVED.git-id deleted file mode 100644 index 35b08c3b2d..0000000000 --- a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_io.o.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -8cf70f4c9bf61d50ad28b1eb014c0c9c366af434 \ No newline at end of file diff --git a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_maphardwaretype.o b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_maphardwaretype.o deleted file mode 100644 index caeea169fb..0000000000 Binary files a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_maphardwaretype.o and /dev/null differ diff --git a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_memory.o b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_memory.o deleted file mode 100644 index 8d7f61afb9..0000000000 Binary files a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_memory.o and /dev/null differ diff --git a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_networking.o.REMOVED.git-id b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_networking.o.REMOVED.git-id deleted file mode 100644 index f9153db0bb..0000000000 --- a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_networking.o.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -2e6aca36b1f1bc468d57c112a6812fecd62982b0 \ No newline at end of file diff --git a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_tcpstate.o b/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_tcpstate.o deleted file mode 100644 index de26869ddc..0000000000 Binary files a/external/corefx/src/Native/Unix/System.Native/.libs/libmono_system_native_la-pal_tcpstate.o and /dev/null differ diff --git a/external/corefx/src/Native/Unix/System.Native/CMakeLists.txt b/external/corefx/src/Native/Unix/System.Native/CMakeLists.txt index 3651796302..ca8ef3cf9f 100644 --- a/external/corefx/src/Native/Unix/System.Native/CMakeLists.txt +++ b/external/corefx/src/Native/Unix/System.Native/CMakeLists.txt @@ -4,30 +4,30 @@ project(System.Native) add_compile_options(-fvisibility=hidden) set(NATIVE_SOURCES - pal_console.cpp + pal_console.c pal_errno.c pal_interfaceaddresses.c pal_io.c pal_maphardwaretype.c pal_memory.c - pal_mount.cpp + pal_mount.c pal_networking.c pal_networkstatistics.c - pal_process.cpp + pal_process.c pal_random.c - pal_runtimeinformation.cpp - pal_runtimeextensions.cpp + pal_runtimeinformation.c + pal_runtimeextensions.c pal_signal.c - pal_string.cpp + pal_string.c pal_tcpstate.c - pal_time.cpp - pal_uid.cpp - pal_datetime.cpp - pal_sysctl.cpp + pal_time.c + pal_uid.c + pal_datetime.c + pal_sysctl.c ) if (CMAKE_SYSTEM_NAME STREQUAL Linux) - set(NATIVE_SOURCES ${NATIVE_SOURCES} pal_networkchange.cpp) + set(NATIVE_SOURCES ${NATIVE_SOURCES} pal_networkchange.c) if (!HAVE_LINUX_RTNETLINK_H) message(FATAL_ERROR "Could not find linux/rtnetlink.h") diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_errno.lo b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_errno.lo new file mode 100644 index 0000000000..1f936b0bfb --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_errno.lo @@ -0,0 +1,4 @@ +# ../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_errno.lo - a libtool object file +# Generated by doltcompile, not libtool +pic_object='.libs/libmono_native_la-pal_errno.o' +non_pic_object='libmono_native_la-pal_errno.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_errno.o b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_errno.o similarity index 62% rename from external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_errno.o rename to external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_errno.o index 76faa99224..575dece4b0 100644 Binary files a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_errno.o and b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_errno.o differ diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_io.lo b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_io.lo new file mode 100644 index 0000000000..8570ad9aef --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_io.lo @@ -0,0 +1,4 @@ +# ../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_io.lo - a libtool object file +# Generated by doltcompile, not libtool +pic_object='.libs/libmono_native_la-pal_io.o' +non_pic_object='libmono_native_la-pal_io.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_io.o.REMOVED.git-id b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_io.o.REMOVED.git-id new file mode 100644 index 0000000000..7261670e0c --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_io.o.REMOVED.git-id @@ -0,0 +1 @@ +c1c6fb1dc9aaf918441d11b1c7eb3e67b650558d \ No newline at end of file diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_maphardwaretype.lo b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_maphardwaretype.lo new file mode 100644 index 0000000000..8e0a2c4f3d --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_maphardwaretype.lo @@ -0,0 +1,4 @@ +# ../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_maphardwaretype.lo - a libtool object file +# Generated by doltcompile, not libtool +pic_object='.libs/libmono_native_la-pal_maphardwaretype.o' +non_pic_object='libmono_native_la-pal_maphardwaretype.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_maphardwaretype.o b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_maphardwaretype.o new file mode 100644 index 0000000000..ebe17bb34c Binary files /dev/null and b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_maphardwaretype.o differ diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_memory.lo b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_memory.lo new file mode 100644 index 0000000000..e8da03ebc3 --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_memory.lo @@ -0,0 +1,4 @@ +# ../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_memory.lo - a libtool object file +# Generated by doltcompile, not libtool +pic_object='.libs/libmono_native_la-pal_memory.o' +non_pic_object='libmono_native_la-pal_memory.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_memory.o b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_memory.o new file mode 100644 index 0000000000..c3897eef7f Binary files /dev/null and b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_memory.o differ diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networking.lo b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networking.lo new file mode 100644 index 0000000000..ecd74f31b9 --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networking.lo @@ -0,0 +1,4 @@ +# ../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networking.lo - a libtool object file +# Generated by doltcompile, not libtool +pic_object='.libs/libmono_native_la-pal_networking.o' +non_pic_object='libmono_native_la-pal_networking.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networking.o.REMOVED.git-id b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networking.o.REMOVED.git-id new file mode 100644 index 0000000000..92d8e4a8a7 --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networking.o.REMOVED.git-id @@ -0,0 +1 @@ +ba3da05bd6cc88d37d39601a1bed2cb7ddc02bce \ No newline at end of file diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networkstatistics.lo b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networkstatistics.lo new file mode 100644 index 0000000000..e1a8c00b87 --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networkstatistics.lo @@ -0,0 +1,4 @@ +# ../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networkstatistics.lo - a libtool object file +# Generated by doltcompile, not libtool +pic_object='.libs/libmono_native_la-pal_networkstatistics.o' +non_pic_object='libmono_native_la-pal_networkstatistics.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networkstatistics.o b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networkstatistics.o similarity index 100% rename from external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networkstatistics.o rename to external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_networkstatistics.o diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_random.lo b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_random.lo new file mode 100644 index 0000000000..b92ecee117 --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_random.lo @@ -0,0 +1,4 @@ +# ../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_random.lo - a libtool object file +# Generated by doltcompile, not libtool +pic_object='.libs/libmono_native_la-pal_random.o' +non_pic_object='libmono_native_la-pal_random.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_random.o b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_random.o similarity index 70% rename from external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_random.o rename to external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_random.o index a702cd72d0..487b372455 100644 Binary files a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_random.o and b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_random.o differ diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_tcpstate.lo b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_tcpstate.lo new file mode 100644 index 0000000000..97180a210c --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_tcpstate.lo @@ -0,0 +1,4 @@ +# ../../external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_tcpstate.lo - a libtool object file +# Generated by doltcompile, not libtool +pic_object='.libs/libmono_native_la-pal_tcpstate.o' +non_pic_object='libmono_native_la-pal_tcpstate.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_tcpstate.o b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_tcpstate.o new file mode 100644 index 0000000000..c6cbf5f9ce Binary files /dev/null and b/external/corefx/src/Native/Unix/System.Native/libmono_native_la-pal_tcpstate.o differ diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_errno.lo b/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_errno.lo deleted file mode 100644 index c7782dde33..0000000000 --- a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_errno.lo +++ /dev/null @@ -1,4 +0,0 @@ -# ../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_errno.lo - a libtool object file -# Generated by doltcompile, not libtool -pic_object='.libs/libmono_system_native_la-pal_errno.o' -non_pic_object='libmono_system_native_la-pal_errno.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_io.lo b/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_io.lo deleted file mode 100644 index 3a96b8aecd..0000000000 --- a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_io.lo +++ /dev/null @@ -1,4 +0,0 @@ -# ../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_io.lo - a libtool object file -# Generated by doltcompile, not libtool -pic_object='.libs/libmono_system_native_la-pal_io.o' -non_pic_object='libmono_system_native_la-pal_io.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_io.o.REMOVED.git-id b/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_io.o.REMOVED.git-id deleted file mode 100644 index 0eae103bab..0000000000 --- a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_io.o.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -b5f68f2a1003027fe6aa20f56c4c7f5b92efee04 \ No newline at end of file diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_maphardwaretype.lo b/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_maphardwaretype.lo deleted file mode 100644 index 93dcd4e11e..0000000000 --- a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_maphardwaretype.lo +++ /dev/null @@ -1,4 +0,0 @@ -# ../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_maphardwaretype.lo - a libtool object file -# Generated by doltcompile, not libtool -pic_object='.libs/libmono_system_native_la-pal_maphardwaretype.o' -non_pic_object='libmono_system_native_la-pal_maphardwaretype.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_maphardwaretype.o b/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_maphardwaretype.o deleted file mode 100644 index 26e9ed6eb4..0000000000 Binary files a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_maphardwaretype.o and /dev/null differ diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_memory.lo b/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_memory.lo deleted file mode 100644 index c3860be2f5..0000000000 --- a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_memory.lo +++ /dev/null @@ -1,4 +0,0 @@ -# ../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_memory.lo - a libtool object file -# Generated by doltcompile, not libtool -pic_object='.libs/libmono_system_native_la-pal_memory.o' -non_pic_object='libmono_system_native_la-pal_memory.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_memory.o b/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_memory.o deleted file mode 100644 index f268685f71..0000000000 Binary files a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_memory.o and /dev/null differ diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networking.lo b/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networking.lo deleted file mode 100644 index 28da07d926..0000000000 --- a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networking.lo +++ /dev/null @@ -1,4 +0,0 @@ -# ../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networking.lo - a libtool object file -# Generated by doltcompile, not libtool -pic_object='.libs/libmono_system_native_la-pal_networking.o' -non_pic_object='libmono_system_native_la-pal_networking.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networking.o.REMOVED.git-id b/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networking.o.REMOVED.git-id deleted file mode 100644 index c04727fab3..0000000000 --- a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networking.o.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -9d073102395241a169f95cfba5a149ed33df2f5c \ No newline at end of file diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networkstatistics.lo b/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networkstatistics.lo deleted file mode 100644 index 65579db051..0000000000 --- a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networkstatistics.lo +++ /dev/null @@ -1,4 +0,0 @@ -# ../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_networkstatistics.lo - a libtool object file -# Generated by doltcompile, not libtool -pic_object='.libs/libmono_system_native_la-pal_networkstatistics.o' -non_pic_object='libmono_system_native_la-pal_networkstatistics.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_random.lo b/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_random.lo deleted file mode 100644 index b856dbd7f8..0000000000 --- a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_random.lo +++ /dev/null @@ -1,4 +0,0 @@ -# ../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_random.lo - a libtool object file -# Generated by doltcompile, not libtool -pic_object='.libs/libmono_system_native_la-pal_random.o' -non_pic_object='libmono_system_native_la-pal_random.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_tcpstate.lo b/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_tcpstate.lo deleted file mode 100644 index ec49835c53..0000000000 --- a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_tcpstate.lo +++ /dev/null @@ -1,4 +0,0 @@ -# ../../external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_tcpstate.lo - a libtool object file -# Generated by doltcompile, not libtool -pic_object='.libs/libmono_system_native_la-pal_tcpstate.o' -non_pic_object='libmono_system_native_la-pal_tcpstate.o' diff --git a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_tcpstate.o b/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_tcpstate.o deleted file mode 100644 index 1e12d419bc..0000000000 Binary files a/external/corefx/src/Native/Unix/System.Native/libmono_system_native_la-pal_tcpstate.o and /dev/null differ diff --git a/external/corefx/src/Native/Unix/System.Native/pal_console.cpp b/external/corefx/src/Native/Unix/System.Native/pal_console.c similarity index 76% rename from external/corefx/src/Native/Unix/System.Native/pal_console.cpp rename to external/corefx/src/Native/Unix/System.Native/pal_console.c index 0bb51d2606..afbbd8eeb1 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_console.cpp +++ b/external/corefx/src/Native/Unix/System.Native/pal_console.c @@ -18,16 +18,16 @@ #include #include -extern "C" int32_t SystemNative_GetWindowSize(WinSize* windowSize) +int32_t SystemNative_GetWindowSize(WinSize* windowSize) { - assert(windowSize != nullptr); + assert(windowSize != NULL); #if HAVE_IOCTL && HAVE_TIOCGWINSZ int error = ioctl(STDOUT_FILENO, TIOCGWINSZ, windowSize); if (error != 0) { - *windowSize = {}; // managed out param must be initialized + memset(windowSize, 0, sizeof(WinSize)); // managed out param must be initialized } return error; @@ -37,30 +37,30 @@ extern "C" int32_t SystemNative_GetWindowSize(WinSize* windowSize) #endif } -extern "C" int32_t SystemNative_IsATty(intptr_t fd) +int32_t SystemNative_IsATty(intptr_t fd) { return isatty(ToFileDescriptor(fd)); } -static char* g_keypadXmit = nullptr; // string used to enable application mode, from terminfo +static char* g_keypadXmit = NULL; // string used to enable application mode, from terminfo static void WriteKeypadXmit() // used in a signal handler, must be signal-safe { // If a terminfo "application mode" keypad_xmit string has been supplied, // write it out to the terminal to enter the mode. - if (g_keypadXmit != nullptr) + if (g_keypadXmit != NULL) { ssize_t ret; - while (CheckInterrupted(ret = write(STDOUT_FILENO, g_keypadXmit, static_cast(sizeof(char) * strlen(g_keypadXmit))))); + while (CheckInterrupted(ret = write(STDOUT_FILENO, g_keypadXmit, (size_t)(sizeof(char) * strlen(g_keypadXmit))))); assert(ret >= 0); // failure to change the mode should not prevent app from continuing } } -extern "C" void SystemNative_SetKeypadXmit(const char* terminfoString) +void SystemNative_SetKeypadXmit(const char* terminfoString) { - assert(terminfoString != nullptr); + assert(terminfoString != NULL); - if (g_keypadXmit != nullptr) // should only happen if initialization initially failed + if (g_keypadXmit != NULL) // should only happen if initialization initially failed { free(g_keypadXmit); assert(false && "g_keypadXmit was already initialized"); @@ -71,12 +71,12 @@ extern "C" void SystemNative_SetKeypadXmit(const char* terminfoString) WriteKeypadXmit(); } -static bool g_readInProgress = false; // tracks whether a read is currently in progress, such that attributes have been changed -static bool g_signalForBreak = true; // tracks whether the terminal should send signals for breaks, such that attributes have been changed -static bool g_haveInitTermios = false; // whether g_initTermios has been initialized -static struct termios g_initTermios = {}; // the initial attributes captured when Console was initialized -static struct termios g_preReadTermios = {}; // the original attributes captured before a read; valid if g_readInProgress is true -static struct termios g_currTermios = {}; // the current attributes set during a read; valid if g_readInProgress is true +static bool g_readInProgress = false; // tracks whether a read is currently in progress, such that attributes have been changed +static bool g_signalForBreak = true; // tracks whether the terminal should send signals for breaks, such that attributes have been changed +static bool g_haveInitTermios = false; // whether g_initTermios has been initialized +static struct termios g_initTermios; // the initial attributes captured when Console was initialized +static struct termios g_preReadTermios; // the original attributes captured before a read; valid if g_readInProgress is true +static struct termios g_currTermios; // the current attributes set during a read; valid if g_readInProgress is true void UninitializeConsole() { @@ -99,13 +99,13 @@ void UninitializeConsole() static void IncorporateBreak(struct termios *termios, int32_t signalForBreak) { - assert(termios != nullptr); + assert(termios != NULL); assert(signalForBreak == 0 || signalForBreak == 1); if (signalForBreak) - termios->c_lflag |= static_cast(ISIG); + termios->c_lflag |= (uint32_t)ISIG; else - termios->c_lflag &= static_cast(~ISIG); + termios->c_lflag &= (uint32_t)(~ISIG); } // In order to support Console.ReadKey(intercept: true), we need to disable echo and canonical mode. @@ -118,7 +118,7 @@ static void IncorporateBreak(struct termios *termios, int32_t signalForBreak) // and the cons of the latter minimal and constrained to the one API that we've chosen the second approach. // Thus, InitializeConsoleBeforeRead is called to set up the state of the console, then a read is done, // and then UninitializeConsoleAfterRead is called. -extern "C" void SystemNative_InitializeConsoleBeforeRead(uint8_t minChars, uint8_t decisecondsTimeout) +void SystemNative_InitializeConsoleBeforeRead(uint8_t minChars, uint8_t decisecondsTimeout) { struct termios newTermios; if (tcgetattr(STDIN_FILENO, &newTermios) >= 0) @@ -131,8 +131,8 @@ extern "C" void SystemNative_InitializeConsoleBeforeRead(uint8_t minChars, uint8 g_preReadTermios = newTermios; } - newTermios.c_iflag &= static_cast(~(IXON | IXOFF)); - newTermios.c_lflag &= static_cast(~(ECHO | ICANON | IEXTEN)); + newTermios.c_iflag &= (uint32_t)(~(IXON | IXOFF)); + newTermios.c_lflag &= (uint32_t)(~(ECHO | ICANON | IEXTEN)); newTermios.c_cc[VMIN] = minChars; newTermios.c_cc[VTIME] = decisecondsTimeout; IncorporateBreak(&newTermios, g_signalForBreak); @@ -145,7 +145,7 @@ extern "C" void SystemNative_InitializeConsoleBeforeRead(uint8_t minChars, uint8 } } -extern "C" void SystemNative_UninitializeConsoleAfterRead() +void SystemNative_UninitializeConsoleAfterRead() { if (g_readInProgress) { @@ -219,14 +219,14 @@ static int TranslatePalControlCharacterName(int name) } } -extern "C" void SystemNative_GetControlCharacters( +void SystemNative_GetControlCharacters( int32_t* controlCharacterNames, uint8_t* controlCharacterValues, int32_t controlCharacterLength, uint8_t* posixDisableValue) { - assert(controlCharacterNames != nullptr); - assert(controlCharacterValues != nullptr); + assert(controlCharacterNames != NULL); + assert(controlCharacterValues != NULL); assert(controlCharacterLength >= 0); - assert(posixDisableValue != nullptr); + assert(posixDisableValue != NULL); #ifdef _POSIX_VDISABLE *posixDisableValue = _POSIX_VDISABLE; @@ -234,11 +234,13 @@ extern "C" void SystemNative_GetControlCharacters( *posixDisableValue = 0; #endif - memset(controlCharacterValues, *posixDisableValue, sizeof(uint8_t) * UnsignedCast(controlCharacterLength)); + memset(controlCharacterValues, *posixDisableValue, sizeof(uint8_t) * Int32ToSizeT(controlCharacterLength)); if (controlCharacterLength > 0) { - struct termios newTermios = {}; + struct termios newTermios; + memset(&newTermios, 0, sizeof(struct termios)); + if (tcgetattr(STDIN_FILENO, &newTermios) >= 0) { for (int i = 0; i < controlCharacterLength; i++) @@ -253,7 +255,7 @@ extern "C" void SystemNative_GetControlCharacters( } } -extern "C" int32_t SystemNative_StdinReady() +int32_t SystemNative_StdinReady() { SystemNative_InitializeConsoleBeforeRead(1, 0); struct pollfd fd = { .fd = STDIN_FILENO, .events = POLLIN }; @@ -262,9 +264,9 @@ extern "C" int32_t SystemNative_StdinReady() return rv; } -extern "C" int32_t SystemNative_ReadStdin(void* buffer, int32_t bufferSize) +int32_t SystemNative_ReadStdin(void* buffer, int32_t bufferSize) { - assert(buffer != nullptr || bufferSize == 0); + assert(buffer != NULL || bufferSize == 0); assert(bufferSize >= 0); if (bufferSize < 0) @@ -274,16 +276,16 @@ extern "C" int32_t SystemNative_ReadStdin(void* buffer, int32_t bufferSize) } ssize_t count; - while (CheckInterrupted(count = read(STDIN_FILENO, buffer, UnsignedCast(bufferSize)))); - return static_cast(count); + while (CheckInterrupted(count = read(STDIN_FILENO, buffer, Int32ToSizeT(bufferSize)))); + return (int32_t)count; } -extern "C" int32_t SystemNative_GetSignalForBreak() +int32_t SystemNative_GetSignalForBreak() { return g_signalForBreak; } -extern "C" int32_t SystemNative_SetSignalForBreak(int32_t signalForBreak) +int32_t SystemNative_SetSignalForBreak(int32_t signalForBreak) { assert(signalForBreak == 0 || signalForBreak == 1); @@ -320,7 +322,7 @@ void ReinitializeConsole() WriteKeypadXmit(); } -extern "C" int32_t SystemNative_InitializeConsole() +int32_t SystemNative_InitializeConsole() { if (!InitializeSignalHandling()) { diff --git a/external/corefx/src/Native/Unix/System.Native/pal_console.h b/external/corefx/src/Native/Unix/System.Native/pal_console.h index 8b294b042e..5729e20ead 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_console.h +++ b/external/corefx/src/Native/Unix/System.Native/pal_console.h @@ -37,20 +37,20 @@ enum /* * Window Size of the terminal */ -struct WinSize +typedef struct { uint16_t Row; uint16_t Col; uint16_t XPixel; uint16_t YPixel; -}; +} WinSize; /** * Gets the windows size of the terminal * * Returns 0 on success; otherwise, returns errorNo. */ -DLLEXPORT int32_t SystemNative_GetWindowSize(struct WinSize* windowsSize); +DLLEXPORT int32_t SystemNative_GetWindowSize(WinSize* windowsSize); /** * Gets whether the specified file descriptor is for a terminal. diff --git a/external/corefx/src/Native/Unix/System.Native/pal_datetime.cpp b/external/corefx/src/Native/Unix/System.Native/pal_datetime.c similarity index 78% rename from external/corefx/src/Native/Unix/System.Native/pal_datetime.cpp rename to external/corefx/src/Native/Unix/System.Native/pal_datetime.c index 1a8e609438..fb0548d231 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_datetime.cpp +++ b/external/corefx/src/Native/Unix/System.Native/pal_datetime.c @@ -22,19 +22,19 @@ static const int64_t TICKS_PER_MICROSECOND = 10; /* 1000 / 100 */ // SystemNative_GetSystemTimeAsTicks return the system time as ticks (100 nanoseconds) // since 00:00 01 January 1970 UTC (Unix epoch) // -extern "C" int64_t SystemNative_GetSystemTimeAsTicks() +int64_t SystemNative_GetSystemTimeAsTicks() { #if HAVE_CLOCK_REALTIME struct timespec time; if (clock_gettime(CLOCK_REALTIME, &time) == 0) { - return static_cast(time.tv_sec) * TICKS_PER_SECOND + (time.tv_nsec / NANOSECONDS_PER_TICK); + return (int64_t)(time.tv_sec) * TICKS_PER_SECOND + (time.tv_nsec / NANOSECONDS_PER_TICK); } #else struct timeval time; if (gettimeofday(&time, NULL) == 0) { - return static_cast(time.tv_sec) * TICKS_PER_SECOND + (time.tv_usec * TICKS_PER_MICROSECOND); + return (int64_t)(time.tv_sec) * TICKS_PER_SECOND + (time.tv_usec * TICKS_PER_MICROSECOND); } #endif // in failure we return 00:00 01 January 1970 UTC (Unix epoch) diff --git a/external/corefx/src/Native/Unix/System.Native/pal_errno.c b/external/corefx/src/Native/Unix/System.Native/pal_errno.c index 996d777da0..bb00d95534 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_errno.c +++ b/external/corefx/src/Native/Unix/System.Native/pal_errno.c @@ -178,8 +178,10 @@ int32_t SystemNative_ConvertErrorPlatformToPal(int32_t platformErrno) return Error_ETXTBSY; case EXDEV: return Error_EXDEV; +#ifdef ESOCKTNOSUPPORT case ESOCKTNOSUPPORT: return Error_ESOCKTNOSUPPORT; +#endif case EPFNOSUPPORT: return Error_EPFNOSUPPORT; case ESHUTDOWN: @@ -366,8 +368,10 @@ int32_t SystemNative_ConvertErrorPalToPlatform(int32_t error) return EXDEV; case Error_EPFNOSUPPORT: return EPFNOSUPPORT; +#ifdef ESOCKTNOSUPPORT case Error_ESOCKTNOSUPPORT: return ESOCKTNOSUPPORT; +#endif case Error_ESHUTDOWN: return ESHUTDOWN; case Error_EHOSTDOWN: diff --git a/external/corefx/src/Native/Unix/System.Native/pal_io.c b/external/corefx/src/Native/Unix/System.Native/pal_io.c index f95a18a5de..71a3674711 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_io.c +++ b/external/corefx/src/Native/Unix/System.Native/pal_io.c @@ -120,17 +120,6 @@ c_static_assert(PAL_SEEK_SET == SEEK_SET); c_static_assert(PAL_SEEK_CUR == SEEK_CUR); c_static_assert(PAL_SEEK_END == SEEK_END); -// Validate our PollFlags enum values are correct for the platform -// HACK: AIX values are different; we convert them between PAL_POLL and POLL now -#ifndef _AIX -c_static_assert(PAL_POLLIN == POLLIN); -c_static_assert(PAL_POLLPRI == POLLPRI); -c_static_assert(PAL_POLLOUT == POLLOUT); -c_static_assert(PAL_POLLERR == POLLERR); -c_static_assert(PAL_POLLHUP == POLLHUP); -c_static_assert(PAL_POLLNVAL == POLLNVAL); -#endif - // Validate our FileAdvice enum values are correct for the platform #if HAVE_POSIX_ADVISE c_static_assert(PAL_POSIX_FADV_NORMAL == POSIX_FADV_NORMAL); @@ -883,6 +872,7 @@ int32_t SystemNative_MAdvise(void* address, uint64_t length, int32_t advice) int32_t SystemNative_MLock(void* address, uint64_t length) { +#if !defined (__HAIKU__) if (length > SIZE_MAX) { errno = ERANGE; @@ -890,10 +880,15 @@ int32_t SystemNative_MLock(void* address, uint64_t length) } return mlock(address, (size_t)length); +#else + errno = ENOSYS; + return -1; +#endif } int32_t SystemNative_MUnlock(void* address, uint64_t length) { +#if !defined (__HAIKU__) if (length > SIZE_MAX) { errno = ERANGE; @@ -901,6 +896,10 @@ int32_t SystemNative_MUnlock(void* address, uint64_t length) } return munlock(address, (size_t)length); +#else + errno = ENOSYS; + return -1; +#endif } int32_t SystemNative_MProtect(void* address, uint64_t length, int32_t protection) @@ -1108,6 +1107,8 @@ int32_t SystemNative_PosixFAdvise(intptr_t fd, int64_t offset, int64_t length, i #endif } +#ifndef TARGET_ANDROID + char* SystemNative_GetLine(FILE* stream) { assert(stream != NULL); @@ -1119,6 +1120,8 @@ char* SystemNative_GetLine(FILE* stream) return length >= 0 ? lineptr : NULL; } +#endif + int32_t SystemNative_Read(intptr_t fd, void* buffer, int32_t bufferSize) { assert(buffer != NULL || bufferSize == 0); diff --git a/external/corefx/src/Native/Unix/System.Native/pal_maphardwaretype.c b/external/corefx/src/Native/Unix/System.Native/pal_maphardwaretype.c index 7f8e825783..47864e45f9 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_maphardwaretype.c +++ b/external/corefx/src/Native/Unix/System.Native/pal_maphardwaretype.c @@ -56,27 +56,39 @@ uint16_t MapHardwareType(uint16_t nativeType) { case IFT_ETHER: return NetworkInterfaceType_Ethernet; +#ifdef IFT_ISO88025 case IFT_ISO88025: return NetworkInterfaceType_TokenRing; +#endif +#ifdef IFT_FDDI case IFT_FDDI: return NetworkInterfaceType_Fddi; +#endif +#ifdef IFT_ISDNBASIC case IFT_ISDNBASIC: return NetworkInterfaceType_Isdn; +#endif +#ifdef IFT_ISDNPRIMARY case IFT_ISDNPRIMARY: return NetworkInterfaceType_PrimaryIsdn; +#endif case IFT_PPP: return NetworkInterfaceType_Ppp; case IFT_LOOP: return NetworkInterfaceType_Loopback; +#ifdef IFT_XETHER case IFT_XETHER: return NetworkInterfaceType_Ethernet3Megabit; +#endif case IFT_SLIP: return NetworkInterfaceType_Slip; +#ifdef IFT_ATM case IFT_ATM: return NetworkInterfaceType_Atm; +#endif case IFT_MODEM: return NetworkInterfaceType_GenericModem; -#if defined(IFT_IEEE1394) +#ifdef IFT_IEEE1394 case IFT_IEEE1394: return NetworkInterfaceType_HighPerformanceSerialBus; #endif diff --git a/external/corefx/src/Native/Unix/System.Native/pal_mount.cpp b/external/corefx/src/Native/Unix/System.Native/pal_mount.c similarity index 72% rename from external/corefx/src/Native/Unix/System.Native/pal_mount.cpp rename to external/corefx/src/Native/Unix/System.Native/pal_mount.c index ee62ba9e6e..467ed5e263 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_mount.cpp +++ b/external/corefx/src/Native/Unix/System.Native/pal_mount.c @@ -8,6 +8,7 @@ #include #include #include +#include // Check if we should use getmntinfo or /proc/mounts #if HAVE_MNTINFO @@ -28,9 +29,9 @@ static int32_t GetMountInfo(MountPointFound onFound) #if HAVE_MNTINFO // getmntinfo returns pointers to OS-internal structs, so we don't need to worry about free'ing the object #if HAVE_STATFS - struct statfs* mounts = nullptr; + struct statfs* mounts = NULL; #else - struct statvfs* mounts = nullptr; + struct statvfs* mounts = NULL; #endif int count = getmntinfo(&mounts, 0); for (int32_t i = 0; i < count; i++) @@ -45,13 +46,13 @@ static int32_t GetMountInfo(MountPointFound onFound) int result = -1; FILE* fp = setmntent("/proc/mounts", MNTOPT_RO); - if (fp != nullptr) + if (fp != NULL) { // The _r version of getmntent needs all buffers to be passed in; however, we don't know how big of a string // buffer we will need, so pick something that seems like it will be big enough. - char buffer[STRING_BUFFER_SIZE] = {}; - mntent entry; - while (getmntent_r(fp, &entry, buffer, STRING_BUFFER_SIZE) != nullptr) + char buffer[STRING_BUFFER_SIZE] = {0}; + struct mntent entry; + while (getmntent_r(fp, &entry, buffer, STRING_BUFFER_SIZE) != NULL) { onFound(entry.mnt_dir); } @@ -67,21 +68,25 @@ static int32_t GetMountInfo(MountPointFound onFound) #endif -extern "C" int32_t SystemNative_GetAllMountPoints(MountPointFound onFound) +int32_t SystemNative_GetAllMountPoints(MountPointFound onFound) { return GetMountInfo(onFound); } -extern "C" int32_t SystemNative_GetSpaceInfoForMountPoint(const char* name, MountPointInformation* mpi) +int32_t SystemNative_GetSpaceInfoForMountPoint(const char* name, MountPointInformation* mpi) { - assert(name != nullptr); - assert(mpi != nullptr); + assert(name != NULL); + assert(mpi != NULL); #if HAVE_STATFS - struct statfs stats = {}; + struct statfs stats; + memset(&stats, 0, sizeof(struct statfs)); + int result = statfs(name, &stats); #else - struct statvfs stats = {}; + struct statvfs stats; + memset(&stats, 0, sizeof(struct statvfs)); + int result = statvfs(name, &stats); #endif if (result == 0) @@ -89,10 +94,10 @@ extern "C" int32_t SystemNative_GetSpaceInfoForMountPoint(const char* name, Moun // Note that these have signed integer types on some platforms but mustn't be negative. // Also, upcast here (some platforms have smaller types) to 64-bit before multiplying to // avoid overflow. - uint64_t bsize = UnsignedCast(stats.f_bsize); - uint64_t bavail = UnsignedCast(stats.f_bavail); - uint64_t bfree = UnsignedCast(stats.f_bfree); - uint64_t blocks = UnsignedCast(stats.f_blocks); + uint64_t bsize = (uint64_t)(stats.f_bsize); + uint64_t bavail = (uint64_t)(stats.f_bavail); + uint64_t bfree = (uint64_t)(stats.f_bfree); + uint64_t blocks = (uint64_t)(stats.f_blocks); mpi->AvailableFreeSpace = bsize * bavail; mpi->TotalFreeSpace = bsize * bfree; @@ -100,16 +105,16 @@ extern "C" int32_t SystemNative_GetSpaceInfoForMountPoint(const char* name, Moun } else { - *mpi = {}; + memset(mpi, 0, sizeof(MountPointInformation)); } return result; } -extern "C" int32_t +int32_t SystemNative_GetFormatInfoForMountPoint(const char* name, char* formatNameBuffer, int32_t bufferLength, int64_t* formatType) { - assert((formatNameBuffer != nullptr) && (formatType != nullptr)); + assert((formatNameBuffer != NULL) && (formatType != NULL)); assert(bufferLength > 0); #if HAVE_STATFS @@ -134,13 +139,13 @@ SystemNative_GetFormatInfoForMountPoint(const char* name, char* formatNameBuffer } else { - SafeStringCopy(formatNameBuffer, bufferLength, stats.f_fstypename); + SafeStringCopy(formatNameBuffer, Int32ToSizeT(bufferLength), stats.f_fstypename); *formatType = -1; } #else - assert(formatType != nullptr); - *formatType = SignedCast(stats.f_type); - SafeStringCopy(formatNameBuffer, bufferLength, ""); + assert(formatType != NULL); + *formatType = (int64_t)(stats.f_type); + SafeStringCopy(formatNameBuffer, Int32ToSizeT(bufferLength), ""); #endif } else diff --git a/external/corefx/src/Native/Unix/System.Native/pal_mount.h b/external/corefx/src/Native/Unix/System.Native/pal_mount.h index 741fff428f..8156022c06 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_mount.h +++ b/external/corefx/src/Native/Unix/System.Native/pal_mount.h @@ -13,12 +13,12 @@ BEGIN_EXTERN_C /** * Struct to describe the amount of free space and total space on a given mount point */ -struct MountPointInformation +typedef struct { uint64_t AvailableFreeSpace; uint64_t TotalFreeSpace; uint64_t TotalSize; -}; +} MountPointInformation; /** * Function pointer to call back into C# when we find a mount point via GetAllMountPoints. diff --git a/external/corefx/src/Native/Unix/System.Native/pal_networkchange.cpp b/external/corefx/src/Native/Unix/System.Native/pal_networkchange.c similarity index 56% rename from external/corefx/src/Native/Unix/System.Native/pal_networkchange.cpp rename to external/corefx/src/Native/Unix/System.Native/pal_networkchange.c index 5fbbd9fc76..822f7c8732 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_networkchange.cpp +++ b/external/corefx/src/Native/Unix/System.Native/pal_networkchange.c @@ -19,55 +19,57 @@ #pragma clang diagnostic ignored "-Wcast-align" // NLMSG_* macros trigger this -extern "C" Error SystemNative_CreateNetworkChangeListenerSocket(int32_t* retSocket) +Error SystemNative_CreateNetworkChangeListenerSocket(int32_t* retSocket) { - sockaddr_nl sa = {}; + struct sockaddr_nl sa; + memset(&sa, 0, sizeof(struct sockaddr_nl)); + sa.nl_family = AF_NETLINK; sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV4_ROUTE | RTMGRP_IPV6_ROUTE; int32_t sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) { *retSocket = -1; - return static_cast(SystemNative_ConvertErrorPlatformToPal(errno)); + return (Error)(SystemNative_ConvertErrorPlatformToPal(errno)); } - if (bind(sock, reinterpret_cast(&sa), sizeof(sa)) != 0) + if (bind(sock, (struct sockaddr*)(&sa), sizeof(sa)) != 0) { *retSocket = -1; - return static_cast(SystemNative_ConvertErrorPlatformToPal(errno)); + return (Error)(SystemNative_ConvertErrorPlatformToPal(errno)); } *retSocket = sock; return Error_SUCCESS; } -extern "C" Error SystemNative_CloseNetworkChangeListenerSocket(int32_t socket) +Error SystemNative_CloseNetworkChangeListenerSocket(int32_t socket) { int err = close(socket); - return err == 0 || CheckInterrupted(err) ? Error_SUCCESS : static_cast(SystemNative_ConvertErrorPlatformToPal(errno)); + return err == 0 || CheckInterrupted(err) ? Error_SUCCESS : (Error)(SystemNative_ConvertErrorPlatformToPal(errno)); } -static NetworkChangeKind ReadNewLinkMessage(nlmsghdr* hdr) +static NetworkChangeKind ReadNewLinkMessage(struct nlmsghdr* hdr) { - assert(hdr != nullptr); - ifinfomsg* ifimsg; - ifimsg = reinterpret_cast(NLMSG_DATA(hdr)); + assert(hdr != NULL); + struct ifinfomsg* ifimsg; + ifimsg = (struct ifinfomsg*)NLMSG_DATA(hdr); if (ifimsg->ifi_family == AF_INET) { if ((ifimsg->ifi_flags & IFF_UP) != 0) { - return NetworkChangeKind::LinkAdded; + return LinkAdded; } } - return NetworkChangeKind::None; + return None; } -extern "C" void SystemNative_ReadEvents(int32_t sock, NetworkChangeEvent onNetworkChange) +void SystemNative_ReadEvents(int32_t sock, NetworkChangeEvent onNetworkChange) { char buffer[4096]; - iovec iov = {buffer, sizeof(buffer)}; - sockaddr_nl sanl; - msghdr msg = { .msg_name = reinterpret_cast(&sanl), .msg_namelen = sizeof(sockaddr_nl), .msg_iov = &iov, .msg_iovlen = 1 }; + struct iovec iov = {buffer, sizeof(buffer)}; + struct sockaddr_nl sanl; + struct msghdr msg = { .msg_name = (void*)(&sanl), .msg_namelen = sizeof(struct sockaddr_nl), .msg_iov = &iov, .msg_iovlen = 1 }; ssize_t len; while (CheckInterrupted(len = recvmsg(sock, &msg, 0))); if (len == -1) @@ -76,7 +78,8 @@ extern "C" void SystemNative_ReadEvents(int32_t sock, NetworkChangeEvent onNetwo return; } - for (nlmsghdr* hdr = reinterpret_cast(buffer); NLMSG_OK(hdr, UnsignedCast(len)); NLMSG_NEXT(hdr, len)) + assert(len >= 0); + for (struct nlmsghdr* hdr = (struct nlmsghdr*)buffer; NLMSG_OK(hdr, (size_t)len); NLMSG_NEXT(hdr, len)) { switch (hdr->nlmsg_type) { @@ -85,24 +88,24 @@ extern "C" void SystemNative_ReadEvents(int32_t sock, NetworkChangeEvent onNetwo case NLMSG_ERROR: return; case RTM_NEWADDR: - onNetworkChange(sock, NetworkChangeKind::AddressAdded); + onNetworkChange(sock, AddressAdded); break; case RTM_DELADDR: - onNetworkChange(sock, NetworkChangeKind::AddressRemoved); + onNetworkChange(sock, AddressRemoved); break; case RTM_NEWLINK: onNetworkChange(sock, ReadNewLinkMessage(hdr)); break; case RTM_DELLINK: - onNetworkChange(sock, NetworkChangeKind::LinkRemoved); + onNetworkChange(sock, LinkRemoved); break; case RTM_NEWROUTE: case RTM_DELROUTE: { - rtmsg* dataAsRtMsg = reinterpret_cast(NLMSG_DATA(hdr)); + struct rtmsg* dataAsRtMsg = (struct rtmsg*)NLMSG_DATA(hdr); if (dataAsRtMsg->rtm_table == RT_TABLE_MAIN) { - onNetworkChange(sock, NetworkChangeKind::AvailabilityChanged); + onNetworkChange(sock, AvailabilityChanged); return; } break; diff --git a/external/corefx/src/Native/Unix/System.Native/pal_networkchange.h b/external/corefx/src/Native/Unix/System.Native/pal_networkchange.h index 596ce0edd7..a64b574ccb 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_networkchange.h +++ b/external/corefx/src/Native/Unix/System.Native/pal_networkchange.h @@ -11,7 +11,7 @@ BEGIN_EXTERN_C #include "pal_types.h" #include -enum NetworkChangeKind +typedef enum { None = -1, AddressAdded = 0, @@ -19,9 +19,11 @@ enum NetworkChangeKind LinkAdded = 2, LinkRemoved = 3, AvailabilityChanged = 4, -}; +} NetworkChangeKind; -typedef void (*NetworkChangeEvent)(int32_t sock, enum NetworkChangeKind notificationKind); +typedef enum Error Error; + +typedef void (*NetworkChangeEvent)(int32_t sock, NetworkChangeKind notificationKind); DLLEXPORT void SystemNative_ReadEvents(int32_t sock, NetworkChangeEvent onNetworkChange); diff --git a/external/corefx/src/Native/Unix/System.Native/pal_networking.c b/external/corefx/src/Native/Unix/System.Native/pal_networking.c index e6e06106e9..4f6d6a6c15 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_networking.c +++ b/external/corefx/src/Native/Unix/System.Native/pal_networking.c @@ -14,12 +14,12 @@ #include #include #include +#include #if HAVE_EPOLL #include #elif HAVE_KQUEUE #include #include -#include #elif HAVE_SYS_POLL_H #include #endif @@ -31,11 +31,14 @@ #include #include #include +#if HAVE_SYS_SOCKIO_H +#include +#endif #include #if defined(__APPLE__) && __APPLE__ #include #endif -#if !HAVE_GETDOMAINNAME && HAVE_UNAME +#if !HAVE_GETDOMAINNAME && HAVE_UTSNAME_DOMAINNAME #include #include #endif @@ -400,7 +403,7 @@ int32_t SystemNative_GetDomainName(uint8_t* name, int32_t nameLength) #endif return getdomainname((char*)name, namelen); -#elif HAVE_UNAME +#elif HAVE_UTSNAME_DOMAINNAME // On Android, there's no getdomainname but we can use uname to fetch the domain name // of the current device size_t namelen = (uint32_t)nameLength; @@ -1859,9 +1862,11 @@ static bool TryConvertSocketTypePalToPlatform(int32_t palSocketType, int* platfo *platformSocketType = SOCK_RAW; return true; +#ifdef SOCK_RDM case SocketType_SOCK_RDM: *platformSocketType = SOCK_RDM; return true; +#endif case SocketType_SOCK_SEQPACKET: *platformSocketType = SOCK_SEQPACKET; diff --git a/external/corefx/src/Native/Unix/System.Native/pal_process.cpp b/external/corefx/src/Native/Unix/System.Native/pal_process.c similarity index 73% rename from external/corefx/src/Native/Unix/System.Native/pal_process.cpp rename to external/corefx/src/Native/Unix/System.Native/pal_process.c index 1790e76dea..812125e819 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_process.cpp +++ b/external/corefx/src/Native/Unix/System.Native/pal_process.c @@ -9,7 +9,6 @@ #include #include -#include #include #include #include @@ -30,42 +29,42 @@ #endif // Validate that our Signals enum values are correct for the platform -static_assert(PAL_SIGKILL == SIGKILL, ""); +c_static_assert(PAL_SIGKILL == SIGKILL); // Validate that our SysLogPriority values are correct for the platform -static_assert(PAL_LOG_EMERG == LOG_EMERG, ""); -static_assert(PAL_LOG_ALERT == LOG_ALERT, ""); -static_assert(PAL_LOG_CRIT == LOG_CRIT, ""); -static_assert(PAL_LOG_ERR == LOG_ERR, ""); -static_assert(PAL_LOG_WARNING == LOG_WARNING, ""); -static_assert(PAL_LOG_NOTICE == LOG_NOTICE, ""); -static_assert(PAL_LOG_INFO == LOG_INFO, ""); -static_assert(PAL_LOG_DEBUG == LOG_DEBUG, ""); -static_assert(PAL_LOG_KERN == LOG_KERN, ""); -static_assert(PAL_LOG_USER == LOG_USER, ""); -static_assert(PAL_LOG_MAIL == LOG_MAIL, ""); -static_assert(PAL_LOG_DAEMON == LOG_DAEMON, ""); -static_assert(PAL_LOG_AUTH == LOG_AUTH, ""); -static_assert(PAL_LOG_SYSLOG == LOG_SYSLOG, ""); -static_assert(PAL_LOG_LPR == LOG_LPR, ""); -static_assert(PAL_LOG_NEWS == LOG_NEWS, ""); -static_assert(PAL_LOG_UUCP == LOG_UUCP, ""); -static_assert(PAL_LOG_CRON == LOG_CRON, ""); -static_assert(PAL_LOG_AUTHPRIV == LOG_AUTHPRIV, ""); -static_assert(PAL_LOG_FTP == LOG_FTP, ""); -static_assert(PAL_LOG_LOCAL0 == LOG_LOCAL0, ""); -static_assert(PAL_LOG_LOCAL1 == LOG_LOCAL1, ""); -static_assert(PAL_LOG_LOCAL2 == LOG_LOCAL2, ""); -static_assert(PAL_LOG_LOCAL3 == LOG_LOCAL3, ""); -static_assert(PAL_LOG_LOCAL4 == LOG_LOCAL4, ""); -static_assert(PAL_LOG_LOCAL5 == LOG_LOCAL5, ""); -static_assert(PAL_LOG_LOCAL6 == LOG_LOCAL6, ""); -static_assert(PAL_LOG_LOCAL7 == LOG_LOCAL7, ""); +c_static_assert(PAL_LOG_EMERG == LOG_EMERG); +c_static_assert(PAL_LOG_ALERT == LOG_ALERT); +c_static_assert(PAL_LOG_CRIT == LOG_CRIT); +c_static_assert(PAL_LOG_ERR == LOG_ERR); +c_static_assert(PAL_LOG_WARNING == LOG_WARNING); +c_static_assert(PAL_LOG_NOTICE == LOG_NOTICE); +c_static_assert(PAL_LOG_INFO == LOG_INFO); +c_static_assert(PAL_LOG_DEBUG == LOG_DEBUG); +c_static_assert(PAL_LOG_KERN == LOG_KERN); +c_static_assert(PAL_LOG_USER == LOG_USER); +c_static_assert(PAL_LOG_MAIL == LOG_MAIL); +c_static_assert(PAL_LOG_DAEMON == LOG_DAEMON); +c_static_assert(PAL_LOG_AUTH == LOG_AUTH); +c_static_assert(PAL_LOG_SYSLOG == LOG_SYSLOG); +c_static_assert(PAL_LOG_LPR == LOG_LPR); +c_static_assert(PAL_LOG_NEWS == LOG_NEWS); +c_static_assert(PAL_LOG_UUCP == LOG_UUCP); +c_static_assert(PAL_LOG_CRON == LOG_CRON); +c_static_assert(PAL_LOG_AUTHPRIV == LOG_AUTHPRIV); +c_static_assert(PAL_LOG_FTP == LOG_FTP); +c_static_assert(PAL_LOG_LOCAL0 == LOG_LOCAL0); +c_static_assert(PAL_LOG_LOCAL1 == LOG_LOCAL1); +c_static_assert(PAL_LOG_LOCAL2 == LOG_LOCAL2); +c_static_assert(PAL_LOG_LOCAL3 == LOG_LOCAL3); +c_static_assert(PAL_LOG_LOCAL4 == LOG_LOCAL4); +c_static_assert(PAL_LOG_LOCAL5 == LOG_LOCAL5); +c_static_assert(PAL_LOG_LOCAL6 == LOG_LOCAL6); +c_static_assert(PAL_LOG_LOCAL7 == LOG_LOCAL7); // Validate that out PriorityWhich values are correct for the platform -static_assert(PAL_PRIO_PROCESS == static_cast(PRIO_PROCESS), ""); -static_assert(PAL_PRIO_PGRP == static_cast(PRIO_PGRP), ""); -static_assert(PAL_PRIO_USER == static_cast(PRIO_USER), ""); +c_static_assert(PAL_PRIO_PROCESS == (int)PRIO_PROCESS); +c_static_assert(PAL_PRIO_PGRP == (int)PRIO_PGRP); +c_static_assert(PAL_PRIO_USER == (int)PRIO_USER); enum { @@ -98,8 +97,8 @@ static ssize_t WriteSize(int fd, const void* buffer, size_t count) if (result > 0) { rv += result; - buffer = reinterpret_cast(buffer) + result; - count -= static_cast(result); + buffer = (const uint8_t*)buffer + result; + count -= (size_t)result; } else { @@ -119,8 +118,8 @@ static ssize_t ReadSize(int fd, void* buffer, size_t count) if (result > 0) { rv += result; - buffer = reinterpret_cast(buffer) + result; - count -= static_cast(result); + buffer = (uint8_t*)buffer + result; + count -= (size_t)result; } else { @@ -140,7 +139,7 @@ static void ExitChild(int pipeToParent, int error) _exit(error != 0 ? error : EXIT_FAILURE); } -extern "C" int32_t SystemNative_ForkAndExecProcess(const char* filename, +int32_t SystemNative_ForkAndExecProcess(const char* filename, char* const argv[], char* const envp[], const char* cwd, @@ -160,8 +159,8 @@ extern "C" int32_t SystemNative_ForkAndExecProcess(const char* filename, int processId = -1; // Validate arguments - if (nullptr == filename || nullptr == argv || nullptr == envp || nullptr == stdinFd || nullptr == stdoutFd || - nullptr == stderrFd || nullptr == childPid) + if (NULL == filename || NULL == argv || NULL == envp || NULL == stdinFd || NULL == stdoutFd || + NULL == stderrFd || NULL == childPid) { assert(false && "null argument."); errno = EINVAL; @@ -241,7 +240,7 @@ extern "C" int32_t SystemNative_ForkAndExecProcess(const char* filename, } // Change to the designated working directory, if one was specified - if (nullptr != cwd) + if (NULL != cwd) { int result; while (CheckInterrupted(result = chdir(cwd))); @@ -262,7 +261,7 @@ extern "C" int32_t SystemNative_ForkAndExecProcess(const char* filename, *stdoutFd = stdoutFds[READ_END_OF_PIPE]; *stderrFd = stderrFds[READ_END_OF_PIPE]; -done: +done:; int priorErrno = errno; // Regardless of success or failure, close the parent's copy of the child's end of @@ -316,16 +315,16 @@ done: return 0; } -extern "C" FILE* SystemNative_POpen(const char* command, const char* type) +FILE* SystemNative_POpen(const char* command, const char* type) { - assert(command != nullptr); - assert(type != nullptr); + assert(command != NULL); + assert(type != NULL); return popen(command, type); } -extern "C" int32_t SystemNative_PClose(FILE* stream) +int32_t SystemNative_PClose(FILE* stream) { - assert(stream != nullptr); + assert(stream != NULL); return pclose(stream); } @@ -357,25 +356,25 @@ static int32_t ConvertRLimitResourcesPalToPlatform(RLimitResources value) return RLIMIT_NOFILE; } - assert_msg(false, "Unknown RLIMIT value", static_cast(value)); + assert_msg(false, "Unknown RLIMIT value", (int)value); return -1; } +#define LIMIT_MAX(T) _Generic(((T)0), \ + unsigned int: UINT_MAX, \ + unsigned long: ULONG_MAX, \ + unsigned long long: ULLONG_MAX) + // Because RLIM_INFINITY is different per-platform, use the max value of a uint64 (which is RLIM_INFINITY on Ubuntu) // to signify RLIM_INIFINITY; on OS X, where RLIM_INFINITY is slightly lower, we'll translate it to the correct value // here. static rlim_t ConvertFromManagedRLimitInfinityToPalIfNecessary(uint64_t value) { // rlim_t type can vary per platform, so we also treat anything outside its range as infinite. -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunknown-pragmas" -#pragma clang diagnostic ignored "-Wunknown-warning-option" -#pragma clang diagnostic ignored "-Wtautological-type-limit-compare" - if (value == UINT64_MAX || value > std::numeric_limits::max()) -#pragma clang diagnostic pop + if (value == UINT64_MAX || value > LIMIT_MAX(rlim_t)) return RLIM_INFINITY; - return static_cast(value); + return (rlim_t)value; } // Because RLIM_INFINITY is different per-platform, use the max value of a uint64 (which is RLIM_INFINITY on Ubuntu) @@ -386,71 +385,80 @@ static uint64_t ConvertFromNativeRLimitInfinityToManagedIfNecessary(rlim_t value if (value == RLIM_INFINITY) return UINT64_MAX; - return UnsignedCast(value); + assert(value >= 0); + return (uint64_t)value; } -static void ConvertFromRLimitManagedToPal(const RLimit& pal, rlimit& native) +static void ConvertFromRLimitManagedToPal(const RLimit* pal, struct rlimit* native) { - native.rlim_cur = ConvertFromManagedRLimitInfinityToPalIfNecessary(pal.CurrentLimit); - native.rlim_max = ConvertFromManagedRLimitInfinityToPalIfNecessary(pal.MaximumLimit); + native->rlim_cur = ConvertFromManagedRLimitInfinityToPalIfNecessary(pal->CurrentLimit); + native->rlim_max = ConvertFromManagedRLimitInfinityToPalIfNecessary(pal->MaximumLimit); } -static void ConvertFromPalRLimitToManaged(const rlimit& native, RLimit& pal) +static void ConvertFromPalRLimitToManaged(const struct rlimit* native, RLimit* pal) { - pal.CurrentLimit = ConvertFromNativeRLimitInfinityToManagedIfNecessary(native.rlim_cur); - pal.MaximumLimit = ConvertFromNativeRLimitInfinityToManagedIfNecessary(native.rlim_max); + pal->CurrentLimit = ConvertFromNativeRLimitInfinityToManagedIfNecessary(native->rlim_cur); + pal->MaximumLimit = ConvertFromNativeRLimitInfinityToManagedIfNecessary(native->rlim_max); } -extern "C" int32_t SystemNative_GetRLimit(RLimitResources resourceType, RLimit* limits) +#if defined __USE_GNU && !defined __cplusplus +typedef __rlimit_resource_t rlimitResource; +typedef __priority_which_t priorityWhich; +#else +typedef int rlimitResource; +typedef int priorityWhich; +#endif + +int32_t SystemNative_GetRLimit(RLimitResources resourceType, RLimit* limits) { - assert(limits != nullptr); + assert(limits != NULL); int32_t platformLimit = ConvertRLimitResourcesPalToPlatform(resourceType); - rlimit internalLimit; - int result = getrlimit(platformLimit, &internalLimit); + struct rlimit internalLimit; + int result = getrlimit((rlimitResource)platformLimit, &internalLimit); if (result == 0) { - ConvertFromPalRLimitToManaged(internalLimit, *limits); + ConvertFromPalRLimitToManaged(&internalLimit, limits); } else { - *limits = {}; + *limits = (RLimit){0,0}; } return result; } -extern "C" int32_t SystemNative_SetRLimit(RLimitResources resourceType, const RLimit* limits) +int32_t SystemNative_SetRLimit(RLimitResources resourceType, const RLimit* limits) { - assert(limits != nullptr); + assert(limits != NULL); int32_t platformLimit = ConvertRLimitResourcesPalToPlatform(resourceType); - rlimit internalLimit; - ConvertFromRLimitManagedToPal(*limits, internalLimit); - return setrlimit(platformLimit, &internalLimit); + struct rlimit internalLimit; + ConvertFromRLimitManagedToPal(limits, &internalLimit); + return setrlimit((rlimitResource)platformLimit, &internalLimit); } -extern "C" int32_t SystemNative_Kill(int32_t pid, int32_t signal) +int32_t SystemNative_Kill(int32_t pid, int32_t signal) { return kill(pid, signal); } -extern "C" int32_t SystemNative_GetPid() +int32_t SystemNative_GetPid() { return getpid(); } -extern "C" int32_t SystemNative_GetSid(int32_t pid) +int32_t SystemNative_GetSid(int32_t pid) { return getsid(pid); } -extern "C" void SystemNative_SysLog(SysLogPriority priority, const char* message, const char* arg1) +void SystemNative_SysLog(SysLogPriority priority, const char* message, const char* arg1) { - syslog(static_cast(priority), message, arg1); + syslog((int)priority, message, arg1); } -extern "C" int32_t SystemNative_WaitIdAnyExitedNoHangNoWait() +int32_t SystemNative_WaitIdAnyExitedNoHangNoWait() { siginfo_t siginfo; int32_t result; @@ -467,9 +475,9 @@ extern "C" int32_t SystemNative_WaitIdAnyExitedNoHangNoWait() return result; } -extern "C" int32_t SystemNative_WaitPidExitedNoHang(int32_t pid, int32_t* exitCode) +int32_t SystemNative_WaitPidExitedNoHang(int32_t pid, int32_t* exitCode) { - assert(exitCode != nullptr); + assert(exitCode != NULL); int32_t result; int status; @@ -494,7 +502,7 @@ extern "C" int32_t SystemNative_WaitPidExitedNoHang(int32_t pid, int32_t* exitCo return result; } -extern "C" int64_t SystemNative_PathConf(const char* path, PathConfName name) +int64_t SystemNative_PathConf(const char* path, PathConfName name) { int32_t confValue = -1; switch (name) @@ -530,7 +538,7 @@ extern "C" int64_t SystemNative_PathConf(const char* path, PathConfName name) if (confValue == -1) { - assert_msg(false, "Unknown PathConfName", static_cast(name)); + assert_msg(false, "Unknown PathConfName", (int)name); errno = EINVAL; return -1; } @@ -538,43 +546,43 @@ extern "C" int64_t SystemNative_PathConf(const char* path, PathConfName name) return pathconf(path, confValue); } -extern "C" int32_t SystemNative_GetPriority(PriorityWhich which, int32_t who) +int32_t SystemNative_GetPriority(PriorityWhich which, int32_t who) { // GetPriority uses errno 0 to show success to make sure we don't have a stale value errno = 0; #if PRIORITY_REQUIRES_INT_WHO - return getpriority(which, who); + return getpriority((priorityWhich)which, who); #else - return getpriority(which, static_cast(who)); + return getpriority((priorityWhich)which, (id_t)who); #endif } -extern "C" int32_t SystemNative_SetPriority(PriorityWhich which, int32_t who, int32_t nice) +int32_t SystemNative_SetPriority(PriorityWhich which, int32_t who, int32_t nice) { #if PRIORITY_REQUIRES_INT_WHO - return setpriority(which, who, nice); + return setpriority((priorityWhich)which, who, nice); #else - return setpriority(which, static_cast(who), nice); + return setpriority((priorityWhich)which, (id_t)who, nice); #endif } -extern "C" char* SystemNative_GetCwd(char* buffer, int32_t bufferSize) +char* SystemNative_GetCwd(char* buffer, int32_t bufferSize) { assert(bufferSize >= 0); if (bufferSize < 0) { errno = EINVAL; - return nullptr; + return NULL; } - return getcwd(buffer, UnsignedCast(bufferSize)); + return getcwd(buffer, Int32ToSizeT(bufferSize)); } #if HAVE_SCHED_SETAFFINITY -extern "C" int32_t SystemNative_SchedSetAffinity(int32_t pid, intptr_t* mask) +int32_t SystemNative_SchedSetAffinity(int32_t pid, intptr_t* mask) { - assert(mask != nullptr); + assert(mask != NULL); int maxCpu = sizeof(intptr_t) * 8; assert(maxCpu <= CPU_SETSIZE); @@ -585,7 +593,7 @@ extern "C" int32_t SystemNative_SchedSetAffinity(int32_t pid, intptr_t* mask) intptr_t bits = *mask; for (int cpu = 0; cpu < maxCpu; cpu++) { - if ((bits & static_cast(1u << cpu)) != 0) + if ((bits & (((intptr_t)1u) << cpu)) != 0) { CPU_SET(cpu, &set); } @@ -596,9 +604,9 @@ extern "C" int32_t SystemNative_SchedSetAffinity(int32_t pid, intptr_t* mask) #endif #if HAVE_SCHED_GETAFFINITY -extern "C" int32_t SystemNative_SchedGetAffinity(int32_t pid, intptr_t* mask) +int32_t SystemNative_SchedGetAffinity(int32_t pid, intptr_t* mask) { - assert(mask != nullptr); + assert(mask != NULL); cpu_set_t set; int32_t result = sched_getaffinity(pid, sizeof(cpu_set_t), &set); diff --git a/external/corefx/src/Native/Unix/System.Native/pal_process.h b/external/corefx/src/Native/Unix/System.Native/pal_process.h index 81ee2d0619..f36e50fe9b 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_process.h +++ b/external/corefx/src/Native/Unix/System.Native/pal_process.h @@ -58,7 +58,7 @@ DLLEXPORT int32_t SystemNative_PClose(FILE* stream); * These values differ from OS to OS, so make a constant contract. * These values apply for the current process only */ -enum RLimitResources : int32_t +typedef enum { PAL_RLIMIT_CPU = 0, // CPU limit in seconds PAL_RLIMIT_FSIZE = 1, // Largest file that can be created, in bytes @@ -70,9 +70,9 @@ enum RLimitResources : int32_t PAL_RLIMIT_MEMLOCK = 7, // Locked-in-memory address space PAL_RLIMIT_NPROC = 8, // Number of processes PAL_RLIMIT_NOFILE = 9, // Number of open files -}; +} RLimitResources; -enum Signals : int32_t +enum Signals { PAL_SIGKILL = 9, /* kill the specified process */ }; @@ -85,7 +85,7 @@ enum Signals : int32_t * * These values keep their original definition and are taken from syslog.h */ -enum SysLogPriority : int32_t +typedef enum { // Priorities PAL_LOG_EMERG = 0, /* system is unusable */ @@ -118,7 +118,7 @@ enum SysLogPriority : int32_t PAL_LOG_LOCAL5 = (21 << 3), /* reserved for local use */ PAL_LOG_LOCAL6 = (22 << 3), /* reserved for local use */ PAL_LOG_LOCAL7 = (23 << 3), /* reserved for local use */ -}; +} SysLogPriority; /** * Constants to pass into pathconf. @@ -127,7 +127,7 @@ enum SysLogPriority : int32_t * values; they must be converted to the correct platform * values before passing to pathconf. */ -enum PathConfName : int32_t +typedef enum { PAL_PC_LINK_MAX = 1, PAL_PC_MAX_CANON = 2, @@ -138,27 +138,27 @@ enum PathConfName : int32_t PAL_PC_CHOWN_RESTRICTED = 7, PAL_PC_NO_TRUNC = 8, PAL_PC_VDISABLE = 9, -}; +} PathConfName; /** * Constants for passing to GetPriority and SetPriority. */ -enum PriorityWhich : int32_t +typedef enum { PAL_PRIO_PROCESS = 0, PAL_PRIO_PGRP = 1, PAL_PRIO_USER = 2, -}; +} PriorityWhich; /** * The current and maximum resource values for the current process. * These values are depict the resource according to the above enum. */ -struct RLimit +typedef struct { uint64_t CurrentLimit; uint64_t MaximumLimit; -}; +} RLimit; /** * The native struct is dependent on the size of a numeric type @@ -194,7 +194,7 @@ DLLEXPORT int32_t SystemNative_Kill(int32_t pid, int32_t signal); * Returns the Process ID of the current executing process. * This call should never fail */ -DLLEXPORT int32_t SystemNative_GetPid(); +DLLEXPORT int32_t SystemNative_GetPid(void); /** * Returns the sessions ID of the specified process; if 0 is passed in, returns the @@ -216,7 +216,7 @@ DLLEXPORT void SystemNative_SysLog(SysLogPriority priority, const char* message, * 2) if no children are terminated, 0 is returned * 3) on error, -1 is returned */ -extern "C" int32_t SystemNative_WaitIdAnyExitedNoHangNoWait(); +DLLEXPORT int32_t SystemNative_WaitIdAnyExitedNoHangNoWait(void); /** * Reaps a terminated child. @@ -226,7 +226,7 @@ extern "C" int32_t SystemNative_WaitIdAnyExitedNoHangNoWait(); * 3) if the child has not yet terminated, 0 is returned * 4) on error, -1 is returned. */ -extern "C" int32_t SystemNative_WaitPidExitedNoHang(int32_t pid, int32_t* exitCode); +DLLEXPORT int32_t SystemNative_WaitPidExitedNoHang(int32_t pid, int32_t* exitCode); /** * Gets the configurable limit or variable for system path or file descriptor options. @@ -275,6 +275,4 @@ DLLEXPORT int32_t SystemNative_SchedSetAffinity(int32_t pid, intptr_t* mask); DLLEXPORT int32_t SystemNative_SchedGetAffinity(int32_t pid, intptr_t* mask); #endif -DLLEXPORT char** SystemNative_GetEnviron(); - END_EXTERN_C diff --git a/external/corefx/src/Native/Unix/System.Native/pal_random.c b/external/corefx/src/Native/Unix/System.Native/pal_random.c index 5c216cc88e..8a267a34bd 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_random.c +++ b/external/corefx/src/Native/Unix/System.Native/pal_random.c @@ -24,7 +24,7 @@ void SystemNative_GetNonCryptographicallySecureRandomBytes(uint8_t* buffer, int3 { assert(buffer != NULL); -#if HAVE_ARC4RANDOM +#if HAVE_ARC4RANDOM_BUF arc4random_buf(buffer, (size_t)bufferLength); #else static volatile int rand_des = -1; @@ -105,5 +105,5 @@ void SystemNative_GetNonCryptographicallySecureRandomBytes(uint8_t* buffer, int3 *(buffer + i) ^= num; num >>= 8; } -#endif // HAS_ARC4RANDOM +#endif // HAVE_ARC4RANDOM_BUF } diff --git a/external/corefx/src/Native/Unix/System.Native/pal_runtimeextensions.cpp b/external/corefx/src/Native/Unix/System.Native/pal_runtimeextensions.c similarity index 75% rename from external/corefx/src/Native/Unix/System.Native/pal_runtimeextensions.cpp rename to external/corefx/src/Native/Unix/System.Native/pal_runtimeextensions.c index 97d82577b4..d87e527516 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_runtimeextensions.cpp +++ b/external/corefx/src/Native/Unix/System.Native/pal_runtimeextensions.c @@ -7,12 +7,12 @@ #include #include -extern "C" int32_t SystemNative_GetNodeName(char* version, int* capacity) +int32_t SystemNative_GetNodeName(char* version, int* capacity) { struct utsname _utsname; if (uname(&_utsname) != -1) { - int r = snprintf(version, static_cast(*capacity), "%s", _utsname.nodename); + int r = snprintf(version, (size_t)(*capacity), "%s", _utsname.nodename); if (r > *capacity) { *capacity = r + 1; diff --git a/external/corefx/src/Native/Unix/System.Native/pal_runtimeinformation.cpp b/external/corefx/src/Native/Unix/System.Native/pal_runtimeinformation.c similarity index 75% rename from external/corefx/src/Native/Unix/System.Native/pal_runtimeinformation.cpp rename to external/corefx/src/Native/Unix/System.Native/pal_runtimeinformation.c index 6994312e41..a9bfc145e3 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_runtimeinformation.cpp +++ b/external/corefx/src/Native/Unix/System.Native/pal_runtimeinformation.c @@ -9,25 +9,25 @@ #include #include -extern "C" const char* SystemNative_GetUnixName() +const char* SystemNative_GetUnixName() { return PAL_UNIX_NAME; } -extern "C" char* SystemNative_GetUnixRelease() +char* SystemNative_GetUnixRelease() { struct utsname _utsname; return uname(&_utsname) != -1 ? strdup(_utsname.release) : - nullptr; + NULL; } -extern "C" int32_t SystemNative_GetUnixVersion(char* version, int* capacity) +int32_t SystemNative_GetUnixVersion(char* version, int* capacity) { struct utsname _utsname; if (uname(&_utsname) != -1) { - int r = snprintf(version, static_cast(*capacity), "%s %s %s", _utsname.sysname, _utsname.release, _utsname.version); + int r = snprintf(version, (size_t)(*capacity), "%s %s %s", _utsname.sysname, _utsname.release, _utsname.version); if (r > *capacity) { *capacity = r + 1; @@ -43,7 +43,7 @@ extern "C" int32_t SystemNative_GetUnixVersion(char* version, int* capacity) 1 - x64 2 - ARM 3 - ARM64 */ -extern "C" int32_t SystemNative_GetOSArchitecture() +int32_t SystemNative_GetOSArchitecture() { #if defined(_ARM_) return ARCH_ARM; @@ -63,7 +63,7 @@ extern "C" int32_t SystemNative_GetOSArchitecture() 1 - x64 2 - ARM 3 - ARM64 */ -extern "C" int32_t SystemNative_GetProcessArchitecture() +int32_t SystemNative_GetProcessArchitecture() { #if defined(_ARM_) return ARCH_ARM; diff --git a/external/corefx/src/Native/Unix/System.Native/pal_runtimeinformation.h b/external/corefx/src/Native/Unix/System.Native/pal_runtimeinformation.h index 670cd7cc75..91d310dcf4 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_runtimeinformation.h +++ b/external/corefx/src/Native/Unix/System.Native/pal_runtimeinformation.h @@ -10,15 +10,15 @@ BEGIN_EXTERN_C #include "pal_types.h" -DLLEXPORT const char* SystemNative_GetUnixName(); +DLLEXPORT const char* SystemNative_GetUnixName(void); -DLLEXPORT char* SystemNative_GetUnixRelease(); +DLLEXPORT char* SystemNative_GetUnixRelease(void); DLLEXPORT int32_t SystemNative_GetUnixVersion(char* version, int* capacity); -DLLEXPORT int32_t SystemNative_GetOSArchitecture(); +DLLEXPORT int32_t SystemNative_GetOSArchitecture(void); -DLLEXPORT int32_t SystemNative_GetProcessArchitecture(); +DLLEXPORT int32_t SystemNative_GetProcessArchitecture(void); enum { diff --git a/external/corefx/src/Native/Unix/System.Native/pal_string.cpp b/external/corefx/src/Native/Unix/System.Native/pal_string.c similarity index 69% rename from external/corefx/src/Native/Unix/System.Native/pal_string.cpp rename to external/corefx/src/Native/Unix/System.Native/pal_string.c index f9ad3ea301..6562816319 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_string.cpp +++ b/external/corefx/src/Native/Unix/System.Native/pal_string.c @@ -11,23 +11,23 @@ #include #include -extern "C" int32_t SystemNative_SNPrintF(char* string, int32_t size, const char* format, ...) +int32_t SystemNative_SNPrintF(char* string, int32_t size, const char* format, ...) { - assert(string != nullptr || size == 0); + assert(string != NULL || size == 0); assert(size >= 0); - assert(format != nullptr); + assert(format != NULL); if (size < 0) return -1; va_list arguments; va_start(arguments, format); - int result = vsnprintf(string, UnsignedCast(size), format, arguments); + int result = vsnprintf(string, Int32ToSizeT(size), format, arguments); va_end(arguments); return result; } -extern "C" int32_t SystemNative_PrintF(const char* format, ...) +int32_t SystemNative_PrintF(const char* format, ...) { va_list arguments; va_start(arguments, format); diff --git a/external/corefx/src/Native/Unix/System.Native/pal_sysctl.cpp b/external/corefx/src/Native/Unix/System.Native/pal_sysctl.c similarity index 75% rename from external/corefx/src/Native/Unix/System.Native/pal_sysctl.cpp rename to external/corefx/src/Native/Unix/System.Native/pal_sysctl.c index bc4305ba24..d568d9e691 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_sysctl.cpp +++ b/external/corefx/src/Native/Unix/System.Native/pal_sysctl.c @@ -15,18 +15,17 @@ #include "pal_safecrt.h" #include -#include #include #include -extern "C" int32_t SystemNative_Sysctl(int* name, unsigned int namelen, void* value, size_t* len) +int32_t SystemNative_Sysctl(int* name, unsigned int namelen, void* value, size_t* len) { - void* newp = nullptr; + void* newp = NULL; size_t newlen = 0; #ifdef __linux__ - return sysctl(name, static_cast(namelen), value, len, newp, newlen); + return sysctl(name, (int)(namelen), value, len, newp, newlen); #else return sysctl(name, namelen, value, len, newp, newlen); #endif diff --git a/external/corefx/src/Native/Unix/System.Native/pal_sysctl.h b/external/corefx/src/Native/Unix/System.Native/pal_sysctl.h index 79e0c17160..f343ab7e75 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_sysctl.h +++ b/external/corefx/src/Native/Unix/System.Native/pal_sysctl.h @@ -15,4 +15,3 @@ BEGIN_EXTERN_C DLLEXPORT int32_t SystemNative_Sysctl(int* name, unsigned int namelen, void* value, size_t* len); END_EXTERN_C - diff --git a/external/corefx/src/Native/Unix/System.Native/pal_tcpstate.c b/external/corefx/src/Native/Unix/System.Native/pal_tcpstate.c index 7ea8fc1895..5026d4b7bd 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_tcpstate.c +++ b/external/corefx/src/Native/Unix/System.Native/pal_tcpstate.c @@ -11,7 +11,7 @@ #elif HAVE_TCP_H_TCPSTATE_ENUM #include #else -#error System must have TCP states defined in either tcp.h or tcp_fsm.h. +#warning System doesn't have TCP states defined in either tcp.h or tcp_fsm.h; falling back to always returning unknown. #endif int32_t SystemNative_MapTcpState(int32_t tcpState) @@ -39,8 +39,6 @@ int32_t SystemNative_MapTcpState(int32_t tcpState) return TcpState_FinWait2; case TCPS_TIME_WAIT: return TcpState_TimeWait; - default: - return TcpState_Unknown; #elif HAVE_TCP_H_TCPSTATE_ENUM case TCP_ESTABLISHED: return TcpState_Established; @@ -64,8 +62,8 @@ int32_t SystemNative_MapTcpState(int32_t tcpState) return TcpState_Listen; case TCP_CLOSING: return TcpState_Closing; +#endif default: return TcpState_Unknown; -#endif } } diff --git a/external/corefx/src/Native/Unix/System.Native/pal_time.cpp b/external/corefx/src/Native/Unix/System.Native/pal_time.c similarity index 72% rename from external/corefx/src/Native/Unix/System.Native/pal_time.cpp rename to external/corefx/src/Native/Unix/System.Native/pal_time.c index e40c3b351b..513408810b 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_time.cpp +++ b/external/corefx/src/Native/Unix/System.Native/pal_time.c @@ -20,25 +20,25 @@ enum SecondsToNanoSeconds = 1000000000 // 10^9 }; -static void ConvertUTimBuf(const UTimBuf& pal, utimbuf& native) +static void ConvertUTimBuf(const UTimBuf* pal, struct utimbuf* native) { - native.actime = static_cast(pal.AcTime); - native.modtime = static_cast(pal.ModTime); + native->actime = (time_t)(pal->AcTime); + native->modtime = (time_t)(pal->ModTime); } -extern "C" int32_t SystemNative_UTime(const char* path, UTimBuf* times) +int32_t SystemNative_UTime(const char* path, UTimBuf* times) { - assert(times != nullptr); + assert(times != NULL); - utimbuf temp; - ConvertUTimBuf(*times, temp); + struct utimbuf temp; + ConvertUTimBuf(times, &temp); int32_t result; while (CheckInterrupted(result = utime(path, &temp))); return result; } -extern "C" int32_t SystemNative_GetTimestampResolution(uint64_t* resolution) +int32_t SystemNative_GetTimestampResolution(uint64_t* resolution) { assert(resolution); @@ -62,7 +62,7 @@ extern "C" int32_t SystemNative_GetTimestampResolution(uint64_t* resolution) mach_timebase_info_data_t mtid; if (mach_timebase_info(&mtid) == KERN_SUCCESS) { - *resolution = SecondsToNanoSeconds * (static_cast(mtid.denom) / static_cast(mtid.numer)); + *resolution = SecondsToNanoSeconds * ((uint64_t)(mtid.denom) / (uint64_t)(mtid.numer)); return 1; } else @@ -78,7 +78,7 @@ extern "C" int32_t SystemNative_GetTimestampResolution(uint64_t* resolution) #endif } -extern "C" int32_t SystemNative_GetTimestamp(uint64_t* timestamp) +int32_t SystemNative_GetTimestamp(uint64_t* timestamp) { assert(timestamp); @@ -87,7 +87,7 @@ extern "C" int32_t SystemNative_GetTimestamp(uint64_t* timestamp) int result = clock_gettime(CLOCK_MONOTONIC, &ts); assert(result == 0); // only possible errors are if MONOTONIC isn't supported or &ts is an invalid address (void)result; // suppress unused parameter warning in release builds - *timestamp = (static_cast(ts.tv_sec) * SecondsToNanoSeconds) + static_cast(ts.tv_nsec); + *timestamp = ((uint64_t)(ts.tv_sec) * SecondsToNanoSeconds) + (uint64_t)(ts.tv_nsec); return 1; #elif HAVE_MACH_ABSOLUTE_TIME @@ -98,7 +98,7 @@ extern "C" int32_t SystemNative_GetTimestamp(uint64_t* timestamp) struct timeval tv; if (gettimeofday(&tv, NULL) == 0) { - *timestamp = (static_cast(tv.tv_sec) * SecondsToMicroSeconds) + static_cast(tv.tv_usec); + *timestamp = ((uint64_t)(tv.tv_sec) * SecondsToMicroSeconds) + (uint64_t)(tv.tv_usec); return 1; } else @@ -110,7 +110,7 @@ extern "C" int32_t SystemNative_GetTimestamp(uint64_t* timestamp) #endif } -extern "C" int32_t SystemNative_GetAbsoluteTime(uint64_t* timestamp) +int32_t SystemNative_GetAbsoluteTime(uint64_t* timestamp) { assert(timestamp); @@ -124,7 +124,7 @@ extern "C" int32_t SystemNative_GetAbsoluteTime(uint64_t* timestamp) #endif } -extern "C" int32_t SystemNative_GetTimebaseInfo(uint32_t* numer, uint32_t* denom) +int32_t SystemNative_GetTimebaseInfo(uint32_t* numer, uint32_t* denom) { #if HAVE_MACH_TIMEBASE_INFO mach_timebase_info_data_t timebase; diff --git a/external/corefx/src/Native/Unix/System.Native/pal_time.h b/external/corefx/src/Native/Unix/System.Native/pal_time.h index 99308ff9e3..b8b5a385c2 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_time.h +++ b/external/corefx/src/Native/Unix/System.Native/pal_time.h @@ -10,11 +10,11 @@ BEGIN_EXTERN_C #include "pal_types.h" -struct UTimBuf +typedef struct UTimBuf { int64_t AcTime; int64_t ModTime; -}; +} UTimBuf; /** * Sets the last access and last modified time of a file diff --git a/external/corefx/src/Native/Unix/System.Native/pal_uid.cpp b/external/corefx/src/Native/Unix/System.Native/pal_uid.c similarity index 68% rename from external/corefx/src/Native/Unix/System.Native/pal_uid.cpp rename to external/corefx/src/Native/Unix/System.Native/pal_uid.c index 7de1a8eeb5..23faa3f3b4 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_uid.cpp +++ b/external/corefx/src/Native/Unix/System.Native/pal_uid.c @@ -13,20 +13,22 @@ #include #include +#ifndef TARGET_ANDROID + static int32_t ConvertNativePasswdToPalPasswd(int error, struct passwd* nativePwd, struct passwd* result, Passwd* pwd) { // positive error number returned -> failure other than entry-not-found if (error != 0) { assert(error > 0); - *pwd = {}; // managed out param must be initialized + memset(pwd, 0, sizeof(Passwd)); // managed out param must be initialized return error; } // 0 returned with null result -> entry-not-found - if (result == nullptr) + if (result == NULL) { - *pwd = {}; // managed out param must be initialized + memset(pwd, 0, sizeof(Passwd)); // managed out param must be initialized return -1; // shim convention for entry-not-found } @@ -42,10 +44,10 @@ static int32_t ConvertNativePasswdToPalPasswd(int error, struct passwd* nativePw return 0; } -extern "C" int32_t SystemNative_GetPwUidR(uint32_t uid, Passwd* pwd, char* buf, int32_t buflen) +int32_t SystemNative_GetPwUidR(uint32_t uid, Passwd* pwd, char* buf, int32_t buflen) { - assert(pwd != nullptr); - assert(buf != nullptr); + assert(pwd != NULL); + assert(buf != NULL); assert(buflen >= 0); if (buflen < 0) @@ -54,15 +56,15 @@ extern "C" int32_t SystemNative_GetPwUidR(uint32_t uid, Passwd* pwd, char* buf, struct passwd nativePwd; struct passwd* result; int error; - while ((error = getpwuid_r(uid, &nativePwd, buf, UnsignedCast(buflen), &result)) == EINTR); + while ((error = getpwuid_r(uid, &nativePwd, buf, Int32ToSizeT(buflen), &result)) == EINTR); return ConvertNativePasswdToPalPasswd(error, &nativePwd, result, pwd); } -extern "C" int32_t SystemNative_GetPwNamR(const char* name, Passwd* pwd, char* buf, int32_t buflen) +int32_t SystemNative_GetPwNamR(const char* name, Passwd* pwd, char* buf, int32_t buflen) { - assert(pwd != nullptr); - assert(buf != nullptr); + assert(pwd != NULL); + assert(buf != NULL); assert(buflen >= 0); if (buflen < 0) @@ -71,22 +73,23 @@ extern "C" int32_t SystemNative_GetPwNamR(const char* name, Passwd* pwd, char* b struct passwd nativePwd; struct passwd* result; int error; - while ((error = getpwnam_r(name, &nativePwd, buf, UnsignedCast(buflen), &result)) == EINTR); + while ((error = getpwnam_r(name, &nativePwd, buf, Int32ToSizeT(buflen), &result)) == EINTR); return ConvertNativePasswdToPalPasswd(error, &nativePwd, result, pwd); } +#endif -extern "C" uint32_t SystemNative_GetEUid() +uint32_t SystemNative_GetEUid() { return geteuid(); } -extern "C" uint32_t SystemNative_GetEGid() +uint32_t SystemNative_GetEGid() { return getegid(); } -extern "C" int32_t SystemNative_SetEUid(uid_t euid) +int32_t SystemNative_SetEUid(uid_t euid) { return seteuid(euid); } diff --git a/external/corefx/src/Native/Unix/System.Native/pal_uid.h b/external/corefx/src/Native/Unix/System.Native/pal_uid.h index c117a59ed3..9ed6cd6766 100644 --- a/external/corefx/src/Native/Unix/System.Native/pal_uid.h +++ b/external/corefx/src/Native/Unix/System.Native/pal_uid.h @@ -14,7 +14,7 @@ BEGIN_EXTERN_C /** * Passwd struct */ -struct Passwd +typedef struct { char* Name; char* Password; @@ -23,7 +23,7 @@ struct Passwd char* UserInfo; char* HomeDirectory; char* Shell; -}; +} Passwd; /** * Gets a password structure for the given uid. @@ -50,7 +50,7 @@ DLLEXPORT int32_t SystemNative_GetPwNamR(const char* name, Passwd* pwd, char* bu * * Always succeeds. */ -DLLEXPORT uint32_t SystemNative_GetEUid(); +DLLEXPORT uint32_t SystemNative_GetEUid(void); /** * Gets and returns the effective group's identity. @@ -58,7 +58,7 @@ DLLEXPORT uint32_t SystemNative_GetEUid(); * * Always succeeds. */ -DLLEXPORT uint32_t SystemNative_GetEGid(); +DLLEXPORT uint32_t SystemNative_GetEGid(void); /** * Sets the effective user ID of the calling process diff --git a/external/corefx/src/Native/Unix/System.Net.Security.Native/.deps/libmono_native_compat_la-pal_gssapi.Plo b/external/corefx/src/Native/Unix/System.Net.Security.Native/.deps/libmono_native_compat_la-pal_gssapi.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Net.Security.Native/.deps/libmono_native_compat_la-pal_gssapi.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Net.Security.Native/.deps/libmono_native_la-pal_gssapi.Plo b/external/corefx/src/Native/Unix/System.Net.Security.Native/.deps/libmono_native_la-pal_gssapi.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Net.Security.Native/.deps/libmono_native_la-pal_gssapi.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Net.Security.Native/.deps/libmono_native_unified_la-pal_gssapi.Plo b/external/corefx/src/Native/Unix/System.Net.Security.Native/.deps/libmono_native_unified_la-pal_gssapi.Plo new file mode 100644 index 0000000000..9ce06a81ea --- /dev/null +++ b/external/corefx/src/Native/Unix/System.Net.Security.Native/.deps/libmono_native_unified_la-pal_gssapi.Plo @@ -0,0 +1 @@ +# dummy diff --git a/external/corefx/src/Native/Unix/System.Net.Security.Native/CMakeLists.txt b/external/corefx/src/Native/Unix/System.Net.Security.Native/CMakeLists.txt index 2071458067..2342b97931 100644 --- a/external/corefx/src/Native/Unix/System.Net.Security.Native/CMakeLists.txt +++ b/external/corefx/src/Native/Unix/System.Net.Security.Native/CMakeLists.txt @@ -1,7 +1,9 @@ -project(System.Net.Security.Native) +project(System.Net.Security.Native C) set(CMAKE_INCLUDE_CURRENT_DIR ON) +add_compile_options(-Wno-incompatible-pointer-types-discards-qualifiers) + add_definitions(-DPIC=1) if (HAVE_GSSFW_HEADERS) @@ -24,7 +26,7 @@ else() endif() set(NATIVEGSS_SOURCES - pal_gssapi.cpp + pal_gssapi.c ) add_library(System.Net.Security.Native @@ -48,4 +50,4 @@ target_link_libraries(System.Net.Security.Native ) install_library_and_symbols (System.Net.Security.Native) -install (TARGETS System.Net.Security.Native-Static DESTINATION .) +install (TARGETS System.Net.Security.Native-Static DESTINATION .) \ No newline at end of file diff --git a/external/corefx/src/Native/Unix/System.Net.Security.Native/pal_gssapi.cpp b/external/corefx/src/Native/Unix/System.Net.Security.Native/pal_gssapi.c similarity index 51% rename from external/corefx/src/Native/Unix/System.Net.Security.Native/pal_gssapi.cpp rename to external/corefx/src/Native/Unix/System.Net.Security.Native/pal_gssapi.c index b03691b649..a97bce4919 100644 --- a/external/corefx/src/Native/Unix/System.Net.Security.Native/pal_gssapi.cpp +++ b/external/corefx/src/Native/Unix/System.Net.Security.Native/pal_gssapi.c @@ -21,42 +21,42 @@ #include #include -static_assert(PAL_GSS_C_DELEG_FLAG == GSS_C_DELEG_FLAG, ""); -static_assert(PAL_GSS_C_MUTUAL_FLAG == GSS_C_MUTUAL_FLAG, ""); -static_assert(PAL_GSS_C_REPLAY_FLAG == GSS_C_REPLAY_FLAG, ""); -static_assert(PAL_GSS_C_SEQUENCE_FLAG == GSS_C_SEQUENCE_FLAG, ""); -static_assert(PAL_GSS_C_CONF_FLAG == GSS_C_CONF_FLAG, ""); -static_assert(PAL_GSS_C_INTEG_FLAG == GSS_C_INTEG_FLAG, ""); -static_assert(PAL_GSS_C_ANON_FLAG == GSS_C_ANON_FLAG, ""); -static_assert(PAL_GSS_C_PROT_READY_FLAG == GSS_C_PROT_READY_FLAG, ""); -static_assert(PAL_GSS_C_TRANS_FLAG == GSS_C_TRANS_FLAG, ""); -static_assert(PAL_GSS_C_DCE_STYLE == GSS_C_DCE_STYLE, ""); -static_assert(PAL_GSS_C_IDENTIFY_FLAG == GSS_C_IDENTIFY_FLAG, ""); -static_assert(PAL_GSS_C_EXTENDED_ERROR_FLAG == GSS_C_EXTENDED_ERROR_FLAG, ""); -static_assert(PAL_GSS_C_DELEG_POLICY_FLAG == GSS_C_DELEG_POLICY_FLAG, ""); +c_static_assert(PAL_GSS_C_DELEG_FLAG == GSS_C_DELEG_FLAG); +c_static_assert(PAL_GSS_C_MUTUAL_FLAG == GSS_C_MUTUAL_FLAG); +c_static_assert(PAL_GSS_C_REPLAY_FLAG == GSS_C_REPLAY_FLAG); +c_static_assert(PAL_GSS_C_SEQUENCE_FLAG == GSS_C_SEQUENCE_FLAG); +c_static_assert(PAL_GSS_C_CONF_FLAG == GSS_C_CONF_FLAG); +c_static_assert(PAL_GSS_C_INTEG_FLAG == GSS_C_INTEG_FLAG); +c_static_assert(PAL_GSS_C_ANON_FLAG == GSS_C_ANON_FLAG); +c_static_assert(PAL_GSS_C_PROT_READY_FLAG == GSS_C_PROT_READY_FLAG); +c_static_assert(PAL_GSS_C_TRANS_FLAG == GSS_C_TRANS_FLAG); +c_static_assert(PAL_GSS_C_DCE_STYLE == GSS_C_DCE_STYLE); +c_static_assert(PAL_GSS_C_IDENTIFY_FLAG == GSS_C_IDENTIFY_FLAG); +c_static_assert(PAL_GSS_C_EXTENDED_ERROR_FLAG == GSS_C_EXTENDED_ERROR_FLAG); +c_static_assert(PAL_GSS_C_DELEG_POLICY_FLAG == GSS_C_DELEG_POLICY_FLAG); -static_assert(PAL_GSS_COMPLETE == GSS_S_COMPLETE, ""); -static_assert(PAL_GSS_CONTINUE_NEEDED == GSS_S_CONTINUE_NEEDED, ""); +c_static_assert(PAL_GSS_COMPLETE == GSS_S_COMPLETE); +c_static_assert(PAL_GSS_CONTINUE_NEEDED == GSS_S_CONTINUE_NEEDED); #if !HAVE_GSS_SPNEGO_MECHANISM static char gss_spnego_oid_value[] = "\x2b\x06\x01\x05\x05\x02"; // Binary representation of SPNEGO Oid (RFC 4178) static gss_OID_desc gss_mech_spnego_OID_desc = {.length = ARRAY_SIZE(gss_spnego_oid_value) - 1, - .elements = static_cast(gss_spnego_oid_value)}; + .elements = gss_spnego_oid_value}; static char gss_ntlm_oid_value[] = "\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a"; // Binary representation of NTLM OID // (https://msdn.microsoft.com/en-us/library/cc236636.aspx) static gss_OID_desc gss_mech_ntlm_OID_desc = {.length = ARRAY_SIZE(gss_ntlm_oid_value) - 1, - .elements = static_cast(gss_ntlm_oid_value)}; + .elements = gss_ntlm_oid_value}; #endif // transfers ownership of the underlying data from gssBuffer to PAL_GssBuffer -static void NetSecurityNative_MoveBuffer(gss_buffer_t gssBuffer, struct PAL_GssBuffer* targetBuffer) +static void NetSecurityNative_MoveBuffer(gss_buffer_t gssBuffer, PAL_GssBuffer* targetBuffer) { - assert(gssBuffer != nullptr); - assert(targetBuffer != nullptr); + assert(gssBuffer != NULL); + assert(targetBuffer != NULL); - targetBuffer->length = static_cast(gssBuffer->length); - targetBuffer->data = static_cast(gssBuffer->value); + targetBuffer->length = (uint64_t)(gssBuffer->length); + targetBuffer->data = (uint8_t*)(gssBuffer->value); } static uint32_t NetSecurityNative_AcquireCredSpNego(uint32_t* minorStatus, @@ -64,10 +64,10 @@ static uint32_t NetSecurityNative_AcquireCredSpNego(uint32_t* minorStatus, gss_cred_usage_t credUsage, GssCredId** outputCredHandle) { - assert(minorStatus != nullptr); - assert(desiredName != nullptr); - assert(outputCredHandle != nullptr); - assert(*outputCredHandle == nullptr); + assert(minorStatus != NULL); + assert(desiredName != NULL); + assert(outputCredHandle != NULL); + assert(*outputCredHandle == NULL); #if HAVE_GSS_SPNEGO_MECHANISM gss_OID_set_desc gss_mech_spnego_OID_set_desc = {.count = 1, .elements = GSS_SPNEGO_MECHANISM}; @@ -75,7 +75,7 @@ static uint32_t NetSecurityNative_AcquireCredSpNego(uint32_t* minorStatus, gss_OID_set_desc gss_mech_spnego_OID_set_desc = {.count = 1, .elements = &gss_mech_spnego_OID_desc}; #endif uint32_t majorStatus = gss_acquire_cred( - minorStatus, desiredName, 0, &gss_mech_spnego_OID_set_desc, credUsage, outputCredHandle, nullptr, nullptr); + minorStatus, desiredName, 0, &gss_mech_spnego_OID_set_desc, credUsage, outputCredHandle, NULL, NULL); // call gss_set_cred_option with GSS_KRB5_CRED_NO_CI_FLAGS_X to support Kerberos Sign Only option from *nix client against a windows server #if HAVE_GSS_KRB5_CRED_NO_CI_FLAGS_X @@ -89,16 +89,16 @@ static uint32_t NetSecurityNative_AcquireCredSpNego(uint32_t* minorStatus, return majorStatus; } -extern "C" uint32_t +uint32_t NetSecurityNative_InitiateCredSpNego(uint32_t* minorStatus, GssName* desiredName, GssCredId** outputCredHandle) { return NetSecurityNative_AcquireCredSpNego(minorStatus, desiredName, GSS_C_INITIATE, outputCredHandle); } -extern "C" uint32_t NetSecurityNative_DeleteSecContext(uint32_t* minorStatus, GssCtxId** contextHandle) +uint32_t NetSecurityNative_DeleteSecContext(uint32_t* minorStatus, GssCtxId** contextHandle) { - assert(minorStatus != nullptr); - assert(contextHandle != nullptr); + assert(minorStatus != NULL); + assert(contextHandle != NULL); return gss_delete_sec_context(minorStatus, contextHandle, GSS_C_NO_BUFFER); } @@ -106,13 +106,13 @@ extern "C" uint32_t NetSecurityNative_DeleteSecContext(uint32_t* minorStatus, Gs static uint32_t NetSecurityNative_DisplayStatus(uint32_t* minorStatus, uint32_t statusValue, int statusType, - struct PAL_GssBuffer* outBuffer) + PAL_GssBuffer* outBuffer) { - assert(minorStatus != nullptr); - assert(outBuffer != nullptr); + assert(minorStatus != NULL); + assert(outBuffer != NULL); uint32_t messageContext; - GssBuffer gssBuffer{.length = 0, .value = nullptr}; + GssBuffer gssBuffer = {.length = 0, .value = NULL}; uint32_t majorStatus = gss_display_status(minorStatus, statusValue, statusType, GSS_C_NO_OID, &messageContext, &gssBuffer); @@ -120,77 +120,76 @@ static uint32_t NetSecurityNative_DisplayStatus(uint32_t* minorStatus, return majorStatus; } -extern "C" uint32_t -NetSecurityNative_DisplayMinorStatus(uint32_t* minorStatus, uint32_t statusValue, struct PAL_GssBuffer* outBuffer) +uint32_t +NetSecurityNative_DisplayMinorStatus(uint32_t* minorStatus, uint32_t statusValue, PAL_GssBuffer* outBuffer) { return NetSecurityNative_DisplayStatus(minorStatus, statusValue, GSS_C_MECH_CODE, outBuffer); } -extern "C" uint32_t -NetSecurityNative_DisplayMajorStatus(uint32_t* minorStatus, uint32_t statusValue, struct PAL_GssBuffer* outBuffer) +uint32_t +NetSecurityNative_DisplayMajorStatus(uint32_t* minorStatus, uint32_t statusValue, PAL_GssBuffer* outBuffer) { return NetSecurityNative_DisplayStatus(minorStatus, statusValue, GSS_C_GSS_CODE, outBuffer); } -extern "C" uint32_t +uint32_t NetSecurityNative_ImportUserName(uint32_t* minorStatus, char* inputName, uint32_t inputNameLen, GssName** outputName) { - assert(minorStatus != nullptr); - assert(inputName != nullptr); - assert(outputName != nullptr); - assert(*outputName == nullptr); + assert(minorStatus != NULL); + assert(inputName != NULL); + assert(outputName != NULL); + assert(*outputName == NULL); - GssBuffer inputNameBuffer{.length = inputNameLen, .value = inputName}; - gss_OID nameType = const_cast(GSS_C_NT_USER_NAME); - return gss_import_name(minorStatus, &inputNameBuffer, nameType, outputName); + GssBuffer inputNameBuffer = {.length = inputNameLen, .value = inputName}; + return gss_import_name(minorStatus, &inputNameBuffer, GSS_C_NT_USER_NAME, outputName); } -extern "C" uint32_t NetSecurityNative_ImportPrincipalName(uint32_t* minorStatus, - char* inputName, - uint32_t inputNameLen, - GssName** outputName) +uint32_t NetSecurityNative_ImportPrincipalName(uint32_t* minorStatus, + char* inputName, + uint32_t inputNameLen, + GssName** outputName) { - assert(minorStatus != nullptr); - assert(inputName != nullptr); - assert(outputName != nullptr); - assert(*outputName == nullptr); + assert(minorStatus != NULL); + assert(inputName != NULL); + assert(outputName != NULL); + assert(*outputName == NULL); gss_OID nameType; - if (strchr(inputName, '/') != nullptr) + if (strchr(inputName, '/') != NULL) { - nameType = const_cast(GSS_KRB5_NT_PRINCIPAL_NAME); + nameType = GSS_KRB5_NT_PRINCIPAL_NAME; } else { - nameType = const_cast(GSS_C_NT_HOSTBASED_SERVICE); + nameType = GSS_C_NT_HOSTBASED_SERVICE; } - GssBuffer inputNameBuffer{.length = inputNameLen, .value = inputName}; + GssBuffer inputNameBuffer = {.length = inputNameLen, .value = inputName}; return gss_import_name(minorStatus, &inputNameBuffer, nameType, outputName); } -extern "C" uint32_t NetSecurityNative_InitSecContext(uint32_t* minorStatus, - GssCredId* claimantCredHandle, - GssCtxId** contextHandle, - uint32_t isNtlm, - GssName* targetName, - uint32_t reqFlags, - uint8_t* inputBytes, - uint32_t inputLength, - struct PAL_GssBuffer* outBuffer, - uint32_t* retFlags, - int32_t* isNtlmUsed) +uint32_t NetSecurityNative_InitSecContext(uint32_t* minorStatus, + GssCredId* claimantCredHandle, + GssCtxId** contextHandle, + uint32_t isNtlm, + GssName* targetName, + uint32_t reqFlags, + uint8_t* inputBytes, + uint32_t inputLength, + PAL_GssBuffer* outBuffer, + uint32_t* retFlags, + int32_t* isNtlmUsed) { - assert(minorStatus != nullptr); - assert(contextHandle != nullptr); + assert(minorStatus != NULL); + assert(contextHandle != NULL); assert(isNtlm == 0 || isNtlm == 1); - assert(targetName != nullptr); - assert(inputBytes != nullptr || inputLength == 0); - assert(outBuffer != nullptr); - assert(retFlags != nullptr); - assert(isNtlmUsed != nullptr); - assert(inputBytes != nullptr || inputLength == 0); + assert(targetName != NULL); + assert(inputBytes != NULL || inputLength == 0); + assert(outBuffer != NULL); + assert(retFlags != NULL); + assert(isNtlmUsed != NULL); + assert(inputBytes != NULL || inputLength == 0); // Note: claimantCredHandle can be null // Note: *contextHandle is null only in the first call and non-null in the subsequent calls @@ -219,12 +218,12 @@ extern "C" uint32_t NetSecurityNative_InitSecContext(uint32_t* minorStatus, } gss_OID desiredMech = &gss_mech_OID_desc; - gss_OID krbMech = const_cast(gss_mech_krb5); + gss_OID krbMech = gss_mech_krb5; #endif *isNtlmUsed = 1; - GssBuffer inputToken{.length = UnsignedCast(inputLength), .value = inputBytes}; - GssBuffer gssBuffer{.length = 0, .value = nullptr}; + GssBuffer inputToken = {.length = inputLength, .value = inputBytes}; + GssBuffer gssBuffer = {.length = 0, .value = NULL}; gss_OID_desc* outmech; uint32_t majorStatus = gss_init_sec_context(minorStatus, @@ -239,10 +238,10 @@ extern "C" uint32_t NetSecurityNative_InitSecContext(uint32_t* minorStatus, &outmech, &gssBuffer, retFlags, - nullptr); + NULL); // Outmech can be null when gssntlmssp lib uses NTLM mechanism - if (outmech != nullptr && gss_oid_equal(outmech, krbMech) != 0) + if (outmech != NULL && gss_oid_equal(outmech, krbMech) != 0) { *isNtlmUsed = 0; } @@ -251,82 +250,82 @@ extern "C" uint32_t NetSecurityNative_InitSecContext(uint32_t* minorStatus, return majorStatus; } -extern "C" uint32_t NetSecurityNative_AcceptSecContext(uint32_t* minorStatus, - GssCtxId** contextHandle, - uint8_t* inputBytes, - uint32_t inputLength, - struct PAL_GssBuffer* outBuffer) +uint32_t NetSecurityNative_AcceptSecContext(uint32_t* minorStatus, + GssCtxId** contextHandle, + uint8_t* inputBytes, + uint32_t inputLength, + PAL_GssBuffer* outBuffer) { - assert(minorStatus != nullptr); - assert(contextHandle != nullptr); - assert(inputBytes != nullptr || inputLength == 0); - assert(outBuffer != nullptr); + assert(minorStatus != NULL); + assert(contextHandle != NULL); + assert(inputBytes != NULL || inputLength == 0); + assert(outBuffer != NULL); // Note: *contextHandle is null only in the first call and non-null in the subsequent calls - GssBuffer inputToken{.length = UnsignedCast(inputLength), .value = inputBytes}; - GssBuffer gssBuffer{.length = 0, .value = nullptr}; + GssBuffer inputToken = {.length = inputLength, .value = inputBytes}; + GssBuffer gssBuffer = {.length = 0, .value = NULL}; uint32_t majorStatus = gss_accept_sec_context(minorStatus, contextHandle, GSS_C_NO_CREDENTIAL, &inputToken, GSS_C_NO_CHANNEL_BINDINGS, - nullptr, - nullptr, + NULL, + NULL, &gssBuffer, 0, - nullptr, - nullptr); + NULL, + NULL); NetSecurityNative_MoveBuffer(&gssBuffer, outBuffer); return majorStatus; } -extern "C" uint32_t NetSecurityNative_ReleaseCred(uint32_t* minorStatus, GssCredId** credHandle) +uint32_t NetSecurityNative_ReleaseCred(uint32_t* minorStatus, GssCredId** credHandle) { - assert(minorStatus != nullptr); - assert(credHandle != nullptr); + assert(minorStatus != NULL); + assert(credHandle != NULL); return gss_release_cred(minorStatus, credHandle); } -extern "C" void NetSecurityNative_ReleaseGssBuffer(void* buffer, uint64_t length) +void NetSecurityNative_ReleaseGssBuffer(void* buffer, uint64_t length) { - assert(buffer != nullptr); + assert(buffer != NULL); uint32_t minorStatus; - GssBuffer gssBuffer{.length = static_cast(length), .value = buffer}; + GssBuffer gssBuffer = {.length = (size_t)(length), .value = buffer}; gss_release_buffer(&minorStatus, &gssBuffer); } -extern "C" uint32_t NetSecurityNative_ReleaseName(uint32_t* minorStatus, GssName** inputName) +uint32_t NetSecurityNative_ReleaseName(uint32_t* minorStatus, GssName** inputName) { - assert(minorStatus != nullptr); - assert(inputName != nullptr); + assert(minorStatus != NULL); + assert(inputName != NULL); return gss_release_name(minorStatus, inputName); } -extern "C" uint32_t NetSecurityNative_Wrap(uint32_t* minorStatus, - GssCtxId* contextHandle, - int32_t isEncrypt, - uint8_t* inputBytes, - int32_t offset, - int32_t count, - struct PAL_GssBuffer* outBuffer) +uint32_t NetSecurityNative_Wrap(uint32_t* minorStatus, + GssCtxId* contextHandle, + int32_t isEncrypt, + uint8_t* inputBytes, + int32_t offset, + int32_t count, + PAL_GssBuffer* outBuffer) { - assert(minorStatus != nullptr); - assert(contextHandle != nullptr); + assert(minorStatus != NULL); + assert(contextHandle != NULL); assert(isEncrypt == 1 || isEncrypt == 0); - assert(inputBytes != nullptr); + assert(inputBytes != NULL); assert(offset >= 0); assert(count >= 0); - assert(outBuffer != nullptr); + assert(outBuffer != NULL); // count refers to the length of the input message. That is, number of bytes of inputBytes // starting at offset that need to be wrapped. int confState; - GssBuffer inputMessageBuffer{.length = UnsignedCast(count), .value = inputBytes + offset}; + GssBuffer inputMessageBuffer = {.length = (size_t)count, .value = inputBytes + offset}; GssBuffer gssBuffer; uint32_t majorStatus = gss_wrap(minorStatus, contextHandle, isEncrypt, GSS_C_QOP_DEFAULT, &inputMessageBuffer, &confState, &gssBuffer); @@ -335,25 +334,25 @@ extern "C" uint32_t NetSecurityNative_Wrap(uint32_t* minorStatus, return majorStatus; } -extern "C" uint32_t NetSecurityNative_Unwrap(uint32_t* minorStatus, - GssCtxId* contextHandle, - uint8_t* inputBytes, - int32_t offset, - int32_t count, - struct PAL_GssBuffer* outBuffer) +uint32_t NetSecurityNative_Unwrap(uint32_t* minorStatus, + GssCtxId* contextHandle, + uint8_t* inputBytes, + int32_t offset, + int32_t count, + PAL_GssBuffer* outBuffer) { - assert(minorStatus != nullptr); - assert(contextHandle != nullptr); - assert(inputBytes != nullptr); + assert(minorStatus != NULL); + assert(contextHandle != NULL); + assert(inputBytes != NULL); assert(offset >= 0); assert(count >= 0); - assert(outBuffer != nullptr); + assert(outBuffer != NULL); // count refers to the length of the input message. That is, the number of bytes of inputBytes // starting at offset that need to be wrapped. - GssBuffer inputMessageBuffer{.length = UnsignedCast(count), .value = inputBytes + offset}; - GssBuffer gssBuffer{.length = 0, .value = nullptr}; - uint32_t majorStatus = gss_unwrap(minorStatus, contextHandle, &inputMessageBuffer, &gssBuffer, nullptr, nullptr); + GssBuffer inputMessageBuffer = {.length = (size_t)count, .value = inputBytes + offset}; + GssBuffer gssBuffer = {.length = 0, .value = NULL}; + uint32_t majorStatus = gss_unwrap(minorStatus, contextHandle, &inputMessageBuffer, &gssBuffer, NULL, NULL); NetSecurityNative_MoveBuffer(&gssBuffer, outBuffer); return majorStatus; } @@ -366,12 +365,12 @@ static uint32_t NetSecurityNative_AcquireCredWithPassword(uint32_t* minorStatus, gss_cred_usage_t credUsage, GssCredId** outputCredHandle) { - assert(minorStatus != nullptr); + assert(minorStatus != NULL); assert(isNtlm == 1 || isNtlm == 0); - assert(desiredName != nullptr); - assert(password != nullptr); - assert(outputCredHandle != nullptr); - assert(*outputCredHandle == nullptr); + assert(desiredName != NULL); + assert(password != NULL); + assert(outputCredHandle != NULL); + assert(*outputCredHandle == NULL); #if HAVE_GSS_SPNEGO_MECHANISM (void)isNtlm; // unused @@ -392,9 +391,9 @@ static uint32_t NetSecurityNative_AcquireCredWithPassword(uint32_t* minorStatus, gss_OID_set desiredMech = &gss_mech_OID_set_desc; #endif - GssBuffer passwordBuffer{.length = passwdLen, .value = password}; + GssBuffer passwordBuffer = {.length = passwdLen, .value = password}; uint32_t majorStatus = gss_acquire_cred_with_password( - minorStatus, desiredName, &passwordBuffer, 0, desiredMech, credUsage, outputCredHandle, nullptr, nullptr); + minorStatus, desiredName, &passwordBuffer, 0, desiredMech, credUsage, outputCredHandle, NULL, NULL); // call gss_set_cred_option with GSS_KRB5_CRED_NO_CI_FLAGS_X to support Kerberos Sign Only option from *nix client against a windows server #if HAVE_GSS_KRB5_CRED_NO_CI_FLAGS_X @@ -408,13 +407,13 @@ static uint32_t NetSecurityNative_AcquireCredWithPassword(uint32_t* minorStatus, return majorStatus; } -extern "C" uint32_t NetSecurityNative_InitiateCredWithPassword(uint32_t* minorStatus, - int32_t isNtlm, - GssName* desiredName, - char* password, - uint32_t passwdLen, - GssCredId** outputCredHandle) +uint32_t NetSecurityNative_InitiateCredWithPassword(uint32_t* minorStatus, + int32_t isNtlm, + GssName* desiredName, + char* password, + uint32_t passwdLen, + GssCredId** outputCredHandle) { return NetSecurityNative_AcquireCredWithPassword( minorStatus, isNtlm, desiredName, password, passwdLen, GSS_C_INITIATE, outputCredHandle); -} +} \ No newline at end of file diff --git a/external/corefx/src/Native/Unix/System.Net.Security.Native/pal_gssapi.h b/external/corefx/src/Native/Unix/System.Net.Security.Native/pal_gssapi.h index 78ddc84dab..91071cf56e 100644 --- a/external/corefx/src/Native/Unix/System.Net.Security.Native/pal_gssapi.h +++ b/external/corefx/src/Native/Unix/System.Net.Security.Native/pal_gssapi.h @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. #pragma once +#include "pal_compiler.h" #if HAVE_GSSFW_HEADERS || HAVE_HEIMDAL_HEADERS typedef struct gss_name_t_desc_struct GssName; @@ -16,13 +17,13 @@ typedef struct gss_cred_id_struct GssCredId; typedef struct gss_buffer_desc_struct GssBuffer; #endif -enum PAL_GssStatus : uint32_t +typedef enum { PAL_GSS_COMPLETE = 0, PAL_GSS_CONTINUE_NEEDED = 1 -}; +} PAL_GssStatus; -enum PAL_GssFlags : uint32_t +typedef enum { PAL_GSS_C_DELEG_FLAG = 0x1, PAL_GSS_C_MUTUAL_FLAG = 0x2, @@ -37,7 +38,7 @@ enum PAL_GssFlags : uint32_t PAL_GSS_C_IDENTIFY_FLAG = 0x2000, PAL_GSS_C_EXTENDED_ERROR_FLAG = 0x4000, PAL_GSS_C_DELEG_POLICY_FLAG = 0x8000 -}; +} PAL_GssFlags; /* Issue: #7342 @@ -45,117 +46,117 @@ Disable padded warning which occurs in case of 32-bit builds */ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" -struct PAL_GssBuffer +typedef struct { uint64_t length; uint8_t* data; -}; +} PAL_GssBuffer; #pragma clang diagnostic pop /* Shims the gss_release_buffer method. */ -extern "C" void NetSecurityNative_ReleaseGssBuffer(void* buffer, uint64_t length); +DLLEXPORT void NetSecurityNative_ReleaseGssBuffer(void* buffer, uint64_t length); /* Shims the gss_display_status method for minor status (status_type = GSS_C_MECH_CODE). */ -extern "C" uint32_t -NetSecurityNative_DisplayMinorStatus(uint32_t* minorStatus, uint32_t statusValue, struct PAL_GssBuffer* outBuffer); +DLLEXPORT uint32_t +NetSecurityNative_DisplayMinorStatus(uint32_t* minorStatus, uint32_t statusValue, PAL_GssBuffer* outBuffer); /* Shims the gss_display_status method for major status (status_type = GSS_C_GSS_CODE). */ -extern "C" uint32_t -NetSecurityNative_DisplayMajorStatus(uint32_t* minorStatus, uint32_t statusValue, struct PAL_GssBuffer* outBuffer); +DLLEXPORT uint32_t +NetSecurityNative_DisplayMajorStatus(uint32_t* minorStatus, uint32_t statusValue, PAL_GssBuffer* outBuffer); /* Shims the gss_import_name method with nametype = GSS_C_NT_USER_NAME. */ -extern "C" uint32_t +DLLEXPORT uint32_t NetSecurityNative_ImportUserName(uint32_t* minorStatus, char* inputName, uint32_t inputNameLen, GssName** outputName); /* Shims the gss_import_name method with nametype = GSS_C_NT_USER_NAME. */ -extern "C" uint32_t NetSecurityNative_ImportPrincipalName(uint32_t* minorStatus, - char* inputName, - uint32_t inputNameLen, - GssName** outputName); +DLLEXPORT uint32_t NetSecurityNative_ImportPrincipalName(uint32_t* minorStatus, + char* inputName, + uint32_t inputNameLen, + GssName** outputName); /* Shims the gss_release_name method. */ -extern "C" uint32_t NetSecurityNative_ReleaseName(uint32_t* minorStatus, GssName** inputName); +DLLEXPORT uint32_t NetSecurityNative_ReleaseName(uint32_t* minorStatus, GssName** inputName); /* Shims the gss_acquire_cred method with SPNEGO oids with GSS_C_INITIATE. */ -extern "C" uint32_t +DLLEXPORT uint32_t NetSecurityNative_InitiateCredSpNego(uint32_t* minorStatus, GssName* desiredName, GssCredId** outputCredHandle); /* Shims the gss_release_cred method. */ -extern "C" uint32_t NetSecurityNative_ReleaseCred(uint32_t* minorStatus, GssCredId** credHandle); +DLLEXPORT uint32_t NetSecurityNative_ReleaseCred(uint32_t* minorStatus, GssCredId** credHandle); /* Shims the gss_init_sec_context method with SPNEGO oids. */ -extern "C" uint32_t NetSecurityNative_InitSecContext(uint32_t* minorStatus, - GssCredId* claimantCredHandle, - GssCtxId** contextHandle, - uint32_t isNtlm, - GssName* targetName, - uint32_t reqFlags, - uint8_t* inputBytes, - uint32_t inputLength, - struct PAL_GssBuffer* outBuffer, - uint32_t* retFlags, - int32_t* isNtlmUsed); +DLLEXPORT uint32_t NetSecurityNative_InitSecContext(uint32_t* minorStatus, + GssCredId* claimantCredHandle, + GssCtxId** contextHandle, + uint32_t isNtlm, + GssName* targetName, + uint32_t reqFlags, + uint8_t* inputBytes, + uint32_t inputLength, + PAL_GssBuffer* outBuffer, + uint32_t* retFlags, + int32_t* isNtlmUsed); /* Shims the gss_accept_sec_context method. */ -extern "C" uint32_t NetSecurityNative_AcceptSecContext(uint32_t* minorStatus, - GssCtxId** contextHandle, - uint8_t* inputBytes, - uint32_t inputLength, - struct PAL_GssBuffer* outBuffer); +DLLEXPORT uint32_t NetSecurityNative_AcceptSecContext(uint32_t* minorStatus, + GssCtxId** contextHandle, + uint8_t* inputBytes, + uint32_t inputLength, + PAL_GssBuffer* outBuffer); /* Shims the gss_delete_sec_context method. */ -extern "C" uint32_t NetSecurityNative_DeleteSecContext(uint32_t* minorStatus, GssCtxId** contextHandle); +DLLEXPORT uint32_t NetSecurityNative_DeleteSecContext(uint32_t* minorStatus, GssCtxId** contextHandle); /* Shims the gss_wrap method. */ -extern "C" uint32_t NetSecurityNative_Wrap(uint32_t* minorStatus, - GssCtxId* contextHandle, - int32_t isEncrypt, - uint8_t* inputBytes, - int32_t offset, - int32_t count, - struct PAL_GssBuffer* outBuffer); +DLLEXPORT uint32_t NetSecurityNative_Wrap(uint32_t* minorStatus, + GssCtxId* contextHandle, + int32_t isEncrypt, + uint8_t* inputBytes, + int32_t offset, + int32_t count, + PAL_GssBuffer* outBuffer); /* Shims the gss_unwrap method. */ -extern "C" uint32_t NetSecurityNative_Unwrap(uint32_t* minorStatus, - GssCtxId* contextHandle, - uint8_t* inputBytes, - int32_t offset, - int32_t count, - struct PAL_GssBuffer* outBuffer); +DLLEXPORT uint32_t NetSecurityNative_Unwrap(uint32_t* minorStatus, + GssCtxId* contextHandle, + uint8_t* inputBytes, + int32_t offset, + int32_t count, + PAL_GssBuffer* outBuffer); /* Shims the gss_acquire_cred_with_password method with GSS_C_INITIATE. */ -extern "C" uint32_t NetSecurityNative_InitiateCredWithPassword(uint32_t* minorStatus, - int32_t isNtlm, - GssName* desiredName, - char* password, - uint32_t passwdLen, - GssCredId** outputCredHandle); +DLLEXPORT uint32_t NetSecurityNative_InitiateCredWithPassword(uint32_t* minorStatus, + int32_t isNtlm, + GssName* desiredName, + char* password, + uint32_t passwdLen, + GssCredId** outputCredHandle); \ No newline at end of file diff --git a/external/corefx/src/System.Collections/src/System/Collections/Generic/Queue.cs b/external/corefx/src/System.Collections/src/System/Collections/Generic/Queue.cs index 24735d8e53..69652d31e5 100644 --- a/external/corefx/src/System.Collections/src/System/Collections/Generic/Queue.cs +++ b/external/corefx/src/System.Collections/src/System/Collections/Generic/Queue.cs @@ -21,7 +21,9 @@ namespace System.Collections.Generic [DebuggerTypeProxy(typeof(QueueDebugView<>))] [DebuggerDisplay("Count = {Count}")] [Serializable] -#if !MONO +#if MONO + [System.Runtime.CompilerServices.TypeForwardedFrom(Consts.AssemblySystem)] +#else [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] #endif public class Queue : IEnumerable, diff --git a/external/corefx/src/System.Collections/src/System/Collections/Generic/Stack.cs b/external/corefx/src/System.Collections/src/System/Collections/Generic/Stack.cs index 48b33a18e8..294eefe2e2 100644 --- a/external/corefx/src/System.Collections/src/System/Collections/Generic/Stack.cs +++ b/external/corefx/src/System.Collections/src/System/Collections/Generic/Stack.cs @@ -22,7 +22,9 @@ namespace System.Collections.Generic [DebuggerTypeProxy(typeof(StackDebugView<>))] [DebuggerDisplay("Count = {Count}")] [Serializable] -#if !MONO +#if MONO + [System.Runtime.CompilerServices.TypeForwardedFrom(Consts.AssemblySystem)] +#else [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] #endif public class Stack : IEnumerable, diff --git a/external/corefx/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Linux.cs b/external/corefx/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Linux.cs index 1460de92e2..3b3e7dcace 100644 --- a/external/corefx/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Linux.cs +++ b/external/corefx/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Linux.cs @@ -9,7 +9,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; -#if MONO +#if MONO && !MOBILE using System; using System.IO; diff --git a/external/corefx/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs b/external/corefx/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs index 87c6181857..9f7e512425 100644 --- a/external/corefx/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs +++ b/external/corefx/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs @@ -16,7 +16,7 @@ using FSEventStreamEventId = System.UInt64; using CFRunLoopRef = System.IntPtr; using Microsoft.Win32.SafeHandles; -#if MONO +#if MONO && !MOBILE using System; using System.IO; diff --git a/external/corefx/src/System.IO.UnmanagedMemoryStream/tests/UmsFlush.cs b/external/corefx/src/System.IO.UnmanagedMemoryStream/tests/UmsFlush.cs index 691bd8fa8e..2d636ba967 100644 --- a/external/corefx/src/System.IO.UnmanagedMemoryStream/tests/UmsFlush.cs +++ b/external/corefx/src/System.IO.UnmanagedMemoryStream/tests/UmsFlush.cs @@ -8,7 +8,7 @@ using Xunit; namespace System.IO.Tests { - public class FlushTests + public class UnmanagedMemoryStreamFlushTests { [Fact] public static void Flush() diff --git a/external/corefx/src/System.IO/tests/BinaryWriter/BinaryWriter.WriteByteCharTests.cs b/external/corefx/src/System.IO/tests/BinaryWriter/BinaryWriter.WriteByteCharTests.cs index f003820acd..cc2f55f411 100644 --- a/external/corefx/src/System.IO/tests/BinaryWriter/BinaryWriter.WriteByteCharTests.cs +++ b/external/corefx/src/System.IO/tests/BinaryWriter/BinaryWriter.WriteByteCharTests.cs @@ -100,6 +100,8 @@ namespace System.IO.Tests mem.Dispose(); } + +#if !MONO // Avoid CodePagesEncodingProvider dependency in CoreFX test assembly /// /// Cases Tested: /// Writing bytes casted to chars and using a different encoding; iso-2022-jp. @@ -139,6 +141,7 @@ namespace System.IO.Tests writer.Dispose(); reader.Dispose(); } +#endif /// /// Testing that bytes can be written to a stream with BinaryWriter. diff --git a/external/corefx/src/System.IO/tests/MemoryStream/MemoryStream.ConstructorTests.cs b/external/corefx/src/System.IO/tests/MemoryStream/MemoryStream.ConstructorTests.cs index ed4ce70112..62dabe2673 100644 --- a/external/corefx/src/System.IO/tests/MemoryStream/MemoryStream.ConstructorTests.cs +++ b/external/corefx/src/System.IO/tests/MemoryStream/MemoryStream.ConstructorTests.cs @@ -35,7 +35,9 @@ namespace System.IO.Tests { Assert.Throws(() => new MemoryStream(int.MinValue)); Assert.Throws(() => new MemoryStream(-1)); +#if !MONO Assert.Throws(() => new MemoryStream(int.MaxValue)); +#endif } } } diff --git a/external/corefx/src/System.IO/tests/MemoryStream/MemoryStreamTests.netcoreapp.cs b/external/corefx/src/System.IO/tests/MemoryStream/MemoryStreamTests.netcoreapp.cs index 4ea914b071..650a72e52d 100644 --- a/external/corefx/src/System.IO/tests/MemoryStream/MemoryStreamTests.netcoreapp.cs +++ b/external/corefx/src/System.IO/tests/MemoryStream/MemoryStreamTests.netcoreapp.cs @@ -63,6 +63,7 @@ namespace System.IO.Tests } [Fact] + [SkipOnTargetFramework(TargetFrameworkMonikers.Mono)] // Requires base Stream span API public void DerivedMemoryStream_ReadWriteSpanCalled_ReadWriteArrayUsed() { var s = new ReadWriteOverridingMemoryStream(); diff --git a/external/corefx/src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs b/external/corefx/src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs index 814efe7897..98fa41db87 100644 --- a/external/corefx/src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs +++ b/external/corefx/src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs @@ -209,6 +209,73 @@ namespace System.Linq.Expressions.Interpreter } } +#if FEATURE_MAKE_RUN_METHODS + [PreserveDependency("MakeRunVoid15`15")] + [PreserveDependency("MakeRun0`1")] + [PreserveDependency("MakeRun1`2")] + [PreserveDependency("MakeRun2`3")] + [PreserveDependency("MakeRun3`4")] + [PreserveDependency("MakeRun4`5")] + [PreserveDependency("MakeRun5`6")] + [PreserveDependency("MakeRun6`7")] + [PreserveDependency("MakeRun7`8")] + [PreserveDependency("MakeRun8`9")] + [PreserveDependency("MakeRun9`10")] + [PreserveDependency("MakeRun10`11")] + [PreserveDependency("MakeRun11`12")] + [PreserveDependency("MakeRun12`13")] + [PreserveDependency("MakeRun13`14")] + [PreserveDependency("MakeRun14`15")] + [PreserveDependency("MakeRun15`16")] + [PreserveDependency("MakeRunVoid0")] + [PreserveDependency("MakeRunVoid1`1")] + [PreserveDependency("MakeRunVoid2`2")] + [PreserveDependency("MakeRunVoid3`3")] + [PreserveDependency("MakeRunVoid4`4")] + [PreserveDependency("MakeRunVoid5`5")] + [PreserveDependency("MakeRunVoid6`6")] + [PreserveDependency("MakeRunVoid7`7")] + [PreserveDependency("MakeRunVoid8`8")] + [PreserveDependency("MakeRunVoid9`9")] + [PreserveDependency("MakeRunVoid10`10")] + [PreserveDependency("MakeRunVoid11`11")] + [PreserveDependency("MakeRunVoid12`12")] + [PreserveDependency("MakeRunVoid13`13")] + [PreserveDependency("MakeRunVoid14`14")] +#endif + [PreserveDependency("Run0`1")] + [PreserveDependency("Run1`2")] + [PreserveDependency("Run2`3")] + [PreserveDependency("Run3`4")] + [PreserveDependency("Run4`5")] + [PreserveDependency("Run5`6")] + [PreserveDependency("Run6`7")] + [PreserveDependency("Run7`8")] + [PreserveDependency("Run8`9")] + [PreserveDependency("Run9`10")] + [PreserveDependency("Run10`11")] + [PreserveDependency("Run11`12")] + [PreserveDependency("Run12`13")] + [PreserveDependency("Run13`14")] + [PreserveDependency("Run14`15")] + [PreserveDependency("Run15`16")] + [PreserveDependency("RunVoid0")] + [PreserveDependency("RunVoid1`1")] + [PreserveDependency("RunVoid2`2")] + [PreserveDependency("RunVoid3`3")] + [PreserveDependency("RunVoid4`4")] + [PreserveDependency("RunVoid5`5")] + [PreserveDependency("RunVoid6`6")] + [PreserveDependency("RunVoid7`7")] + [PreserveDependency("RunVoid8`8")] + [PreserveDependency("RunVoid9`9")] + [PreserveDependency("RunVoid10`10")] + [PreserveDependency("RunVoid11`11")] + [PreserveDependency("RunVoid12`12")] + [PreserveDependency("RunVoid13`13")] + [PreserveDependency("RunVoid14`14")] + [PreserveDependency("RunVoid15`15")] + [PreserveDependency("RunVoidRef2`2")] private static Func MakeRunDelegateCtor(Type delegateType) { MethodInfo method = delegateType.GetInvokeMethod(); diff --git a/external/corefx/src/System.Memory/tests/ParsersAndFormatters/Formatter/FormatterTests.cs b/external/corefx/src/System.Memory/tests/ParsersAndFormatters/Formatter/FormatterTests.cs index 49b75f58cc..a94e183230 100644 --- a/external/corefx/src/System.Memory/tests/ParsersAndFormatters/Formatter/FormatterTests.cs +++ b/external/corefx/src/System.Memory/tests/ParsersAndFormatters/Formatter/FormatterTests.cs @@ -73,7 +73,6 @@ namespace System.Buffers.Text.Tests [Theory] [MemberData(nameof(TestData.DecimalFormatterTheoryData), MemberType = typeof(TestData))] - [SkipOnTargetFramework(TargetFrameworkMonikers.Mono)] public static void TestFormatterDecimal(FormatterTestData testData) { ValidateFormatter(testData); diff --git a/external/corefx/src/System.Memory/tests/ParsersAndFormatters/TestData.cs b/external/corefx/src/System.Memory/tests/ParsersAndFormatters/TestData.cs index 2f0a571410..4e95b808fe 100644 --- a/external/corefx/src/System.Memory/tests/ParsersAndFormatters/TestData.cs +++ b/external/corefx/src/System.Memory/tests/ParsersAndFormatters/TestData.cs @@ -220,7 +220,6 @@ namespace System.Buffers.Text.Tests { get { -#if !MONO foreach (long l in Int64TestData) { yield return l; @@ -246,10 +245,6 @@ namespace System.Buffers.Text.Tests yield return 0.00m; yield return -1.00m; yield return -0.00m; -#else - // See https://github.com/mono/mono/issues/8710 for details. - yield break; -#endif } } diff --git a/external/corefx/src/System.Memory/tests/ReadOnlySpan/CompareTo.cs b/external/corefx/src/System.Memory/tests/ReadOnlySpan/CompareTo.cs index 823c10697a..6c3d38b151 100644 --- a/external/corefx/src/System.Memory/tests/ReadOnlySpan/CompareTo.cs +++ b/external/corefx/src/System.Memory/tests/ReadOnlySpan/CompareTo.cs @@ -239,8 +239,8 @@ namespace System.SpanTests [InlineData("aaaaaaaaaaaaaa", 1, "aaaxaaaaaaaaaa", 3, 100, StringComparison.Ordinal, -1)] // Different long alignment, abs of 4, one of them is 2, different at n=1 [InlineData("-aaaaaaaaaaaaa", 1, "++++aaaaaaaaaa", 4, 10, StringComparison.Ordinal, 0)] // Different long alignment, equal compare [InlineData("aaaaaaaaaaaaaa", 1, "aaaaaaaaaaaaax", 4, 100, StringComparison.Ordinal, -1)] // Different long alignment -// [InlineData("\0", 0, "", 0, 1, StringComparison.Ordinal, 1)] // Same memory layout, except for m_stringLength (m_firstChars are both 0) -// [InlineData("\0\0", 0, "", 0, 2, StringComparison.Ordinal, 1)] // Same as above, except m_stringLength for one is 2 + [InlineData("\0", 0, "", 0, 1, StringComparison.Ordinal, 1)] // Same memory layout, except for m_stringLength (m_firstChars are both 0) + [InlineData("\0\0", 0, "", 0, 2, StringComparison.Ordinal, 1)] // Same as above, except m_stringLength for one is 2 [InlineData("", 0, "\0b", 0, 2, StringComparison.Ordinal, -1)] // strA's second char != strB's second char codepath [InlineData("", 0, "b", 0, 1, StringComparison.Ordinal, -1)] // Should hit strA.m_firstChar != strB.m_firstChar codepath [InlineData("abcxxxxxxxxxxxxxxxxxxxxxx", 0, "abdxxxxxxxxxxxxxxx", 0, int.MaxValue, StringComparison.Ordinal, -1)] // 64-bit: first long compare is different diff --git a/external/corefx/src/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.Unix.cs b/external/corefx/src/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.Unix.cs index eaec8cd2a2..0fd3087b60 100644 --- a/external/corefx/src/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.Unix.cs +++ b/external/corefx/src/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.Unix.cs @@ -8,10 +8,7 @@ using System.Text; namespace System.Net.Sockets { /// Represents a Unix Domain Socket endpoint as a path. -#if !MONO - public -#endif - sealed partial class UnixDomainSocketEndPoint : EndPoint + public sealed partial class UnixDomainSocketEndPoint : EndPoint { private static readonly int s_nativePathOffset; private static readonly int s_nativePathLength; diff --git a/external/corefx/src/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.cs b/external/corefx/src/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.cs index 8d6dbf65de..534df754d3 100644 --- a/external/corefx/src/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.cs +++ b/external/corefx/src/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.cs @@ -8,10 +8,7 @@ using System.Text; namespace System.Net.Sockets { /// Represents a Unix Domain Socket endpoint as a path. -#if !MONO - public -#endif - sealed partial class UnixDomainSocketEndPoint : EndPoint + public sealed partial class UnixDomainSocketEndPoint : EndPoint { private const AddressFamily EndPointAddressFamily = AddressFamily.Unix; diff --git a/external/corefx/src/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs b/external/corefx/src/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs index f8337e90b9..16f8c06018 100644 --- a/external/corefx/src/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs +++ b/external/corefx/src/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs @@ -2,25 +2,39 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections; using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; using Xunit; namespace System.Reflection.Tests { public class RuntimeReflectionExtensionsTests { + [Fact] + public void GetRuntimeEvents() + { + AssertExtensions.Throws("type", () => default(Type).GetRuntimeEvents()); + + List events = typeof(TestType).GetRuntimeEvents().ToList(); + Assert.Equal(1, events.Count); + Assert.Equal("StuffHappened", events[0].Name); + } + [Fact] public void GetRuntimeMethods() { var types = GetTypes(); - Assert.Throws(() => + AssertExtensions.Throws("type", () => { - RuntimeReflectionExtensions.GetRuntimeMethods(null); + RuntimeReflectionExtensions.GetRuntimeMethods(default(Type)); }); - List methods = new List(); + List methods = new List(); foreach (TypeInfo type in types) { @@ -28,10 +42,10 @@ namespace System.Reflection.Tests continue; methods.Clear(); - methods.AddRange((IEnumerable)type.GetDeclaredField("DeclaredMethodNames").GetValue(null)); - methods.AddRange((IEnumerable)type.GetDeclaredField("InheritedMethodNames").GetValue(null)); + methods.AddRange((IEnumerable)type.GetDeclaredField("DeclaredMethodNames").GetValue(null)); + methods.AddRange((IEnumerable)type.GetDeclaredField("InheritedMethodNames").GetValue(null)); if (type.GetDeclaredField("NewMethodNames") != null) - methods.AddRange((IEnumerable)type.GetDeclaredField("NewMethodNames").GetValue(null)); + methods.AddRange((IEnumerable)type.GetDeclaredField("NewMethodNames").GetValue(null)); //inherited from object methods.Add("System.String ToString()"); @@ -52,12 +66,12 @@ namespace System.Reflection.Tests { var types = GetTypes(); - Assert.Throws(() => + AssertExtensions.Throws("type", () => { - RuntimeReflectionExtensions.GetRuntimeFields(null); + RuntimeReflectionExtensions.GetRuntimeFields(default(Type)); }); - List fields = new List(); + List fields = new List(); foreach (TypeInfo type in types) { @@ -65,35 +79,49 @@ namespace System.Reflection.Tests continue; fields.Clear(); - fields.AddRange((IEnumerable)type.GetDeclaredField("DeclaredFieldNames").GetValue(null)); - fields.AddRange((IEnumerable)type.GetDeclaredField("InheritedFieldNames").GetValue(null)); + fields.AddRange((IEnumerable)type.GetDeclaredField("DeclaredFieldNames").GetValue(null)); + fields.AddRange((IEnumerable)type.GetDeclaredField("InheritedFieldNames").GetValue(null)); if (type.GetDeclaredField("NewFieldNames") != null) - fields.AddRange((IEnumerable)type.GetDeclaredField("NewFieldNames").GetValue(null)); + fields.AddRange((IEnumerable)type.GetDeclaredField("NewFieldNames").GetValue(null)); Assert.All(type.AsType().GetRuntimeFields(), f => Assert.True(fields.Remove(f.Name))); Assert.Empty(fields); } } + [Fact] + public void GetRuntimeProperties() + { + AssertExtensions.Throws("type", () => default(Type).GetRuntimeProperties()); + + List properties = typeof(TestType).GetRuntimeProperties().ToList(); + List propertyNames = properties.Select(p => p.Name).Distinct().ToList(); + Assert.Equal(5, properties.Count); + Assert.Contains("Length", propertyNames); + Assert.Contains("Position", propertyNames); + Assert.Contains("CanRead", propertyNames); + Assert.Contains("CanWrite", propertyNames); + Assert.Contains("CanSeek", propertyNames); + } + [Fact] public void GetRuntimeProperty() { var types = GetTypes(); - Assert.Throws(() => + AssertExtensions.Throws("type", () => { - RuntimeReflectionExtensions.GetRuntimeProperty(null, "foo"); + RuntimeReflectionExtensions.GetRuntimeProperty(default(Type), "foo"); }); - - - Assert.Throws(() => + AssertExtensions.Throws("name", () => { typeof(RuntimeReflectionExtensionsTests).GetRuntimeProperty(null); }); + Assert.Null(typeof(TestType).GetRuntimeProperty("")); - List properties = new List(); + List properties = new List(); foreach (TypeInfo type in types) { @@ -101,11 +129,11 @@ namespace System.Reflection.Tests continue; properties.Clear(); - properties.AddRange((IEnumerable)type.GetDeclaredField("PublicPropertyNames").GetValue(null)); + properties.AddRange((IEnumerable)type.GetDeclaredField("PublicPropertyNames").GetValue(null)); - foreach (String propertyName in properties) + foreach (string propertyName in properties) { - Boolean exceptionExpected = propertyName.Equals("Item"); + bool exceptionExpected = propertyName.Equals("Item"); // Slight duplication of code her to allow use of Assert.Throws if (exceptionExpected == true) @@ -122,6 +150,8 @@ namespace System.Reflection.Tests } } } + + Assert.Equal(typeof(TestType).GetProperty("Length"), typeof(TestType).GetRuntimeProperty("Length")); } [Fact] @@ -129,18 +159,20 @@ namespace System.Reflection.Tests { var types = GetTypes(); - Assert.Throws(() => + AssertExtensions.Throws("type", () => { - RuntimeReflectionExtensions.GetRuntimeEvent(null, "foo"); + RuntimeReflectionExtensions.GetRuntimeEvent(default(Type), "foo"); }); - Assert.Throws(() => + Assert.Throws(null, () => { typeof(RuntimeReflectionExtensionsTests).GetRuntimeEvent(null); }); - List events = new List(); + Assert.Null(typeof(TestType).GetRuntimeEvent("")); + + List events = new List(); foreach (TypeInfo type in types) { @@ -151,13 +183,15 @@ namespace System.Reflection.Tests continue; events.Clear(); - events.AddRange((IEnumerable)type.GetDeclaredField("PublicEvents").GetValue(null)); + events.AddRange((IEnumerable)type.GetDeclaredField("PublicEvents").GetValue(null)); - foreach (String eventName in events) + foreach (string eventName in events) { Assert.NotNull(type.AsType().GetRuntimeEvent(eventName)); } } + + Assert.Equal(typeof(TestType).GetEvent("StuffHappened"), typeof(TestType).GetRuntimeEvent("StuffHappened")); } [Fact] @@ -165,24 +199,26 @@ namespace System.Reflection.Tests { var types = GetTypes(); - Assert.Throws(() => + AssertExtensions.Throws("type", () => { - RuntimeReflectionExtensions.GetRuntimeMethod(null, "foo", new Type[0]); + RuntimeReflectionExtensions.GetRuntimeMethod(default(Type), "foo", Type.EmptyTypes); }); - Assert.Throws(() => + AssertExtensions.Throws("name", () => { - typeof(RuntimeReflectionExtensionsTests).GetRuntimeMethod(null, new Type[0]); + typeof(RuntimeReflectionExtensionsTests).GetRuntimeMethod(null, Type.EmptyTypes); }); - Assert.Throws(() => + AssertExtensions.Throws("types", () => { typeof(RuntimeReflectionExtensionsTests).GetRuntimeMethod("RunTest_GetRuntimeMethod", null); }); - List methods = new List(); + Assert.Null(typeof(TestType).GetRuntimeMethod("", Type.EmptyTypes)); + + List methods = new List(); foreach (TypeInfo type in types) { @@ -190,15 +226,17 @@ namespace System.Reflection.Tests continue; methods.Clear(); - methods.AddRange((IEnumerable)type.GetDeclaredField("PublicMethodNames").GetValue(null)); + methods.AddRange((IEnumerable)type.GetDeclaredField("PublicMethodNames").GetValue(null)); - foreach (String method in methods) + foreach (string method in methods) { - String methodName = GetMethodName(method); + string methodName = GetMethodName(method); Type[] parameters = GetMethodParameters(method); Assert.NotNull(type.AsType().GetRuntimeMethod(methodName, parameters)); } } + + Assert.Equal(typeof(TestType).GetMethod("Flush"), typeof(TestType).GetRuntimeMethod("Flush", Array.Empty())); } [Fact] @@ -206,18 +244,20 @@ namespace System.Reflection.Tests { var types = GetTypes(); - Assert.Throws(() => + AssertExtensions.Throws("type", () => { - RuntimeReflectionExtensions.GetRuntimeField(null, "foo"); + RuntimeReflectionExtensions.GetRuntimeField(default(Type), "foo"); }); - Assert.Throws(() => + Assert.Throws(null, () => { typeof(RuntimeReflectionExtensionsTests).GetRuntimeField(null); }); - List fields = new List(); + Assert.Null(typeof(TestType).GetRuntimeField("")); + + List fields = new List(); foreach (TypeInfo type in types) { @@ -225,37 +265,79 @@ namespace System.Reflection.Tests continue; fields.Clear(); - fields.AddRange((IEnumerable)type.GetDeclaredField("PublicFieldNames").GetValue(null)); + fields.AddRange((IEnumerable)type.GetDeclaredField("PublicFieldNames").GetValue(null)); - foreach (String fieldName in fields) + foreach (string fieldName in fields) { Assert.NotNull(type.AsType().GetRuntimeField(fieldName)); } } + + Assert.Equal(typeof(TestType).GetField("_pizzaSize"), typeof(TestType).GetRuntimeField("_pizzaSize")); } - private static String GetMethodName(String methodName) + [Fact] + public void GetMethodInfo() + { + AssertExtensions.Throws("del", () => default(Action).GetMethodInfo()); + Assert.Equal(typeof(RuntimeReflectionExtensionsTests).GetMethod("GetMethodInfo"), ((Action)GetMethodInfo).GetMethodInfo()); + } + + [Fact] + public void GetRuntimeBaseDefinition() + { + Assert.Throws(() => default(MethodInfo).GetRuntimeBaseDefinition()); + + MethodInfo derivedFoo = typeof(TestDerived).GetMethod(nameof(TestDerived.Foo)); + MethodInfo baseFoo = typeof(TestBase).GetMethod(nameof(TestBase.Foo)); + MethodInfo actual = derivedFoo.GetRuntimeBaseDefinition(); + Assert.Equal(baseFoo, actual); + } + + [Fact] + public void GetRuntimeInterfaceMap() + { + AssertExtensions.Throws("typeInfo", () => default(TypeInfo).GetRuntimeInterfaceMap(typeof(ICloneable))); + AssertExtensions.Throws("ifaceType", () => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(null)); + Assert.Throws(() => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(ICloneable))); + Assert.Throws(() => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(string))); + + InterfaceMapping map = typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(IDisposable)); + Assert.Same(typeof(TestType), map.TargetType); + Assert.Same(typeof(IDisposable), map.InterfaceType); + Assert.Equal(1, map.InterfaceMethods.Length); + Assert.Equal(1, map.TargetMethods.Length); + MethodInfo ifaceDispose = map.InterfaceMethods[0]; + MethodInfo targetDispose = map.TargetMethods[0]; + Assert.Equal(ifaceDispose.CallingConvention, targetDispose.CallingConvention); + Assert.Equal(ifaceDispose.Name, targetDispose.Name); + Assert.Same(ifaceDispose.ReturnType, targetDispose.ReturnType); + Assert.Equal(ifaceDispose.GetParameters().Length, targetDispose.GetParameters().Length); + Assert.Same(typeof(TestTypeBase), targetDispose.DeclaringType); + Assert.Same(typeof(IDisposable), ifaceDispose.DeclaringType); + } + + private static string GetMethodName(string methodName) { int startIndex = methodName.IndexOf(" ") + 1; int endIndex = methodName.IndexOf("("); return methodName.Substring(startIndex, endIndex - startIndex); } - private static Type[] GetMethodParameters(String methodName) + private static Type[] GetMethodParameters(string methodName) { int startIndex = methodName.IndexOf("(") + 1; int endIndex = methodName.IndexOf(")"); if (endIndex <= startIndex) return new Type[0]; - String[] parameters = methodName.Substring(startIndex, endIndex - startIndex).Split(','); + string[] parameters = methodName.Substring(startIndex, endIndex - startIndex).Split(','); List parameterList = new List(); - foreach (String parameter in parameters) + foreach (string parameter in parameters) parameterList.Add(Type.GetType(parameter.Trim())); return parameterList.ToArray(); } - private static TypeInfo[] GetTypes() { Assembly asm = typeof(PropertyTestBaseClass).GetTypeInfo().Assembly; @@ -267,5 +349,125 @@ namespace System.Reflection.Tests } return list.ToArray(); } + + private abstract class TestBase + { + public abstract void Foo(); + } + + private class TestDerived : TestBase + { + public override void Foo() { throw null; } + } + + abstract class TestTypeBase : IDisposable + { + public abstract bool CanRead { get; } + public abstract bool CanWrite { get; } + public abstract bool CanSeek { get; } + public abstract long Length { get; } + public abstract long Position { get; set; } + + public virtual Task FlushAsync() + { + throw null; + } + + public abstract void Flush(); + + public virtual Task ReadAsync(byte[] buffer, int offset, int count) + { + throw null; + } + + public abstract int Read(byte[] buffer, int offset, int count); + + public abstract long Seek(long offset, SeekOrigin origin); + + public abstract void SetLength(long value); + + public abstract void Write(byte[] buffer, int offset, int count); + public virtual Task WriteAsync(byte[] buffer, int offset, int count) + { + throw null; + } + + public void Dispose() + { + throw null; + } + } + + class TestType : TestTypeBase + { + public TestType() + { + } + + public class Nested + { + + } + + #pragma warning disable 0067 // event never used + public event Action StuffHappened; + #pragma warning restore 0067 + + #pragma warning disable 0169 // field never used + private int _pizzaSize; + #pragma warning restore 0169 + + public override bool CanRead => false; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length + { + get + { + throw new NotImplementedException(); + } + } + + public override long Position + { + get + { + throw new NotImplementedException(); + } + + set + { + throw new NotImplementedException(); + } + } + + public override void Flush() + { + throw new NotImplementedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + throw new NotImplementedException(); + } + + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotImplementedException(); + } + + public override void SetLength(long value) + { + throw new NotImplementedException(); + } + + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotImplementedException(); + } + } } } diff --git a/external/corefx/src/System.Reflection/tests/Configurations.props b/external/corefx/src/System.Reflection/tests/Configurations.props index c398e42e89..8b803e0772 100644 --- a/external/corefx/src/System.Reflection/tests/Configurations.props +++ b/external/corefx/src/System.Reflection/tests/Configurations.props @@ -2,6 +2,7 @@ + netcoreapp; netstandard; diff --git a/external/corefx/src/System.Reflection/tests/ConstructorInfoTests.cs b/external/corefx/src/System.Reflection/tests/ConstructorInfoTests.cs index 5bc838ff53..0078386655 100644 --- a/external/corefx/src/System.Reflection/tests/ConstructorInfoTests.cs +++ b/external/corefx/src/System.Reflection/tests/ConstructorInfoTests.cs @@ -38,6 +38,7 @@ namespace System.Reflection.Tests public void Equals(ConstructorInfo constructorInfo1, ConstructorInfo constructorInfo2, bool expected) { Assert.Equal(expected, constructorInfo1.Equals(constructorInfo2)); + Assert.NotEqual(expected, constructorInfo1 != constructorInfo2); } [Fact] @@ -146,7 +147,7 @@ namespace System.Reflection.Tests [Fact] public void Invoke_ExistingInstance() { - // Should not prouce a second object. + // Should not produce a second object. ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); ClassWith3Constructors obj1 = new ClassWith3Constructors(100, "hello"); ClassWith3Constructors obj2 = (ClassWith3Constructors)constructors[2].Invoke(obj1, new object[] { 999, "initialized" }); diff --git a/external/corefx/src/System.Reflection/tests/FieldInfoTests.cs b/external/corefx/src/System.Reflection/tests/FieldInfoTests.cs index 2611c6362e..e630c15c8f 100644 --- a/external/corefx/src/System.Reflection/tests/FieldInfoTests.cs +++ b/external/corefx/src/System.Reflection/tests/FieldInfoTests.cs @@ -423,6 +423,16 @@ namespace System.Reflection.Tests Assert.Equal(initialValue, fi.GetValue(obj)); } + [Fact(Skip="It's CAS-related and not actual in Mono")] + public void SecurityAttributes() + { + FieldInfo info = GetField(typeof(FieldInfoTests), nameof(FieldInfoTests.s_intField)); + + Assert.True(info.IsSecurityCritical); + Assert.False(info.IsSecuritySafeCritical); + Assert.False(info.IsSecurityTransparent); + } + private static FieldInfo GetField(Type type, string name) { return type.GetTypeInfo().DeclaredFields.FirstOrDefault(fieldInfo => fieldInfo.Name.Equals(name)); @@ -533,7 +543,7 @@ namespace System.Reflection.Tests public object field; } - [Theory] + [Theory(Skip="Mono issue #10372")] [InlineData(222)] [InlineData("new value")] [InlineData('A')] diff --git a/external/corefx/src/System.Reflection/tests/GetTypeTests.cs b/external/corefx/src/System.Reflection/tests/GetTypeTests.cs index 3d87ff5318..dba49e329d 100644 --- a/external/corefx/src/System.Reflection/tests/GetTypeTests.cs +++ b/external/corefx/src/System.Reflection/tests/GetTypeTests.cs @@ -12,6 +12,13 @@ namespace System.Reflection.Tests [Fact] public void GetType_EmptyString() { +#if MONO + string exceptionParamName = "typeName"; + string msg = "Name cannot be empty"; +#else + string exceptionParamName = "typeName@0"; + string msg = null; +#endif Assembly a = typeof(GetTypeTests).GetTypeInfo().Assembly; Module m = a.ManifestModule; @@ -26,7 +33,7 @@ namespace System.Reflection.Tests Assert.Null(Type.GetType(aqn, throwOnError: false)); Assert.Throws(() => Type.GetType(typeName, throwOnError: true)); - AssertExtensions.Throws("typeName@0", () => Type.GetType(aqn, throwOnError: true)); + AssertExtensions.Throws(exceptionParamName, () => Type.GetType(aqn, throwOnError: true)); Assert.Null(Type.GetType(typeName, throwOnError: false, ignoreCase: false)); Assert.Null(Type.GetType(typeName, throwOnError: false, ignoreCase: true)); @@ -35,22 +42,22 @@ namespace System.Reflection.Tests Assert.Throws(() => Type.GetType(typeName, throwOnError: true, ignoreCase: false)); Assert.Throws(() => Type.GetType(typeName, throwOnError: true, ignoreCase: true)); - AssertExtensions.Throws("typeName@0", () => Type.GetType(aqn, throwOnError: true, ignoreCase: false)); - AssertExtensions.Throws("typeName@0", () => Type.GetType(aqn, throwOnError: true, ignoreCase: true)); + AssertExtensions.Throws(exceptionParamName, () => Type.GetType(aqn, throwOnError: true, ignoreCase: false)); + AssertExtensions.Throws(exceptionParamName, () => Type.GetType(aqn, throwOnError: true, ignoreCase: true)); // Assembly.GetType - AssertExtensions.Throws(null, () => a.GetType(typeName)); + AssertExtensions.Throws(msg, () => a.GetType(typeName)); Assert.Null(a.GetType(aqn)); - AssertExtensions.Throws(null, () => a.GetType(typeName, throwOnError: false, ignoreCase: false)); - AssertExtensions.Throws(null, () => a.GetType(typeName, throwOnError: false, ignoreCase: true)); + AssertExtensions.Throws(msg, () => a.GetType(typeName, throwOnError: false, ignoreCase: false)); + AssertExtensions.Throws(msg, () => a.GetType(typeName, throwOnError: false, ignoreCase: true)); Assert.Null(a.GetType(aqn, throwOnError: false, ignoreCase: false)); Assert.Null(a.GetType(aqn, throwOnError: false, ignoreCase: true)); - AssertExtensions.Throws(null, () => a.GetType(typeName, throwOnError: true, ignoreCase: false)); - AssertExtensions.Throws(null, () => a.GetType(typeName, throwOnError: true, ignoreCase: true)); - AssertExtensions.Throws("typeName@0", () => a.GetType(aqn, throwOnError: true, ignoreCase: false)); - AssertExtensions.Throws("typeName@0", () => a.GetType(aqn, throwOnError: true, ignoreCase: true)); + AssertExtensions.Throws(msg, () => a.GetType(typeName, throwOnError: true, ignoreCase: false)); + AssertExtensions.Throws(msg, () => a.GetType(typeName, throwOnError: true, ignoreCase: true)); + AssertExtensions.Throws(exceptionParamName, () => a.GetType(aqn, throwOnError: true, ignoreCase: false)); + AssertExtensions.Throws(exceptionParamName, () => a.GetType(aqn, throwOnError: true, ignoreCase: true)); // Module.GetType AssertExtensions.Throws(null, () => m.GetType(typeName, throwOnError: false, ignoreCase: false)); @@ -60,8 +67,8 @@ namespace System.Reflection.Tests AssertExtensions.Throws(null, () => m.GetType(typeName, throwOnError: true, ignoreCase: false)); AssertExtensions.Throws(null, () => m.GetType(typeName, throwOnError: true, ignoreCase: true)); - AssertExtensions.Throws("typeName@0", () => m.GetType(aqn, throwOnError: true, ignoreCase: false)); - AssertExtensions.Throws("typeName@0", () => m.GetType(aqn, throwOnError: true, ignoreCase: true)); + AssertExtensions.Throws(exceptionParamName, () => m.GetType(aqn, throwOnError: true, ignoreCase: false)); + AssertExtensions.Throws(exceptionParamName, () => m.GetType(aqn, throwOnError: true, ignoreCase: true)); } public static IEnumerable GetType_TestData() @@ -81,7 +88,10 @@ namespace System.Reflection.Tests Type type = typeof(MyNamespace1.MynAmespace3.Goo); yield return new object[] { type.FullName, type }; +// see issue https://github.com/mono/mono/issues/11269 +#if !MONO yield return new object[] { type.FullName.ToUpper(), type }; +#endif yield return new object[] { type.FullName.ToLower(), type }; } diff --git a/external/corefx/src/System.Reflection/tests/MemberInfoTests.cs b/external/corefx/src/System.Reflection/tests/MemberInfoTests.cs index d90d138bbe..42986f469f 100644 --- a/external/corefx/src/System.Reflection/tests/MemberInfoTests.cs +++ b/external/corefx/src/System.Reflection/tests/MemberInfoTests.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; +using System.Runtime.InteropServices; using Xunit; #pragma warning disable 0414 @@ -16,25 +17,246 @@ namespace System.Reflection.Tests [Fact] public void MetadataToken() { - Assert.Equal(GetMembers(typeof(SampleClass)), GetMembers(typeof(SampleClass))); - Assert.Equal(GetMembers(new MemberInfoTests().GetType()), GetMembers(new MemberInfoTests().GetType())); - Assert.Equal(GetMembers(new Dictionary().GetType()), GetMembers(new Dictionary().GetType())); - Assert.Equal(GetMembers(typeof(int)), GetMembers(typeof(int))); - Assert.Equal(GetMembers(typeof(Dictionary<,>)), GetMembers(typeof(Dictionary<,>))); + Assert.Equal(GetMetadataTokens(typeof(SampleClass)), GetMetadataTokens(typeof(SampleClass))); + Assert.Equal(GetMetadataTokens(new MemberInfoTests().GetType()), GetMetadataTokens(new MemberInfoTests().GetType())); + Assert.Equal(GetMetadataTokens(new Dictionary().GetType()), GetMetadataTokens(new Dictionary().GetType())); + Assert.Equal(GetMetadataTokens(typeof(int)), GetMetadataTokens(typeof(int))); + Assert.Equal(GetMetadataTokens(typeof(Dictionary<,>)), GetMetadataTokens(typeof(Dictionary<,>))); } - private IEnumerable GetMembers(Type type) + [Fact] + public void ReflectedType() + { + Type t = typeof(Derived); + MemberInfo[] members = t.GetMembers(); + foreach (MemberInfo member in members) + { + Assert.Equal(t, member.ReflectedType); + } + } + + [Fact] + public void PropertyReflectedType() + { + Type t = typeof(Base); + PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1)); + Assert.Equal(t, p.ReflectedType); + Assert.NotNull(p.GetMethod); + Assert.NotNull(p.SetMethod); + } + + [Fact] + public void InheritedPropertiesHidePrivateAccessorMethods() + { + Type t = typeof(Derived); + PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1)); + Assert.Equal(t, p.ReflectedType); + Assert.NotNull(p.GetMethod); + Assert.Null(p.SetMethod); + } + + [Fact(Skip="Mono issue #10276")] + public void GenericMethodsInheritTheReflectedTypeOfTheirTemplate() + { + Type t = typeof(Derived); + MethodInfo moo = t.GetMethod("Moo"); + Assert.Equal(t, moo.ReflectedType); + MethodInfo mooInst = moo.MakeGenericMethod(typeof(int)); + Assert.Equal(t, mooInst.ReflectedType); + } + + [Fact] + public void DeclaringMethodOfTypeParametersOfInheritedMethods() + { + Type t = typeof(Derived); + MethodInfo moo = t.GetMethod("Moo"); + Assert.Equal(t, moo.ReflectedType); + Type theM = moo.GetGenericArguments()[0]; + MethodBase moo1 = theM.DeclaringMethod; + Type reflectedTypeOfMoo1 = moo1.ReflectedType; + Assert.Equal(typeof(Base), reflectedTypeOfMoo1); + } + + [Fact] + public void DeclaringMethodOfTypeParametersOfInheritedMethods2() + { + Type t = typeof(GDerived); + MethodInfo moo = t.GetMethod("Moo"); + Assert.Equal(t, moo.ReflectedType); + Type theM = moo.GetGenericArguments()[0]; + MethodBase moo1 = theM.DeclaringMethod; + Type reflectedTypeOfMoo1 = moo1.ReflectedType; + Assert.Equal(typeof(GBase<>), reflectedTypeOfMoo1); + } + + [Fact] + public void InheritedPropertyAccessors() + { + Type t = typeof(Derived); + PropertyInfo p = t.GetProperty(nameof(Base.MyProperty)); + MethodInfo getter = p.GetMethod; + MethodInfo setter = p.SetMethod; + Assert.Equal(t, getter.ReflectedType); + Assert.Equal(t, setter.ReflectedType); + } + + [Fact(Skip="Mono issue #10277")] + public void InheritedEventAccessors() + { + Type t = typeof(Derived); + EventInfo e = t.GetEvent(nameof(Base.MyEvent)); + MethodInfo adder = e.AddMethod; + MethodInfo remover = e.RemoveMethod; + Assert.Equal(t, adder.ReflectedType); + Assert.Equal(t, remover.ReflectedType); + } + + [Fact] + public void ReflectedTypeIsPartOfIdentity() + { + Type b = typeof(Base); + Type d = typeof(Derived); + + { + EventInfo e = b.GetEvent(nameof(Base.MyEvent)); + EventInfo ei = d.GetEvent(nameof(Derived.MyEvent)); + Assert.False(e.Equals(ei)); + } + + { + FieldInfo f = b.GetField(nameof(Base.MyField)); + FieldInfo fi = d.GetField(nameof(Derived.MyField)); + Assert.False(f.Equals(fi)); + } + + { + MethodInfo m = b.GetMethod(nameof(Base.Moo)); + MethodInfo mi = d.GetMethod(nameof(Derived.Moo)); + Assert.False(m.Equals(mi)); + } + + { + PropertyInfo p = b.GetProperty(nameof(Base.MyProperty)); + PropertyInfo pi = d.GetProperty(nameof(Derived.MyProperty)); + Assert.False(p.Equals(pi)); + } + } + + [Fact] + public void FieldInfoReflectedTypeDoesNotSurviveRuntimeHandles() + { + Type t = typeof(Derived); + FieldInfo f = t.GetField(nameof(Base.MyField)); + Assert.Equal(typeof(Derived), f.ReflectedType); + RuntimeFieldHandle h = f.FieldHandle; + FieldInfo f2 = FieldInfo.GetFieldFromHandle(h); + Assert.Equal(typeof(Base), f2.ReflectedType); + } + + [Fact] + public void MethodInfoReflectedTypeDoesNotSurviveRuntimeHandles() + { + Type t = typeof(Derived); + MethodInfo m = t.GetMethod(nameof(Base.Moo)); + Assert.Equal(typeof(Derived), m.ReflectedType); + RuntimeMethodHandle h = m.MethodHandle; + MethodBase m2 = MethodBase.GetMethodFromHandle(h); + Assert.Equal(typeof(Base), m2.ReflectedType); + } + + [Fact] + public void GetCustomAttributesData() + { + MemberInfo[] m = typeof(MemberInfoTests).GetMember("SampleClass"); + Assert.Equal(1, m.Count()); + foreach(CustomAttributeData cad in m[0].GetCustomAttributesData()) + { + if (cad.AttributeType == typeof(ComVisibleAttribute)) + { + ConstructorInfo c = cad.Constructor; + Assert.False(c.IsStatic); + Assert.Equal(typeof(ComVisibleAttribute), c.DeclaringType); + ParameterInfo[] p = c.GetParameters(); + Assert.Equal(1, p.Length); + Assert.Equal(typeof(bool), p[0].ParameterType); + return; + } + } + + Assert.True(false, "Expected to find ComVisibleAttribute"); + } + + public static IEnumerable EqualityOperator_TestData() + { + yield return new object[] { typeof(SampleClass) }; + yield return new object[] { new MemberInfoTests().GetType() }; + yield return new object[] { typeof(int) }; + yield return new object[] { typeof(Dictionary<,>) }; + } + + [Theory] + [MemberData(nameof(EqualityOperator_TestData))] + public void EqualityOperator_Equal_ReturnsTrue(Type type) + { + MemberInfo[] members1 = GetOrderedMembers(type); + MemberInfo[] members2 = GetOrderedMembers(type); + + Assert.Equal(members1.Length, members2.Length); + for (int i = 0; i < members1.Length; i++) + { + Assert.True(members1[i] == members2[i]); + Assert.False(members1[i] != members2[i]); + } + } + + private MemberInfo[] GetMembers(Type type) + { + return type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + } + + private IEnumerable GetMetadataTokens(Type type) { return type.GetTypeInfo().GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Select(m => m.HasMetadataToken() ? m.MetadataToken : 0); } + private MemberInfo[] GetOrderedMembers(Type type) => GetMembers(type).OrderBy(member => member.Name).ToArray(); + + private class Base + { + public event Action MyEvent { add { } remove { } } +#pragma warning disable 0649 + public int MyField; +#pragma warning restore 0649 + public int MyProperty { get; set; } + + public int MyProperty1 { get; private set; } + public int MyProperty2 { private get; set; } + + public void Moo() { } + } + + private class Derived : Base + { + } + + private class GBase + { + public void Moo() { } + } + + private class GDerived : GBase + { + } + #pragma warning disable 0067, 0169 +#pragma warning disable 0067, 0169 + [ComVisible(false)] public class SampleClass { public int PublicField; private int PrivateField; - public SampleClass() { } + public SampleClass(bool y) { } private SampleClass(int x) { } public void PublicMethod() { } diff --git a/external/corefx/src/System.Runtime/tests/System/Reflection/MemberInfoTests.netcoreapp.cs b/external/corefx/src/System.Reflection/tests/MemberInfoTests.netcoreapp.cs similarity index 99% rename from external/corefx/src/System.Runtime/tests/System/Reflection/MemberInfoTests.netcoreapp.cs rename to external/corefx/src/System.Reflection/tests/MemberInfoTests.netcoreapp.cs index cbbbe2805a..f2fd5c88e8 100644 --- a/external/corefx/src/System.Runtime/tests/System/Reflection/MemberInfoTests.netcoreapp.cs +++ b/external/corefx/src/System.Reflection/tests/MemberInfoTests.netcoreapp.cs @@ -143,7 +143,7 @@ namespace System.Reflection.Tests Assert.False(tginst1.HasSameMetadataDefinitionAs(tnong)); } - [Fact] + [Fact(Skip="Mono issue #10127")] public static void HasSameMetadataDefinitionAs_GenericTypeParameters() { Type theT = typeof(GenericTestClass<>).GetTypeInfo().GenericTypeParameters[0]; @@ -264,7 +264,7 @@ namespace System.Reflection.Tests } } - [Fact] + [Fact(Skip="Mono issue #10129")] public static void HasSameMetadataDefinitionAs__CornerCase_HasElementTypes() { // HasSameMetadataDefinitionAs on an array/byref/pointer type is uninteresting (they'll never be an actual member of a type) @@ -337,7 +337,7 @@ namespace System.Reflection.Tests ); } - [Fact] + [SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "Mono issue #10159")] [PlatformSpecific(TestPlatforms.Windows)] public static void HasSameMetadataDefinitionAs_CornerCase_CLSIDConstructor() { diff --git a/external/corefx/src/System.Reflection/tests/ModuleTests.cs b/external/corefx/src/System.Reflection/tests/ModuleTests.cs index fe132711bf..9d4d480c99 100644 --- a/external/corefx/src/System.Reflection/tests/ModuleTests.cs +++ b/external/corefx/src/System.Reflection/tests/ModuleTests.cs @@ -28,7 +28,7 @@ namespace System.Reflection.Tests Assert.Equal(typeInfo.Assembly, module.Assembly); } - [Theory] + [Theory(Skip="Mono issue #11569")] [InlineData(typeof(Attr), 77, "AttrSimple")] [InlineData(typeof(Int32Attr), 77, "Int32AttrSimple")] [InlineData(typeof(Int64Attr), (long)77, "Int64AttrSimple")] diff --git a/external/corefx/src/System.Reflection/tests/ParameterInfoTests.cs b/external/corefx/src/System.Reflection/tests/ParameterInfoTests.cs index 279f911c21..95f5682b16 100644 --- a/external/corefx/src/System.Reflection/tests/ParameterInfoTests.cs +++ b/external/corefx/src/System.Reflection/tests/ParameterInfoTests.cs @@ -5,6 +5,8 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; using Xunit; namespace System.Reflection.Tests @@ -86,6 +88,33 @@ namespace System.Reflection.Tests Assert.NotNull(parameterInfo.RawDefaultValue); } + [Fact] + public void RawDefaultValue_Enum() + { + ParameterInfo p = GetParameterInfo(typeof(ParameterInfoMetadata), "Foo1", 0); + object raw = p.RawDefaultValue; + Assert.Equal(typeof(int), raw.GetType()); + Assert.Equal((int)raw, (int)BindingFlags.DeclaredOnly); + } + + [Fact(Skip="Mono issue #11051")] + public void RawDefaultValueFromAttribute() + { + ParameterInfo p = GetParameterInfo(typeof(ParameterInfoMetadata), "Foo2", 0); + object raw = p.RawDefaultValue; + Assert.Equal(typeof(int), raw.GetType()); + Assert.Equal((int)raw, (int)BindingFlags.IgnoreCase); + } + + [Fact] + public void RawDefaultValue_MetadataTrumpsAttribute() + { + ParameterInfo p = GetParameterInfo(typeof(ParameterInfoMetadata), "Foo3", 0); + object raw = p.RawDefaultValue; + Assert.Equal(typeof(int), raw.GetType()); + Assert.Equal((int)raw, (int)BindingFlags.FlattenHierarchy); + } + [Theory] [InlineData(typeof(ParameterInfoMetadata), "MethodWithRefParameter", 0, false)] [InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 1, true)] @@ -169,6 +198,27 @@ namespace System.Reflection.Tests Assert.True(prov.IsDefined(attrType, true)); } + [Fact] + public void VerifyGetCustomAttributesData() + { + ParameterInfo p = GetParameterInfo(typeof(ParameterInfoMetadata), "MethodWithCustomAttribute", 0); + foreach (CustomAttributeData cad in p.GetCustomAttributesData()) + { + if(cad.AttributeType == typeof(MyAttribute)) + { + ConstructorInfo c = cad.Constructor; + Assert.False(c.IsStatic); + Assert.False(c.IsPublic); + ParameterInfo[] paramInfo = c.GetParameters(); + Assert.Equal(1, paramInfo.Length); + Assert.Equal(typeof(int), paramInfo[0].ParameterType); + return; + } + } + + Assert.True(false, "Expected to find MyAttribute"); + } + public static IEnumerable s_CustomAttributesTestData { get @@ -207,6 +257,47 @@ namespace System.Reflection.Tests Assert.Equal(expected, parameterInfo.GetRequiredCustomModifiers()); } + [Theory] + [MemberData(nameof(VerifyParameterInfoGetRealObjectWorks_TestData))] + public void VerifyParameterInfoGetRealObjectWorks(MemberInfo pretendMember, int pretendPosition, string expectedParameterName) + { + // Regression test for https://github.com/dotnet/corefx/issues/20574 + // + // It's easy to forget that ParameterInfo's and runtime-implemented ParameterInfo's are different objects and just because the + // latter doesn't support serialization doesn't mean other providers won't either. + // + // For historical reasons, ParameterInfo contains some serialization support that subtypes can optionally hang off. This + // test ensures that support doesn't get vaporized. + + // Just pretend that we're BinaryFormatter and are deserializing a Parameter... + IObjectReference podParameter = new PodPersonParameterInfo(pretendMember, pretendPosition); + StreamingContext sc = new StreamingContext(StreamingContextStates.Clone); + ParameterInfo result = (ParameterInfo)(podParameter.GetRealObject(sc)); + + Assert.Equal(pretendPosition, result.Position); + Assert.Equal(expectedParameterName, result.Name); + Assert.Equal(pretendMember.Name, result.Member.Name); + } + + public static IEnumerable VerifyParameterInfoGetRealObjectWorks_TestData + { + get + { + Type t = typeof(PretendParent); + ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(int), typeof(int) }); + MethodInfo method = t.GetMethod(nameof(PretendParent.PretendMethod)); + PropertyInfo property = t.GetProperty("Item"); + + yield return new object[] { ctor, 0, "a" }; + yield return new object[] { ctor, 1, "b" }; + yield return new object[] { method, -1, null }; + yield return new object[] { method, 0, "x" }; + yield return new object[] { method, 1, "y" }; + yield return new object[] { property, 0, "index1" }; + yield return new object[] { property, 1, "index2" }; + } + } + private static ParameterInfo GetParameterInfo(Type type, string name, int index) { ParameterInfo[] parameters = GetMethod(type, name).GetParameters(); @@ -221,6 +312,12 @@ namespace System.Reflection.Tests // Metadata for reflection public class ParameterInfoMetadata { + public void Foo1(BindingFlags bf = BindingFlags.DeclaredOnly) { } + public void Foo2([CustomBindingFlags(Value = BindingFlags.IgnoreCase)] BindingFlags bf) { } + public void Foo3([CustomBindingFlags(Value = BindingFlags.DeclaredOnly)] BindingFlags bf = BindingFlags.FlattenHierarchy ) { } + + public void MethodWithCustomAttribute([My(2)]string str, int iValue, long lValue) { } + public void Method1(string str, int iValue, long lValue) { } public void Method2() { } public void MethodWithArray(string[] strArray) { } @@ -244,5 +341,39 @@ namespace System.Reflection.Tests public void GenericMethod(T t) { } public string GenericMethodWithDefault(int i, T t = default(T)) { return "somestring"; } } + + private class MyAttribute : Attribute + { + internal MyAttribute(int i) { } + } + + internal sealed class CustomBindingFlagsAttribute : UsableCustomConstantAttribute + { + public new object Value { get { return RealValue; } set { RealValue = value; } } + } + + internal abstract class UsableCustomConstantAttribute : CustomConstantAttribute + { + public sealed override object Value => RealValue; + protected object RealValue { get; set; } + } + + private sealed class PretendParent + { + public PretendParent(int a, int b) { } + public void PretendMethod(int x, int y) { } + public int this[int index1, int index2] { get { throw null; } } + } + + private sealed class PodPersonParameterInfo : MockParameterInfo + { + public PodPersonParameterInfo(MemberInfo pretendMember, int pretendPosition) + { + // Serialization can recreate a ParameterInfo from just these two pieces of data. Of course, this is just a test and no one + // ever told this Member that it was adopting a counterfeit Parameter, but this is just a test... + MemberImpl = pretendMember; + PositionImpl = pretendPosition; + } + } } } diff --git a/external/corefx/src/System.Reflection/tests/PropertyInfoTests.cs b/external/corefx/src/System.Reflection/tests/PropertyInfoTests.cs index a24b1abaaa..4f4594ab51 100644 --- a/external/corefx/src/System.Reflection/tests/PropertyInfoTests.cs +++ b/external/corefx/src/System.Reflection/tests/PropertyInfoTests.cs @@ -249,6 +249,8 @@ namespace System.Reflection.Tests PropertyInfo propertyInfo1 = GetProperty(type1, name1); PropertyInfo propertyInfo2 = GetProperty(type2, name2); Assert.Equal(expected, propertyInfo1.Equals(propertyInfo2)); + Assert.Equal(expected, propertyInfo1 == propertyInfo2); + Assert.Equal(!expected, propertyInfo1 != propertyInfo2); } [Fact] diff --git a/external/corefx/src/System.Reflection/tests/System.Reflection.Tests.csproj b/external/corefx/src/System.Reflection/tests/System.Reflection.Tests.csproj index 93277f5d3a..ad1c0e21aa 100644 --- a/external/corefx/src/System.Reflection/tests/System.Reflection.Tests.csproj +++ b/external/corefx/src/System.Reflection/tests/System.Reflection.Tests.csproj @@ -1,12 +1,14 @@ - - - + {B027C72E-F04E-42E0-A7F7-993AEF8400D2} + netcoreapp-Debug;netcoreapp-Release;netstandard-Debug;netstandard-Release + true - - + + Common\System\Reflection\MockParameterInfo.cs + + @@ -21,6 +23,7 @@ + @@ -32,6 +35,10 @@ ResourceTextFile.txt + + + + @@ -49,5 +56,4 @@ System.Reflection.Tests.TestExe - - \ No newline at end of file + diff --git a/external/corefx/src/System.Reflection/tests/TypeInfoTests.cs b/external/corefx/src/System.Reflection/tests/TypeInfoTests.cs index ccc17587c8..f3228cd3a3 100644 --- a/external/corefx/src/System.Reflection/tests/TypeInfoTests.cs +++ b/external/corefx/src/System.Reflection/tests/TypeInfoTests.cs @@ -2,8 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections; using System.Collections.Generic; using System.Linq; +using System.IO; using System.Runtime.InteropServices; using Xunit; @@ -17,25 +19,27 @@ namespace System.Reflection.Tests [InlineData(typeof(TI_SubClass), 2)] [InlineData(typeof(ClassWithStaticConstructor), 0)] [InlineData(typeof(ClassWithMultipleConstructors), 4)] - public void DeclaredEvents(Type type, int expectedCount) + public void DeclaredConstructors(Type type, int expectedCount) { ConstructorInfo[] constructors = type.GetTypeInfo().DeclaredConstructors.Where(ctorInfo => !ctorInfo.IsStatic).ToArray(); Assert.Equal(expectedCount, constructors.Length); foreach (ConstructorInfo constructorInfo in constructors) { Assert.NotNull(constructorInfo); + Assert.True(constructorInfo.IsSpecialName); } } [Theory] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.EventPublic), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.EventPublicStatic), true)] - [InlineData(typeof(TI_BaseClass), "NoSuchEvent", false)] - [InlineData(typeof(TI_BaseClass), "", false)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.EventPublicNew), true)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.EventPublic), true)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.EventPublicStatic), false)] - public void DeclaredEvents(Type type, string name, bool exists) + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.EventPublic), true, "EventHandler")] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.EventPublicStatic), true, "EventHandler")] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.StuffHappened), true, "Action`1")] + [InlineData(typeof(TI_BaseClass), "NoSuchEvent", false, "EventHandler")] + [InlineData(typeof(TI_BaseClass), "", false, "EventHandler")] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.EventPublicNew), true, "EventHandler")] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.EventPublic), true, "EventHandler")] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.EventPublicStatic), false, "EventHandler")] + public void DeclaredEvents(Type type, string name, bool exists, string eventHandlerTypeName) { IEnumerable events = type.GetTypeInfo().DeclaredEvents; Assert.Equal(exists, events.Any(eventInfo => eventInfo.Name.Equals(name))); @@ -44,6 +48,7 @@ namespace System.Reflection.Tests if (exists) { Assert.Equal(name, declaredEventInfo.Name); + Assert.Equal(eventHandlerTypeName, declaredEventInfo.EventHandlerType.Name); } else { @@ -52,24 +57,26 @@ namespace System.Reflection.Tests } [Theory] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._field1), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._field2), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._readonlyField), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._volatileField), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_field), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_readonlyField), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_volatileField), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_arrayField), true)] - [InlineData(typeof(TI_BaseClass), "NoSuchField", false)] - [InlineData(typeof(TI_BaseClass), "", false)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass._field2), true)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass._readonlyField), true)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass._volatileField), true)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.s_field), true)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.s_readonlyField), true)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.s_volatileField), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_SubClass.s_arrayField), true)] - public void DeclaredFields(Type type, string name, bool exists) + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._field1), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._field2), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._readonlyField), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._volatileField), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_field), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_readonlyField), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_volatileField), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_arrayField), true, typeof(string[]), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.StuffHappened), true, typeof(Action), true)] + [InlineData(typeof(TI_BaseClass), "_privateField", true, typeof(int), true)] + [InlineData(typeof(TI_BaseClass), "NoSuchField", false, default(Type), default(Boolean))] + [InlineData(typeof(TI_BaseClass), "", false, default(Type), default(Boolean))] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass._field2), true, typeof(string), false)] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass._readonlyField), true, typeof(string), false)] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass._volatileField), true, typeof(string), false)] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.s_field), true, typeof(string), false)] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.s_readonlyField), true, typeof(string), false)] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.s_volatileField), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_SubClass.s_arrayField), true, typeof(string[]), false)] + public void DeclaredFields(Type type, string name, bool exists, Type fieldType, bool isPrivate) { IEnumerable fields = type.GetTypeInfo().DeclaredFields.Select(fieldInfo => fieldInfo.Name); FieldInfo declaredFieldInfo = type.GetTypeInfo().GetDeclaredField(name); @@ -77,6 +84,8 @@ namespace System.Reflection.Tests { Assert.Equal(name, declaredFieldInfo.Name); Assert.Contains(name, fields); + Assert.Equal(fieldType, declaredFieldInfo.FieldType); + Assert.Equal(isPrivate, declaredFieldInfo.IsPrivate); } else { @@ -101,6 +110,10 @@ namespace System.Reflection.Tests [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.VirtualVoidMethodReturningVoid1), true)] [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.VirtualVoidMethodReturningVoid2), true)] [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.StaticVoidMethodReturningVoid), true)] + [InlineData(typeof(TI_BaseClass), "add_StuffHappened", true)] + [InlineData(typeof(TI_BaseClass), "remove_StuffHappened", true)] + [InlineData(typeof(TI_BaseClass), "set_StringProperty1", true)] + [InlineData(typeof(TI_BaseClass), "get_StringProperty1", true)] [InlineData(typeof(TI_BaseClass), "NoSuchMethod", false)] [InlineData(typeof(TI_BaseClass), "", false)] [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.VoidMethodReturningVoid2), true)] @@ -165,8 +178,10 @@ namespace System.Reflection.Tests [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.StaticStringProperty))] public void DeclaredProperties(Type type, string name) { - IEnumerable properties = type.GetTypeInfo().DeclaredProperties.Select(property => property.Name); + TypeInfo typeInfo = type.GetTypeInfo(); + IEnumerable properties = typeInfo.DeclaredProperties.Select(property => property.Name); Assert.Contains(name, properties); + Assert.Equal(name, typeInfo.GetDeclaredProperty(name).Name); } [Fact] @@ -459,7 +474,12 @@ namespace System.Reflection.Tests [Fact] public void IsEnumDefined_Invalid() { +#if MONO +// https://github.com/dotnet/corefx/issues/32510 + AssertExtensions.Throws("enumType", () => typeof(NonGenericClassWithNoInterfaces).GetTypeInfo().IsEnumDefined(10)); +#else AssertExtensions.Throws("", () => typeof(NonGenericClassWithNoInterfaces).GetTypeInfo().IsEnumDefined(10)); +#endif Assert.Throws(() => typeof(IntEnum).GetTypeInfo().IsEnumDefined(null)); Assert.Throws(() => typeof(IntEnum).GetTypeInfo().IsEnumDefined(new NonGenericClassWithNoInterfaces())); } @@ -474,7 +494,7 @@ namespace System.Reflection.Tests [InlineData(typeof(CompoundClass3), new Type[] { typeof(GenericInterface1), typeof(TI_NonGenericInterface1) })] [InlineData(typeof(CompoundClass4<>), new Type[] { typeof(GenericInterface1), typeof(TI_NonGenericInterface1) })] [InlineData(typeof(CompoundClass4), new Type[] { typeof(GenericInterface1), typeof(TI_NonGenericInterface1) })] - public void ImplementedInterfaces(Type type, params Type[] expected) + public void ImplementedInterfaces(Type type, Type[] expected) { TypeInfo typeInfo = type.GetTypeInfo(); Type[] implementedInterfaces = type.GetTypeInfo().ImplementedInterfaces.ToArray(); @@ -511,6 +531,10 @@ namespace System.Reflection.Tests [InlineData(typeof(object), typeof(TI_ClassWithInterface1), true)] [InlineData(typeof(int?), typeof(int), true)] [InlineData(typeof(List), typeof(List<>), false)] + [InlineData(typeof(IDisposable), typeof(Stream), true)] + [InlineData(typeof(IList), typeof(ArrayList), true)] + [InlineData(typeof(object), typeof(int), true)] + [InlineData(typeof(object), typeof(string), true)] // Null [InlineData(typeof(BaseClassWithInterface1Interface2), null, false)] // Lists and arrays @@ -542,7 +566,10 @@ namespace System.Reflection.Tests [InlineData(typeof(InnerNamespace.AbstractBaseClass), typeof(InnerNamespace.AbstractSubSubClass), true)] [InlineData(typeof(InnerNamespace.AbstractSubClass), typeof(InnerNamespace.AbstractSubSubClass), true)] // T[] is assignable to IList iff T[] is assignable to U[] +#if !MONO +// https://github.com/mono/mono/issues/10848 [InlineData(typeof(TI_NonGenericInterface1[]), typeof(NonGenericStructWithNonGenericInterface[]), false)] +#endif [InlineData(typeof(TI_NonGenericInterface1[]), typeof(SubClassWithInterface1Interface2[]), true)] [InlineData(typeof(IList), typeof(NonGenericStructWithNonGenericInterface[]), false)] [InlineData(typeof(IList), typeof(SubClassWithInterface1Interface2[]), true)] @@ -1567,6 +1594,7 @@ namespace System.Reflection.Tests public event EventHandler EventPublic; // Inherited public static event EventHandler EventPublicStatic; + public event Action StuffHappened; public static string[] s_arrayField = new string[5]; public string _field1 = ""; @@ -1577,6 +1605,8 @@ namespace System.Reflection.Tests public static readonly string s_readonlyField = ""; public static volatile string s_volatileField = ""; + private int _privateField; + public void VoidMethodReturningVoid1() { } public void StringMethodReturningVoid(string str) { } public void VoidMethodReturningVoid2() { } diff --git a/external/corefx/src/System.Runtime/tests/System/Reflection/TypeInfoTests.netcoreapp.cs b/external/corefx/src/System.Reflection/tests/TypeInfoTests.netcoreapp.cs similarity index 100% rename from external/corefx/src/System.Runtime/tests/System/Reflection/TypeInfoTests.netcoreapp.cs rename to external/corefx/src/System.Reflection/tests/TypeInfoTests.netcoreapp.cs diff --git a/external/corefx/src/System.Runtime.Extensions/tests/System/BitConverterArray.cs b/external/corefx/src/System.Runtime.Extensions/tests/System/BitConverterArray.cs index 7dca6318f0..e8ab5a301d 100644 --- a/external/corefx/src/System.Runtime.Extensions/tests/System/BitConverterArray.cs +++ b/external/corefx/src/System.Runtime.Extensions/tests/System/BitConverterArray.cs @@ -50,11 +50,19 @@ namespace System.Tests public override void ConvertFromFloat(float num, byte[] expected) { +#if MONO // https://github.com/mono/mono/issues/10963 + if (float.IsNaN(num)) + return; +#endif Assert.Equal(expected, BitConverter.GetBytes(num)); } public override void ConvertFromDouble(double num, byte[] expected) { +#if MONO // https://github.com/mono/mono/issues/10963 + if (double.IsNaN(num)) + return; +#endif Assert.Equal(expected, BitConverter.GetBytes(num)); } diff --git a/external/corefx/src/System.Runtime.Extensions/tests/System/BitConverterSpan.cs b/external/corefx/src/System.Runtime.Extensions/tests/System/BitConverterSpan.cs index cc8e15b2f8..3000b67f30 100644 --- a/external/corefx/src/System.Runtime.Extensions/tests/System/BitConverterSpan.cs +++ b/external/corefx/src/System.Runtime.Extensions/tests/System/BitConverterSpan.cs @@ -96,6 +96,10 @@ namespace System.Tests public override void ConvertFromFloat(float num, byte[] expected) { +#if MONO // https://github.com/mono/mono/issues/10963 + if (float.IsNaN(num)) + return; +#endif Span span = new Span(new byte[4]); Assert.True(BitConverter.TryWriteBytes(span, num)); Assert.Equal(expected, span.ToArray()); @@ -103,6 +107,10 @@ namespace System.Tests public override void ConvertFromDouble(double num, byte[] expected) { +#if MONO // https://github.com/mono/mono/issues/10963 + if (double.IsNaN(num)) + return; +#endif Span span = new Span(new byte[8]); Assert.True(BitConverter.TryWriteBytes(span, num)); Assert.Equal(expected, span.ToArray()); diff --git a/external/corefx/src/System.Runtime.Extensions/tests/System/Math.cs.REMOVED.git-id b/external/corefx/src/System.Runtime.Extensions/tests/System/Math.cs.REMOVED.git-id index 3272440122..a377069a98 100644 --- a/external/corefx/src/System.Runtime.Extensions/tests/System/Math.cs.REMOVED.git-id +++ b/external/corefx/src/System.Runtime.Extensions/tests/System/Math.cs.REMOVED.git-id @@ -1 +1 @@ -70211b3fca1a649c5401d4dc08ba39a2d031b82b \ No newline at end of file +a88d340f49e6d6833f631d10d19210ce17d2bf1a \ No newline at end of file diff --git a/external/corefx/src/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/HandleCollectorTests.cs b/external/corefx/src/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/HandleCollectorTests.cs index d67005548d..6b650e7e05 100644 --- a/external/corefx/src/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/HandleCollectorTests.cs +++ b/external/corefx/src/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/HandleCollectorTests.cs @@ -121,6 +121,7 @@ namespace System.Runtime.InteropServices } [Fact] + [SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "GC has different behavior on Mono")] // see https://github.com/mono/mono/issues/11132 public static void TestHandleCollector() { (int gen0, int gen1, int gen2) initialGcState = (GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2)); diff --git a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/Comparison.cs b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/Comparison.cs index 4d7629f0c2..971de18fdd 100644 --- a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/Comparison.cs +++ b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/Comparison.cs @@ -374,7 +374,7 @@ namespace System.Numerics.Tests } [Fact] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void IComparable_Invalid_netcore() { IComparable_Invalid("obj"); diff --git a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/IsEven.cs b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/IsEven.cs index b9e7c05947..363d1d14fc 100644 --- a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/IsEven.cs +++ b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/IsEven.cs @@ -13,7 +13,7 @@ namespace System.Numerics.Tests private static int s_seed = 0; [Fact] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void RunIsEvenTests() { Random random = new Random(s_seed); diff --git a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/ToByteArray.netcoreapp.cs b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/ToByteArray.netcoreapp.cs index 2411ced08b..80a354c8b8 100644 --- a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/ToByteArray.netcoreapp.cs +++ b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/ToByteArray.netcoreapp.cs @@ -55,6 +55,7 @@ namespace System.Numerics.Tests MatrixGenerator(FromStringTests_MemberDataSeed(), true); [Theory] + [MemberData(nameof(FromStringTests_MemberData))] public void ToByteArray_FromStringTests(string str, bool isUnsigned, bool isBigEndian, byte[] expectedBytes) { BigInteger bi = BigInteger.Parse(str); diff --git a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/cast_from.cs b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/cast_from.cs index c934761fdd..0d8e582382 100644 --- a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/cast_from.cs +++ b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/cast_from.cs @@ -577,7 +577,7 @@ namespace System.Numerics.Tests [Fact] [OuterLoop] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void RunDoubleExplicitCastFromLargeBigIntegerTests() { DoubleExplicitCastFromLargeBigIntegerTests(0, 4, 32, 3); diff --git a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/log.cs b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/log.cs index f2bab92433..5bce526550 100644 --- a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/log.cs +++ b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/log.cs @@ -134,7 +134,7 @@ namespace System.Numerics.Tests [Fact] [OuterLoop] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void RunLargeValueLogTests() { LargeValueLogTests(0, 4, 64, 3); diff --git a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/modpow.cs b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/modpow.cs index a7e28b9656..24b316f73c 100644 --- a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/modpow.cs +++ b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/modpow.cs @@ -140,7 +140,7 @@ namespace System.Numerics.Tests } [Fact] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void ModPow1Large2SmallInt_Threshold() { // Again, with lower threshold @@ -165,7 +165,7 @@ namespace System.Numerics.Tests } [Fact] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void ModPow2Large1SmallInt_Threshold() { // Again, with lower threshold @@ -186,7 +186,7 @@ namespace System.Numerics.Tests [InlineData("736513799451968530811005754031332418210960966881742655756522735504778110620671049112529346250333710388060811959329786494662578020803", "2461175085563866950903873687720858523536520498137697316698237108626602445202960480677695918813575265778826908481129155012799", "-4722693720735888562993277045098354134891725536023070176847814685098361292027040929352405620815883795027263132404351040", "4351573186631261607388198896754285562669240685903971199359912143458682154189588696264319780329366022294935204028039787")] [InlineData("1596188639947986471148999794547338", "685242191738212089917782567856594513073397739443", "41848166029740752457613562518205823134173790454761036532025758411484449588176128053901271638836032557551179866133091058357374964041641117585422447497779410336188602585660372002644517668041207657383104649333118253", "39246949850380693159338034407642149926180988060650630387722725303281343126585456713282439764667310808891687831648451269002447916277601468727040185218264602698691553232132525542650964722093335105211816394635493987")] [InlineData("-1506852741293695463963822334869441845197951776565891060639754936248401744065969556756496718308248025911048010080232290368562210204958094544173209793990218122", "64905085725614938357105826012272472070910693443851911667721848542473785070747281964799379996923261457185847459711", "2740467233603031668807697475486217767705051", "-1905434239471820365929630558127219204166613")] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void ModPow3LargeInt(string value, string exponent, string modulus, string expected) { BigInteger valueInt = BigInteger.Parse(value); diff --git a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/multiply.cs b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/multiply.cs index e7d28dc078..9cedd2e86a 100644 --- a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/multiply.cs +++ b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/multiply.cs @@ -35,7 +35,7 @@ namespace System.Numerics.Tests } [Fact] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void RunMultiply_TwoLargeBigIntegers_Threshold() { // Again, with lower threshold diff --git a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/pow.cs b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/pow.cs index d89c6b29a2..4906ba1fb3 100644 --- a/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/pow.cs +++ b/external/corefx/src/System.Runtime.Numerics/tests/BigInteger/pow.cs @@ -169,7 +169,7 @@ namespace System.Numerics.Tests } [Fact] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void RunOverflow() { var bytes = new byte[1000]; diff --git a/external/corefx/src/System.Runtime.Numerics/tests/ComplexTests.cs b/external/corefx/src/System.Runtime.Numerics/tests/ComplexTests.cs index c05876af4b..45cb5a157c 100644 --- a/external/corefx/src/System.Runtime.Numerics/tests/ComplexTests.cs +++ b/external/corefx/src/System.Runtime.Numerics/tests/ComplexTests.cs @@ -65,7 +65,7 @@ namespace System.Numerics.Tests } [Fact] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void SqrtMinusOne() { Assert.Equal(Complex.Sqrt(-1.0), Complex.ImaginaryOne); @@ -256,7 +256,7 @@ namespace System.Numerics.Tests [Theory] [MemberData(nameof(Abs_Advanced_TestData))] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void Abs_Advanced(double real, double imaginary, double expected) { var complex = new Complex(real, imaginary); @@ -325,7 +325,7 @@ namespace System.Numerics.Tests } [Theory, MemberData(nameof(ACos_Advanced_TestData))] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void ACos_Advanced(double real, double imaginary, double expectedReal, double expectedImaginary) { var complex = new Complex(real, imaginary); @@ -441,7 +441,7 @@ namespace System.Numerics.Tests } [Theory, MemberData(nameof(ASin_Advanced_TestData))] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void ASin_Advanced(double real, double imaginary, double expectedReal, double expectedImaginary) { var complex = new Complex(real, imaginary); @@ -591,7 +591,7 @@ namespace System.Numerics.Tests [Theory] [MemberData(nameof(Cos_Advanced_TestData_Shared))] [MemberData(nameof(Cos_Advanced_TestData))] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void Cos_Advanced(double real, double imaginary, double expectedReal, double expectedImaginary) { var complex = new Complex(real, imaginary); @@ -669,7 +669,7 @@ namespace System.Numerics.Tests [Theory] [MemberData(nameof(Cosh_Advanced_TestData_Shared))] [MemberData(nameof(Cosh_Advanced_TestData))] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void Cosh_Advanced(double real, double imaginary, double expectedReal, double expectedImaginary) { var complex = new Complex(real, imaginary); @@ -746,7 +746,7 @@ namespace System.Numerics.Tests } [Fact] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void Equals_netcore() { // Invalid values @@ -888,7 +888,7 @@ namespace System.Numerics.Tests [MemberData(nameof(Exp_TestData))] [MemberData(nameof(Primitives_2_TestData))] [MemberData(nameof(SmallRandom_2_TestData))] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void Exp(double real, double imaginary) { Complex expected; @@ -989,7 +989,7 @@ namespace System.Numerics.Tests [Theory] [MemberData(nameof(FromPolarCoordinates_TestData))] [MemberData(nameof(Invalid_2_TestData))] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void FromPolarCoordinates(double magnitude, double phase) { Complex complex = Complex.FromPolarCoordinates(magnitude, phase); @@ -1388,7 +1388,7 @@ namespace System.Numerics.Tests [Theory] [MemberData(nameof(Sin_Advanced_TestData_Shared))] [MemberData(nameof(Sin_Advanced_TestData))] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void Sin_Advanced(double real, double imaginary, double expectedReal, double expectedImaginary) { var complex = new Complex(real, imaginary); @@ -1465,7 +1465,7 @@ namespace System.Numerics.Tests [Theory] [MemberData(nameof(Sinh_Advanced_TestData_Shared))] [MemberData(nameof(Sinh_Advanced_TestData))] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void Sinh_Advanced(double real, double imaginary, double expectedReal, double expectedImaginary) { var complex = new Complex(real, imaginary); @@ -1588,7 +1588,7 @@ namespace System.Numerics.Tests [Theory] [MemberData(nameof(Sqrt_AdvancedTestData))] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void Sqrt_Advanced(double real, double imaginary, double expectedReal, double expectedImaginary) { var complex = new Complex(real, imaginary); @@ -1659,7 +1659,7 @@ namespace System.Numerics.Tests } [Theory, MemberData(nameof(Tan_Advanced_TestData))] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void Tan_Advanced(double real, double imaginary, double expectedReal, double expectedImaginary) { var complex = new Complex(real, imaginary); @@ -1732,7 +1732,7 @@ namespace System.Numerics.Tests } [Theory, MemberData(nameof(Tanh_Advanced_TestData))] - [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)] public static void Tanh_Advanced(double real, double imaginary, double expectedReal, double expectedImaginary) { var complex = new Complex(real, imaginary); diff --git a/external/corefx/src/System.Runtime/tests/System.Runtime.Tests.csproj b/external/corefx/src/System.Runtime/tests/System.Runtime.Tests.csproj index 8c5b158bdd..f8bc27a627 100644 --- a/external/corefx/src/System.Runtime/tests/System.Runtime.Tests.csproj +++ b/external/corefx/src/System.Runtime/tests/System.Runtime.Tests.csproj @@ -1,23 +1,11 @@ - - - + {B1BF7CE0-CAB5-4FA2-A39C-450B05D5DB1C} true 1718 - $(DefineConstants);netcoreapp - $(DefineConstants);uapaot - - $(MSBuildProjectDirectory)\App.config + netcoreapp-Debug;netcoreapp-Release;netfx-Debug;netfx-Release;netstandard-Debug;netstandard-Release;uap-Debug;uap-Release;uapaot-Debug;uapaot-Release + true - - - - - - - - Common\System\EnumTypes.cs @@ -46,17 +34,35 @@ Common\System\IO\TempFile.cs - - Common\System\Reflection\MockParameterInfo.cs + + System\StringTests.cs + + + System\SpanTestHelpers.cs + + + Common\System\Collections\IDictionary.NonGeneric.Tests.cs + + + Common\System\Collections\IList.NonGeneric.Tests.cs + + + Common\System\Collections\ICollection.NonGeneric.Tests.cs + + + Common\System\Collections\IEnumerable.NonGeneric.Tests.cs - - + + + + + @@ -70,48 +76,64 @@ + + + + + + + + + + + + + + + + + - + - @@ -125,6 +147,7 @@ + @@ -135,7 +158,6 @@ - @@ -144,25 +166,17 @@ - - - - - - - - @@ -170,17 +184,24 @@ + + + + + + + Common\System\RandomDataGenerator.cs - + @@ -192,6 +213,7 @@ + @@ -201,9 +223,10 @@ + + - @@ -213,23 +236,30 @@ + - - + + + + + + System\SpanExtensions.netstandard.cs + + Common\System\Collections\IEnumerable.Generic.Serialization.Tests.cs @@ -241,7 +271,7 @@ System.Reflection.Tests.EmbeddedTextFile.txt - System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs + Common\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs {69e46a6f-9966-45a5-8945-2559fe337827} @@ -274,5 +304,4 @@ - - + \ No newline at end of file diff --git a/external/corefx/src/System.Runtime/tests/System/Reflection/ConstructorInfoTests.cs b/external/corefx/src/System.Runtime/tests/System/Reflection/ConstructorInfoTests.cs deleted file mode 100644 index 912a40e6b3..0000000000 --- a/external/corefx/src/System.Runtime/tests/System/Reflection/ConstructorInfoTests.cs +++ /dev/null @@ -1,249 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Xunit; - -namespace System.Reflection.Tests -{ - public static class ConstructorInfoTests - { - public static IEnumerable Equality_TestData() - { - ConstructorInfo[] methodSampleConstructors1 = GetConstructors(typeof(ConstructorInfoInvokeSample)); - ConstructorInfo[] methodSampleConstructors2 = GetConstructors(typeof(ConstructorInfoInvokeSample)); - yield return new object[] { methodSampleConstructors1[0], methodSampleConstructors2[0], true }; - yield return new object[] { methodSampleConstructors1[1], methodSampleConstructors2[1], true }; - yield return new object[] { methodSampleConstructors1[2], methodSampleConstructors2[2], true }; - yield return new object[] { methodSampleConstructors1[1], methodSampleConstructors2[2], false }; - } - - [Theory] - [MemberData(nameof(Equality_TestData))] - public static void Test_Equality(ConstructorInfo constructorInfo1, ConstructorInfo constructorInfo2, bool expected) - { - Assert.Equal(expected, constructorInfo1 == constructorInfo2); - Assert.NotEqual(expected, constructorInfo1 != constructorInfo2); - } - - [Fact] - public static void Verify_Invoke_ReturnsNewObject() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); - Assert.Equal(cis.Length, 3); - ConstructorInfoInvokeSample obj = (ConstructorInfoInvokeSample)cis[0].Invoke(null); - Assert.NotNull(obj); - } - - [Fact] - [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Invoking static constructors not supported on UapAot")] - public static void TestInvoke_Nullery() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoClassA)); - Object obj = cis[0].Invoke(null, new object[] { }); - Assert.Null(obj); - } - - [Fact] - public static void TestInvokeNeg() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoClassA)); - Object obj = null; - Assert.Throws(() => { obj = cis[0].Invoke(new object[] { }); }); - Assert.Null(obj); - } - - [Fact] - public static void TestInvoke_1DArray() - { - ConstructorInfo[] cis = GetConstructors(typeof(System.Object[])); - object[] arr = null; - //Test data for array length - int[] arraylength = { 1, 2, 99, 65535 }; - - //try to invoke Array ctors with different lengths - foreach (int length in arraylength) - { - //create big Array with elements - arr = (object[])cis[0].Invoke(new Object[] { length }); - Assert.NotNull(arr); - Assert.Equal(arr.Length, length); - } - } - - [Fact] - public static void TestInvoke_1DArrayWithNegativeLength() - { - ConstructorInfo[] cis = GetConstructors(typeof(System.Object[])); - object[] arr = null; - //Test data for array length - int[] arraylength = { -1, -2, -99 }; - //try to invoke Array ctors with different lengths - foreach (int length in arraylength) - { - //create big Array with elements - Assert.Throws(() => { arr = (object[])cis[0].Invoke(new Object[] { length }); }); - } - } - - [Fact] - public static void TestInvokeWithOneParam() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); - //try to invoke Array ctors with one param - ConstructorInfoInvokeSample obj = null; - obj = (ConstructorInfoInvokeSample)cis[1].Invoke(new object[] { 100 }); - - Assert.NotNull(obj); - Assert.Equal(obj.intValue, 100); - } - - [Fact] - public static void TestInvokeWithTwoParams() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); - //try to invoke Array ctors with one param - ConstructorInfoInvokeSample obj = null; - obj = (ConstructorInfoInvokeSample)cis[2].Invoke(new object[] { 101, "hello" }); - - Assert.NotNull(obj); - Assert.Equal(obj.intValue, 101); - Assert.Equal(obj.strValue, "hello"); - } - - [Fact] - public static void TestInvoke_NoParamsProvided() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); - //try to invoke Array ctors with one param - ConstructorInfoInvokeSample obj = null; - Assert.Throws(() => { obj = (ConstructorInfoInvokeSample)cis[2].Invoke(new object[] { }); }); - } - - [Fact] - public static void TestInvoke_ParamMismatch() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); - //try to invoke Array ctors with one param - ConstructorInfoInvokeSample obj = null; - Assert.Throws(() => { obj = (ConstructorInfoInvokeSample)cis[2].Invoke(new object[] { 121 }); }); - } - - [Fact] - public static void TestInvoke_WrongParamType() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); - //try to invoke Array ctors with one param - ConstructorInfoInvokeSample obj = null; - AssertExtensions.Throws(null, () => { obj = (ConstructorInfoInvokeSample)cis[1].Invoke(new object[] { "hello" }); }); - } - - [Fact] - public static void TestInvoke_ConstructorOnExistingInstance() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); - //try to invoke Array ctors with one param - ConstructorInfoInvokeSample obj1 = new ConstructorInfoInvokeSample(100, "hello"); - ConstructorInfoInvokeSample obj2 = null; - obj2 = (ConstructorInfoInvokeSample)cis[2].Invoke(obj1, new object[] { 999, "initialized" }); - Assert.Null(obj2); - Assert.Equal(obj1.intValue, 999); - Assert.Equal(obj1.strValue, "initialized"); - } - - [Fact] - public static void TestInvoke_AbstractConstructor() - { - ConstructorInfo[] cis = GetConstructors(typeof(Base)); - Object obj = null; - Assert.Throws(() => { obj = (Base)cis[0].Invoke(new object[] { }); }); - } - - [Fact] - public static void TestInvoke_DerivedConstructor() - { - ConstructorInfo[] cis = GetConstructors(typeof(Derived)); - Derived obj = null; - obj = (Derived)cis[0].Invoke(new object[] { }); - Assert.NotNull(obj); - } - - [Fact] - public static void TestInvoke_Struct() - { - ConstructorInfo[] cis = GetConstructors(typeof(MyStruct)); - MyStruct obj; - obj = (MyStruct)cis[0].Invoke(new object[] { 1, 2 }); - Assert.NotNull(obj); - Assert.Equal(obj.x, 1); - Assert.Equal(obj.y, 2); - } - - public static ConstructorInfo[] GetConstructors(Type type) - { - return type.GetTypeInfo().DeclaredConstructors.ToArray(); - } - } - - //Metadata for Reflection - public class ConstructorInfoInvokeSample - { - public int intValue = 0; - public string strValue = ""; - - public ConstructorInfoInvokeSample() { } - - public ConstructorInfoInvokeSample(int i) - { - this.intValue = i; - } - - public ConstructorInfoInvokeSample(int i, string s) - { - this.intValue = i; - this.strValue = s; - } - - public string Method1(DateTime t) - { - return ""; - } - } - - public static class ConstructorInfoClassA - { - static ConstructorInfoClassA() - { - } - } - - public abstract class Base - { - public Base() - { - } - } - - public class Derived : Base - { - public Derived() - { - } - } - - public struct MyStruct - { - public int x; - public int y; - - public MyStruct(int p1, int p2) - { - x = p1; - y = p2; - } - }; -} diff --git a/external/corefx/src/System.Runtime/tests/System/Reflection/EventInfoTests.cs b/external/corefx/src/System.Runtime/tests/System/Reflection/EventInfoTests.cs deleted file mode 100644 index f43d9fcdff..0000000000 --- a/external/corefx/src/System.Runtime/tests/System/Reflection/EventInfoTests.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Reflection; -using Xunit; - -namespace System.Reflection.Tests -{ - public static class EventInfoTests - { - public static IEnumerable Equality_TestData() - { - yield return new object[] { GetEventInfo(typeof(BaseClass), "EventPublic"), GetEventInfo(typeof(BaseClass), "EventPublic"), true }; - yield return new object[] { GetEventInfo(typeof(BaseClass), "EventPublic"), GetEventInfo(typeof(SubClass), "EventPublic"), false }; - yield return new object[] { GetEventInfo(typeof(BaseClass), "EventPublic"), GetEventInfo(typeof(BaseClass), "EventPublicStatic"), false }; - } - - [Theory] - [MemberData(nameof(Equality_TestData))] - public static void Test_Equality(EventInfo constructorInfo1, EventInfo constructorInfo2, bool expected) - { - Assert.Equal(expected, constructorInfo1 == constructorInfo2); - Assert.NotEqual(expected, constructorInfo1 != constructorInfo2); - } - - //private helper methods - private static EventInfo GetEventInfo(Type t, string eventName) - { - TypeInfo ti = t.GetTypeInfo(); - IEnumerator allevents = ti.DeclaredEvents.GetEnumerator(); - EventInfo eventFound = null; - while (allevents.MoveNext()) - { - if (eventName.Equals(allevents.Current.Name)) - { - eventFound = allevents.Current; - break; - } - } - return eventFound; - } - } - -#pragma warning disable 0067 // the event was declared but never used - // Metadata for Reflection - public class BaseClass - { - public event EventHandler EventPublic; // inherited - public static event EventHandler EventPublicStatic; - } - - public class SubClass : BaseClass - { - public new event EventHandler EventPublic; //overrides event - } -#pragma warning restore 0067 -} \ No newline at end of file diff --git a/external/corefx/src/System.Runtime/tests/System/Reflection/FieldInfoTests.cs b/external/corefx/src/System.Runtime/tests/System/Reflection/FieldInfoTests.cs deleted file mode 100644 index f18d429516..0000000000 --- a/external/corefx/src/System.Runtime/tests/System/Reflection/FieldInfoTests.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Reflection; -using Xunit; - -namespace System.Reflection.Tests -{ - public class FieldInfoTests - { - [Theory] - [InlineData("nonstatic_strField", "nonstatic_strField", true)] - [InlineData("nonstatic_strField", "intFieldStatic", false)] - public static void TestEquality_EqualAndNotEqualFields(string fieldName1, string fieldName2, bool expected) - { - FieldInfo info1 = GetField(fieldName1); - FieldInfo info2 = GetField(fieldName2); - - Assert.NotNull(info1); - Assert.NotNull(info2); - Assert.Equal(expected, info1 == info2); - Assert.NotEqual(expected, info1 != info2); - } - - [Fact] - public static void Test_SecurityAttributes() - { - FieldInfo info = GetField("intFieldStatic"); - - Assert.True(info.IsSecurityCritical); - Assert.False(info.IsSecuritySafeCritical); - Assert.False(info.IsSecurityTransparent); - } - - // Helper method to get field from Type type - private static FieldInfo GetField(string fieldName) - { - Type t = typeof(FieldInfoTests); - TypeInfo ti = t.GetTypeInfo(); - IEnumerator alldefinedFields = ti.DeclaredFields.GetEnumerator(); - FieldInfo fi = null, found = null; - - while (alldefinedFields.MoveNext()) - { - fi = alldefinedFields.Current; - if (fi.Name.Equals(fieldName)) - { - //found type - found = fi; - break; - } - } - return found; - } - - // Fields for Reflection - public static int intFieldStatic = 100; - public int intFieldNonStatic = 101; - public static string static_strField = "Static string field"; - public string nonstatic_strField = "NonStatic string field"; - } -} \ No newline at end of file diff --git a/external/corefx/src/System.Runtime/tests/System/Reflection/MemberInfoTests.cs b/external/corefx/src/System.Runtime/tests/System/Reflection/MemberInfoTests.cs deleted file mode 100644 index 78a7deb8d3..0000000000 --- a/external/corefx/src/System.Runtime/tests/System/Reflection/MemberInfoTests.cs +++ /dev/null @@ -1,256 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; -using Xunit; - -namespace System.Reflection.Tests -{ - public class MemberInfoTests - { - [Fact] - public static void TestReflectedType() - { - Type t = typeof(Derived); - MemberInfo[] members = t.GetMembers(); - foreach (MemberInfo member in members) - { - Assert.Equal(t, member.ReflectedType); - } - } - - [Fact] - public static void TestPropertyReflectedType() - { - Type t = typeof(Base); - PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1)); - Assert.Equal(t, p.ReflectedType); - Assert.NotNull(p.GetMethod); - Assert.NotNull(p.SetMethod); - } - - [Fact] - public static void TestInheritedPropertiesHidePrivateAccessorMethods() - { - Type t = typeof(Derived); - PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1)); - Assert.Equal(t, p.ReflectedType); - Assert.NotNull(p.GetMethod); - Assert.Null(p.SetMethod); - } - - [Fact] - public static void TestGenericMethodsInheritTheReflectedTypeOfTheirTemplate() - { - Type t = typeof(Derived); - MethodInfo moo = t.GetMethod("Moo"); - Assert.Equal(t, moo.ReflectedType); - MethodInfo mooInst = moo.MakeGenericMethod(typeof(int)); - Assert.Equal(t, mooInst.ReflectedType); - } - - [Fact] - public static void TestDeclaringMethodOfTypeParametersOfInheritedMethods() - { - Type t = typeof(Derived); - MethodInfo moo = t.GetMethod("Moo"); - Assert.Equal(t, moo.ReflectedType); - Type theM = moo.GetGenericArguments()[0]; - MethodBase moo1 = theM.DeclaringMethod; - Type reflectedTypeOfMoo1 = moo1.ReflectedType; - Assert.Equal(typeof(Base), reflectedTypeOfMoo1); - } - - [Fact] - public static void TestDeclaringMethodOfTypeParametersOfInheritedMethods2() - { - Type t = typeof(GDerived); - MethodInfo moo = t.GetMethod("Moo"); - Assert.Equal(t, moo.ReflectedType); - Type theM = moo.GetGenericArguments()[0]; - MethodBase moo1 = theM.DeclaringMethod; - Type reflectedTypeOfMoo1 = moo1.ReflectedType; - Assert.Equal(typeof(GBase<>), reflectedTypeOfMoo1); - } - - [Fact] - public static void TestInheritedPropertyAccessors() - { - Type t = typeof(Derived); - PropertyInfo p = t.GetProperty(nameof(Base.MyProperty)); - MethodInfo getter = p.GetMethod; - MethodInfo setter = p.SetMethod; - Assert.Equal(t, getter.ReflectedType); - Assert.Equal(t, setter.ReflectedType); - } - - [Fact] - public static void TestInheritedEventAccessors() - { - Type t = typeof(Derived); - EventInfo e = t.GetEvent(nameof(Base.MyEvent)); - MethodInfo adder = e.AddMethod; - MethodInfo remover = e.RemoveMethod; - Assert.Equal(t, adder.ReflectedType); - Assert.Equal(t, remover.ReflectedType); - } - - [Fact] - public static void TestReflectedTypeIsPartOfIdentity() - { - Type b = typeof(Base); - Type d = typeof(Derived); - - { - EventInfo e = b.GetEvent(nameof(Base.MyEvent)); - EventInfo ei = d.GetEvent(nameof(Derived.MyEvent)); - Assert.False(e.Equals(ei)); - } - - { - FieldInfo f = b.GetField(nameof(Base.MyField)); - FieldInfo fi = d.GetField(nameof(Derived.MyField)); - Assert.False(f.Equals(fi)); - } - - { - MethodInfo m = b.GetMethod(nameof(Base.Moo)); - MethodInfo mi = d.GetMethod(nameof(Derived.Moo)); - Assert.False(m.Equals(mi)); - } - - { - PropertyInfo p = b.GetProperty(nameof(Base.MyProperty)); - PropertyInfo pi = d.GetProperty(nameof(Derived.MyProperty)); - Assert.False(p.Equals(pi)); - } - } - - [Fact] - public static void TestFieldInfoReflectedTypeDoesNotSurviveRuntimeHandles() - { - Type t = typeof(Derived); - FieldInfo f = t.GetField(nameof(Base.MyField)); - Assert.Equal(typeof(Derived), f.ReflectedType); - RuntimeFieldHandle h = f.FieldHandle; - FieldInfo f2 = FieldInfo.GetFieldFromHandle(h); - Assert.Equal(typeof(Base), f2.ReflectedType); - } - - [Fact] - public static void TestMethodInfoReflectedTypeDoesNotSurviveRuntimeHandles() - { - Type t = typeof(Derived); - MethodInfo m = t.GetMethod(nameof(Base.Moo)); - Assert.Equal(typeof(Derived), m.ReflectedType); - RuntimeMethodHandle h = m.MethodHandle; - MethodBase m2 = MethodBase.GetMethodFromHandle(h); - Assert.Equal(typeof(Base), m2.ReflectedType); - } - - [Fact] - public void TestGetCustomAttributesData() - { - MemberInfo[] m = typeof(MemberInfoTests).GetMember("SampleClass"); - Assert.Equal(1, m.Count()); - foreach(CustomAttributeData cad in m[0].GetCustomAttributesData()) - { - if (cad.AttributeType == typeof(ComVisibleAttribute)) - { - ConstructorInfo c = cad.Constructor; - Assert.False(c.IsStatic); - Assert.Equal(typeof(ComVisibleAttribute), c.DeclaringType); - ParameterInfo[] p = c.GetParameters(); - Assert.Equal(1, p.Length); - Assert.Equal(typeof(bool), p[0].ParameterType); - return; - } - } - - Assert.True(false, "Expected to find ComVisibleAttribute"); - } - - public static IEnumerable EqualityOperator_TestData() - { - yield return new object[] { typeof(SampleClass) }; - yield return new object[] { new MemberInfoTests().GetType() }; - yield return new object[] { typeof(int) }; - yield return new object[] { typeof(Dictionary<,>) }; - } - - [Theory] - [MemberData(nameof(EqualityOperator_TestData))] - public void EqualityOperator_Equal_ReturnsTrue(Type type) - { - MemberInfo[] members1 = GetOrderedMembers(type); - MemberInfo[] members2 = GetOrderedMembers(type); - - Assert.Equal(members1.Length, members2.Length); - for (int i = 0; i < members1.Length; i++) - { - Assert.True(members1[i] == members2[i]); - Assert.False(members1[i] != members2[i]); - } - } - - private MemberInfo[] GetOrderedMembers(Type type) => GetMembers(type).OrderBy(member => member.Name).ToArray(); - - private MemberInfo[] GetMembers(Type type) - { - return type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - } - - private class Base - { - public event Action MyEvent { add { } remove { } } -#pragma warning disable 0649 - public int MyField; -#pragma warning restore 0649 - public int MyProperty { get; set; } - - public int MyProperty1 { get; private set; } - public int MyProperty2 { private get; set; } - - public void Moo() { } - } - - private class Derived : Base - { - } - - private class GBase - { - public void Moo() { } - } - - private class GDerived : GBase - { - } - -#pragma warning disable 0067, 0169 - [ComVisible(false)] - public class SampleClass - { - public int PublicField; - private int PrivateField; - - public SampleClass(bool y) { } - private SampleClass(int x) { } - - public void PublicMethod() { } - private void PrivateMethod() { } - - public int PublicProp { get; set; } - private int PrivateProp { get; set; } - - public event EventHandler PublicEvent; - private event EventHandler PrivateEvent; - } -#pragma warning restore 0067, 0169 - } -} \ No newline at end of file diff --git a/external/corefx/src/System.Runtime/tests/System/Reflection/ModuleTests.cs b/external/corefx/src/System.Runtime/tests/System/Reflection/ModuleTests.cs index 71de569377..498468cb2a 100644 --- a/external/corefx/src/System.Runtime/tests/System/Reflection/ModuleTests.cs +++ b/external/corefx/src/System.Runtime/tests/System/Reflection/ModuleTests.cs @@ -75,7 +75,9 @@ namespace System.Reflection.Tests Assert.Equal(1, complicatedAttribute.NamedArguments.Count); Assert.Equal(false, complicatedAttribute.NamedArguments[0].IsField); Assert.Equal("Stuff", complicatedAttribute.NamedArguments[0].MemberName); +#if !MONO // Mono issue #11572 Assert.Equal(typeof(ComplicatedAttribute).GetProperty("Stuff"), complicatedAttribute.NamedArguments[0].MemberInfo); +#endif Assert.Equal(typeof(int), complicatedAttribute.NamedArguments[0].TypedValue.ArgumentType); Assert.Equal(2, complicatedAttribute.NamedArguments[0].TypedValue.Value); } @@ -91,7 +93,11 @@ namespace System.Reflection.Tests [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.Name does not indicate file location on UwpAot")] public void Name() { +#if MONO + Assert.EndsWith("corlib_xunit-test.dll", Module.Name); +#else Assert.Equal("system.runtime.tests.dll", Module.Name, ignoreCase: true); +#endif } [Fact] @@ -110,7 +116,6 @@ namespace System.Reflection.Tests [Theory] [InlineData(typeof(ModuleTests))] [InlineData(typeof(PointerTests))] - [InlineData(typeof(EventInfoTests))] public void TestGetType(Type type) { Assert.Equal(type, Module.GetType(type.FullName, true, true)); @@ -120,7 +125,11 @@ namespace System.Reflection.Tests [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.ToString() does not indicate file location on UwpAot")] public void TestToString() { +#if MONO + Assert.EndsWith("corlib_xunit-test.dll", Module.ToString()); +#else Assert.Equal("System.Runtime.Tests.dll", Module.ToString()); +#endif } [Fact] @@ -153,7 +162,7 @@ namespace System.Reflection.Tests Assert.NotNull(ex.Message); } - [Fact] + [Fact(Skip="Mono issue")] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.GetField apis not supported on UapAot.")] public void GetField() { @@ -167,7 +176,7 @@ namespace System.Reflection.Tests Assert.Equal(200L, (long)testLong.GetValue(null)); } - [Fact] + [Fact(Skip="Mono issue")] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.GetField apis not supported on UapAot.")] public void GetFields() { @@ -306,7 +315,7 @@ namespace System.Reflection.Tests Assert.Equal(method, actual); } - [Fact] + [Fact(Skip="Mono issue")] public void GetTypes() { List types = TestModule.GetTypes().ToList(); diff --git a/external/corefx/src/System.Runtime/tests/System/Reflection/ParameterInfoTests.cs b/external/corefx/src/System.Runtime/tests/System/Reflection/ParameterInfoTests.cs deleted file mode 100644 index 6b51c65deb..0000000000 --- a/external/corefx/src/System.Runtime/tests/System/Reflection/ParameterInfoTests.cs +++ /dev/null @@ -1,181 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.Serialization; -using Xunit; - -namespace System.Reflection.Tests -{ - public static class ParameterInfoTests - { - [Fact] - public static void RawDefaultValue() - { - MethodInfo m = GetMethod(typeof(ParameterInfoTests), "Foo1"); - ParameterInfo p = m.GetParameters()[0]; - object raw = p.RawDefaultValue; - Assert.Equal(typeof(int), raw.GetType()); - Assert.Equal((int)raw, (int)BindingFlags.DeclaredOnly); - } - - [Fact] - public static void RawDefaultValueFromAttribute() - { - MethodInfo m = GetMethod(typeof(ParameterInfoTests), "Foo2"); - ParameterInfo p = m.GetParameters()[0]; - object cooked = p.DefaultValue; - object raw = p.RawDefaultValue; - - Assert.Equal(typeof(int), raw.GetType()); - Assert.Equal((int)raw, (int)BindingFlags.IgnoreCase); - } - - [Fact] - public static void RawDefaultValue_MetadataTrumpsAttribute() - { - MethodInfo m = GetMethod(typeof(ParameterInfoTests), "Foo3"); - ParameterInfo p = m.GetParameters()[0]; - object cooked = p.DefaultValue; - object raw = p.RawDefaultValue; - - Assert.Equal(typeof(int), raw.GetType()); - Assert.Equal((int)raw, (int)BindingFlags.FlattenHierarchy); - } - - [Fact] - public static void VerifyGetCustomAttributesData() - { - MethodInfo m = GetMethod(typeof(MyClass), "Method1"); - ParameterInfo p = m.GetParameters()[0]; - - foreach (CustomAttributeData cad in p.GetCustomAttributesData()) - { - if(cad.AttributeType == typeof(MyAttribute)) - { - ConstructorInfo c = cad.Constructor; - Assert.False(c.IsStatic); - Assert.False(c.IsPublic); - ParameterInfo[] paramInfo = c.GetParameters(); - Assert.Equal(1, paramInfo.Length); - Assert.Equal(typeof(int), paramInfo[0].ParameterType); - return; - } - } - - Assert.True(false, "Expected to find MyAttribute"); - } - - [Theory] - [MemberData(nameof(VerifyParameterInfoGetRealObjectWorks_TestData))] - public static void VerifyParameterInfoGetRealObjectWorks(MemberInfo pretendMember, int pretendPosition, string expectedParameterName) - { - // Regression test for https://github.com/dotnet/corefx/issues/20574 - // - // It's easy to forget that ParameterInfo's and runtime-implemented ParameterInfo's are different objects and just because the - // latter doesn't support serialization doesn't mean other providers won't either. - // - // For historical reasons, ParameterInfo contains some serialization support that subtypes can optionally hang off. This - // test ensures that support doesn't get vaporized. - - // Just pretend that we're BinaryFormatter and are deserializing a Parameter... - IObjectReference podParameter = new PodPersonParameterInfo(pretendMember, pretendPosition); - StreamingContext sc = new StreamingContext(StreamingContextStates.Clone); - ParameterInfo result = (ParameterInfo)(podParameter.GetRealObject(sc)); - - Assert.Equal(pretendPosition, result.Position); - Assert.Equal(expectedParameterName, result.Name); - Assert.Equal(pretendMember.Name, result.Member.Name); - } - - public static IEnumerable VerifyParameterInfoGetRealObjectWorks_TestData - { - get - { - Type t = typeof(PretendParent); - ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(int), typeof(int) }); - MethodInfo method = t.GetMethod(nameof(PretendParent.PretendMethod)); - PropertyInfo property = t.GetProperty("Item"); - - yield return new object[] { ctor, 0, "a" }; - yield return new object[] { ctor, 1, "b" }; - yield return new object[] { method, -1, null }; - yield return new object[] { method, 0, "x" }; - yield return new object[] { method, 1, "y" }; - yield return new object[] { property, 0, "index1" }; - yield return new object[] { property, 1, "index2" }; - } - } - - private sealed class PretendParent - { - public PretendParent(int a, int b) { } - public void PretendMethod(int x, int y) { } - public int this[int index1, int index2] { get { throw null; } } - } - - private sealed class PodPersonParameterInfo : MockParameterInfo - { - public PodPersonParameterInfo(MemberInfo pretendMember, int pretendPosition) - { - // Serialization can recreate a ParameterInfo from just these two pieces of data. Of course, this is just a test and no one - // ever told this Member that it was adopting a counterfeit Parameter, but this is just a test... - MemberImpl = pretendMember; - PositionImpl = pretendPosition; - } - } - - private static void Foo1(BindingFlags bf = BindingFlags.DeclaredOnly) { } - - private static void Foo2([CustomBindingFlags(Value = BindingFlags.IgnoreCase)] BindingFlags bf) { } - - private static void Foo3([CustomBindingFlags(Value = BindingFlags.DeclaredOnly)] BindingFlags bf = BindingFlags.FlattenHierarchy ) { } - - //Gets MethodInfo object from a Type - public static MethodInfo GetMethod(Type t, string method) - { - TypeInfo ti = t.GetTypeInfo(); - IEnumerator alldefinedMethods = ti.DeclaredMethods.GetEnumerator(); - MethodInfo mi = null; - - while (alldefinedMethods.MoveNext()) - { - if (alldefinedMethods.Current.Name.Equals(method)) - { - //found method - mi = alldefinedMethods.Current; - break; - } - } - return mi; - } - - // Class For Reflection Metadata - public class MyClass - { - public void Method1([My(2)]String str, int iValue, long lValue) - { - } - } - - private class MyAttribute : Attribute - { - internal MyAttribute(int i) { } - } - } - - internal sealed class CustomBindingFlagsAttribute : UsableCustomConstantAttribute - { - public new object Value { get { return RealValue; } set { RealValue = value; } } - } - - internal abstract class UsableCustomConstantAttribute : CustomConstantAttribute - { - public sealed override object Value => RealValue; - protected object RealValue { get; set; } - } -} \ No newline at end of file diff --git a/external/corefx/src/System.Runtime/tests/System/Reflection/PointerTests.cs b/external/corefx/src/System.Runtime/tests/System/Reflection/PointerTests.cs index 731a9ef48f..1a63f2acd4 100644 --- a/external/corefx/src/System.Runtime/tests/System/Reflection/PointerTests.cs +++ b/external/corefx/src/System.Runtime/tests/System/Reflection/PointerTests.cs @@ -84,7 +84,7 @@ namespace System.Reflection.Tests new object[] { int.MinValue }, }; - [Theory] + [Theory(Skip="Mono issue")] [MemberData(nameof(Pointers))] public void PointerFieldSetValue(int value) { @@ -103,7 +103,7 @@ namespace System.Reflection.Tests Assert.Equal(0, unchecked((int)obj.field)); } - [Theory] + [Theory(Skip="Mono issue")] [MemberData(nameof(Pointers))] public void IntPtrFieldSetValue(int value) { @@ -125,7 +125,7 @@ namespace System.Reflection.Tests }); } - [Theory] + [Theory(Skip="Mono issue")] [MemberData(nameof(Pointers))] public void PointerFieldGetValue(int value) { @@ -138,7 +138,7 @@ namespace System.Reflection.Tests Assert.Equal(value, unchecked((int)actualPointer)); } - [Theory] + [Theory(Skip="Mono issue")] [MemberData(nameof(Pointers))] public void PointerPropertySetValue(int value) { @@ -170,7 +170,7 @@ namespace System.Reflection.Tests }); } - [Theory] + [Theory(Skip="Mono issue")] [MemberData(nameof(Pointers))] public void PointerPropertyGetValue(int value) { @@ -183,7 +183,7 @@ namespace System.Reflection.Tests Assert.Equal(value, unchecked((int)actualPointer)); } - [Theory] + [Theory(Skip="Mono issue")] [MemberData(nameof(Pointers))] public void PointerMethodParameter(int value) { @@ -233,7 +233,7 @@ namespace System.Reflection.Tests Assert.Equal(value, unchecked((int)actualPointer)); } - [Theory] + [Theory(Skip="Mono issue")] [MemberData(nameof(Pointers))] public void PointerMethodDelegateParameter(int value) { diff --git a/external/corefx/src/System.Runtime/tests/System/Reflection/PropertyInfoTests.cs b/external/corefx/src/System.Runtime/tests/System/Reflection/PropertyInfoTests.cs deleted file mode 100644 index 794a2e8e94..0000000000 --- a/external/corefx/src/System.Runtime/tests/System/Reflection/PropertyInfoTests.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Reflection; -using Xunit; - -namespace System.Reflection.Tests -{ - public static class PropertyInfoTests - { - [Fact] - public static void GetRawConstantValueOnProperty() - { - // - // Why does PropertyInfo expose a GetRawConstantValue property? - // - // - ECMA metadata has the ability to specify a "default value" for a property but C# has no way to generate it. - // - The CustomConstantAttribute class is not marked as usable on a property. - // - PropertyInfo f = typeof(TestClass).GetTypeInfo().GetDeclaredProperty(nameof(TestClass.MyProp)); - Assert.Throws(() => f.GetRawConstantValue()); - } - - [Fact] - public static void TestEquality_False() - { - PropertyInfo pi1 = typeof(SampleMethod).GetTypeInfo().GetProperty("MyPropAA"); - PropertyInfo pi2 = typeof(SampleMethod).GetTypeInfo().GetProperty("MyPropBB"); - - Assert.False(pi1 == pi2); - Assert.True(pi1 != pi2); - } - - [Fact] - public static void TestEquality_True() - { - PropertyInfo pi1 = typeof(SampleMethod).GetTypeInfo().GetProperty("MyPropAA"); - PropertyInfo pi2 = typeof(SampleMethod).GetTypeInfo().GetProperty("MyPropAA"); - - Assert.True(pi1 == pi2); - Assert.False(pi1 != pi2); - } - - private class TestClass - { - public static BindingFlags MyProp { get; } - } - - //Reflection Metadata - public class SampleMethod - { - public double m_PropBB = 1; - public short m_PropAA = 2; - //indexer Property - public string[] mystrings = { "abc", "def", "ghi", "jkl" }; - - public string this[int Index] - { - get - { - return mystrings[Index]; - } - set - { - mystrings[Index] = value; - } - } - - // MyPropAA - ReadWrite property - public String MyPropAA - { - get { return m_PropAA.ToString(); } - set { m_PropAA = Int16.Parse(value); } - } - - public double MyPropBB - { - get { return m_PropBB; } - set { m_PropBB = value; } - } - } - } -} \ No newline at end of file diff --git a/external/corefx/src/System.Runtime/tests/System/Reflection/RuntimeReflectionExtensionsTests.cs b/external/corefx/src/System.Runtime/tests/System/Reflection/RuntimeReflectionExtensionsTests.cs deleted file mode 100644 index c5330bd033..0000000000 --- a/external/corefx/src/System.Runtime/tests/System/Reflection/RuntimeReflectionExtensionsTests.cs +++ /dev/null @@ -1,206 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Xunit; - -namespace System.Reflection.Tests -{ - public class RuntimeReflectionExtensionsTests - { - [Fact] - public void GetMethodInfo() - { - Assert.Equal(typeof(RuntimeReflectionExtensionsTests).GetMethod("GetMethodInfo"), ((Action)GetMethodInfo).GetMethodInfo()); - } - - [Fact] - public void GetMethodInfoOnNull() => AssertExtensions.Throws("del", () => default(Action).GetMethodInfo()); - - [Fact] - public void GetRuntimeBaseDefinition() - { - MethodInfo derivedFoo = typeof(TestDerived).GetMethod(nameof(TestDerived.Foo)); - MethodInfo baseFoo = typeof(TestBase).GetMethod(nameof(TestBase.Foo)); - MethodInfo actual = derivedFoo.GetRuntimeBaseDefinition(); - Assert.Equal(baseFoo, actual); - } - - [Fact] - public void GetRuntimeBaseDefinitionOnNull() => - Assert.Throws(() => default(MethodInfo).GetRuntimeBaseDefinition()); - - private abstract class TestBase - { - public abstract void Foo(); - } - - private class TestDerived : TestBase - { - public override void Foo() { throw null; } - } - - [Fact] - public void GetRuntimeEvent() - { - Assert.Equal(typeof(TestType).GetEvent("StuffHappened"), typeof(TestType).GetRuntimeEvent("StuffHappened")); - } - - [Fact] - public void GetRuntimeEventOnNull() => AssertExtensions.Throws("type", () => default(Type).GetRuntimeEvent("")); - - [Fact] - public void GetRuntimeEventWithNull() => - Assert.Throws(null, () => typeof(TestType).GetRuntimeEvent(null)); - - [Fact] - public void GetRuntimeEventEmptyName() => Assert.Null(typeof(TestType).GetRuntimeEvent("")); - - [Fact] - public void GetRuntimeField() - { - Assert.Equal(typeof(TestType).GetField("_pizzaSize"), typeof(TestType).GetRuntimeField("_pizzaSize")); - } - - [Fact] - public void GetRuntimeFieldOnNull() => AssertExtensions.Throws("type", () => default(Type).GetRuntimeField("")); - - [Fact] - public void GetRuntimeFieldWithNull() => - Assert.Throws(null, () => typeof(TestType).GetRuntimeField(null)); - - [Fact] - public void GetRuntimeFieldEmptyName() => Assert.Null(typeof(TestType).GetRuntimeField("")); - - [Fact] - public void GetRuntimeMethod() - { - Assert.Equal(typeof(TestType).GetMethod("Flush"), typeof(TestType).GetRuntimeMethod("Flush", Array.Empty())); - } - - [Fact] - public void GetRuntimeMethodOnNull() => AssertExtensions.Throws("type", () => default(Type).GetRuntimeMethod("", Type.EmptyTypes)); - - [Fact] - public void GetRuntimeMethodWithNullName() => AssertExtensions.Throws("name", () => typeof(TestType).GetRuntimeMethod(null, Type.EmptyTypes)); - - [Fact] - public void GetRuntimeMethodWithNullTypes() => AssertExtensions.Throws("types", () => typeof(TestType).GetRuntimeMethod("", null)); - - [Fact] - public void GetRuntimeMethodEmptyName() => Assert.Null(typeof(TestType).GetRuntimeMethod("", Type.EmptyTypes)); - - [Fact] - public void GetRuntimeProperty() - { - Assert.Equal(typeof(TestType).GetProperty("Length"), typeof(TestType).GetRuntimeProperty("Length")); - } - - [Fact] - public void GetRuntimePropertyOnNull() => - AssertExtensions.Throws("type", () => default(Type).GetRuntimeProperty("")); - - [Fact] - public void GetRuntimePropertyWithNull() => - AssertExtensions.Throws("name", () => typeof(TestType).GetRuntimeProperty(null)); - - [Fact] - public void GetRuntimePropertyEmptyName() => Assert.Null(typeof(TestType).GetRuntimeProperty("")); - - [Fact] - public void GetRuntimeEvents() - { - List events = typeof(TestType).GetRuntimeEvents().ToList(); - Assert.Equal(1, events.Count); - Assert.Equal("StuffHappened", events[0].Name); - } - - [Fact] - public void GetRuntimeEventsOnNull() => AssertExtensions.Throws("type", () => default(Type).GetRuntimeEvents()); - - - [Fact] - public void GetRuntimeFields() - { - List fields = typeof(TestType).GetRuntimeFields().ToList(); - Assert.Equal(2, fields.Count); - List fieldNames = fields.Select(f => f.Name).ToList(); - Assert.Contains("StuffHappened", fieldNames); - Assert.Contains("_pizzaSize", fieldNames); - } - - [Fact] - public void GetRuntimeFieldsOnNull() => AssertExtensions.Throws("type", () => default(Type).GetRuntimeFields()); - - [Fact] - public void GetRuntimeMethods() - { - List methods = typeof(TestType).GetRuntimeMethods().ToList(); - List methodNames = methods.Select(m => m.Name).Distinct().ToList(); - Assert.Contains("remove_StuffHappened", methodNames); - Assert.Contains("add_StuffHappened", methodNames); - Assert.Contains("Equals", methodNames); - Assert.Contains("GetHashCode", methodNames); - Assert.Contains("ToString", methodNames); - Assert.Contains("get_CanRead", methodNames); - Assert.Contains("Read", methodNames); - } - - [Fact] - public void GetRuntimeMethodsOnNull() => AssertExtensions.Throws("type", () => default(Type).GetRuntimeMethods()); - - [Fact] - public void GetRuntimeProperties() - { - List properties = typeof(TestType).GetRuntimeProperties().ToList(); - List propertyNames = properties.Select(p => p.Name).Distinct().ToList(); - Assert.Equal(5, properties.Count); - Assert.Contains("Length", propertyNames); - Assert.Contains("Position", propertyNames); - Assert.Contains("CanRead", propertyNames); - Assert.Contains("CanWrite", propertyNames); - Assert.Contains("CanSeek", propertyNames); - } - - [Fact] - public void GetRuntimePropertiesOnNull() => - AssertExtensions.Throws("type", () => default(Type).GetRuntimeProperties()); - - [Fact] - public void GetRuntimeInterfaceMap() - { - InterfaceMapping map = typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(IDisposable)); - Assert.Same(typeof(TestType), map.TargetType); - Assert.Same(typeof(IDisposable), map.InterfaceType); - Assert.Equal(1, map.InterfaceMethods.Length); - Assert.Equal(1, map.TargetMethods.Length); - MethodInfo ifaceDispose = map.InterfaceMethods[0]; - MethodInfo targetDispose = map.TargetMethods[0]; - Assert.Equal(ifaceDispose.CallingConvention, targetDispose.CallingConvention); - Assert.Equal(ifaceDispose.Name, targetDispose.Name); - Assert.Same(ifaceDispose.ReturnType, targetDispose.ReturnType); - Assert.Equal(ifaceDispose.GetParameters().Length, targetDispose.GetParameters().Length); - Assert.Same(typeof(TestTypeBase), targetDispose.DeclaringType); - Assert.Same(typeof(IDisposable), ifaceDispose.DeclaringType); - } - - [Fact] - public void GetRuntimeInterfaceMapOnNull() => - AssertExtensions.Throws("typeInfo", () => default(TypeInfo).GetRuntimeInterfaceMap(typeof(ICloneable))); - - [Fact] - public void GetRuntimeInterfaceMapWithNull() => - AssertExtensions.Throws("ifaceType", () => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(null)); - - [Fact] - public void GetRuntimeInterfaceMapNotImplemented() => - Assert.Throws(() => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(ICloneable))); - - [Fact] - public void GetRuntimeInterfaceMapNotInterface() => - Assert.Throws(() => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(string))); - } -} diff --git a/external/corefx/src/System.Runtime/tests/System/Reflection/TypeInfoTests.cs b/external/corefx/src/System.Runtime/tests/System/Reflection/TypeInfoTests.cs deleted file mode 100644 index ed3c620f59..0000000000 --- a/external/corefx/src/System.Runtime/tests/System/Reflection/TypeInfoTests.cs +++ /dev/null @@ -1,263 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Xunit; - -namespace System.Reflection.Tests -{ - public abstract class TestTypeBase : IDisposable - { - public abstract bool CanRead { get; } - public abstract bool CanWrite { get; } - public abstract bool CanSeek { get; } - public abstract long Length { get; } - public abstract long Position { get; set; } - - public virtual Task FlushAsync() - { - throw null; - } - - public abstract void Flush(); - - public virtual Task ReadAsync(byte[] buffer, int offset, int count) - { - throw null; - } - - public abstract int Read(byte[] buffer, int offset, int count); - - public abstract long Seek(long offset, SeekOrigin origin); - - public abstract void SetLength(long value); - - public abstract void Write(byte[] buffer, int offset, int count); - public virtual Task WriteAsync(byte[] buffer, int offset, int count) - { - throw null; - } - - public void Dispose() - { - throw null; - } - } - - public class TestType : TestTypeBase - { - public TestType() - { - } - - public class Nested - { - - } - -#pragma warning disable 0067 // event never used - public event Action StuffHappened; -#pragma warning restore 0067 - -#pragma warning disable 0169 // field never used - private int _pizzaSize; -#pragma warning restore 0169 - - public override bool CanRead => false; - - public override bool CanSeek => false; - - public override bool CanWrite => false; - - public override long Length - { - get - { - throw new NotImplementedException(); - } - } - - public override long Position - { - get - { - throw new NotImplementedException(); - } - - set - { - throw new NotImplementedException(); - } - } - - public override void Flush() - { - throw new NotImplementedException(); - } - - public override int Read(byte[] buffer, int offset, int count) - { - throw new NotImplementedException(); - } - - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotImplementedException(); - } - - public override void SetLength(long value) - { - throw new NotImplementedException(); - } - - public override void Write(byte[] buffer, int offset, int count) - { - throw new NotImplementedException(); - } - } - - public class TypeInfoTests - { - public TypeInfo TestTypeInfo => typeof(TestType).GetTypeInfo(); - - [Fact] - public void DeclaredConstructors() - { - List ctors = TestTypeInfo.DeclaredConstructors.ToList(); - Assert.Equal(1, ctors.Count); - Assert.True(ctors[0].IsSpecialName); - Assert.Equal(0, ctors[0].GetParameters().Count()); - } - - [Fact] - public void DeclaredEvents() - { - List events = TestTypeInfo.DeclaredEvents.ToList(); - Assert.Equal(1, events.Count); - Assert.Equal("StuffHappened", events[0].Name); - Assert.Equal("Action`1", events[0].EventHandlerType.Name); - } - - [Fact] - public void GetDeclaredEvent() - { - Assert.Equal("StuffHappened", TestTypeInfo.GetDeclaredEvent("StuffHappened").Name); - } - - [Fact] - public void DeclaredFields() - { - List fields = TestTypeInfo.DeclaredFields.ToList(); - Assert.Equal(2, fields.Count); - FieldInfo stuffHappened = fields.Single(f => f.Name == "StuffHappened"); - Assert.Equal(typeof(Action), stuffHappened.FieldType); - Assert.True(stuffHappened.IsPrivate); - FieldInfo pizzaSize = fields.Single(f => f.Name == "_pizzaSize"); - Assert.Equal(typeof(int), pizzaSize.FieldType); - Assert.True(pizzaSize.IsPrivate); - } - - [Fact] - public void GetDeclaredField() - { - Assert.Equal("_pizzaSize", TestTypeInfo.GetDeclaredField("_pizzaSize").Name); - } - - [Fact] - public void DeclaredMethods() - { - List methods = TestTypeInfo.DeclaredMethods.OrderBy(m => m.Name).ToList(); - Assert.Equal(13, methods.Count); - List methodNames = methods.Select(m => m.Name).ToList(); - Assert.Contains("add_StuffHappened", methodNames); - Assert.Contains("Flush", methodNames); - Assert.Contains("get_CanRead", methodNames); - Assert.Contains("get_CanSeek", methodNames); - Assert.Contains("get_CanWrite", methodNames); - Assert.Contains("get_Length", methodNames); - Assert.Contains("get_Position", methodNames); - Assert.Contains("Read", methodNames); - Assert.Contains("remove_StuffHappened", methodNames); - Assert.Contains("Seek", methodNames); - Assert.Contains("set_Position", methodNames); - Assert.Contains("SetLength", methodNames); - Assert.Contains("Write", methodNames); - } - - [Fact] - public void GetDeclaredMethod() - { - Assert.Equal("Flush", TestTypeInfo.GetDeclaredMethod("Flush").Name); - } - - [Fact] - public void DeclaredNestedTypes() - { - List types = TestTypeInfo.DeclaredNestedTypes.ToList(); - Assert.Equal(1, types.Count); - Assert.Equal("Nested", types[0].Name); - Assert.True(types[0].IsNestedPublic); - } - - [Fact] - public void GetDeclaredNestedType() - { - Assert.Equal("Nested", TestTypeInfo.GetDeclaredNestedType("Nested").Name); - } - - [Fact] - public void DeclaredProperties() - { - List properties = TestTypeInfo.DeclaredProperties.OrderBy(p => p.Name).ToList(); - Assert.Equal(5, properties.Count); - Assert.Equal("CanRead", properties[0].Name); - Assert.Equal("CanSeek", properties[1].Name); - Assert.Equal("CanWrite", properties[2].Name); - Assert.Equal("Length", properties[3].Name); - Assert.Equal("Position", properties[4].Name); - } - - [Fact] - public void GetDeclaredProperty() - { - Assert.Equal("CanRead", TestTypeInfo.GetDeclaredProperty("CanRead").Name); - } - - [Fact] - public void GenericTypeParameters() - { - Type[] parameters = TestTypeInfo.GenericTypeParameters; - Assert.Equal(0, parameters.Length); - } - - [Fact] - public void ImplementedInterfaces() - { - List interfaces = TestTypeInfo.ImplementedInterfaces.OrderBy(t => t.Name).ToList(); - Assert.Equal(1, interfaces.Count); - Assert.Equal(typeof(IDisposable), interfaces[0]); - } - - [Fact] - public void AsType() - { - Type type = TestTypeInfo.AsType(); - Assert.Equal(typeof(TestType), type); - } - - [Theory] - [InlineData(typeof(IDisposable), typeof(Stream))] - [InlineData(typeof(IList), typeof(ArrayList))] - [InlineData(typeof(object), typeof(int))] - [InlineData(typeof(object), typeof(string))] - public void IsAssignableFrom(Type to, Type from) - { - Assert.True(to.GetTypeInfo().IsAssignableFrom(from)); - } - } -} \ No newline at end of file diff --git a/external/corefx/src/System.Runtime/tests/System/Reflection/TypeTests.Get.CornerCases.cs b/external/corefx/src/System.Runtime/tests/System/Reflection/TypeTests.Get.CornerCases.cs index 7291c8dcd2..7b8f31f65b 100644 --- a/external/corefx/src/System.Runtime/tests/System/Reflection/TypeTests.Get.CornerCases.cs +++ b/external/corefx/src/System.Runtime/tests/System/Reflection/TypeTests.Get.CornerCases.cs @@ -271,7 +271,7 @@ namespace System.Reflection.Tests public static class TypeTests_HiddenTestingOrder { - [Fact] + [Fact(Skip="Mono issue #11235")] public static void HideDetectionHappensBeforeBindingFlagChecks() { // Hiding members suppress results even if the hiding member itself is filtered out by the binding flags. @@ -299,7 +299,7 @@ namespace System.Reflection.Tests Assert.Equal(nameof(Base.MyProp), properties[0].Name); } - [Fact] + [Fact(Skip="Mono issue #11235")] public static void HideDetectionHappensBeforeStaticInNonFlattenedHierarchyChecks() { // Hiding members suppress results even if the hiding member is filtered out due to being a static member in a base class (and BindingFlags.FlattenHierarchy not being specified.) diff --git a/external/corefx/src/System.Runtime/tests/System/Text/StringBuilderTests.cs b/external/corefx/src/System.Runtime/tests/System/Text/StringBuilderTests.cs index 935f9a8e05..d5e57a118e 100644 --- a/external/corefx/src/System.Runtime/tests/System/Text/StringBuilderTests.cs +++ b/external/corefx/src/System.Runtime/tests/System/Text/StringBuilderTests.cs @@ -522,9 +522,7 @@ namespace System.Text.Tests } [Theory] -#if !MOBILE [InlineData("Hello", '\0', 1, "Hello\0")] -#endif [InlineData("Hello", 'a', 1, "Helloa")] [InlineData("", 'b', 1, "b")] [InlineData("Hello", 'c', 2, "Hellocc")] @@ -1300,9 +1298,7 @@ namespace System.Text.Tests } [Theory] -#if !MOBILE [InlineData("Hello", 0, "\0", "\0Hello")] -#endif [InlineData("Hello", 3, "abc", "Helabclo")] [InlineData("Hello", 5, "def", "Hellodef")] [InlineData("Hello", 0, "", "Hello")] @@ -1492,10 +1488,8 @@ namespace System.Text.Tests } [Theory] -#if !MOBILE [InlineData("Hello", 0, "\0", 0, "Hello")] [InlineData("Hello", 0, "\0", 1, "\0Hello")] -#endif [InlineData("Hello", 3, "abc", 1, "Helabclo")] [InlineData("Hello", 5, "def", 1, "Hellodef")] [InlineData("Hello", 0, "", 1, "Hello")] diff --git a/external/corefx/src/System.Threading/tests/ThreadLocalTests.cs b/external/corefx/src/System.Threading/tests/ThreadLocalTests.cs index 300a213298..b7ee3afae5 100644 --- a/external/corefx/src/System.Threading/tests/ThreadLocalTests.cs +++ b/external/corefx/src/System.Threading/tests/ThreadLocalTests.cs @@ -319,6 +319,7 @@ namespace System.Threading.Tests } [Fact] + [SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "This test requires precise stack scanning")] public static void RunThreadLocalTest8_Values_NegativeCases() { // Test that Dispose works and that objects are released on dispose diff --git a/external/corert/BuildToolsVersion.txt b/external/corert/BuildToolsVersion.txt index 4edf3134b6..c42edc75ea 100644 --- a/external/corert/BuildToolsVersion.txt +++ b/external/corert/BuildToolsVersion.txt @@ -1 +1 @@ -2.1.0-preview2-02521-03 +3.0.0-preview1-03205-01 \ No newline at end of file diff --git a/external/corert/Documentation/cross-building.md b/external/corert/Documentation/cross-building.md index c95fd15dd5..291a92df78 100644 --- a/external/corert/Documentation/cross-building.md +++ b/external/corert/Documentation/cross-building.md @@ -52,54 +52,104 @@ As usual the resulting binaries will be found in `bin/Product/BuildOS.BuildArch. Using CoreRT for cross compiling under arm on x86 host ----------------------- -It is possible to use CoreRT for compiling under arm/armel on x86 host (or on x64 machine using roots). +It's possible to use CoreRT for compiling under arm/armel on x86 host (or on x64 machine using rootfs). +You can build Debug or Release version. +For example Release means: release CoreRT/CoreCLR/CoreFX builds + CoreRT(ILC) release enabled optimizations. +For better components compatibility, if you want to build Debug version, you must compile ALL projects as Debug version. +Otherwise, ALL as Release version. -1. Build CoreCLR for x86 (`checked` version) +1. Build CoreCLR for x86 ``` sudo ./cross/build-rootfs.sh x86 xenial -./build.sh clang3.9 x86 checked verbose cross skiptests +./build.sh x86 debug verbose cross +``` +2. Build CoreFX +``` +sudo ./cross/build-rootfs.sh x86 xenial +./build-native.sh -debug -buildArch=x86 -- verbose cross +./build-managed.sh -debug -verbose +``` +3. Build CoreRT for x86 and armel +``` +sudo ./cross/build-rootfs.sh armel tizen +sudo ./cross/build-rootfs.sh x86 xenial +./build.sh armel debug verbose cross +./build.sh x86 debug verbose cross crosstarget skiptests ``` -2. Build CoreFX (`Debug` version) -3. Build CoreRT for armel, x64, x86 -``` -sudo ./cross/build-rootfs.sh armel tizen cross -./build.sh clang3.9 armel debug verbose cross -./build.sh debug verbose skiptests -./build.sh clang3.9 x86 debug verbose cross skiptests +4. Copy necessary binaries to working directory in x86 rootfs. +Or in any host directory, if you have 32-bit multiarch-support on your x64 host. ``` +# 1) Copy CoreCLR(with CoreRun) part +cp ${CORECLR}/bin/Product/Linux.x86.Debug/* ${WORKING_DIR} -4. Copy necessary binaries to working directory (in x86 rootfs) -``` -cp ${CORECLR}/bin/Product/Linux.x86.Checked ${WORKING_DIR} -cp ${CORERT}/bin/Linux.x86.Debug/tools/ilc.dll ${WORKING_DIR} -cp ${CORERT}/bin/Linux.x86.Debug/tools/ILCompiler.* ${WORKING_DIR} -cp ${CORERT}/bin/Linux.x86.Debug/tools/System.CommandLine.dll ${WORKING_DIR} -cp ${CORERT}/bin/Linux.x86.Debug/tools/Microsoft.DiaSymReader.dll ${WORKING_DIR} -cp ${CORERT}/bin/Linux.x86.Debug/tools/jitinterface.so ${WORKING_DIR} -cp -r ${CORERT}/bin/Linux.x86.Debug/framework ${WORKING_DIR} - -# Copy CoreRT sdk binaries from target (armel) output folder +# 2) Copy CoreRT part +cp ${CORERT}/bin/Linux.armel.Debug/tools/ilc.dll ${WORKING_DIR} +cp ${CORERT}/bin/Linux.armel.Debug/tools/ILCompiler.* ${WORKING_DIR} +cp ${CORERT}/bin/Linux.armel.Debug/tools/System.CommandLine.dll ${WORKING_DIR} +cp ${CORERT}/bin/Linux.armel.Debug/tools/Microsoft.DiaSymReader.dll ${WORKING_DIR} +cp -r ${CORERT}/bin/Linux.armel.Debug/framework ${WORKING_DIR} cp -r ${CORERT}/bin/Linux.armel.Debug/sdk ${WORKING_DIR} + +# 3) Copy CoreRT x86 jitinterface with target armel version +cp ${CORERT}/bin/Linux.x86.Debug/tools/armeljitinterface.so ${WORKING_DIR}/jitinterface.so + +# 4) Copy CoreFX part +# Copy native architecture dependence libs +cp ${COREFX}/bin/Linux.x86.Debug/native/* ${WORKING_DIR} +# Copy arch independence libs +# This part varies depending on the application, these dependencies for HelloWorld only +NETCORE_PATH=netcoreapp-Linux-Debug-x64 +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Runtime.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Runtime.Extensions.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Collections.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Reflection.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Reflection.Metadata.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Collections.Immutable.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Console.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.IO.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Runtime.InteropServices.RuntimeInformation.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Runtime.InteropServices.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Threading.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Diagnostics.Debug.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Linq.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.IO.FileSystem.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.IO.MemoryMappedFiles.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.IO.UnmanagedMemoryStream.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.IO.FileSystem.Primitives.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Runtime.Handles.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Text.Encoding.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Text.Encoding.Extensions.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Reflection.Primitives.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Collections.Concurrent.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Security.Cryptography.Algorithms.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Security.Cryptography.Primitives.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Runtime.CompilerServices.Unsafe.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Globalization.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Private.Xml.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Diagnostics.Tracing.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Buffers.dll ${WORKING_DIR} +cp ${COREFX}/bin/runtime/${NETCORE_PATH}/System.Memory.dll ${WORKING_DIR} ``` 5. Rename RyuJIT compiler library ``` # Use cross-compiler library as default for ILC +# libclrjit.so is used by the CoreCLR that compiler runs on, +# and libclrjitilc.so is used for the actual compilation. cp ${WORKING_DIR}/libarmelnonjit.so ${WORKING_DIR}/libclrjitilc.so - -# ... or ARM version instead if it's needed -# cp ${WORKING_DIR}/libprotojit.so ${WORKING_DIR}/libclrjitilc.so ``` 6. [Build ObjectWriter library](how-to-build-ObjectWriter.md). You have to compile it on x86 chroot. 7. And to execute use: ``` +# Hello.ilc.rsp is in CoreRT armel build. It's necessary to edit the paths on the relatively our working directory. ./corerun ilc.dll --codegenopt "AltJitNgen=*" --verbose @Hello.ilc.rsp + # Any other options to RyuJIT could be passed via --codegenopt argument, e.g.: -#./corerun ilc.dll --codegenopt "AltJitNgen=*" --codegenopt "NgenDisasm=*" --verbose @Hello.ilc.rsp +# ./corerun ilc.dll --codegenopt "AltJitNgen=*" --codegenopt "NgenDisasm=*" --verbose @Hello.ilc.rsp # For linking -clang-3.9 -target arm-linux-gnueabi --sysroot=corert/cross/rootfs/armel -Bcorert/cross/rootfs/armel/usr/lib/gcc/armv7l-tizen-linux-gnueabi/6.2.1 -Lcorert/cross/rootfs/armel/usr/lib/gcc/armv7l-tizen-linux-gnueabi/6.2.1 Hello.o -o Hello corert/bin/Linux.armel.Debug/sdk/libbootstrapper.a corert/bin/Linux.armel.Debug/sdk/libRuntime.a corert/bin/Linux.armel.Debug/sdk/libSystem.Private.CoreLib.Native.a corert/bin/Linux.armel.Debug/framework/System.Native.a corert/bin/Linux.armel.Debug/framework/libSystem.Globalization.Native.a -g -Wl,-rpath,'$ORIGIN' -pthread -lstdc++ -ldl -lm -luuid -lrt -fPIC +clang -target arm-linux-gnueabi --sysroot=corert/cross/rootfs/armel -Bcorert/cross/rootfs/armel/usr/lib/gcc/armv7l-tizen-linux-gnueabi/6.2.1 -Lcorert/cross/rootfs/armel/usr/lib/gcc/armv7l-tizen-linux-gnueabi/6.2.1 Hello.o -o Hello corert/bin/Linux.armel.Debug/sdk/libbootstrapper.a corert/bin/Linux.armel.Debug/sdk/libRuntime.a corert/bin/Linux.armel.Debug/sdk/libSystem.Private.CoreLib.Native.a corert/bin/Linux.armel.Debug/framework/System.Native.a corert/bin/Linux.armel.Debug/framework/System.Globalization.Native.a -g -Wl,-rpath,'$ORIGIN' -pthread -lstdc++ -ldl -lm -luuid -lrt -fPIC ``` diff --git a/external/corert/Documentation/how-to-build-ObjectWriter.md b/external/corert/Documentation/how-to-build-ObjectWriter.md index 3f20e177cb..8999a44037 100644 --- a/external/corert/Documentation/how-to-build-ObjectWriter.md +++ b/external/corert/Documentation/how-to-build-ObjectWriter.md @@ -3,6 +3,14 @@ ObjWriter is based on LLVM, so it requires recent CMake and GCC/Clang to build LLVM. See [LLVM requirements](http://llvm.org/docs/GettingStarted.html#requirements) for more details. +`build.cmd`/`build.sh` script downloads a pre-built ObjWriter NuGet package. ObjWriter library is not built by default because +it takes a long time and changes rarely. + +To build a fresh ObjWriter, pass additional `objwriter` argument to the `build.cmd`/`build.sh` script. It will cause the build to clone +a matching copy of LLVM and use it to build ObjWriter library. + +The following manual steps are useful for troubleshooting ObjWriter build issues. + 1. Clone LLVM from official LLVM mirror github git repository: ``` @@ -12,7 +20,7 @@ See [LLVM requirements](http://llvm.org/docs/GettingStarted.html#requirements) f 2. Copy ObjWriter directory from CoreRT into LLVM tree ``` - cp -r CoreRT/src/Native/ObjWriter llvm/tools/ + cp -r corert/src/Native/ObjWriter llvm/tools/ ``` 3. Apply the patch to LLVM: diff --git a/external/corert/Documentation/how-to-build-WebAssembly.md b/external/corert/Documentation/how-to-build-WebAssembly.md index 84e6ed6dfe..0f1845ff9b 100644 --- a/external/corert/Documentation/how-to-build-WebAssembly.md +++ b/external/corert/Documentation/how-to-build-WebAssembly.md @@ -4,6 +4,7 @@ 1. Install Emscripten by following the instructions [here](https://kripken.github.io/emscripten-site/docs/getting_started/downloads.html). 2. Follow the instructions [here](https://kripken.github.io/emscripten-site/docs/getting_started/downloads.html#updating-the-sdk) to update Emscripten to the latest version. +3. Install [Firefox](https://www.getfirefox.com) (for testing). 3. Get CoreRT set up by following the [Visual Studio instructions](how-to-build-and-run-ilcompiler-in-visual-studio.md). 4. Build the WebAssembly runtime by running ```build.cmd wasm``` from the repo root. 5. Run the WebAssembly "Hello World" test by running ```C:\corert\tests\runtest.cmd wasm```. @@ -36,6 +37,7 @@ This is Windows only for now. # Useful tips # * To manually make ILC compile to WebAssembly, add ```--wasm``` to the command line. +* To debug C# source, add ```-g4``` to the emcc command line and change ```-s WASM=1``` to ```-s WASM=0```. This will generate a JavaScript source map that browser debuggers and Visual Studio Code can work with. Using Visual Studio Code's Chrome debugger works particularly well. * Add ```-g3``` to the emcc command line to generate more debuggable output and a .wast file with the text form of the WebAssembly. -* Omit ```-s WASM=1``` from the emcc command line to generate asm.js. Browser debuggers currently work better with asm.js and it's often a bit more readable than wast. +* Change ```-s WASM=1``` to ```-s WASM=0``` in the emcc command line to generate asm.js. Browser debuggers currently work better with asm.js and it's often a bit more readable than wast. * Add ```-O2 --llvm-lto 2``` to the emcc command line to enable optimizations. This makes the generated WebAssembly as much as 75% smaller as well as more efficient. diff --git a/external/corert/Documentation/how-to-build-and-run-ilcompiler-in-console-shell-prompt.md b/external/corert/Documentation/how-to-build-and-run-ilcompiler-in-console-shell-prompt.md index 48b1f3b479..d5b38f8ee6 100644 --- a/external/corert/Documentation/how-to-build-and-run-ilcompiler-in-console-shell-prompt.md +++ b/external/corert/Documentation/how-to-build-and-run-ilcompiler-in-console-shell-prompt.md @@ -14,9 +14,9 @@ This will result in the following: - Build native and managed components of ILCompiler. The final binaries are placed to `\bin\..\tools`. - Build and run tests -# Install .NET Core 2.0 SDK +# Install .NET Core 2.1 SDK -* Download .NET Core 2.0 SDK from [https://www.microsoft.com/net/download/core](https://www.microsoft.com/net/download/core) +* Download .NET Core 2.1 SDK from [https://www.microsoft.com/net/download/core](https://www.microsoft.com/net/download/core) * On windows ensure you are using the 'x64 Native Tools Command Prompt for VS 2017' (This is distinct from the 'Developer Command Prompt for VS 2017') @@ -35,7 +35,7 @@ You should now be able to use the `dotnet` commands of the CLI tools. Exe - netcoreapp2.0 + netcoreapp2.1 @@ -61,7 +61,7 @@ From the shell/command prompt, issue the following commands, from the folder con dotnet publish -r win-x64|linux-x64|osx-x64 ``` -Native executable will be dropped in `./bin/x64/[configuration]/netcoreapp2.0/publish/` folder and will have the same name as the folder in which your source file is present. +Native executable will be dropped in `./bin/x64/[configuration]/netcoreapp2.1/publish/` folder and will have the same name as the folder in which your source file is present. ## Using CPP Code Generator ## @@ -93,7 +93,7 @@ If you are seeing errors such as: ``` libcpmtd.lib(nothrow.obj) : fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'x64' [C:\Users\[omitted]\nativetest\app\app.csproj] -C:\Users\[omitted]\nativetest\bin\Windows_NT.x64.Debug\build\Microsoft.NETCore.Native.targets(151,5): error MSB3073: The command "link @"obj\Debug\netcoreapp1.0\native\link.rsp"" exited with code 1112. [C:\Users\[omitted]\nativetest\app\app.csproj] +C:\Users\[omitted]\nativetest\bin\Windows_NT.x64.Debug\build\Microsoft.NETCore.Native.targets(151,5): error MSB3073: The command "link @"obj\Debug\netcoreapp2.1\native\link.rsp"" exited with code 1112. [C:\Users\[omitted]\nativetest\app\app.csproj] ``` or diff --git a/external/corert/Documentation/how-to-build-and-run-ilcompiler-in-vscode.md b/external/corert/Documentation/how-to-build-and-run-ilcompiler-in-vscode.md index e17ca9bbc1..43bf635a98 100644 --- a/external/corert/Documentation/how-to-build-and-run-ilcompiler-in-vscode.md +++ b/external/corert/Documentation/how-to-build-and-run-ilcompiler-in-vscode.md @@ -49,7 +49,7 @@ dotnet build /t:LinkNative /t:Rebuild /v:Detailed | grep ".ilc.rsp" Once you have the ilc path, you can change ```launch.json``` accordingly: ```json - "args": ["@obj/Debug/netcoreapp1.0/native/.ilc.rsp"], + "args": ["@obj/Debug/netcoreapp2.1/native/.ilc.rsp"], "cwd": "", ``` diff --git a/external/corert/Documentation/how-to-run-tests.md b/external/corert/Documentation/how-to-run-tests.md index 9e43d11918..af747e28b2 100644 --- a/external/corert/Documentation/how-to-run-tests.md +++ b/external/corert/Documentation/how-to-run-tests.md @@ -1,6 +1,6 @@ # Testing CoreRT -The CoreRT test harness can run in two modes - with the tests local to the CoreRT repo, or with tests from the [CoreCLR](http://github.com/dotnet/coreclr) repo. The local tests only provide basic sanity testing and it's recommended to run the CoreCLR tests which are much more thorough. +The CoreRT test harness can run in two modes - with the tests local to the CoreRT repo, with tests from the [CoreCLR](https://github.com/dotnet/coreclr) repo or the tests from the [CoreFX](https://github.com/dotnet/corefx) repo. The local tests only provide basic sanity testing and it's recommended to run the CoreCLR and CoreFX tests which are much more thorough. The tests exercise both the runtime and the ILC compiler, which compiles IL into native code. The harness can test both the RyuJIT code generation backend, or the C++ backend of the ILC compiler. @@ -33,37 +33,41 @@ CPP - TOTAL: 2 PASSED: 2 WASM - TOTAL: 1 PASSED: 1 ``` -## External Tests - -*Note: These are currently supported only on Windows and Ubuntu/macOS support is coming soon.* +## External Tests - CoreCLR When runtest.cmd is passed the /coreclr switch, the harness will download the CoreCLR project's test suite, compile them to native with the CoreRT compiler, and run them. ### How To Run Choose the set of tests you want to run. Currently the options are: + * Top200 - * Small set of the suite selected to provide broad coverage quickly (Under 10 minutes). These run as part of the CI when submitting a pull request. + * Small set of the suite selected to provide broad coverage quickly (Under 10 minutes). These run as part of the CI when submitting a pull request. * KnownGood - * Subset of the suite previously validated to all pass on CoreRT. If these all pass you can be pretty sure you haven't regressed the compiler. + * Subset of the suite previously validated to all pass on CoreRT. If these all pass you can be pretty sure you haven't regressed the compiler. We currently only have a KnownGood list on Windows. * All - * The entire suite. Many of the tests will fail since CoreRT is still pre-release and some tests don't play well with an ahead-of-time compiler. + * The entire suite. Many of the tests will fail since CoreRT is still pre-release and some tests don't play well with an ahead-of-time compiler. On Windows: + ``` tests\runtest.cmd /coreclr Top200|All|KnownGood ``` On Linux / macOS: +``` tests/runtest.sh -coreclr Top200|All|KnownGood +``` ### Suppress Windows Error Reporting Dialogs + It's advisable to use some sort of a dialog killer tool if you see test regressions as many tests fail with pop-ups for Windows Error Reporting. However, the following regedit scripts have also proven to be useful to mask these pop-ups. Disable WER *temporarily*: **Contents of disable-wer.reg** + ``` REGEDIT4 @@ -75,6 +79,7 @@ REGEDIT4 Remember to enable: **Contents of enable-wer.reg** + ``` REGEDIT4 @@ -84,9 +89,75 @@ REGEDIT4 ``` ### Filtering Tests + If you know a test is failing for a good reason or you want a clean baseline, please use ```corert\tests\KnownGood.CoreCLR.issues.targets``` to weed out bad tests or infrastructure errors until we fix them. ### Test Logs + When the tests finish execution, the log location will be written out and should be in bin\Logs: **Example:** ```corert\bin\Logs\TestRun_Windows_NT__x64__debug.html``` + +## External tests - CoreFX + +Similarly to the CoreCLR tests, when runtest.cmd is passed the /corefx switch, the harness will download the CoreFX project's test suite, compile them to native with the CoreRT compiler, and run them. + +### How to run + +To run CoreFX tests on CoreRT, make sure that `build.cmd` has been run at least once in the configuration you'd like to test (i.e. `Debug` or `Release`), open a new console window and from the repo root execute the following: + +On Windows: + +``` +tests\runtest.cmd /corefx +``` + +On Linux / macOS: + +``` +tests/runtest.sh -corefx +``` + +The tests assemblies to run are defined in `TopN.CoreFX.[Windows/Unix].issues.json` with their respectively excluded test methods, classes or namespaces. + +### Reproducing test failures + +If you need to reproduce a failing test, navigate to ```test_downloaded\CoreFX``` and then to the folder of the failing test - each test suite is located in its own folder. From the test suite directory run the following: + +On Windows: + +``` +.\native\xunit.console.netcore.exe .\ @"./.rsp" -notrait category=nonnetcoreapptests -notrait category=nonwindowstests -notrait category=failing +``` + +On Linux / macOS: + +``` +./native/xunit.console.netcore.exe ./ @"./.rsp" -notrait category=nonnetcoreapptests -notrait category=failing +``` + +Additionally for Linux, add `-notrait category=nonlinuxtests` and for macOS `-notrait category=nonosxtests`. + +**e.g.** for System.Collections.Tests on Windows: + +Navigate to C:\repos\corert\test_downloaded\CoreFX\System.Collections.Tests. +Open Command Promps and run: + +``` +.\native\xunit.console.netcore.exe .\System.Collections.Tests.dll `@"System.Collections.Tests.rsp" -notrait category=nonnetcoreapptests -notrait category=nonwindowstests -notrait category=failing +``` + +### Enabling tests + +To enable a new CoreFX test project to run against CoreRT add its fully qualified name to `TopN.CoreFX.[Windows/Unix].issues.json`. +To remove a test from a test project which is already enabled, in the same file find and delete the definition containing its name. + +### Disabling tests + +Tests can be excluded from a run in the following ways: + +* To exclude a specific test method, add its fully-qualified name in the `method` array of the `exclusions` attribute of relevant test project or pass it as a value to the `-skipmethod` flag when calling `xunit.console.netcore.exe`. + +* To exclude all tests in a class, add its fully-qualified name in the `class` array of the `exclusions` attribute of relevant test project or pass it as a value to the `-skipclass` flag when calling `xunit.console.netcore.exe`. + +* To exclude all tests in a class, add its fully-qualified name in the `namespace` array of the `exclusions` attribute of relevant test project or pass it as a value to the `-skipnamespace` flag when calling `xunit.console.netcore.exe`. diff --git a/external/corert/Documentation/intro-to-corert.md b/external/corert/Documentation/intro-to-corert.md index 775d6fd77e..8bc78a14d9 100644 --- a/external/corert/Documentation/intro-to-corert.md +++ b/external/corert/Documentation/intro-to-corert.md @@ -1,19 +1,21 @@ -Intro to .NET Native and CoreRT -=============================== +Intro to CoreRT +=============== -Native compilation is a great scenario addition to .NET Core apps on Windows, OS X and Linux. We've seen significant startup and throughput benefits of native compilation for Windows UWP apps, using .NET Native. Today, many native apps and tools benefit from being compiled by a C++ compiler, and not as much by being written in C++. .NET Native brings much of the performance and all of the deployment benefits of native compilation, while retaining your ability to write in your favorite .NET programming language. +Native (AOT) compilation is a great scenario addition to .NET Core apps on Windows, OS X and Linux. We've seen significant startup and throughput benefits of native compilation for Windows UWP apps, using .NET Native. Today, many native apps and tools benefit from being compiled by a C++ compiler, and not as much by being written in C++. CoreRT brings much of the performance and all of the deployment benefits of native compilation, while retaining your ability to write in your favorite .NET programming language. Architecture ============ -[.NET Native](https://msdn.microsoft.com/library/dn584397.aspx) is a native toolchain that compiles [CIL byte code](https://en.wikipedia.org/wiki/Common_Intermediate_Language) to machine code (e.g. X64 instructions). By default, .NET Native (for .NET Core, as opposed to UWP) uses RyuJIT as an ahead-of-time (AOT) compiler, the same one that CoreCLR uses as a just-in-time (JIT) compiler. It can also be used with other compilers, such as [LLILC](https://github.com/dotnet/llilc), UTC for UWP apps and [IL to CPP](https://github.com/dotnet/corert/tree/master/src/ILCompiler.CppCodeGen/src/CppCodeGen) (an IL to textual C++ compiler we have built as a reference prototype). +[CoreRT](https://github.com/dotnet/corert) is a native toolchain that compiles [CIL byte code](https://en.wikipedia.org/wiki/Common_Intermediate_Language) to machine code (e.g. X64 instructions). By default, CoreRT uses RyuJIT as an ahead-of-time (AOT) compiler, the same one that CoreCLR uses as a just-in-time (JIT) compiler. CoreRT can also be used with other compilers, such as [LLILC](https://github.com/dotnet/llilc), and [IL to CPP](https://github.com/dotnet/corert/tree/master/src/ILCompiler.CppCodeGen/src/CppCodeGen) (an IL to textual C++ compiler we have built as a reference prototype). [.NET Native](https://docs.microsoft.com/en-us/dotnet/framework/net-native/index) uses CoreRT in conjunction with the UTC compiler to provide native compilation for UWP apps. -[CoreRT](https://github.com/dotnet/corert) is the .NET Core runtime that is optimized for AOT scenarios, which .NET Native targets. This is a refactored and layered runtime. The base is a small native execution engine that provides services such as garbage collection(GC). This is the same GC used in CoreCLR. Many other parts of the traditional .NET runtime, such as the [type system](https://github.com/dotnet/corert/tree/master/src/Common/src/TypeSystem), are implemented in C#. We've always wanted to implement runtime functionality in C#. We now have the infrastructure to do that. In addition, library implementations that were built deep into CoreCLR, have also been cleanly refactored and implemented as C# libraries. +CoreRT is a refactored and layered .Net Core runtime. The base is a small native execution engine that provides services such as garbage collection(GC). This is the same GC used in CoreCLR. Many other parts of the traditional .NET runtime, such as the [type system](https://github.com/dotnet/corert/tree/master/src/Common/src/TypeSystem), are implemented in C#. We've always wanted to implement runtime functionality in C#. We now have the infrastructure to do that. In addition, library implementations that were built deep into CoreCLR, have also been cleanly refactored and implemented as C# libraries. + +For more information about the architecture, see http://mattwarren.org/2018/06/07/CoreRT-.NET-Runtime-for-AOT/ . Experience ========== -.NET Native offers great benefits that are critical for many apps. +CoreRT offers great benefits that are critical for many apps. - The native compiler generates a *SINGLE FILE*, including the app, managed dependencies and CoreRT. - Native compiled apps startup faster since they execute already compiled code. They don't need to generate machine code at runtime nor load a JIT compiler. diff --git a/external/corert/Documentation/prerequisites-for-building.md b/external/corert/Documentation/prerequisites-for-building.md index 368e8f4cda..77f31366ff 100644 --- a/external/corert/Documentation/prerequisites-for-building.md +++ b/external/corert/Documentation/prerequisites-for-building.md @@ -20,7 +20,7 @@ sudo apt-get update ``` ```sh -sudo apt-get install cmake clang-3.9 libicu52 libunwind8 uuid-dev libcurl4-openssl-dev zlib1g-dev +sudo apt-get install cmake clang-3.9 libicu52 libunwind8 uuid-dev libcurl4-openssl-dev zlib1g-dev libkrb5-dev ``` # macOS (10.12+) @@ -59,5 +59,5 @@ sudo apt-get update ``` ```sh -sudo apt-get install cmake clang-3.9 libunwind8 uuid-dev +sudo apt-get install cmake clang-3.9 libunwind8 uuid-dev libcurl4-openssl-dev zlib1g-dev libkrb5-dev ``` diff --git a/external/corert/DotnetCLIVersion.txt b/external/corert/DotnetCLIVersion.txt index eca07e4c1a..6f1c03c6a3 100644 --- a/external/corert/DotnetCLIVersion.txt +++ b/external/corert/DotnetCLIVersion.txt @@ -1 +1 @@ -2.1.2 +2.1.401 \ No newline at end of file diff --git a/external/corert/NuGet.config b/external/corert/NuGet.config index 57feb087be..d93431bd1c 100644 --- a/external/corert/NuGet.config +++ b/external/corert/NuGet.config @@ -2,6 +2,7 @@ + diff --git a/external/corert/Packaging.props b/external/corert/Packaging.props index 339171f666..af9e5689ec 100644 --- a/external/corert/Packaging.props +++ b/external/corert/Packaging.props @@ -29,15 +29,6 @@ - - /dev/null || { echo >&2 "Please install cmake before running this script"; exit 1; } - - # Check for clang - hash clang-$__ClangMajorVersion.$__ClangMinorVersion 2>/dev/null || hash clang$__ClangMajorVersion$__ClangMinorVersion 2>/dev/null || hash clang 2>/dev/null || { echo >&2 "Please install clang before running this script"; exit 1; } -} - get_current_linux_rid() { # Construct RID for current distro @@ -65,9 +51,7 @@ get_current_linux_rid() { if [ -e /etc/os-release ]; then source /etc/os-release if [[ $ID == "alpine" ]]; then - # remove the last version digit - VERSION_ID=${VERSION_ID%.*} - rid=alpine.$VERSION_ID + rid="linux-musl" fi elif [ -e /etc/redhat-release ]; then @@ -105,18 +89,10 @@ export __UnprocessedBuildArgs= export __CleanBuild=0 export __VerboseBuild=0 export __ObjWriterBuild=0 -export __ClangMajorVersion=3 -export __ClangMinorVersion=9 export __CrossBuild=0 __BuildArch=$__HostArch -# Checking for any clang versions, if there is a symlink -if [ -x "$(command -v clang)" ]; then - __ClangMajorVersion="$(echo | clang -dM -E - | grep __clang_major__ | cut -f3 -d ' ')" - __ClangMinorVersion="$(echo | clang -dM -E - | grep __clang_minor__ | cut -f3 -d ' ')" -fi - while [ "$1" != "" ]; do lowerI="$(echo $1 | awk '{print tolower($0)}')" case $lowerI in @@ -130,24 +106,6 @@ while [ "$1" != "" ]; do native) export __buildnative=true ;; - x86) - __BuildArch=x86 - ;; - x64) - __BuildArch=x64 - ;; - arm) - __BuildArch=arm - ;; - arm64) - __BuildArch=arm64 - ;; - armel) - __BuildArch=armel - ;; - wasm) - __BuildArch=wasm - ;; debug) export __BuildType=Debug ;; @@ -162,38 +120,7 @@ while [ "$1" != "" ]; do ;; objwriter) export __ObjWriterBuild=1 - ;; - clang3.6) - export __ClangMajorVersion=3 - export __ClangMinorVersion=6 - ;; - clang3.7) - export __ClangMajorVersion=3 - export __ClangMinorVersion=7 - ;; - clang3.8) - export __ClangMajorVersion=3 - export __ClangMinorVersion=8 - ;; - clang3.9) - export __ClangMajorVersion=3 - export __ClangMinorVersion=9 - ;; - clang4.0) - export __ClangMajorVersion=4 - export __ClangMinorVersion=0 - ;; - clang5.0) - export __ClangMajorVersion=5 - export __ClangMinorVersion=0 - ;; - clang6.0) - export __ClangMajorVersion=6 - export __ClangMinorVersion=0 - ;; - clang7.0) - export __ClangMajorVersion=7 - export __ClangMinorVersion=0 + export __ExtraMsBuildArgs="$__ExtraMsBuildArgs /p:ObjWriterBuild=true" ;; cross) export __CrossBuild=1 @@ -209,12 +136,37 @@ while [ "$1" != "" ]; do skiptests) export __SkipTests=true ;; + x86|x64|arm|arm64|armel|wasm) + __BuildArch=$lowerI + ;; + clang*) + export __ClangMajorVersion=${lowerI:5:1} + export __ClangMinorVersion=${lowerI:7:1} + ;; *) - export __UnprocessedBuildArgs="$__UnprocessedBuildArgs $1" + export __UnprocessedBuildArgs="$__UnprocessedBuildArgs $1" esac shift done +if [ -z "$__ClangMajorVersion" ] || [ -z "$__ClangMinorVersion" ]; then + # Checking for any clang versions, if there is a symlink + if [ -x "$(command -v clang)" ]; then + export __ClangMajorVersion="$(echo | clang -dM -E - | grep __clang_major__ | cut -f3 -d ' ')" + export __ClangMinorVersion="$(echo | clang -dM -E - | grep __clang_minor__ | cut -f3 -d ' ')" + if [ "${__HostOS}" != "OSX" ]; then + export CppCompilerAndLinker=clang + fi + else + export __ClangMajorVersion=3 + export __ClangMinorVersion=9 + fi +fi + +if [ "${__HostOS}" != "OSX" ] && [ -z "$CppCompilerAndLinker" ]; then + export CppCompilerAndLinker=clang-${__ClangMajorVersion}.${__ClangMinorVersion} +fi + export $__BuildArch # Use uname to determine what the OS is. @@ -250,11 +202,6 @@ case $OSName in ;; esac -# For msbuild -if [ $__HostOS != "OSX" ]; then - export CppCompilerAndLinker=clang-${__ClangMajorVersion}.${__ClangMinorVersion} -fi - export __BuildOS="$__HostOS" # Overwrite __BuildOS with WebAssembly if wasm is target build arch, but keep the __NugetRuntimeId to match the Host OS diff --git a/external/corert/cross/arm/toolchain.cmake b/external/corert/cross/arm/toolchain.cmake deleted file mode 100644 index 772148750d..0000000000 --- a/external/corert/cross/arm/toolchain.cmake +++ /dev/null @@ -1,28 +0,0 @@ -set(CROSS_ROOTFS $ENV{ROOTFS_DIR}) - -set(CMAKE_SYSTEM_NAME Linux) -set(CMAKE_SYSTEM_VERSION 1) -set(CMAKE_SYSTEM_PROCESSOR armv7l) - -add_compile_options(-target armv7-linux-gnueabihf) -add_compile_options(-mthumb) -add_compile_options(-mfpu=vfpv3) -add_compile_options(--sysroot=${CROSS_ROOTFS}) - -set(CROSS_LINK_FLAGS "-target arm-linux-gnueabihf") -set(CROSS_LINK_FLAGS "${CROSS_LINK_FLAGS} -B ${CROSS_ROOTFS}/usr/lib/gcc/arm-linux-gnueabihf") -set(CROSS_LINK_FLAGS "${CROSS_LINK_FLAGS} -L${CROSS_ROOTFS}/lib/arm-linux-gnueabihf") -set(CROSS_LINK_FLAGS "${CROSS_LINK_FLAGS} --sysroot=${CROSS_ROOTFS}") - -set(CMAKE_EXE_LINKER_FLAGS "${CROSS_LINK_FLAGS}" CACHE STRING "TOOLCHAIN_EXE_LINKER_FLAGS" FORCE) -set(CMAKE_SHARED_LINKER_FLAGS "${CROSS_LINK_FLAGS}" CACHE STRING "TOOLCHAIN_SHARED_LINKER_FLAGS" FORCE) -set(CMAKE_MODULE_LINKER_FLAGS "${CROSS_LINK_FLAGS}" CACHE STRING "TOOLCHAIN_MODULE_LINKER_FLAGS" FORCE) - -set(CMAKE_FIND_ROOT_PATH "${CROSS_ROOTFS}") -set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) - -set(WITH_LLDB_LIBS "${CROSS_ROOTFS}/usr/lib/arm-linux-gnueabihf" CACHE STRING "") -set(WITH_LLDB_INCLUDES "${CROSS_ROOTFS}/usr/lib/llvm-3.6/include" CACHE STRING "") \ No newline at end of file diff --git a/external/corert/cross/arm/tryrun.cmake b/external/corert/cross/arm/tryrun.cmake deleted file mode 100644 index 7ce7dad2d5..0000000000 --- a/external/corert/cross/arm/tryrun.cmake +++ /dev/null @@ -1,111 +0,0 @@ -SET( REALPATH_SUPPORTS_NONEXISTENT_FILES_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( SSCANF_SUPPORT_ll_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( SSCANF_CANNOT_HANDLE_MISSING_EXPONENT_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_LARGE_SNPRINTF_SUPPORT_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_SCHED_GET_PRIORITY_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_WORKING_GETTIMEOFDAY_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_WORKING_CLOCK_GETTIME_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_CLOCK_MONOTONIC_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_MMAP_DEV_ZERO_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( MMAP_IGNORES_HINT_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( MMAP_DOESNOT_ALLOW_REMAP_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( PTHREAD_CREATE_MODIFIES_ERRNO_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( SEM_INIT_MODIFIES_ERRNO_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_ACOS_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_ASIN_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_POW_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_VALID_NEGATIVE_INF_POW_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_VALID_POSITIVE_INF_POW_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_ATAN2_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_LOG_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_LOG10_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( UNGETC_NOT_RETURN_EOF_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAS_POSIX_SEMAPHORES_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( GETPWUID_R_SETS_ERRNO_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( FILE_OPS_CHECK_FERROR_OF_PREVIOUS_CALL_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_SCHED_GETCPU_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_CLOCK_MONOTONIC_COARSE_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) diff --git a/external/corert/cross/arm64/toolchain.cmake b/external/corert/cross/arm64/toolchain.cmake deleted file mode 100644 index 18c4caafa8..0000000000 --- a/external/corert/cross/arm64/toolchain.cmake +++ /dev/null @@ -1,23 +0,0 @@ -set(CROSS_ROOTFS $ENV{ROOTFS_DIR}) - -set(CMAKE_SYSTEM_NAME Linux) -set(CMAKE_SYSTEM_VERSION 1) -set(CMAKE_SYSTEM_PROCESSOR aarch64) - -add_compile_options(-target aarch64-linux-gnu) -add_compile_options(--sysroot=${CROSS_ROOTFS}) - -set(CROSS_LINK_FLAGS "-target aarch64-linux-gnu") -set(CROSS_LINK_FLAGS "${CROSS_LINK_FLAGS} -B ${CROSS_ROOTFS}/usr/lib/gcc/aarch64-linux-gnu") -set(CROSS_LINK_FLAGS "${CROSS_LINK_FLAGS} -L${CROSS_ROOTFS}/lib/aarch64-linux-gnu") -set(CROSS_LINK_FLAGS "${CROSS_LINK_FLAGS} --sysroot=${CROSS_ROOTFS}") - -set(CMAKE_EXE_LINKER_FLAGS "${CROSS_LINK_FLAGS}" CACHE STRING "TOOLCHAIN_EXE_LINKER_FLAGS" FORCE) -set(CMAKE_SHARED_LINKER_FLAGS "${CROSS_LINK_FLAGS}" CACHE STRING "TOOLCHAIN_SHARED_LINKER_FLAGS" FORCE) -set(CMAKE_MODULE_LINKER_FLAGS "${CROSS_LINK_FLAGS}" CACHE STRING "TOOLCHAIN_MODULE_LINKER_FLAGS" FORCE) - -set(CMAKE_FIND_ROOT_PATH "${CROSS_ROOTFS}") -set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) \ No newline at end of file diff --git a/external/corert/cross/arm64/tryrun.cmake b/external/corert/cross/arm64/tryrun.cmake deleted file mode 100644 index 7ce7dad2d5..0000000000 --- a/external/corert/cross/arm64/tryrun.cmake +++ /dev/null @@ -1,111 +0,0 @@ -SET( REALPATH_SUPPORTS_NONEXISTENT_FILES_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( SSCANF_SUPPORT_ll_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( SSCANF_CANNOT_HANDLE_MISSING_EXPONENT_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_LARGE_SNPRINTF_SUPPORT_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_SCHED_GET_PRIORITY_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_WORKING_GETTIMEOFDAY_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_WORKING_CLOCK_GETTIME_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_CLOCK_MONOTONIC_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_MMAP_DEV_ZERO_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( MMAP_IGNORES_HINT_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( MMAP_DOESNOT_ALLOW_REMAP_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( PTHREAD_CREATE_MODIFIES_ERRNO_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( SEM_INIT_MODIFIES_ERRNO_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_ACOS_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_ASIN_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_POW_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_VALID_NEGATIVE_INF_POW_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_VALID_POSITIVE_INF_POW_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_ATAN2_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_LOG_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_LOG10_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( UNGETC_NOT_RETURN_EOF_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAS_POSIX_SEMAPHORES_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( GETPWUID_R_SETS_ERRNO_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( FILE_OPS_CHECK_FERROR_OF_PREVIOUS_CALL_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_SCHED_GETCPU_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_CLOCK_MONOTONIC_COARSE_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) diff --git a/external/corert/cross/armel/tizen-fetch.sh b/external/corert/cross/armel/tizen-fetch.sh index 58e4b5a347..d9649f0339 100755 --- a/external/corert/cross/armel/tizen-fetch.sh +++ b/external/corert/cross/armel/tizen-fetch.sh @@ -51,7 +51,7 @@ if [ ! -d $TMPDIR ]; then mkdir -p $TMPDIR fi -TIZEN_URL=http://download.tizen.org/releases/daily/tizen +TIZEN_URL=http://download.tizen.org/snapshots/tizen BUILD_XML=build.xml REPOMD_XML=repomd.xml PRIMARY_XML=primary.xml @@ -157,20 +157,14 @@ fetch_tizen_pkgs() Inform "Initialize base" fetch_tizen_pkgs_init standard base Inform "fetch common packages" -fetch_tizen_pkgs armv7l gcc glibc glibc-devel +fetch_tizen_pkgs armv7l gcc glibc glibc-devel libicu icu libicu-devel fetch_tizen_pkgs noarch linux-glibc-devel Inform "fetch coreclr packages" -fetch_tizen_pkgs armv7l lldb lldb-devel libuuid libuuid-devel libgcc libstdc++ libstdc++-devel libunwind libunwind-devel +fetch_tizen_pkgs armv7l lldb lldb-devel libuuid libuuid-devel libgcc libstdc++ libstdc++-devel libunwind libunwind-devel tizen-release Inform "fetch corefx packages" -fetch_tizen_pkgs armv7l libcom_err libcom_err-devel zlib zlib-devel libopenssl libopenssl-devel +fetch_tizen_pkgs armv7l libcom_err libcom_err-devel zlib zlib-devel libopenssl libopenssl-devel krb5 krb5-devel libcurl libcurl-devel Inform "Initialize unified" fetch_tizen_pkgs_init standard unified -Inform "fetch common packages" -fetch_tizen_pkgs armv7l libicu icu libicu-devel -Inform "fetch coreclr packages" -fetch_tizen_pkgs armv7l tizen-release Inform "fetch corefx packages" -fetch_tizen_pkgs armv7l gssdp gssdp-devel krb5 krb5-devel libcurl libcurl-devel - - +fetch_tizen_pkgs armv7l gssdp gssdp-devel diff --git a/external/corert/cross/armel/toolchain.cmake b/external/corert/cross/armel/toolchain.cmake deleted file mode 100644 index ac42b54ddc..0000000000 --- a/external/corert/cross/armel/toolchain.cmake +++ /dev/null @@ -1,59 +0,0 @@ -set(CROSS_ROOTFS $ENV{ROOTFS_DIR}) - -set(CMAKE_SYSTEM_NAME Linux) -set(CMAKE_SYSTEM_VERSION 1) -set(CMAKE_SYSTEM_PROCESSOR armv7l) - -## Specify the toolchain -set(TOOLCHAIN "arm-linux-gnueabi") -set(TOOLCHAIN_PREFIX ${TOOLCHAIN}-) -#set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}gcc) -#set(CMAKE_CXX_COMPILER ${TOOLCHAIN_PREFIX}g++) -#set(CMAKE_ASM_COMPILER ${TOOLCHAIN_PREFIX}as) -#set(CMAKE_AR ${TOOLCHAIN_PREFIX}ar) -#set(CMAKE_OBJCOPY ${TOOLCHAIN_PREFIX}objcopy) -#set(CMAKE_OBJDUMP ${TOOLCHAIN_PREFIX}objdump) - -add_compile_options(-target armv7-linux-gnueabi) -add_compile_options(-mthumb) -add_compile_options(-mfpu=vfpv3) -add_compile_options(--sysroot=${CROSS_ROOTFS}) - -set(CROSS_LINK_FLAGS "-target ${TOOLCHAIN}") -set(CROSS_LINK_FLAGS "${CROSS_LINK_FLAGS} --sysroot=${CROSS_ROOTFS}") - -if("$ENV{__DistroRid}" MATCHES "tizen.*") - set(TIZEN_TOOLCHAIN "armv7l-tizen-linux-gnueabi/6.2.1") - add_compile_options(-I$ENV{ROOTFS_DIR}/usr/lib/gcc/${TIZEN_TOOLCHAIN}/include/c++/) - add_compile_options(-I$ENV{ROOTFS_DIR}/usr/lib/gcc/${TIZEN_TOOLCHAIN}/include/c++/armv7l-tizen-linux-gnueabi) - add_compile_options(-Wno-deprecated-declarations) # compile-time option - add_compile_options(-D__extern_always_inline=inline) - set(CROSS_LINK_FLAGS "${CROSS_LINK_FLAGS} -B${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}") - set(CROSS_LINK_FLAGS "${CROSS_LINK_FLAGS} -L${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}") -else() - # TODO: this setting assumes debian armel rootfs - include_directories(SYSTEM ${CROSS_ROOTFS}/usr/include/c++/4.9 ${CROSS_ROOTFS}/usr/include/${TOOLCHAIN}/c++/4.9 ) - set(CROSS_LINK_FLAGS "${CROSS_LINK_FLAGS} -B${CROSS_ROOTFS}/usr/lib/gcc/${TOOLCHAIN}/4.9") - set(CROSS_LINK_FLAGS "${CROSS_LINK_FLAGS} -L${CROSS_ROOTFS}/usr/lib/gcc/${TOOLCHAIN}/4.9") -endif() - -set(CMAKE_EXE_LINKER_FLAGS "${CROSS_LINK_FLAGS}" CACHE STRING "TOOLCHAIN_EXE_LINKER_FLAGS" FORCE) -set(CMAKE_SHARED_LINKER_FLAGS "${CROSS_LINK_FLAGS}" CACHE STRING "TOOLCHAIN_SHARED_LINKER_FLAGS" FORCE) -set(CMAKE_MODULE_LINKER_FLAGS "${CROSS_LINK_FLAGS}" CACHE STRING "TOOLCHAIN_MODULE_LINKER_FLAGS" FORCE) - -set(CMAKE_FIND_ROOT_PATH "${CROSS_ROOTFS}") -set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) - -set(LLVM_ARM_DIR "$ENV{LLVM_ARM_HOME}") -if(LLVM_ARM_DIR) - set(WITH_LLDB_LIBS "${LLVM_ARM_DIR}/lib/" CACHE STRING "") - set(WITH_LLDB_INCLUDES "${LLVM_ARM_DIR}/include" CACHE STRING "") - set(LLDB_H "${WITH_LLDB_INCLUDES}" CACHE STRING "") - set(LLDB "${LLVM_ARM_DIR}/lib/liblldb.so" CACHE STRING "") -else() - set(WITH_LLDB_LIBS "${CROSS_ROOTFS}/usr/lib/${TOOLCHAIN}" CACHE STRING "") - set(WITH_LLDB_INCLUDES "${CROSS_ROOTFS}/usr/lib/llvm-3.6/include" CACHE STRING "") -endif() diff --git a/external/corert/cross/armel/tryrun.cmake b/external/corert/cross/armel/tryrun.cmake deleted file mode 100644 index 98b7ed0e60..0000000000 --- a/external/corert/cross/armel/tryrun.cmake +++ /dev/null @@ -1,11 +0,0 @@ -SET( HAVE_CLOCK_MONOTONIC_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_SCHED_GETCPU_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_CLOCK_MONOTONIC_COARSE_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) diff --git a/external/corert/cross/build-rootfs.sh b/external/corert/cross/build-rootfs.sh index 07d6c3be76..ec6af484fa 100755 --- a/external/corert/cross/build-rootfs.sh +++ b/external/corert/cross/build-rootfs.sh @@ -2,10 +2,11 @@ usage() { - echo "Usage: $0 [BuildArch] [LinuxCodeName] [cross]" + echo "Usage: $0 [BuildArch] [LinuxCodeName] [lldbx.y] [--skipunmount]" echo "BuildArch can be: arm(default), armel, arm64, x86" - echo "LinuxCodeName - optional, Code name for Linux, can be: trusty(default), vivid, wily, jessie, xenial. If BuildArch is armel, LinuxCodeName is jessie(default) or tizen." - echo "cross - optional, it initializes rootfs for cross building, works only for armel tizen now" + echo "LinuxCodeName - optional, Code name for Linux, can be: trusty(default), vivid, wily, xenial, zesty, alpine. If BuildArch is armel, LinuxCodeName is jessie(default) or tizen." + echo "lldbx.y - optional, LLDB version, can be: lldb3.6(default), lldb3.8, lldb3.9, lldb4.0, no-lldb. Ignored for alpine" + echo "--skipunmount - optional, will skip the unmount of rootfs folder." exit 1 } @@ -15,30 +16,62 @@ __InitialDir=$PWD __BuildArch=arm __UbuntuArch=armhf __UbuntuRepo="http://ports.ubuntu.com/" -__UbuntuPackages="build-essential lldb-3.6-dev libunwind8-dev gettext symlinks liblttng-ust-dev libicu-dev" __LLDB_Package="lldb-3.6-dev" -__MachineTriple=arm-linux-gnueabihf -__UnprocessedBuildArgs= __SkipUnmount=0 -for i in "$@" - do - lowerI="$(echo $i | awk '{print tolower($0)}')" - case $lowerI in +# base development support +__UbuntuPackages="build-essential" + +__AlpinePackages="alpine-base" +__AlpinePackages+=" build-base" +__AlpinePackages+=" linux-headers" +__AlpinePackages+=" lldb-dev" +__AlpinePackages+=" llvm-dev" + +# symlinks fixer +__UbuntuPackages+=" symlinks" + +# CoreCLR and CoreFX dependencies +__UbuntuPackages+=" libicu-dev" +__UbuntuPackages+=" liblttng-ust-dev" +__UbuntuPackages+=" libunwind8-dev" + +__AlpinePackages+=" gettext-dev" +__AlpinePackages+=" icu-dev" +__AlpinePackages+=" libunwind-dev" +__AlpinePackages+=" lttng-ust-dev" + +# CoreFX dependencies +__UbuntuPackages+=" libcurl4-openssl-dev" +__UbuntuPackages+=" libkrb5-dev" +__UbuntuPackages+=" libssl-dev" +__UbuntuPackages+=" zlib1g-dev" + +__AlpinePackages+=" curl-dev" +__AlpinePackages+=" krb5-dev" +__AlpinePackages+=" openssl-dev" +__AlpinePackages+=" zlib-dev" + +__UnprocessedBuildArgs= +for i in "$@" ; do + lowerI="$(echo $i | awk '{print tolower($0)}')" + case $lowerI in -?|-h|--help) - usage - exit 1 - ;; + usage + exit 1 + ;; arm) - __BuildArch=arm - __UbuntuArch=armhf - ;; + __BuildArch=arm + __UbuntuArch=armhf + __AlpineArch=armhf + __QEMUArch=arm + ;; arm64) - __BuildArch=arm64 - __UbuntuArch=arm64 - __UbuntuPackages="build-essential libunwind8-dev gettext symlinks liblttng-ust-dev libicu-dev" - __MachineTriple=aarch64-linux-gnu - ;; + __BuildArch=arm64 + __UbuntuArch=arm64 + __AlpineArch=aarch64 + __QEMUArch=aarch64 + ;; armel) __BuildArch=armel __UbuntuArch=armel @@ -56,6 +89,15 @@ for i in "$@" lldb3.8) __LLDB_Package="lldb-3.8-dev" ;; + lldb3.9) + __LLDB_Package="liblldb-3.9-dev" + ;; + lldb4.0) + __LLDB_Package="liblldb-4.0-dev" + ;; + no-lldb) + unset __LLDB_Package + ;; vivid) if [ "$__LinuxCodeName" != "jessie" ]; then __LinuxCodeName=vivid @@ -71,6 +113,11 @@ for i in "$@" __LinuxCodeName=xenial fi ;; + zesty) + if [ "$__LinuxCodeName" != "jessie" ]; then + __LinuxCodeName=zesty + fi + ;; jessie) __LinuxCodeName=jessie __UbuntuRepo="http://ftp.debian.org/debian/" @@ -85,32 +132,25 @@ for i in "$@" __UbuntuRepo= __Tizen=tizen ;; - cross) - if [ "$__Tizen" != "tizen" ]; then - echo "Cross building rootfs is available only for armel tizen." - usage; - exit 1; - fi - # Cross building is available for armel tizen only with x86 rootfs - echo Building x86 xenial rootfs for armel tizen cross build... - $0 x86 xenial - echo Building armel rootfs... + alpine) + __LinuxCodeName=alpine + __UbuntuRepo= ;; --skipunmount) __SkipUnmount=1 ;; *) - __UnprocessedBuildArgs="$__UnprocessedBuildArgs $i" + __UnprocessedBuildArgs="$__UnprocessedBuildArgs $i" + ;; esac done if [ "$__BuildArch" == "armel" ]; then __LLDB_Package="lldb-3.5-dev" fi - -__RootfsDir="$__CrossDir/rootfs/$__BuildArch" __UbuntuPackages+=" ${__LLDB_Package:-}" +__RootfsDir="$__CrossDir/rootfs/$__BuildArch" if [[ -n "$ROOTFS_DIR" ]]; then __RootfsDir=$ROOTFS_DIR @@ -123,8 +163,22 @@ if [ -d "$__RootfsDir" ]; then rm -rf $__RootfsDir fi - -if [[ -n $__LinuxCodeName ]]; then +if [[ "$__LinuxCodeName" == "alpine" ]]; then + __ApkToolsVersion=2.9.1 + __AlpineVersion=3.7 + __ApkToolsDir=$(mktemp -d) + wget https://github.com/alpinelinux/apk-tools/releases/download/v$__ApkToolsVersion/apk-tools-$__ApkToolsVersion-x86_64-linux.tar.gz -P $__ApkToolsDir + tar -xf $__ApkToolsDir/apk-tools-$__ApkToolsVersion-x86_64-linux.tar.gz -C $__ApkToolsDir + mkdir -p $__RootfsDir/usr/bin + cp -v /usr/bin/qemu-$__QEMUArch-static $__RootfsDir/usr/bin + $__ApkToolsDir/apk-tools-$__ApkToolsVersion/apk \ + -X http://dl-cdn.alpinelinux.org/alpine/v$__AlpineVersion/main \ + -X http://dl-cdn.alpinelinux.org/alpine/v$__AlpineVersion/community \ + -X http://dl-cdn.alpinelinux.org/alpine/edge/testing \ + -U --allow-untrusted --root $__RootfsDir --arch $__AlpineArch --initdb \ + add $__AlpinePackages + rm -r $__ApkToolsDir +elif [[ -n $__LinuxCodeName ]]; then qemu-debootstrap --arch $__UbuntuArch $__LinuxCodeName $__RootfsDir $__UbuntuRepo cp $__CrossDir/$__BuildArch/sources.list.$__LinuxCodeName $__RootfsDir/etc/apt/sources.list chroot $__RootfsDir apt-get update @@ -135,6 +189,13 @@ if [[ -n $__LinuxCodeName ]]; then if [ $__SkipUnmount == 0 ]; then umount $__RootfsDir/* fi + + if [[ "$__BuildArch" == "arm" && "$__LinuxCodeName" == "trusty" ]]; then + pushd $__RootfsDir + patch -p1 < $__CrossDir/$__BuildArch/trusty.patch + patch -p1 < $__CrossDir/$__BuildArch/trusty-lttng-2.4.patch + popd + fi elif [ "$__Tizen" == "tizen" ]; then ROOTFS_DIR=$__RootfsDir $__CrossDir/$__BuildArch/tizen-build-rootfs.sh else diff --git a/external/corert/cross/toolchain.cmake b/external/corert/cross/toolchain.cmake new file mode 100644 index 0000000000..071d411241 --- /dev/null +++ b/external/corert/cross/toolchain.cmake @@ -0,0 +1,138 @@ +set(CROSS_ROOTFS $ENV{ROOTFS_DIR}) + +set(TARGET_ARCH_NAME $ENV{TARGET_BUILD_ARCH}) +set(CMAKE_SYSTEM_NAME Linux) +set(CMAKE_SYSTEM_VERSION 1) + +if(TARGET_ARCH_NAME STREQUAL "armel") + set(CMAKE_SYSTEM_PROCESSOR armv7l) + set(TOOLCHAIN "arm-linux-gnueabi") + if("$ENV{__DistroRid}" MATCHES "tizen.*") + set(TIZEN_TOOLCHAIN "armv7l-tizen-linux-gnueabi/6.2.1") + endif() +elseif(TARGET_ARCH_NAME STREQUAL "arm") + set(CMAKE_SYSTEM_PROCESSOR armv7l) + if(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/armv6-alpine-linux-musleabihf) + set(TOOLCHAIN "armv6-alpine-linux-musleabihf") + else() + set(TOOLCHAIN "arm-linux-gnueabihf") + endif() +elseif(TARGET_ARCH_NAME STREQUAL "arm64") + set(CMAKE_SYSTEM_PROCESSOR aarch64) + if(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/aarch64-alpine-linux-musl) + set(TOOLCHAIN "aarch64-alpine-linux-musl") + else() + set(TOOLCHAIN "aarch64-linux-gnu") + endif() +elseif(TARGET_ARCH_NAME STREQUAL "x86") + set(CMAKE_SYSTEM_PROCESSOR i686) + set(TOOLCHAIN "i686-linux-gnu") +else() + message(FATAL_ERROR "Arch is ${TARGET_ARCH_NAME}. Only armel, arm, arm64 and x86 are supported!") +endif() + +# Specify include paths +if(TARGET_ARCH_NAME STREQUAL "armel") + if(DEFINED TIZEN_TOOLCHAIN) + include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}/include/c++/) + include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}/include/c++/armv7l-tizen-linux-gnueabi) + endif() +endif() + +# add_compile_param - adds only new options without duplicates. +# arg0 - list with result options, arg1 - list with new options. +# arg2 - optional argument, quick summary string for optional using CACHE FORCE mode. +macro(add_compile_param) + if(NOT ${ARGC} MATCHES "^(2|3)$") + message(FATAL_ERROR "Wrong using add_compile_param! Two or three parameters must be given! See add_compile_param description.") + endif() + foreach(OPTION ${ARGV1}) + if(NOT ${ARGV0} MATCHES "${OPTION}($| )") + set(${ARGV0} "${${ARGV0}} ${OPTION}") + if(${ARGC} EQUAL "3") # CACHE FORCE mode + set(${ARGV0} "${${ARGV0}}" CACHE STRING "${ARGV2}" FORCE) + endif() + endif() + endforeach() +endmacro() + +# Specify link flags +add_compile_param(CROSS_LINK_FLAGS "--sysroot=${CROSS_ROOTFS}") +add_compile_param(CROSS_LINK_FLAGS "--gcc-toolchain=${CROSS_ROOTFS}/usr") +add_compile_param(CROSS_LINK_FLAGS "--target=${TOOLCHAIN}") +add_compile_param(CROSS_LINK_FLAGS "-fuse-ld=gold") + +if(TARGET_ARCH_NAME STREQUAL "armel") + if(DEFINED TIZEN_TOOLCHAIN) # For Tizen only + add_compile_param(CROSS_LINK_FLAGS "-B${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}") + add_compile_param(CROSS_LINK_FLAGS "-L${CROSS_ROOTFS}/lib") + add_compile_param(CROSS_LINK_FLAGS "-L${CROSS_ROOTFS}/usr/lib") + add_compile_param(CROSS_LINK_FLAGS "-L${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}") + endif() +elseif(TARGET_ARCH_NAME STREQUAL "x86") + add_compile_param(CROSS_LINK_FLAGS "-m32") +endif() + +add_compile_param(CMAKE_EXE_LINKER_FLAGS "${CROSS_LINK_FLAGS}" "TOOLCHAIN_EXE_LINKER_FLAGS") +add_compile_param(CMAKE_SHARED_LINKER_FLAGS "${CROSS_LINK_FLAGS}" "TOOLCHAIN_EXE_LINKER_FLAGS") +add_compile_param(CMAKE_MODULE_LINKER_FLAGS "${CROSS_LINK_FLAGS}" "TOOLCHAIN_EXE_LINKER_FLAGS") + +# Specify compile options +add_compile_options("--sysroot=${CROSS_ROOTFS}") +add_compile_options("--target=${TOOLCHAIN}") +add_compile_options("--gcc-toolchain=${CROSS_ROOTFS}/usr") + +if(TARGET_ARCH_NAME MATCHES "^(arm|armel|arm64)$") + set(CMAKE_C_COMPILER_TARGET ${TOOLCHAIN}) + set(CMAKE_CXX_COMPILER_TARGET ${TOOLCHAIN}) + set(CMAKE_ASM_COMPILER_TARGET ${TOOLCHAIN}) +endif() + +if(TARGET_ARCH_NAME MATCHES "^(arm|armel)$") + add_compile_options(-mthumb) + add_compile_options(-mfpu=vfpv3) + if(TARGET_ARCH_NAME STREQUAL "armel") + add_compile_options(-mfloat-abi=softfp) + if(DEFINED TIZEN_TOOLCHAIN) + add_compile_options(-Wno-deprecated-declarations) # compile-time option + add_compile_options(-D__extern_always_inline=inline) # compile-time option + endif() + endif() +elseif(TARGET_ARCH_NAME STREQUAL "x86") + add_compile_options(-m32) + add_compile_options(-Wno-error=unused-command-line-argument) +endif() + +# Set LLDB include and library paths +if(TARGET_ARCH_NAME MATCHES "^(arm|armel|x86)$") + if(TARGET_ARCH_NAME STREQUAL "x86") + set(LLVM_CROSS_DIR "$ENV{LLVM_CROSS_HOME}") + else() # arm/armel case + set(LLVM_CROSS_DIR "$ENV{LLVM_ARM_HOME}") + endif() + if(LLVM_CROSS_DIR) + set(WITH_LLDB_LIBS "${LLVM_CROSS_DIR}/lib/" CACHE STRING "") + set(WITH_LLDB_INCLUDES "${LLVM_CROSS_DIR}/include" CACHE STRING "") + set(LLDB_H "${WITH_LLDB_INCLUDES}" CACHE STRING "") + set(LLDB "${LLVM_CROSS_DIR}/lib/liblldb.so" CACHE STRING "") + else() + if(TARGET_ARCH_NAME STREQUAL "x86") + set(WITH_LLDB_LIBS "${CROSS_ROOTFS}/usr/lib/i386-linux-gnu" CACHE STRING "") + set(CHECK_LLVM_DIR "${CROSS_ROOTFS}/usr/lib/llvm-3.8/include") + if(EXISTS "${CHECK_LLVM_DIR}" AND IS_DIRECTORY "${CHECK_LLVM_DIR}") + set(WITH_LLDB_INCLUDES "${CHECK_LLVM_DIR}") + else() + set(WITH_LLDB_INCLUDES "${CROSS_ROOTFS}/usr/lib/llvm-3.6/include") + endif() + else() # arm/armel case + set(WITH_LLDB_LIBS "${CROSS_ROOTFS}/usr/lib/${TOOLCHAIN}" CACHE STRING "") + set(WITH_LLDB_INCLUDES "${CROSS_ROOTFS}/usr/lib/llvm-3.6/include" CACHE STRING "") + endif() + endif() +endif() + +set(CMAKE_FIND_ROOT_PATH "${CROSS_ROOTFS}") +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) diff --git a/external/corert/cross/tryrun.cmake b/external/corert/cross/tryrun.cmake new file mode 100644 index 0000000000..6cc80f4bc1 --- /dev/null +++ b/external/corert/cross/tryrun.cmake @@ -0,0 +1,54 @@ +set(TARGET_ARCH_NAME $ENV{TARGET_BUILD_ARCH}) + +macro(set_cache_value) + set(${ARGV0} ${ARGV1} CACHE STRING "Result from TRY_RUN" FORCE) +endmacro() + +if(NOT TARGET_ARCH_NAME MATCHES "^(armel|arm|arm64|x86)$") + message(FATAL_ERROR "Arch is ${TARGET_ARCH_NAME}. Only armel, arm, arm64 and x86 are supported!") +endif() + +set_cache_value(HAVE_CLOCK_MONOTONIC_COARSE_EXITCODE 0) +set_cache_value(HAVE_CLOCK_MONOTONIC_EXITCODE 0) +set_cache_value(HAVE_SCHED_GETCPU_EXITCODE 0) + +if(TARGET_ARCH_NAME STREQUAL "x86") + set_cache_value(HAVE_CLOCK_THREAD_CPUTIME_EXITCODE 0) + set_cache_value(HAVE_COMPATIBLE_POW_EXITCODE 0) + set_cache_value(HAVE_FUNCTIONAL_PTHREAD_ROBUST_MUTEXES 0) + set_cache_value(HAVE_PROCFS_CTL_EXITCODE 1) + set_cache_value(HAVE_PROCFS_MAPS_EXITCODE 0) + set_cache_value(HAVE_PROCFS_STATUS_EXITCODE 0) + set_cache_value(HAVE_PROCFS_STAT_EXITCODE 0) +endif() + +if(TARGET_ARCH_NAME MATCHES "^(arm|arm64)$") + set_cache_value(HAVE_COMPATIBLE_POW_EXITCODE 1) + set_cache_value(MMAP_DOESNOT_ALLOW_REMAP_EXITCODE 1) + set_cache_value(MMAP_IGNORES_HINT_EXITCODE 1) +endif() + +if(TARGET_ARCH_NAME MATCHES "^(arm|arm64|x86)$") + set_cache_value(FILE_OPS_CHECK_FERROR_OF_PREVIOUS_CALL_EXITCODE 1) + set_cache_value(GETPWUID_R_SETS_ERRNO_EXITCODE 0) + set_cache_value(HAS_POSIX_SEMAPHORES_EXITCODE 0) + set_cache_value(HAVE_COMPATIBLE_ACOS_EXITCODE 0) + set_cache_value(HAVE_COMPATIBLE_ASIN_EXITCODE 0) + set_cache_value(HAVE_COMPATIBLE_ATAN2_EXITCODE 0) + set_cache_value(HAVE_COMPATIBLE_LOG10_EXITCODE 0) + set_cache_value(HAVE_COMPATIBLE_LOG_EXITCODE 0) + set_cache_value(HAVE_LARGE_SNPRINTF_SUPPORT_EXITCODE 0) + set_cache_value(HAVE_MMAP_DEV_ZERO_EXITCODE 0) + set_cache_value(HAVE_SCHED_GET_PRIORITY_EXITCODE 0) + set_cache_value(HAVE_VALID_NEGATIVE_INF_POW_EXITCODE 0) + set_cache_value(HAVE_VALID_POSITIVE_INF_POW_EXITCODE 0) + set_cache_value(HAVE_WORKING_CLOCK_GETTIME_EXITCODE 0) + set_cache_value(HAVE_WORKING_GETTIMEOFDAY_EXITCODE 0) + set_cache_value(ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS_EXITCODE 1) + set_cache_value(PTHREAD_CREATE_MODIFIES_ERRNO_EXITCODE 1) + set_cache_value(REALPATH_SUPPORTS_NONEXISTENT_FILES_EXITCODE 1) + set_cache_value(SEM_INIT_MODIFIES_ERRNO_EXITCODE 1) + set_cache_value(SSCANF_CANNOT_HANDLE_MISSING_EXPONENT_EXITCODE 1) + set_cache_value(SSCANF_SUPPORT_ll_EXITCODE 0) + set_cache_value(UNGETC_NOT_RETURN_EOF_EXITCODE 0) +endif() diff --git a/external/corert/cross/x86/toolchain.cmake b/external/corert/cross/x86/toolchain.cmake deleted file mode 100644 index ccc3a03565..0000000000 --- a/external/corert/cross/x86/toolchain.cmake +++ /dev/null @@ -1,39 +0,0 @@ -set(CROSS_ROOTFS $ENV{ROOTFS_DIR}) - -set(CMAKE_SYSTEM_NAME Linux) -set(CMAKE_SYSTEM_PROCESSOR i686) - -add_compile_options("-m32") -add_compile_options("--sysroot=${CROSS_ROOTFS}") -add_compile_options("-Wno-error=unused-command-line-argument") - -set(CROSS_LINK_FLAGS "--sysroot=${CROSS_ROOTFS}") -set(CROSS_LINK_FLAGS "${CROSS_LINK_FLAGS} -B ${CROSS_ROOTFS}/usr/lib/gcc/i686-linux-gnu") -set(CROSS_LINK_FLAGS "${CROSS_LINK_FLAGS} -L${CROSS_ROOTFS}/lib/i386-linux-gnu") -set(CROSS_LINK_FLAGS "${CROSS_LINK_FLAGS} -m32") - -set(CMAKE_EXE_LINKER_FLAGS "${CROSS_LINK_FLAGS}" CACHE STRING "TOOLCHAIN_EXE_LINKER_FLAGS" FORCE) -set(CMAKE_SHARED_LINKER_FLAGS "${CROSS_LINK_FLAGS}" CACHE STRING "TOOLCHAIN_SHARED_LINKER_FLAGS" FORCE) -set(CMAKE_MODULE_LINKER_FLAGS "${CROSS_LINK_FLAGS}" CACHE STRING "TOOLCHAIN_MODULE_LINKER_FLAGS" FORCE) - -set(CMAKE_FIND_ROOT_PATH "${CROSS_ROOTFS}") -set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) - -set(LLVM_CROSS_DIR "$ENV{LLVM_CROSS_HOME}") -if(LLVM_CROSS_DIR) - set(WITH_LLDB_LIBS "${LLVM_CROSS_DIR}/lib/" CACHE STRING "") - set(WITH_LLDB_INCLUDES "${LLVM_CROSS_DIR}/include" CACHE STRING "") - set(LLDB_H "${WITH_LLDB_INCLUDES}" CACHE STRING "") - set(LLDB "${LLVM_CROSS_DIR}/lib/liblldb.so" CACHE STRING "") -else() - set(WITH_LLDB_LIBS "${CROSS_ROOTFS}/usr/lib/i386-linux-gnu" CACHE STRING "") - set(CHECK_LLVM_DIR "${CROSS_ROOTFS}/usr/lib/llvm-3.8/include") - if(EXISTS "${CHECK_LLVM_DIR}" AND IS_DIRECTORY "${CHECK_LLVM_DIR}") - set(WITH_LLDB_INCLUDES "${CHECK_LLVM_DIR}") - else() - set(WITH_LLDB_INCLUDES "${CROSS_ROOTFS}/usr/lib/llvm-3.6/include") - endif() -endif() diff --git a/external/corert/cross/x86/tryrun.cmake b/external/corert/cross/x86/tryrun.cmake deleted file mode 100644 index 1bf3da935c..0000000000 --- a/external/corert/cross/x86/tryrun.cmake +++ /dev/null @@ -1,127 +0,0 @@ -SET( REALPATH_SUPPORTS_NONEXISTENT_FILES_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( SSCANF_SUPPORT_ll_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( SSCANF_CANNOT_HANDLE_MISSING_EXPONENT_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_LARGE_SNPRINTF_SUPPORT_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_SCHED_GET_PRIORITY_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_WORKING_GETTIMEOFDAY_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_WORKING_CLOCK_GETTIME_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_CLOCK_MONOTONIC_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_MMAP_DEV_ZERO_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( PTHREAD_CREATE_MODIFIES_ERRNO_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( SEM_INIT_MODIFIES_ERRNO_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_ACOS_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_ASIN_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_POW_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_VALID_NEGATIVE_INF_POW_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_VALID_POSITIVE_INF_POW_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_ATAN2_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_LOG_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_COMPATIBLE_LOG10_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( UNGETC_NOT_RETURN_EOF_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAS_POSIX_SEMAPHORES_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( GETPWUID_R_SETS_ERRNO_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( FILE_OPS_CHECK_FERROR_OF_PREVIOUS_CALL_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_CLOCK_THREAD_CPUTIME_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_SCHED_GETCPU_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_CLOCK_MONOTONIC_COARSE_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_PROCFS_CTL_EXITCODE - 1 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_PROCFS_MAPS_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_PROCFS_STAT_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_PROCFS_STATUS_EXITCODE - 0 - CACHE STRING "Result from TRY_RUN" FORCE) - -SET( HAVE_FUNCTIONAL_PTHREAD_ROBUST_MUTEXES - 0 - CACHE STRING "Result from TRY_RUN" FORCE) diff --git a/external/corert/dependencies.props b/external/corert/dependencies.props index 6d97c96dfc..578a743299 100644 --- a/external/corert/dependencies.props +++ b/external/corert/dependencies.props @@ -1,11 +1,13 @@ - 2.1.0-preview2-26207-13 - 1.0.19-prerelease-00001 - 4.5.0-preview2-26202-05 - 4.6.0-preview2-26202-05 - 2.1.0-preview2-26207-13 - 2.0.0 - 1.0.1-prerelease-02104-02 + 3.0.0-preview1-26831-01 + 1.0.0-alpha-26412-0 + 4.6.0-preview1-26831-01 + 4.7.0-preview1-26831-01 + 3.0.0-preview1-26831-01 + 2.1.0 + 15.8.0 + 2.4.1-pre.build.4059 + 2.4.0-beta.18420.3 diff --git a/external/corert/dir.props b/external/corert/dir.props index b3b81a0dc1..9ff9c1446d 100644 --- a/external/corert/dir.props +++ b/external/corert/dir.props @@ -149,7 +149,7 @@ - + @@ -254,7 +254,7 @@ true - .NETCoreApp,Version=v2.0 + .NETCoreApp,Version=v2.1 false @@ -263,6 +263,11 @@ true + + + %WINDIR%\Microsoft.NET\Framework\v4.0.30319\ilasm.exe + + diff --git a/external/corert/dir.targets b/external/corert/dir.targets index ba5405fa2b..bb03d1d58d 100644 --- a/external/corert/dir.targets +++ b/external/corert/dir.targets @@ -17,11 +17,11 @@ false - - + + .NETCoreApp - v2.0 + v2.1 @@ -36,6 +36,21 @@ + + + .NETStandard,Version=v2.0 + .NETStandard + v2.0 + + + + 2.0.3 + + + + + + .NETStandard diff --git a/external/corert/init-tools.cmd b/external/corert/init-tools.cmd index 2818750203..7c5fbfa122 100644 --- a/external/corert/init-tools.cmd +++ b/external/corert/init-tools.cmd @@ -2,20 +2,21 @@ setlocal set INIT_TOOLS_LOG=%~dp0init-tools.log -if [%PACKAGES_DIR%]==[] set PACKAGES_DIR=%~dp0packages\ +if [%PACKAGES_DIR%]==[] set PACKAGES_DIR=%~dp0packages if [%TOOLRUNTIME_DIR%]==[] set TOOLRUNTIME_DIR=%~dp0Tools set DOTNET_PATH=%TOOLRUNTIME_DIR%\dotnetcli\ if [%DOTNET_CMD%]==[] set DOTNET_CMD=%DOTNET_PATH%dotnet.exe if [%BUILDTOOLS_SOURCE%]==[] set BUILDTOOLS_SOURCE=https://dotnet.myget.org/F/dotnet-buildtools/api/v3/index.json set /P BUILDTOOLS_VERSION=< "%~dp0BuildToolsVersion.txt" -set BUILD_TOOLS_PATH=%PACKAGES_DIR%Microsoft.DotNet.BuildTools\%BUILDTOOLS_VERSION%\lib\ +set BUILD_TOOLS_PATH=%PACKAGES_DIR%\Microsoft.DotNet.BuildTools\%BUILDTOOLS_VERSION%\lib set INIT_TOOLS_RESTORE_PROJECT=%~dp0init-tools.msbuild -set BUILD_TOOLS_SEMAPHORE=%TOOLRUNTIME_DIR%\%BUILDTOOLS_VERSION%\init-tools.completed +set BUILD_TOOLS_SEMAPHORE_DIR=%TOOLRUNTIME_DIR%\%BUILDTOOLS_VERSION% +set BUILD_TOOLS_SEMAPHORE=%BUILD_TOOLS_SEMAPHORE_DIR%\init-tools.completed :: if force option is specified then clean the tool runtime and build tools package directory to force it to get recreated if [%1]==[force] ( if exist "%TOOLRUNTIME_DIR%" rmdir /S /Q "%TOOLRUNTIME_DIR%" - if exist "%PACKAGES_DIR%Microsoft.DotNet.BuildTools" rmdir /S /Q "%PACKAGES_DIR%Microsoft.DotNet.BuildTools" + if exist "%PACKAGES_DIR%\Microsoft.DotNet.BuildTools" rmdir /S /Q "%PACKAGES_DIR%\Microsoft.DotNet.BuildTools" ) :: If semaphore exists do nothing @@ -26,6 +27,21 @@ if exist "%BUILD_TOOLS_SEMAPHORE%" ( if exist "%TOOLRUNTIME_DIR%" rmdir /S /Q "%TOOLRUNTIME_DIR%" +if exist "%DotNetBuildToolsDir%" ( + echo Using tools from '%DotNetBuildToolsDir%'. + mklink /j "%TOOLRUNTIME_DIR%" "%DotNetBuildToolsDir%" + + if not exist "%DOTNET_CMD%" ( + echo ERROR: Ensure that '%DotNetBuildToolsDir%' contains the .NET Core SDK at '%DOTNET_PATH%' + exit /b 1 + ) + + echo Done initializing tools. + if NOT exist "%BUILD_TOOLS_SEMAPHORE_DIR%" mkdir "%BUILD_TOOLS_SEMAPHORE_DIR%" + echo Using tools from '%DotNetBuildToolsDir%'. > "%BUILD_TOOLS_SEMAPHORE%" + exit /b 0 +) + echo Running %0 > "%INIT_TOOLS_LOG%" set /p DOTNET_VERSION=< "%~dp0DotnetCLIVersion.txt" @@ -37,7 +53,7 @@ set DOTNET_ZIP_NAME=dotnet-sdk-%DOTNET_VERSION%-win-x64.zip set DOTNET_REMOTE_PATH=https://dotnetcli.azureedge.net/dotnet/Sdk/%DOTNET_VERSION%/%DOTNET_ZIP_NAME% set DOTNET_LOCAL_PATH=%DOTNET_PATH%%DOTNET_ZIP_NAME% echo Installing '%DOTNET_REMOTE_PATH%' to '%DOTNET_LOCAL_PATH%' >> "%INIT_TOOLS_LOG%" -powershell -NoProfile -ExecutionPolicy unrestricted -Command "$retryCount = 0; $success = $false; do { try { (New-Object Net.WebClient).DownloadFile('%DOTNET_REMOTE_PATH%', '%DOTNET_LOCAL_PATH%'); $success = $true; } catch { if ($retryCount -ge 6) { throw; } else { $retryCount++; Start-Sleep -Seconds (5 * $retryCount); } } } while ($success -eq $false); Add-Type -Assembly 'System.IO.Compression.FileSystem' -ErrorVariable AddTypeErrors; if ($AddTypeErrors.Count -eq 0) { [System.IO.Compression.ZipFile]::ExtractToDirectory('%DOTNET_LOCAL_PATH%', '%DOTNET_PATH%') } else { (New-Object -com shell.application).namespace('%DOTNET_PATH%').CopyHere((new-object -com shell.application).namespace('%DOTNET_LOCAL_PATH%').Items(),16) }" >> "%INIT_TOOLS_LOG%" +powershell -NoProfile -ExecutionPolicy unrestricted -Command "$retryCount = 0; $success = $false; $proxyCredentialsRequired = $false; do { try { $wc = New-Object Net.WebClient; if ($proxyCredentialsRequired) { [Net.WebRequest]::DefaultWebProxy.Credentials = [Net.CredentialCache]::DefaultNetworkCredentials; } $wc.DownloadFile('%DOTNET_REMOTE_PATH%', '%DOTNET_LOCAL_PATH%'); $success = $true; } catch { if ($retryCount -ge 6) { throw; } else { $we = $_.Exception.InnerException -as [Net.WebException]; $proxyCredentialsRequired = ($we -ne $null -and ([Net.HttpWebResponse]$we.Response).StatusCode -eq [Net.HttpStatusCode]::ProxyAuthenticationRequired); Start-Sleep -Seconds (5 * $retryCount); $retryCount++; } } } while ($success -eq $false); Add-Type -Assembly 'System.IO.Compression.FileSystem' -ErrorVariable AddTypeErrors; if ($AddTypeErrors.Count -eq 0) { [System.IO.Compression.ZipFile]::ExtractToDirectory('%DOTNET_LOCAL_PATH%', '%DOTNET_PATH%') } else { (New-Object -com shell.application).namespace('%DOTNET_PATH%').CopyHere((new-object -com shell.application).namespace('%DOTNET_LOCAL_PATH%').Items(),16) }" >> "%INIT_TOOLS_LOG%" if NOT exist "%DOTNET_LOCAL_PATH%" ( echo ERROR: Could not install dotnet cli correctly. 1>&2 goto :error @@ -47,9 +63,9 @@ if NOT exist "%DOTNET_LOCAL_PATH%" ( if exist "%BUILD_TOOLS_PATH%" goto :afterbuildtoolsrestore echo Restoring BuildTools version %BUILDTOOLS_VERSION%... -echo Running: "%DOTNET_CMD%" restore "%INIT_TOOLS_RESTORE_PROJECT%" --no-cache --packages %PACKAGES_DIR% --source "%BUILDTOOLS_SOURCE%" /p:BuildToolsPackageVersion=%BUILDTOOLS_VERSION% >> "%INIT_TOOLS_LOG%" -call "%DOTNET_CMD%" restore "%INIT_TOOLS_RESTORE_PROJECT%" --no-cache --packages %PACKAGES_DIR% --source "%BUILDTOOLS_SOURCE%" /p:BuildToolsPackageVersion=%BUILDTOOLS_VERSION% >> "%INIT_TOOLS_LOG%" -if NOT exist "%BUILD_TOOLS_PATH%init-tools.cmd" ( +echo Running: "%DOTNET_CMD%" restore "%INIT_TOOLS_RESTORE_PROJECT%" --no-cache --packages "%PACKAGES_DIR%" --source "%BUILDTOOLS_SOURCE%" /p:BuildToolsPackageVersion=%BUILDTOOLS_VERSION% /p:ToolsDir=%TOOLRUNTIME_DIR% >> "%INIT_TOOLS_LOG%" +call "%DOTNET_CMD%" restore "%INIT_TOOLS_RESTORE_PROJECT%" --no-cache --packages "%PACKAGES_DIR%" --source "%BUILDTOOLS_SOURCE%" /p:BuildToolsPackageVersion=%BUILDTOOLS_VERSION% /p:ToolsDir=%TOOLRUNTIME_DIR% >> "%INIT_TOOLS_LOG%" +if NOT exist "%BUILD_TOOLS_PATH%\init-tools.cmd" ( echo ERROR: Could not restore build tools correctly. 1>&2 goto :error ) @@ -57,19 +73,17 @@ if NOT exist "%BUILD_TOOLS_PATH%init-tools.cmd" ( :afterbuildtoolsrestore echo Initializing BuildTools... -echo Running: "%BUILD_TOOLS_PATH%init-tools.cmd" "%~dp0" "%DOTNET_CMD%" "%TOOLRUNTIME_DIR%" >> "%INIT_TOOLS_LOG%" -call "%BUILD_TOOLS_PATH%init-tools.cmd" "%~dp0" "%DOTNET_CMD%" "%TOOLRUNTIME_DIR%" >> "%INIT_TOOLS_LOG%" +echo Running: "%BUILD_TOOLS_PATH%\init-tools.cmd" "%~dp0" "%DOTNET_CMD%" "%TOOLRUNTIME_DIR%" >> "%INIT_TOOLS_LOG%" +call "%BUILD_TOOLS_PATH%\init-tools.cmd" "%~dp0" "%DOTNET_CMD%" "%TOOLRUNTIME_DIR%" "%PACKAGES_DIR%" >> "%INIT_TOOLS_LOG%" set INIT_TOOLS_ERRORLEVEL=%ERRORLEVEL% if not [%INIT_TOOLS_ERRORLEVEL%]==[0] ( echo ERROR: An error occured when trying to initialize the tools. 1>&2 goto :error ) -rem CoreRT does not use special copy of the shared runtime for testing -copy /Y %TOOLRUNTIME_DIR%\csc.runtimeconfig.json %TOOLRUNTIME_DIR%\xunit.console.netcore.runtimeconfig.json - :: Create semaphore file echo Done initializing tools. +if NOT exist "%BUILD_TOOLS_SEMAPHORE_DIR%" mkdir "%BUILD_TOOLS_SEMAPHORE_DIR%" echo Init-Tools.cmd completed for BuildTools Version: %BUILDTOOLS_VERSION% > "%BUILD_TOOLS_SEMAPHORE%" exit /b 0 diff --git a/external/corert/init-tools.msbuild b/external/corert/init-tools.msbuild index 1ec33f6782..f515eb968d 100644 --- a/external/corert/init-tools.msbuild +++ b/external/corert/init-tools.msbuild @@ -1,6 +1,6 @@ - netcoreapp1.0 + netcoreapp2.1 false true $(MSBuildThisFileDirectory)Tools/$(BuildToolsPackageVersion) diff --git a/external/corert/init-tools.sh b/external/corert/init-tools.sh index 969c985487..bb7362a08b 100755 --- a/external/corert/init-tools.sh +++ b/external/corert/init-tools.sh @@ -42,9 +42,7 @@ if [ -z "$__DOTNET_PKG" ]; then if [ -e /etc/os-release ]; then source /etc/os-release if [[ $ID == "alpine" ]]; then - # remove the last version digit - VERSION_ID=${VERSION_ID%.*} - __PKG_RID=alpine.$VERSION_ID + __PKG_RID="linux-musl" fi elif [ -e /etc/redhat-release ]; then @@ -62,7 +60,8 @@ if [ -z "$__DOTNET_PKG" ]; then __PKG_RID=linux ;; esac - __DOTNET_PKG=dotnet-sdk-${__DOTNET_TOOLS_VERSION}-$__PKG_RID-$__HostArch + __PKG_RID=$__PKG_RID-$__HostArch + __DOTNET_PKG=dotnet-sdk-${__DOTNET_TOOLS_VERSION}-$__PKG_RID fi display_error_message() @@ -147,10 +146,7 @@ if [ ! -e $__INIT_TOOLS_DONE_MARKER ]; then ls $__scriptpath/Tools/*.sh | xargs chmod +x ls $__scriptpath/Tools/scripts/docker/*.sh | xargs chmod +x - Tools/crossgen.sh $__scriptpath/Tools - - # CoreRT does not use special copy of the shared runtime for testing - cp $__TOOLRUNTIME_DIR/csc.runtimeconfig.json $__TOOLRUNTIME_DIR/xunit.console.netcore.runtimeconfig.json + Tools/crossgen.sh $__scriptpath/Tools $__PKG_RID mkdir -p $__INIT_TOOLS_DONE_MARKER_DIR touch $__INIT_TOOLS_DONE_MARKER diff --git a/external/corert/netci.groovy b/external/corert/netci.groovy index d98779822c..5877dd7c0e 100644 --- a/external/corert/netci.groovy +++ b/external/corert/netci.groovy @@ -8,96 +8,184 @@ def project = GithubProject // The input branch name (e.g. master) def branch = GithubBranchName -def imageVersionMap = ['Windows_NT':'latest-or-auto', - 'OSX10.12':'latest-or-auto', - 'Ubuntu':'20170118'] - -// Innerloop build OS's -def osList = ['Ubuntu', 'OSX10.12', 'Windows_NT'] +class Constants { + + def static imageVersionMap = ['Windows_NT':'latest-or-auto', + 'OSX10.12':'latest-or-auto', + 'Ubuntu':'20170118'] + + def static scenarios = ['coreclr', 'corefx'] + + // Innerloop build OS's + def static osList = ['Ubuntu', 'OSX10.12', 'Windows_NT', 'Windows_NT_Wasm'] + +} // Generate the builds for debug and release, commit and PRJob -[true, false].each { isPR -> // Defines a closure over true and false, value assigned to isPR - ['Debug', 'Release'].each { configuration -> - osList.each { os -> +Constants.scenarios.each { scenario -> + [true, false].each { isPR -> // Defines a closure over true and false, value assigned to isPR + ['Debug', 'Release'].each { configuration -> + Constants.osList.each { os -> - // Define build string - def lowercaseConfiguration = configuration.toLowerCase() - - // Determine the name for the new job. The first parameter is the project, - // the second parameter is the base name for the job, and the last parameter - // is a boolean indicating whether the job will be a PR job. If true, the - // suffix _prtest will be appended. - def newJobName = Utilities.getFullJobName(project, lowercaseConfiguration + '_' + os.toLowerCase(), isPR) - def buildString = ""; - def prJobDescription = "${os} ${configuration}"; - if (configuration == 'Debug') { - prJobDescription += " and CoreCLR tests" - } - - // Calculate the build commands - if (os == 'Windows_NT') { - buildString = "build.cmd ${lowercaseConfiguration}" - testScriptString = "tests\\runtest.cmd ${configuration} /coreclr " - } - else { - buildString = "./build.sh ${lowercaseConfiguration}" - testScriptString = "tests/runtest.sh ${configuration} -coredumps -coreclr " - } + if (configuration == 'Release' && scenario == 'corefx') { + return + } - // Create a new job with the specified name. The brace opens a new closure - // and calls made within that closure apply to the newly created job. - def newJob = job(newJobName) { - // This opens the set of build steps that will be run. - steps { - if (os == 'Windows_NT') { - // Indicates that a batch script should be run with the build string (see above) - batchFile(buildString) - batchFile("tests\\runtest.cmd ${configuration} /multimodule") + // Disable the corefx scenario for wasm for now since + // the tests won't work + if (os == 'Windows_NT_Wasm' && scenario == 'corefx') { + return + } - if (configuration == 'Debug') { - if (isPR) { - // Run a small set of BVTs during PR validation - batchFile(testScriptString + "Top200") - } - else { - // Run the full set of known passing tests in the post-commit job - batchFile(testScriptString + "KnownGood /multimodule") + // Define build string + def lowercaseConfiguration = configuration.toLowerCase() + + // Determine the name for the new job. The first parameter is the project, + // the second parameter is the base name for the job, and the last parameter + // is a boolean indicating whether the job will be a PR job. If true, the + // suffix _prtest will be appended. + def baseJobName = lowercaseConfiguration + '_' + os.toLowerCase() + if (scenario != 'coreclr') { + baseJobName += '_' + scenario + } + def newJobName = Utilities.getFullJobName(project, baseJobName, isPR) + def buildString = ""; + def prJobDescription = "${os} ${configuration}"; + if (configuration == 'Debug') { + if (scenario == 'coreclr') { + prJobDescription += " and CoreCLR tests" + } + if (scenario == 'corefx') { + prJobDescription += " and CoreFX tests" + } + } + + def buildCommands = calculateBuildCommands(os, configuration, scenario, isPR) + + // Create a new job with the specified name. The brace opens a new closure + // and calls made within that closure apply to the newly created job. + def newJob = job(newJobName) { + // This opens the set of build steps that will be run. + steps { + if (os.startsWith('Windows_NT')) { + // Indicates that a batch script should be run with each build command + buildCommands.each { buildCommand -> + batchFile(buildCommand) } } - } - else { - shell(buildString) - - if (configuration == 'Debug') { - if (isPR) { - // Run a small set of BVTs during PR validation - shell(testScriptString + "top200") - } - else { - // Run the full set of known passing tests in the post-commit job - - // Todo: Enable push test jobs once we establish a reasonable passing set of tests - // shell(testScriptString + "KnownGood") + else { + buildCommands.each { buildCommand -> + shell(buildCommand) } } } } - } - // This call performs test run checks for the CI. - Utilities.addXUnitDotNETResults(newJob, '**/testResults.xml') - Utilities.setMachineAffinity(newJob, os, imageVersionMap[os]) - Utilities.standardJobSetup(newJob, project, isPR, "*/${branch}") - if (isPR) { - Utilities.addGithubPRTriggerForBranch(newJob, branch, prJobDescription) - } - else { - // Set a large timeout since the default (2 hours) is insufficient - Utilities.setJobTimeout(newJob, 1440) - Utilities.addGithubPushTrigger(newJob) + // This call performs test run checks for the CI. + Utilities.addXUnitDotNETResults(newJob, '**/testResults.xml') + Utilities.addArchival(newJob, "**/testResults.xml") + if (os == 'Windows_NT_Wasm') { + Utilities.setMachineAffinity(newJob, 'Windows.10.Wasm.Open') + prJobDescription += " WebAssembly" + } + else { + Utilities.setMachineAffinity(newJob, os, Constants.imageVersionMap[os]) + } + Utilities.standardJobSetup(newJob, project, isPR, "*/${branch}") + + if (isPR) { + Utilities.addGithubPRTriggerForBranch(newJob, branch, prJobDescription) + } + else { + // Set a large timeout since the default (2 hours) is insufficient + Utilities.setJobTimeout(newJob, 1440) + Utilities.addGithubPushTrigger(newJob) + } } } } } +def static calculateBuildCommands(def os, def configuration, def scenario, def isPR) { + + def buildCommands = [] + def lowercaseConfiguration = configuration.toLowerCase() + def testScriptString= '' + + if (os == 'Windows_NT') { + // Calculate the build commands + buildCommands += "build.cmd ${lowercaseConfiguration} skiptests" + + if (scenario == 'coreclr'){ + // Run simple tests and multimodule tests only under CoreCLR mode + buildCommands += "tests\\runtest.cmd ${configuration} " + buildCommands += "tests\\runtest.cmd ${configuration} /multimodule" + if (configuration == 'Debug') + { + // Run CoreCLR tests + testScriptString = "tests\\runtest.cmd ${configuration} /coreclr " + if (isPR) { + // Run a small set of BVTs during PR validation + buildCommands += testScriptString + "Top200" + } + else { + // Run the full set of known passing tests in the post-commit job + buildCommands += testScriptString + "KnownGood /multimodule" + } + } + } + else if (scenario == 'corefx') + { + // CoreFX tests are currently run only under Debug, so skip the configuration check + testScriptString = "tests\\runtest.cmd ${configuration} /corefx " + + //Todo: Add json config files for different testing scenarios + buildCommands += testScriptString + } + } + else if (os == 'Windows_NT_Wasm') { + // Emsdk isn't necessarily activated correctly on CI machines (but should be on the path), so activate it now + buildCommands += "emsdk activate latest" + + buildCommands += "build.cmd wasm ${lowercaseConfiguration} skiptests" + buildCommands += "tests\\runtest.cmd wasm ${configuration}" + } + else { + // Calculate the build commands + buildCommands += "./build.sh ${lowercaseConfiguration} skiptests" + + // Calculate the test commands + if (scenario == 'coreclr' ) + { + // Run simple tests and multimodule tests only under CoreCLR mode + buildCommands += "tests/runtest.sh ${configuration} " + + if (configuration == 'Debug') + { + testScriptString = "tests/runtest.sh ${configuration} -coredumps -coreclr " + if (isPR) { + // Run a small set of BVTs during PR validation + buildCommands += testScriptString + "top200" + } + else { + // Run the full set of known passing tests in the post-commit job + + // Todo: Enable push test jobs once we establish a reasonable passing set of tests + // shell(testScriptString + "KnownGood") + } + } + } + else if (scenario == 'corefx') + { + // CoreFX tests are currently run only under Debug, so skip the configuration check + testScriptString = "tests/runtest.sh ${configuration} -corefx " + + //Todo: Add json config files for different testing scenarios + buildCommands += testScriptString + } + } + + return buildCommands +} + JobReport.Report.generateJobReport(out) diff --git a/external/corert/pkg/Microsoft.DotNet.ILCompiler/TargetSpecific/Microsoft.DotNet.ILCompiler.pkgproj b/external/corert/pkg/Microsoft.DotNet.ILCompiler/TargetSpecific/Microsoft.DotNet.ILCompiler.pkgproj index df63fb391a..25fa52a38f 100644 --- a/external/corert/pkg/Microsoft.DotNet.ILCompiler/TargetSpecific/Microsoft.DotNet.ILCompiler.pkgproj +++ b/external/corert/pkg/Microsoft.DotNet.ILCompiler/TargetSpecific/Microsoft.DotNet.ILCompiler.pkgproj @@ -46,6 +46,9 @@ sdk + + sdk + diff --git a/external/corert/pkg/Microsoft.DotNet.ILVerification/Microsoft.DotNet.ILVerification.builds b/external/corert/pkg/Microsoft.DotNet.ILVerification/Microsoft.DotNet.ILVerification.builds new file mode 100644 index 0000000000..8d8ab2f84f --- /dev/null +++ b/external/corert/pkg/Microsoft.DotNet.ILVerification/Microsoft.DotNet.ILVerification.builds @@ -0,0 +1,10 @@ + + + + + + AnyOS + + + + diff --git a/external/corert/pkg/Microsoft.DotNet.ILVerification/Microsoft.DotNet.ILVerification.pkgproj b/external/corert/pkg/Microsoft.DotNet.ILVerification/Microsoft.DotNet.ILVerification.pkgproj new file mode 100644 index 0000000000..4db2b82e48 --- /dev/null +++ b/external/corert/pkg/Microsoft.DotNet.ILVerification/Microsoft.DotNet.ILVerification.pkgproj @@ -0,0 +1,27 @@ + + + + true + true + false + x64; + true + $(PackageSourceDirectory)\BuildIntegration\StrongNameKeys\ILVerify.snk + netcoreapp2.1 + + + + + + $(AdditionalProperties);PackageTargetRuntime= + + + + + + + + + + diff --git a/external/corert/pkg/Microsoft.DotNet.ObjectWriter/Microsoft.DotNet.ObjectWriter.builds b/external/corert/pkg/Microsoft.DotNet.ObjectWriter/Microsoft.DotNet.ObjectWriter.builds new file mode 100644 index 0000000000..e10dd88743 --- /dev/null +++ b/external/corert/pkg/Microsoft.DotNet.ObjectWriter/Microsoft.DotNet.ObjectWriter.builds @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/external/corert/pkg/Microsoft.DotNet.ObjectWriter/Microsoft.DotNet.ObjectWriter.pkgproj b/external/corert/pkg/Microsoft.DotNet.ObjectWriter/Microsoft.DotNet.ObjectWriter.pkgproj new file mode 100644 index 0000000000..47a1114086 --- /dev/null +++ b/external/corert/pkg/Microsoft.DotNet.ObjectWriter/Microsoft.DotNet.ObjectWriter.pkgproj @@ -0,0 +1,32 @@ + + + + true + false + x64; + true + true + true + true + + true + + + + + + + + %(ProjectReference.AdditionalProperties);PackageTargetRuntime=win-x64 + + + %(ProjectReference.AdditionalProperties);PackageTargetRuntime=linux-x64 + + + %(ProjectReference.AdditionalProperties);PackageTargetRuntime=osx-x64 + + + + + + diff --git a/external/corert/pkg/Microsoft.DotNet.ObjectWriter/TargetSpecific/Microsoft.DotNet.ObjectWriter.pkgproj b/external/corert/pkg/Microsoft.DotNet.ObjectWriter/TargetSpecific/Microsoft.DotNet.ObjectWriter.pkgproj new file mode 100644 index 0000000000..901bcb2d24 --- /dev/null +++ b/external/corert/pkg/Microsoft.DotNet.ObjectWriter/TargetSpecific/Microsoft.DotNet.ObjectWriter.pkgproj @@ -0,0 +1,40 @@ + + + + + win-x64 + linux-x64 + osx-x64 + + + + + true + false + x64; + true + true + true + + + + objwriter.dll + libobjwriter.so + libobjwriter.dylib + + + + + runtimes/$(PackageTargetRuntime)/native + + + + + runtimes/$(PackageTargetRuntime)/native + + + + + + + diff --git a/external/corert/pkg/Microsoft.TargetingPack.Private.CoreRT/Microsoft.TargetingPack.Private.CoreRT.pkgproj b/external/corert/pkg/Microsoft.TargetingPack.Private.CoreRT/Microsoft.TargetingPack.Private.CoreRT.pkgproj index 2598926b49..7835ad32f0 100644 --- a/external/corert/pkg/Microsoft.TargetingPack.Private.CoreRT/Microsoft.TargetingPack.Private.CoreRT.pkgproj +++ b/external/corert/pkg/Microsoft.TargetingPack.Private.CoreRT/Microsoft.TargetingPack.Private.CoreRT.pkgproj @@ -5,7 +5,7 @@ true false x64; - netcoreapp2.0 + netcoreapp2.1 diff --git a/external/corert/pkg/descriptions.json b/external/corert/pkg/descriptions.json index 2720ac36ea..37d5295b3c 100644 --- a/external/corert/pkg/descriptions.json +++ b/external/corert/pkg/descriptions.json @@ -24,4 +24,14 @@ "Description":"Provides the toolchain to compile managed code to native", "CommonTypes": [], }, + { + "Name": "Microsoft.DotNet.ILVerification", + "Description":"Provides a library, containing a cross platform, open-source tool that is capable of verifying MSIL code based on ECMA-335", + "CommonTypes": [], + }, + { + "Name": "Microsoft.DotNet.ObjectWriter", + "Description":"Provides object writer to the managed to native code-generator", + "CommonTypes": [], + }, ] diff --git a/external/corert/pkg/packageIndex.json b/external/corert/pkg/packageIndex.json index f1839ab664..2a31230b20 100644 --- a/external/corert/pkg/packageIndex.json +++ b/external/corert/pkg/packageIndex.json @@ -12,5 +12,9 @@ "StableVersions": [], "BaselineVersion": "1.0.0", }, + "Microsoft.DotNet.ObjectWriter" : { + "StableVersions": [], + "BaselineVersion": "1.0.0", + }, } } diff --git a/external/corert/pkg/packages.proj b/external/corert/pkg/packages.proj index 51a4d79a1c..2234384cb0 100644 --- a/external/corert/pkg/packages.proj +++ b/external/corert/pkg/packages.proj @@ -17,6 +17,9 @@ Windows_NT + + Windows_NT + @@ -25,7 +28,13 @@ $(AdditionalProperties);BuildIdentityPackage=$(BuildIdentityPackage) - + + + + AnyOS + $(AdditionalProperties);BuildIdentityPackage=$(BuildIdentityPackage) + + + - diff --git a/external/corert/samples/HelloWorld/HelloWorld.csproj b/external/corert/samples/HelloWorld/HelloWorld.csproj new file mode 100644 index 0000000000..2d34a08cba --- /dev/null +++ b/external/corert/samples/HelloWorld/HelloWorld.csproj @@ -0,0 +1,12 @@ + + + + Exe + netcoreapp2.1 + + + + + + + diff --git a/external/corert/samples/HelloWorld/Program.cs b/external/corert/samples/HelloWorld/Program.cs new file mode 100644 index 0000000000..8168c80511 --- /dev/null +++ b/external/corert/samples/HelloWorld/Program.cs @@ -0,0 +1,12 @@ +using System; + +namespace HelloWorld +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("Hello World!"); + } + } +} diff --git a/external/corert/samples/HelloWorld/README.md b/external/corert/samples/HelloWorld/README.md new file mode 100644 index 0000000000..37377313bf --- /dev/null +++ b/external/corert/samples/HelloWorld/README.md @@ -0,0 +1,55 @@ +# Building a Hello World console app with CoreRT + +CoreRT is an AOT-optimized .NET Core runtime. This document will guide you through compiling a .NET Core Console application with CoreRT. + +_Please ensure that [pre-requisites](../prerequisites.md) are installed._ + +## Create .NET Core Console project +Open a new shell/command prompt window and run the following commands. +```bash +> dotnet new console -o HelloWorld +> cd HelloWorld +``` + +This will create a simple Hello World console app in `Program.cs` and associated project files. + +## Add CoreRT to your project +Using CoreRT to compile your application is done via the ILCompiler NuGet package, which is [published to MyGet with the CoreRT daily builds](https://dotnet.myget.org/feed/dotnet-core/package/nuget/Microsoft.DotNet.ILCompiler). +For the compiler to work, it first needs to be added to your project. + +In your shell/command prompt navigate to the root directory of your project and run the command: + +```bash +> dotnet new nuget +``` + +This will add a nuget.config file to your application. Open the file and in the `` `` element under ```` add the following: + +```xml + + +``` + +Once you've added the package source, add a reference to the compiler by running the following command: + +```bash +> dotnet add package Microsoft.DotNet.ILCompiler -v 1.0.0-alpha-* +``` + +## Restore and Publish your app + +Once the package has been successfully added it's time to compile and publish your app! In the shell/command prompt window, run the following command: + +```bash +> dotnet publish -r -c +``` + +where `` is your project configuration (such as Debug or Release) and `` is the runtime identifier (one of win-x64, linux-x64, osx-x64). For example, if you want to publish a release configuration of your app for a 64-bit version of Windows the command would look like: + +```bash +> dotnet publish -r win-x64 -c release +``` + +Once completed, you can find the native executable in the root folder of your project under `/bin/x64//netcoreapp2.1/publish/`. Navigate to `/bin/x64//netcoreapp2.1/publish/` in your project folder and run the produced native executable. + +Feel free to modify the sample application and experiment. However, keep in mind some functionality might not yet be supported in CoreRT. Let us know on the [Issues page](https://github.com/dotnet/corert/issues/). diff --git a/external/corert/samples/HelloWorld/nuget.config b/external/corert/samples/HelloWorld/nuget.config new file mode 100644 index 0000000000..d8d3f2b015 --- /dev/null +++ b/external/corert/samples/HelloWorld/nuget.config @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/external/corert/samples/MonoGame/NeonShooter.csproj b/external/corert/samples/MonoGame/NeonShooter.csproj index 3d6614148f..b50cad3b01 100644 --- a/external/corert/samples/MonoGame/NeonShooter.csproj +++ b/external/corert/samples/MonoGame/NeonShooter.csproj @@ -1,8 +1,8 @@ - Exe - netcoreapp2.0 + WinExe + netcoreapp2.1 false $(DefineConstants);WINDOWS;LINUX @@ -85,8 +85,8 @@ - - + + diff --git a/external/corert/samples/MonoGame/Platformer2D.csproj b/external/corert/samples/MonoGame/Platformer2D.csproj index b815519420..3dfec0cbfe 100644 --- a/external/corert/samples/MonoGame/Platformer2D.csproj +++ b/external/corert/samples/MonoGame/Platformer2D.csproj @@ -1,8 +1,8 @@ - Exe - netcoreapp2.0 + WinExe + netcoreapp2.1 false $(DefineConstants);WINDOWS;LINUX @@ -64,8 +64,8 @@ - - + + diff --git a/external/corert/samples/MonoGame/README.md b/external/corert/samples/MonoGame/README.md index 2291d2bedf..bbe30394bd 100644 --- a/external/corert/samples/MonoGame/README.md +++ b/external/corert/samples/MonoGame/README.md @@ -1,10 +1,8 @@ # Building a MonoGame app with CoreRT -This document will guide you through compiling a .NET Core [MonoGame](http://www.monogame.net) game with CoreRT. +CoreRT is an AOT-optimized .NET Core runtime. This document will guide you through compiling a .NET Core [MonoGame](http://www.monogame.net) game with CoreRT. -## Install the .NET Core SDK -CoreRT is an AOT-optimized .NET Core runtime. If you're new to .NET Core make sure to visit the [official starting page](http://dotnet.github.io). It will guide you through installing pre-requisites and building your first app. -If you're already familiar with .NET Core make sure you've [downloaded and installed the .NET Core 2 SDK](https://www.microsoft.com/net/download/core). +_Please ensure that [pre-requisites](../prerequisites.md) are installed._ ## Create .NET Core MonoGame project Open a new shell/command prompt window and run the following commands. @@ -22,7 +20,7 @@ Verify that the empty game builds and runs. You should see blue window: > dotnet run ``` -MonoGame tools require [Mono](http://www.mono-project.com/download/) on non-Windows platforms. +MonoGame tools require [Mono](http://www.mono-project.com/download/) on non-Windows platforms. On Windows, MonoGame tools depend on [Visual Studio 2012 Visual C++ redistributable](https://www.microsoft.com/en-us/download/details.aspx?id=30679). ## Add CoreRT to your project Using CoreRT to compile your application is done via the ILCompiler NuGet package, which is [published to MyGet with the CoreRT daily builds](https://dotnet.myget.org/feed/dotnet-core/package/nuget/Microsoft.DotNet.ILCompiler). @@ -61,7 +59,7 @@ where `` is your project configuration (such as Debug or Release) > dotnet publish -r win-x64 -c release ``` -Once completed, you can find the native executable in the root folder of your project under `/bin/x64//netcoreapp2.0/publish/`. Navigate to `/bin/x64//netcoreapp2.0/publish/` in your project folder and run the produced native executable. +Once completed, you can find the native executable in the root folder of your project under `/bin/x64//netcoreapp2.1/publish/`. Navigate to `/bin/x64//netcoreapp2.1/publish/` in your project folder and run the produced native executable. ## Try MonoGame sample game @@ -75,7 +73,7 @@ MonoGame samples include project files for number of targets, but not for .NET C ```bash > dotnet publish -r win-x64 -c release Platformer2D.csproj -> bin\x64\Release\netcoreapp2.0\publish\Platformer2D.exe +> bin\x64\Release\netcoreapp2.1\publish\Platformer2D.exe ``` The NeonShooter sample works on Windows-only due to https://github.com/MonoGame/MonoGame/issues/3270. diff --git a/external/corert/samples/WebApi/README.md b/external/corert/samples/WebApi/README.md index 5c5ca2ed03..338f4c1bd1 100644 --- a/external/corert/samples/WebApi/README.md +++ b/external/corert/samples/WebApi/README.md @@ -1,13 +1,10 @@ # Building a WebAPI app with CoreRT -This document will guide you through compiling a .NET Core Web API application with CoreRT. +CoreRT is an AOT-optimized .NET Core runtime. This document will guide you through compiling a .NET Core Web API application with CoreRT. -## Install the .NET Core SDK -CoreRT is an AOT-optimized .NET Core runtime. If you're new to .NET Core make sure to visit the [official starting page](http://dotnet.github.io). It will guide you through installing pre-requisites and building your first app. -If you're already familiar with .NET Core make sure you've [downloaded and installed the .NET Core 2 SDK](https://www.microsoft.com/net/download/core). +_Please ensure that [pre-requisites](../prerequisites.md) are installed._ ## Create your app - Open a new shell/command prompt window and run the following commands. ```bash > dotnet new webapi -o myApp @@ -51,6 +48,10 @@ services.AddMvc(); to ```csharp +var applicationPartManager = new ApplicationPartManager(); +applicationPartManager.ApplicationParts.Add(new AssemblyPart(typeof(Startup).Assembly)); +services.Add(new ServiceDescriptor(typeof(ApplicationPartManager), applicationPartManager)); + services.AddMvcCore().AddJsonFormatters(); ``` @@ -86,9 +87,9 @@ where path_to_rdxml_file is the location of the file on your disk. Under the second `` remove the line containing a reference to `Microsoft.AspNetCore.All` and substitute it with: ```xml - - - + + + ``` This substitution removes unnecessary package references added by AspNetCore.All, which will remove them from your application's published files and avoid encountering unsupported features, as described in [the section above](#add-core-mvc-services) @@ -132,12 +133,12 @@ where `` is your project configuration (such as Debug or Release) > dotnet publish -r win-x64 -c release ``` -Once completed, you can find the native executable in the root folder of your project under `/bin/x64//netcoreapp2.0/publish/` +Once completed, you can find the native executable in the root folder of your project under `/bin/x64//netcoreapp2.1/publish/` ## Try it out! If you are running macOS, make sure you have [libuv](https://github.com/libuv/libuv) installed, as ASP.NET is built on top of libuv. You can use [homebrew](https://brew.sh/) to get it (`brew install libuv`). -Navigate to `/bin/x64//netcoreapp2.0/publish/` in your project folder and run the produced executable. It should display "Now listening on: http://localhost:XXXX" with XXXX being a port on your machine. Open your browser and navigate to that URL. You should see "Hello World!" displayed in your browser. +Navigate to `/bin/x64//netcoreapp2.1/publish/` in your project folder and run the produced executable. It should display "Now listening on: http://localhost:XXXX" with XXXX being a port on your machine. Open your browser and navigate to that URL. You should see "Hello World!" displayed in your browser. Feel free to modify the sample application and experiment. However, keep in mind some functionality might not yet be supported in CoreRT. Let us know on the [Issues page](https://github.com/dotnet/corert/issues/). diff --git a/external/corert/samples/WebApi/SampleWebApi.csproj b/external/corert/samples/WebApi/SampleWebApi.csproj index 724c9b9c77..c143a4cafa 100644 --- a/external/corert/samples/WebApi/SampleWebApi.csproj +++ b/external/corert/samples/WebApi/SampleWebApi.csproj @@ -1,7 +1,7 @@ - netcoreapp2.0 + netcoreapp2.1 @@ -13,9 +13,9 @@ - - - + + + diff --git a/external/corert/samples/WebApi/Startup.cs b/external/corert/samples/WebApi/Startup.cs index c432519f5b..ec0db593a4 100644 --- a/external/corert/samples/WebApi/Startup.cs +++ b/external/corert/samples/WebApi/Startup.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -27,6 +28,11 @@ namespace SampleWebApi // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { + // Override automatic discovery of Application parts done by MVC. It is not compatible with single file compilation. + var applicationPartManager = new ApplicationPartManager(); + applicationPartManager.ApplicationParts.Add(new AssemblyPart(typeof(Startup).Assembly)); + services.Add(new ServiceDescriptor(typeof(ApplicationPartManager), applicationPartManager)); + services.AddMvcCore().AddJsonFormatters(); } diff --git a/external/corert/samples/WebApi/rd.xml b/external/corert/samples/WebApi/rd.xml index c491837b16..6cf8e2e4f5 100644 --- a/external/corert/samples/WebApi/rd.xml +++ b/external/corert/samples/WebApi/rd.xml @@ -6,13 +6,12 @@ - - - + + + - @@ -32,6 +31,7 @@ + @@ -40,8 +40,12 @@ + + + + @@ -49,9 +53,15 @@ + + + + + + diff --git a/external/corert/samples/prerequisites.md b/external/corert/samples/prerequisites.md new file mode 100644 index 0000000000..a529966c2e --- /dev/null +++ b/external/corert/samples/prerequisites.md @@ -0,0 +1,20 @@ +If you're new to .NET Core make sure to visit the [official starting page](http://dotnet.github.io). It will guide you through installing pre-requisites and building your first app. +If you're already familiar with .NET Core make sure you've [downloaded and installed the .NET Core 2 SDK](https://www.microsoft.com/net/download/core). + +The following pre-requisites need to be installed for building .NET Core projects with CoreRT: + +# Windows + +* Install [Visual Studio 2017](https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx), including Visual C++ support. + +# Ubuntu (14.04+) + +* Install clang and developer packages for libraries that .NET Core depends on. + +```sh +sudo apt-get install libcurl4-openssl-dev zlib1g-dev libkrb5-dev +``` + +# macOS (10.12+) + +* Install [Command Line Tools for XCode 8](https://developer.apple.com/xcode/download/) or higher. diff --git a/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.Publish.targets b/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.Publish.targets index 5a801d7652..bf6c643daa 100644 --- a/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.Publish.targets +++ b/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.Publish.targets @@ -53,6 +53,10 @@ + + + + @@ -66,4 +70,10 @@ + + + + + + diff --git a/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.Unix.props b/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.Unix.props index 441f4754c4..a8c8bafdb5 100644 --- a/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.Unix.props +++ b/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.Unix.props @@ -36,6 +36,8 @@ See the LICENSE file in the project root for more information. .a .bc + libRuntime + libRuntime.ServerGC @@ -50,7 +52,7 @@ See the LICENSE file in the project root for more information. - + @@ -59,6 +61,7 @@ See the LICENSE file in the project root for more information. + @@ -71,26 +74,28 @@ See the LICENSE file in the project root for more information. + + - + - + diff --git a/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.Windows.props b/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.Windows.props index eadca8826d..b06165b8a8 100644 --- a/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.Windows.props +++ b/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.Windows.props @@ -18,6 +18,8 @@ See the LICENSE file in the project root for more information. cl link lib + Runtime + Runtime.ServerGC @@ -36,7 +38,9 @@ See the LICENSE file in the project root for more information. - + + + @@ -61,10 +65,11 @@ See the LICENSE file in the project root for more information. - + + diff --git a/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.targets b/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.targets index 23b817c7a7..e5d806dceb 100644 --- a/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.targets +++ b/external/corert/src/BuildIntegration/Microsoft.NETCore.Native.targets @@ -39,14 +39,15 @@ See the LICENSE file in the project root for more information. .cpp .bc + true - .exe - - .dll - .dylib - .so - .lib - .a + .exe + + .dll + .dylib + .so + .lib + .a .html .def @@ -66,6 +67,8 @@ See the LICENSE file in the project root for more information. $(NativeOutputPath) $(NativeIntermediateOutputPath) + true + $(FrameworkLibPath)\Framework$(LibFileExt) $(FrameworkLibPath)\libframework$(LibFileExt) SetupProperties @@ -77,11 +80,33 @@ See the LICENSE file in the project root for more information. $(IlcCompileDependsOn);SetupOSSpecificProps + + + + + + + + + + + + + + + + + + + + + - + + @@ -159,6 +184,10 @@ See the LICENSE file in the project root for more information. + + + + @@ -180,9 +209,9 @@ See the LICENSE file in the project root for more information. DependsOnTargets="IlcCompile"> - - - + + + @@ -198,19 +227,19 @@ See the LICENSE file in the project root for more information. DependsOnTargets="$(LinkNativeDependsOn)"> - - - - + + + + - + - - - + + + @@ -224,8 +253,8 @@ See the LICENSE file in the project root for more information. - "$(NativeObject)" -o "$(NativeBinary)" -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 - $(EmccArgs) "$(IlcPath)/sdk/libPortableRuntime.bc" "$(IlcPath)/sdk/libbootstrappercpp.bc" + "$(NativeObject)" -o "$(NativeBinary)" -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 --emrun + $(EmccArgs) "$(IlcPath)/sdk/libPortableRuntime.bc" "$(IlcPath)/sdk/libbootstrappercpp.bc" "$(IlcPath)/sdk/libSystem.Private.CoreLib.Native.bc" $(EmccArgs) -O2 --llvm-lto 2 $(EmccArgs) -g3 diff --git a/external/corert/src/Common/src/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs b/external/corert/src/Common/src/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs index d5da54db8e..a6bb922eec 100644 --- a/external/corert/src/Common/src/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs +++ b/external/corert/src/Common/src/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs @@ -644,7 +644,7 @@ class SchemaDef new MemberDef("Flags", "GenericParameterAttributes"), new MemberDef("Kind", "GenericParameterKind"), new MemberDef("Name", "ConstantStringValue", MemberDefFlags.RecordRef | MemberDefFlags.Child), - new MemberDef("Constraints", TypeDefOrRefOrSpec, MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.EnumerateForHashCode), + new MemberDef("Constraints", TypeDefOrRefOrSpecOrMod, MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.EnumerateForHashCode), new MemberDef("CustomAttributes", "CustomAttribute", MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child), } ), diff --git a/external/corert/src/Common/src/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs.REMOVED.git-id b/external/corert/src/Common/src/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs.REMOVED.git-id index 3ed09f7a3e..6f604078d8 100644 --- a/external/corert/src/Common/src/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs.REMOVED.git-id +++ b/external/corert/src/Common/src/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs.REMOVED.git-id @@ -1 +1 @@ -f068f31f9511fd44c80c628a2a5951841d2da89c \ No newline at end of file +9ade719703f737fcba7dd96fbbe06ff28d6363ac \ No newline at end of file diff --git a/external/corert/src/Common/src/Internal/NativeFormat/NativeFormatReader.cs b/external/corert/src/Common/src/Internal/NativeFormat/NativeFormatReader.cs index beb49d9321..f10028e4fd 100644 --- a/external/corert/src/Common/src/Internal/NativeFormat/NativeFormatReader.cs +++ b/external/corert/src/Common/src/Internal/NativeFormat/NativeFormatReader.cs @@ -223,7 +223,7 @@ namespace Internal.NativeFormat public NativeReader(byte* base_, uint size) { // Limit the maximum blob size to prevent buffer overruns triggered by boundary integer overflows - if (size >= UInt32.MaxValue / 4) + if (size >= uint.MaxValue / 4) ThrowBadImageFormatException(); Debug.Assert(base_ <= base_ + size); diff --git a/external/corert/src/Common/src/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs b/external/corert/src/Common/src/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs index e5fba47ad5..b7e299219b 100644 --- a/external/corert/src/Common/src/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs +++ b/external/corert/src/Common/src/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs @@ -121,7 +121,10 @@ namespace Internal.Runtime.CompilerHelpers for (int i = 0; i < count; i++) { if (pModuleHeaders[i] != IntPtr.Zero) - modules[moduleIndex++] = RuntimeImports.RhpCreateTypeManager(osModule, pModuleHeaders[i], pClasslibFunctions, nClasslibFunctions); + { + modules[moduleIndex] = RuntimeImports.RhpCreateTypeManager(osModule, pModuleHeaders[i], pClasslibFunctions, nClasslibFunctions); + moduleIndex++; + } } return modules; @@ -301,6 +304,6 @@ namespace Internal.Runtime.CompilerHelpers internal unsafe struct TypeManagerSlot { public TypeManagerHandle TypeManager; - public Int32 ModuleIndex; + public int ModuleIndex; } } diff --git a/external/corert/src/Common/src/Internal/Runtime/EEType.cs b/external/corert/src/Common/src/Internal/Runtime/EEType.cs index c9852dd80a..66d952d2f8 100644 --- a/external/corert/src/Common/src/Internal/Runtime/EEType.cs +++ b/external/corert/src/Common/src/Internal/Runtime/EEType.cs @@ -3,9 +3,11 @@ // See the LICENSE file in the project root for more information. using System; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal.NativeFormat; +using Internal.Runtime.CompilerServices; using Debug = System.Diagnostics.Debug; @@ -63,12 +65,12 @@ namespace Internal.Runtime [StructLayout(LayoutKind.Sequential)] internal unsafe struct DispatchMapEntry { - internal UInt16 _usInterfaceIndex; - internal UInt16 _usInterfaceMethodSlot; - internal UInt16 _usImplMethodSlot; + internal ushort _usInterfaceIndex; + internal ushort _usInterfaceMethodSlot; + internal ushort _usImplMethodSlot; } - private UInt32 _entryCount; + private uint _entryCount; private DispatchMapEntry _dispatchMap; // at least one entry if any interfaces defined public bool IsEmpty @@ -79,7 +81,7 @@ namespace Internal.Runtime } } - public UInt32 NumEntries + public uint NumEntries { get { @@ -97,7 +99,7 @@ namespace Internal.Runtime { get { - return sizeof(UInt32) + sizeof(DispatchMapEntry) * (int)_entryCount; + return sizeof(uint) + sizeof(DispatchMapEntry) * (int)_entryCount; } } @@ -106,7 +108,7 @@ namespace Internal.Runtime get { fixed (DispatchMap* pThis = &this) - return (DispatchMapEntry*)((byte*)pThis + sizeof(UInt32) + (sizeof(DispatchMapEntry) * index)); + return (DispatchMapEntry*)((byte*)pThis + sizeof(uint) + (sizeof(DispatchMapEntry) * index)); } } } @@ -147,7 +149,7 @@ namespace Internal.Runtime private static unsafe class OptionalFieldsReader { - internal static UInt32 GetInlineField(byte* pFields, EETypeOptionalFieldTag eTag, UInt32 uiDefaultValue) + internal static uint GetInlineField(byte* pFields, EETypeOptionalFieldTag eTag, uint uiDefaultValue) { if (pFields == null) return uiDefaultValue; @@ -158,7 +160,7 @@ namespace Internal.Runtime byte fieldHeader = NativePrimitiveDecoder.ReadUInt8(ref pFields); isLastField = (fieldHeader & 0x80) != 0; EETypeOptionalFieldTag eCurrentTag = (EETypeOptionalFieldTag)(fieldHeader & 0x7f); - UInt32 uiCurrentValue = NativePrimitiveDecoder.DecodeUnsigned(ref pFields); + uint uiCurrentValue = NativePrimitiveDecoder.DecodeUnsigned(ref pFields); // If we found a tag match return the current value. if (eCurrentTag == eTag) @@ -170,13 +172,29 @@ namespace Internal.Runtime } } - private UInt16 _usComponentSize; - private UInt16 _usFlags; - private UInt32 _uBaseSize; + /// + /// Gets a value indicating whether the statically generated data structures use relative pointers. + /// + internal static bool SupportsRelativePointers + { + [Intrinsic] + get + { +#if PROJECTN + return true; +#else + throw new NotImplementedException(); +#endif + } + } + + private ushort _usComponentSize; + private ushort _usFlags; + private uint _uBaseSize; private RelatedTypeUnion _relatedType; - private UInt16 _usNumVtableSlots; - private UInt16 _usNumInterfaces; - private UInt32 _uHashCode; + private ushort _usNumVtableSlots; + private ushort _usNumInterfaces; + private uint _uHashCode; #if EETYPE_TYPE_MANAGER private IntPtr _ppTypeManager; @@ -187,14 +205,14 @@ namespace Internal.Runtime // if the alignment is 8 bytes or less. If the alignment is higher then there may be a need for more bits to hold // the rest of the padding data. // If paddings of greater than 7 bytes are necessary, then the high bits of the field represent that padding - private const UInt32 ValueTypePaddingLowMask = 0x7; - private const UInt32 ValueTypePaddingHighMask = 0xFFFFFF00; - private const UInt32 ValueTypePaddingMax = 0x07FFFFFF; + private const uint ValueTypePaddingLowMask = 0x7; + private const uint ValueTypePaddingHighMask = 0xFFFFFF00; + private const uint ValueTypePaddingMax = 0x07FFFFFF; private const int ValueTypePaddingHighShift = 8; - private const UInt32 ValueTypePaddingAlignmentMask = 0xF8; + private const uint ValueTypePaddingAlignmentMask = 0xF8; private const int ValueTypePaddingAlignmentShift = 3; - internal UInt16 ComponentSize + internal ushort ComponentSize { get { @@ -208,7 +226,7 @@ namespace Internal.Runtime #endif } - internal UInt16 GenericArgumentCount + internal ushort GenericArgumentCount { get { @@ -224,7 +242,7 @@ namespace Internal.Runtime #endif } - internal UInt16 Flags + internal ushort Flags { get { @@ -238,7 +256,7 @@ namespace Internal.Runtime #endif } - internal UInt32 BaseSize + internal uint BaseSize { get { @@ -252,7 +270,7 @@ namespace Internal.Runtime #endif } - internal UInt16 NumVtableSlots + internal ushort NumVtableSlots { get { @@ -266,7 +284,7 @@ namespace Internal.Runtime #endif } - internal UInt16 NumInterfaces + internal ushort NumInterfaces { get { @@ -280,7 +298,7 @@ namespace Internal.Runtime #endif } - internal UInt32 HashCode + internal uint HashCode { get { @@ -298,7 +316,7 @@ namespace Internal.Runtime { get { - return (EETypeKind)(_usFlags & (UInt16)EETypeFlags.EETypeKindMask); + return (EETypeKind)(_usFlags & (ushort)EETypeFlags.EETypeKindMask); } } @@ -306,7 +324,7 @@ namespace Internal.Runtime { get { - return ((_usFlags & (UInt16)EETypeFlags.OptionalFieldsFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.OptionalFieldsFlag) != 0); } } @@ -316,7 +334,7 @@ namespace Internal.Runtime { get { - return ((_usFlags & (UInt16)EETypeFlags.GenericVarianceFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.GenericVarianceFlag) != 0); } } @@ -399,7 +417,7 @@ namespace Internal.Runtime { get { - return ((_usFlags & (UInt16)EETypeFlags.IsGenericFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.IsGenericFlag) != 0); } } @@ -416,11 +434,10 @@ namespace Internal.Runtime get { Debug.Assert(IsGeneric); - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_GenericDefinition); - fixed (EEType* pThis = &this) - { - return ((EETypeRef*)((byte*)pThis + cbOffset))->Value; - } + if (IsDynamicType || !SupportsRelativePointers) + return GetField>(EETypeField.ETF_GenericDefinition).Value; + + return GetField>(EETypeField.ETF_GenericDefinition).Value; } #if TYPE_LOADER_IMPLEMENTATION set @@ -435,17 +452,39 @@ namespace Internal.Runtime #endif } + [StructLayout(LayoutKind.Sequential)] + private readonly struct GenericComposition + { + public readonly ushort Arity; + + private readonly EETypeRef _genericArgument1; + public EETypeRef* GenericArguments + { + get + { + return (EETypeRef*)Unsafe.AsPointer(ref Unsafe.AsRef(in _genericArgument1)); + } + } + + public GenericVariance* GenericVariance + { + get + { + // Generic variance directly follows the last generic argument + return (GenericVariance*)(GenericArguments + Arity); + } + } + } + internal uint GenericArity { get { Debug.Assert(IsGeneric); - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_GenericComposition); - fixed (EEType* pThis = &this) - { - // Number of generic arguments is the first UInt16 of the composition stream. - return **(UInt16**)((byte*)pThis + cbOffset); - } + if (IsDynamicType || !SupportsRelativePointers) + return GetField>(EETypeField.ETF_GenericComposition).Value->Arity; + + return GetField>(EETypeField.ETF_GenericComposition).Value->Arity; } } @@ -454,13 +493,10 @@ namespace Internal.Runtime get { Debug.Assert(IsGeneric); - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_GenericComposition); - fixed (EEType* pThis = &this) - { - // Generic arguments follow after a (padded) UInt16 specifying their count - // in the generic composition stream. - return ((*(EETypeRef**)((byte*)pThis + cbOffset)) + 1); - } + if (IsDynamicType || !SupportsRelativePointers) + return GetField>(EETypeField.ETF_GenericComposition).Value->GenericArguments; + + return GetField>(EETypeField.ETF_GenericComposition).Value->GenericArguments; } } @@ -473,12 +509,10 @@ namespace Internal.Runtime if (!HasGenericVariance) return null; - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_GenericComposition); - fixed (EEType* pThis = &this) - { - // Variance info follows immediatelly after the generic arguments - return (GenericVariance*)(GenericArguments + GenericArity); - } + if (IsDynamicType || !SupportsRelativePointers) + return GetField>(EETypeField.ETF_GenericComposition).Value->GenericVariance; + + return GetField>(EETypeField.ETF_GenericComposition).Value->GenericVariance; } } @@ -504,7 +538,7 @@ namespace Internal.Runtime { get { - return ((_usFlags & (UInt16)EETypeFlags.IsInterfaceFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.IsInterfaceFlag) != 0); } } @@ -561,7 +595,7 @@ namespace Internal.Runtime // Currently, the meaning is a shape of 0 indicates that this is a Pointer, // shape of 1 indicates a ByRef, and >=SZARRAY_BASE_SIZE indicates that this is an array. // Two types are not equivalent if their shapes do not exactly match. - internal UInt32 ParameterizedTypeShape + internal uint ParameterizedTypeShape { get { @@ -579,7 +613,7 @@ namespace Internal.Runtime { get { - return ((_usFlags & (UInt16)EETypeFlags.RelatedTypeViaIATFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.RelatedTypeViaIATFlag) != 0); } } @@ -595,7 +629,7 @@ namespace Internal.Runtime { get { - return ((_usFlags & (UInt16)EETypeFlags.ICastableFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.ICastableFlag) != 0); } } @@ -611,14 +645,14 @@ namespace Internal.Runtime byte* optionalFields = OptionalFieldsPtr; if(optionalFields != null) { - const UInt16 NoSlot = 0xFFFF; - UInt16 uiSlot = (UInt16)OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ICastableIsInstSlot, NoSlot); + const ushort NoSlot = 0xFFFF; + ushort uiSlot = (ushort)OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ICastableIsInstSlot, NoSlot); if (uiSlot != NoSlot) { if (uiSlot < NumVtableSlots) return GetVTableStartAddress()[uiSlot]; else - return GetSealedVirtualSlot((UInt16)(uiSlot - NumVtableSlots)); + return GetSealedVirtualSlot((ushort)(uiSlot - NumVtableSlots)); } } @@ -643,14 +677,14 @@ namespace Internal.Runtime byte* optionalFields = OptionalFieldsPtr; if(optionalFields != null) { - const UInt16 NoSlot = 0xFFFF; - UInt16 uiSlot = (UInt16)OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ICastableGetImplTypeSlot, NoSlot); + const ushort NoSlot = 0xFFFF; + ushort uiSlot = (ushort)OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ICastableGetImplTypeSlot, NoSlot); if (uiSlot != NoSlot) { if (uiSlot < NumVtableSlots) return GetVTableStartAddress()[uiSlot]; else - return GetSealedVirtualSlot((UInt16)(uiSlot - NumVtableSlots)); + return GetSealedVirtualSlot((ushort)(uiSlot - NumVtableSlots)); } } @@ -667,7 +701,7 @@ namespace Internal.Runtime { get { - return ((_usFlags & (UInt16)EETypeFlags.ValueTypeFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.ValueTypeFlag) != 0); } } @@ -675,7 +709,7 @@ namespace Internal.Runtime { get { - return ((_usFlags & (UInt16)EETypeFlags.HasPointersFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.HasPointersFlag) != 0); } #if TYPE_LOADER_IMPLEMENTATION set @@ -700,7 +734,7 @@ namespace Internal.Runtime } } - internal UInt32 ValueTypeFieldPadding + internal uint ValueTypeFieldPadding { get { @@ -712,15 +746,15 @@ namespace Internal.Runtime // Get the value from the optional fields. The default is zero if that particular field was not included. // The low bits of this field is the ValueType field padding, the rest of the byte is the alignment if present - UInt32 ValueTypeFieldPaddingData = OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ValueTypeFieldPadding, 0); - UInt32 padding = ValueTypeFieldPaddingData & ValueTypePaddingLowMask; + uint ValueTypeFieldPaddingData = OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ValueTypeFieldPadding, 0); + uint padding = ValueTypeFieldPaddingData & ValueTypePaddingLowMask; // If there is additional padding, the other bits have that data padding |= (ValueTypeFieldPaddingData & ValueTypePaddingHighMask) >> (ValueTypePaddingHighShift - ValueTypePaddingAlignmentShift); return padding; } } - internal UInt32 ValueTypeSize + internal uint ValueTypeSize { get { @@ -732,7 +766,7 @@ namespace Internal.Runtime } } - internal UInt32 FieldByteCountNonGCAligned + internal uint FieldByteCountNonGCAligned { get { @@ -769,7 +803,7 @@ namespace Internal.Runtime byte* optionalFields = OptionalFieldsPtr; if (optionalFields == null) return false; - UInt32 idxDispatchMap = OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.DispatchMap, 0xffffffff); + uint idxDispatchMap = OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.DispatchMap, 0xffffffff); if (idxDispatchMap == 0xffffffff) { if (HasDynamicallyAllocatedDispatchMap) @@ -912,7 +946,7 @@ namespace Internal.Runtime get { Debug.Assert(IsNullable); - UInt32 cbNullableTypeOffset = GetFieldOffset(EETypeField.ETF_NullableType); + uint cbNullableTypeOffset = GetFieldOffset(EETypeField.ETF_NullableType); fixed (EEType* pThis = &this) { if (IsNullableTypeViaIAT) @@ -987,30 +1021,30 @@ namespace Internal.Runtime return (IntPtr*)pResult; } - private static IntPtr FollowRelativePointer(Int32* pDist) + private static IntPtr FollowRelativePointer(int* pDist) { - Int32 dist = *pDist; + int dist = *pDist; IntPtr result = (IntPtr)((byte*)pDist + dist); return result; } - internal IntPtr GetSealedVirtualSlot(UInt16 slotNumber) + internal IntPtr GetSealedVirtualSlot(ushort slotNumber) { Debug.Assert(!IsNullable); Debug.Assert((RareFlags & EETypeRareFlags.HasSealedVTableEntriesFlag) != 0); fixed (EEType* pThis = &this) { - if (IsDynamicType) + if (IsDynamicType || !SupportsRelativePointers) { - UInt32 cbSealedVirtualSlotsTypeOffset = GetFieldOffset(EETypeField.ETF_SealedVirtualSlots); + uint cbSealedVirtualSlotsTypeOffset = GetFieldOffset(EETypeField.ETF_SealedVirtualSlots); IntPtr* pSealedVirtualsSlotTable = *(IntPtr**)((byte*)pThis + cbSealedVirtualSlotsTypeOffset); return pSealedVirtualsSlotTable[slotNumber]; } else { - UInt32 cbSealedVirtualSlotsTypeOffset = GetFieldOffset(EETypeField.ETF_SealedVirtualSlots); - Int32* pSealedVirtualsSlotTable = (Int32*)FollowRelativePointer((Int32*)((byte*)pThis + cbSealedVirtualSlotsTypeOffset)); + uint cbSealedVirtualSlotsTypeOffset = GetFieldOffset(EETypeField.ETF_SealedVirtualSlots); + int* pSealedVirtualsSlotTable = (int*)FollowRelativePointer((int*)((byte*)pThis + cbSealedVirtualSlotsTypeOffset)); IntPtr result = FollowRelativePointer(&pSealedVirtualsSlotTable[slotNumber]); return result; } @@ -1038,7 +1072,7 @@ namespace Internal.Runtime if (!HasOptionalFields) return null; - UInt32 cbOptionalFieldsOffset = GetFieldOffset(EETypeField.ETF_OptionalFieldsPtr); + uint cbOptionalFieldsOffset = GetFieldOffset(EETypeField.ETF_OptionalFieldsPtr); fixed (EEType* pThis = &this) { return *(byte**)((byte*)pThis + cbOptionalFieldsOffset); @@ -1063,7 +1097,7 @@ namespace Internal.Runtime get { Debug.Assert(IsDynamicType); - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_DynamicTemplateType); + uint cbOffset = GetFieldOffset(EETypeField.ETF_DynamicTemplateType); fixed (EEType* pThis = &this) { return *(EEType**)((byte*)pThis + cbOffset); @@ -1087,7 +1121,7 @@ namespace Internal.Runtime get { Debug.Assert((RareFlags & EETypeRareFlags.IsDynamicTypeWithGcStatics) != 0); - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_DynamicGcStatics); + uint cbOffset = GetFieldOffset(EETypeField.ETF_DynamicGcStatics); fixed (EEType* pThis = &this) { return (IntPtr)((byte*)pThis + cbOffset); @@ -1111,7 +1145,7 @@ namespace Internal.Runtime get { Debug.Assert((RareFlags & EETypeRareFlags.IsDynamicTypeWithNonGcStatics) != 0); - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_DynamicNonGcStatics); + uint cbOffset = GetFieldOffset(EETypeField.ETF_DynamicNonGcStatics); fixed (EEType* pThis = &this) { return (IntPtr)((byte*)pThis + cbOffset); @@ -1136,7 +1170,7 @@ namespace Internal.Runtime { if ((RareFlags & EETypeRareFlags.HasDynamicModuleFlag) != 0) { - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_DynamicModule); + uint cbOffset = GetFieldOffset(EETypeField.ETF_DynamicModule); fixed (EEType* pThis = &this) { return *(DynamicModule**)((byte*)pThis + cbOffset); @@ -1209,7 +1243,7 @@ namespace Internal.Runtime // Get the value from the optional fields. The default is zero if that particular field was not included. // The low bits of this field is the ValueType field padding, the rest of the value is the alignment if present - UInt32 alignmentValue = (OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ValueTypeFieldPadding, 0) & ValueTypePaddingAlignmentMask) >> ValueTypePaddingAlignmentShift; + uint alignmentValue = (OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ValueTypeFieldPadding, 0) & ValueTypePaddingAlignmentMask) >> ValueTypePaddingAlignmentShift; // Alignment is stored as 1 + the log base 2 of the alignment, except a 0 indicates standard pointer alignment. if (alignmentValue == 0) @@ -1235,10 +1269,10 @@ namespace Internal.Runtime } } - public UInt32 GetFieldOffset(EETypeField eField) + public uint GetFieldOffset(EETypeField eField) { // First part of EEType consists of the fixed portion followed by the vtable. - UInt32 cbOffset = (UInt32)(sizeof(EEType) + (IntPtr.Size * _usNumVtableSlots)); + uint cbOffset = (uint)(sizeof(EEType) + (IntPtr.Size * _usNumVtableSlots)); // Then we have the interface map. if (eField == EETypeField.ETF_InterfaceMap) @@ -1246,7 +1280,7 @@ namespace Internal.Runtime Debug.Assert(NumInterfaces > 0); return cbOffset; } - cbOffset += (UInt32)(sizeof(EEInterfaceInfo) * NumInterfaces); + cbOffset += (uint)(sizeof(EEInterfaceInfo) * NumInterfaces); // Followed by the pointer to the finalizer method. if (eField == EETypeField.ETF_Finalizer) @@ -1255,7 +1289,7 @@ namespace Internal.Runtime return cbOffset; } if (IsFinalizable) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; // Followed by the pointer to the optional fields. if (eField == EETypeField.ETF_OptionalFieldsPtr) @@ -1264,7 +1298,7 @@ namespace Internal.Runtime return cbOffset; } if (HasOptionalFields) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; // Followed by the pointer to the type target of a Nullable. if (eField == EETypeField.ETF_NullableType) @@ -1278,13 +1312,13 @@ namespace Internal.Runtime return cbOffset; if (IsNullable) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; EETypeRareFlags rareFlags = RareFlags; // in the case of sealed vtable entries on static types, we have a UInt sized relative pointer if ((rareFlags & EETypeRareFlags.HasSealedVTableEntriesFlag) != 0) - cbOffset += (IsDynamicType ? (UInt32)IntPtr.Size : 4); + cbOffset += (IsDynamicType || !SupportsRelativePointers ? (uint)IntPtr.Size : 4); if (eField == EETypeField.ETF_DynamicDispatchMap) { @@ -1292,7 +1326,7 @@ namespace Internal.Runtime return cbOffset; } if ((rareFlags & EETypeRareFlags.HasDynamicallyAllocatedDispatchMapFlag) != 0) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; if (eField == EETypeField.ETF_GenericDefinition) { @@ -1300,7 +1334,12 @@ namespace Internal.Runtime return cbOffset; } if (IsGeneric) - cbOffset += (UInt32)IntPtr.Size; + { + if ((rareFlags & EETypeRareFlags.IsDynamicTypeFlag) != 0 || !SupportsRelativePointers) + cbOffset += (uint)IntPtr.Size; + else + cbOffset += 4; + } if (eField == EETypeField.ETF_GenericComposition) { @@ -1308,7 +1347,12 @@ namespace Internal.Runtime return cbOffset; } if (IsGeneric) - cbOffset += (UInt32)IntPtr.Size; + { + if ((rareFlags & EETypeRareFlags.IsDynamicTypeFlag) != 0 || !SupportsRelativePointers) + cbOffset += (uint)IntPtr.Size; + else + cbOffset += 4; + } if (eField == EETypeField.ETF_DynamicModule) { @@ -1316,7 +1360,7 @@ namespace Internal.Runtime } if ((rareFlags & EETypeRareFlags.HasDynamicModuleFlag) != 0) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; if (eField == EETypeField.ETF_DynamicTemplateType) { @@ -1324,7 +1368,7 @@ namespace Internal.Runtime return cbOffset; } if (IsDynamicType) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; if (eField == EETypeField.ETF_DynamicGcStatics) { @@ -1332,7 +1376,7 @@ namespace Internal.Runtime return cbOffset; } if ((rareFlags & EETypeRareFlags.IsDynamicTypeWithGcStatics) != 0) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; if (eField == EETypeField.ETF_DynamicNonGcStatics) { @@ -1340,7 +1384,7 @@ namespace Internal.Runtime return cbOffset; } if ((rareFlags & EETypeRareFlags.IsDynamicTypeWithNonGcStatics) != 0) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; if (eField == EETypeField.ETF_DynamicThreadStaticOffset) { @@ -1354,6 +1398,12 @@ namespace Internal.Runtime return 0; } + public ref T GetField(EETypeField eField) + { + fixed (EEType* pThis = &this) + return ref Unsafe.AddByteOffset(ref Unsafe.As(ref *pThis), (IntPtr)GetFieldOffset(eField)); + } + #if TYPE_LOADER_IMPLEMENTATION internal static UInt32 GetSizeofEEType( UInt16 cVirtuals, @@ -1415,6 +1465,75 @@ namespace Internal.Runtime } } + // Wrapper around pointers + [StructLayout(LayoutKind.Sequential)] + internal unsafe readonly struct Pointer where T : unmanaged + { + private readonly T* _value; + + public T* Value + { + get + { + return _value; + } + } + } + + // Wrapper around pointers that might be indirected through IAT + [StructLayout(LayoutKind.Sequential)] + internal unsafe readonly struct IatAwarePointer where T : unmanaged + { + private readonly T* _value; + + public T* Value + { + get + { + if (((int)_value & IndirectionConstants.IndirectionCellPointer) == 0) + return _value; + return *(T**)((byte*)_value - IndirectionConstants.IndirectionCellPointer); + } + } + } + + // Wrapper around relative pointers + [StructLayout(LayoutKind.Sequential)] + internal unsafe readonly struct RelativePointer where T : unmanaged + { + private readonly int _value; + + public T* Value + { + get + { + return (T*)((byte*)Unsafe.AsPointer(ref Unsafe.AsRef(in _value)) + _value); + } + } + } + + // Wrapper around relative pointers that might be indirected through IAT + [StructLayout(LayoutKind.Sequential)] + internal unsafe readonly struct IatAwareRelativePointer where T : unmanaged + { + private readonly int _value; + + public T* Value + { + get + { + if ((_value & IndirectionConstants.IndirectionCellPointer) == 0) + { + return (T*)((byte*)Unsafe.AsPointer(ref Unsafe.AsRef(in _value)) + _value); + } + else + { + return *(T**)((byte*)Unsafe.AsPointer(ref Unsafe.AsRef(in _value)) + (_value & ~IndirectionConstants.IndirectionCellPointer)); + } + } + } + } + [StructLayout(LayoutKind.Sequential)] internal struct DynamicModule { diff --git a/external/corert/src/Common/src/Internal/Runtime/ModuleHeaders.cs b/external/corert/src/Common/src/Internal/Runtime/ModuleHeaders.cs index 20195b7cc6..af312f84e1 100644 --- a/external/corert/src/Common/src/Internal/Runtime/ModuleHeaders.cs +++ b/external/corert/src/Common/src/Internal/Runtime/ModuleHeaders.cs @@ -22,15 +22,15 @@ namespace Internal.Runtime #pragma warning disable 0169 internal struct ReadyToRunHeader { - private UInt32 Signature; // ReadyToRunHeaderConstants.Signature - private UInt16 MajorVersion; - private UInt16 MinorVersion; + private uint Signature; // ReadyToRunHeaderConstants.Signature + private ushort MajorVersion; + private ushort MinorVersion; - private UInt32 Flags; + private uint Flags; - private UInt16 NumberOfSections; - private Byte EntrySize; - private Byte EntryType; + private ushort NumberOfSections; + private byte EntrySize; + private byte EntryType; // Array of sections follows. }; diff --git a/external/corert/src/Common/src/Interop/Unix/System.Private.CoreLib.Native/Interop.CreateGuid.cs b/external/corert/src/Common/src/Interop/Unix/System.Private.CoreLib.Native/Interop.GetEnviron.cs similarity index 75% rename from external/corert/src/Common/src/Interop/Unix/System.Private.CoreLib.Native/Interop.CreateGuid.cs rename to external/corert/src/Common/src/Interop/Unix/System.Private.CoreLib.Native/Interop.GetEnviron.cs index b6326aed0d..539cdb3cf5 100644 --- a/external/corert/src/Common/src/Interop/Unix/System.Private.CoreLib.Native/Interop.CreateGuid.cs +++ b/external/corert/src/Common/src/Interop/Unix/System.Private.CoreLib.Native/Interop.GetEnviron.cs @@ -3,14 +3,13 @@ // See the LICENSE file in the project root for more information. using System; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; internal static partial class Interop { internal unsafe partial class Sys { - [DllImport(Interop.Libraries.CoreLibNative, EntryPoint = "CoreLibNative_CreateGuid")] - internal static extern void CreateGuid(out Guid guid); + [DllImport(Interop.Libraries.CoreLibNative, EntryPoint = "CoreLibNative_GetEnviron")] + internal static extern unsafe IntPtr GetEnviron(); } } diff --git a/external/corert/src/Common/src/Interop/Windows/Interop.Libraries.cs b/external/corert/src/Common/src/Interop/Windows/Interop.Libraries.cs index 8536bc367e..68a50eadd3 100644 --- a/external/corert/src/Common/src/Interop/Windows/Interop.Libraries.cs +++ b/external/corert/src/Common/src/Interop/Windows/Interop.Libraries.cs @@ -6,9 +6,6 @@ internal static partial class Interop { internal static partial class Libraries { - internal const string CoreFile_L1 = "api-ms-win-core-file-l1-1-0.dll"; - internal const string CoreFile_L1_2 = "api-ms-win-core-file-l1-2-0.dll"; - internal const string CoreFile_L2 = "api-ms-win-core-file-l2-1-0.dll"; internal const string ErrorHandling = "api-ms-win-core-errorhandling-l1-1-0.dll"; internal const string Handle = "api-ms-win-core-handle-l1-1-0.dll"; internal const string IO = "api-ms-win-core-io-l1-1-0.dll"; @@ -17,7 +14,6 @@ internal static partial class Interop internal const string ProcessThreads = "api-ms-win-core-processthreads-l1-1-0.dll"; internal const string RealTime = "api-ms-win-core-realtime-l1-1-0.dll"; internal const string SysInfo = "api-ms-win-core-sysinfo-l1-2-0.dll"; - internal const string Registry_L1 = "api-ms-win-core-registry-l1-1-0.dll"; internal const string ThreadPool = "api-ms-win-core-threadpool-l1-2-0.dll"; internal const string Localization = "api-ms-win-core-localization-l1-2-1.dll"; } diff --git a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.MemAllocFree.cs b/external/corert/src/Common/src/Interop/Windows/mincore/Interop.MemAllocFree.cs index bc537f7499..823516ec48 100644 --- a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.MemAllocFree.cs +++ b/external/corert/src/Common/src/Interop/Windows/mincore/Interop.MemAllocFree.cs @@ -17,7 +17,7 @@ internal static partial class Interop internal static extern IntPtr HeapAlloc(IntPtr hHeap, uint dwFlags, UIntPtr dwBytes); [DllImport("api-ms-win-core-heap-l1-1-0.dll")] - internal static extern int HeapFree(IntPtr hHeap, UInt32 dwFlags, IntPtr lpMem); + internal static extern int HeapFree(IntPtr hHeap, uint dwFlags, IntPtr lpMem); } #if MULTIPLEX_OS diff --git a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.MemReAlloc.cs b/external/corert/src/Common/src/Interop/Windows/mincore/Interop.MemReAlloc.cs index 45dc7c675c..c195f481be 100644 --- a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.MemReAlloc.cs +++ b/external/corert/src/Common/src/Interop/Windows/mincore/Interop.MemReAlloc.cs @@ -11,7 +11,7 @@ internal static partial class Interop internal static unsafe partial class mincore { [DllImport("api-ms-win-core-heap-l1-1-0.dll")] - internal static extern unsafe IntPtr HeapReAlloc(IntPtr hHeap, UInt32 dwFlags, IntPtr lpMem, UIntPtr dwBytes); + internal static extern unsafe IntPtr HeapReAlloc(IntPtr hHeap, uint dwFlags, IntPtr lpMem, UIntPtr dwBytes); } internal static unsafe IntPtr MemReAlloc(IntPtr ptr, UIntPtr newSize) diff --git a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.Threading.cs b/external/corert/src/Common/src/Interop/Windows/mincore/Interop.Threading.cs index 23477e361d..a08c62c819 100644 --- a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.Threading.cs +++ b/external/corert/src/Common/src/Interop/Windows/mincore/Interop.Threading.cs @@ -10,39 +10,6 @@ internal static partial class Interop { internal static partial class mincore { - [DllImport(Libraries.Kernel32, EntryPoint = "CreateEventExW", SetLastError = true, CharSet = CharSet.Unicode)] - internal extern static SafeWaitHandle CreateEventEx(IntPtr lpEventAttributes, string lpName, uint dwFlags, uint dwDesiredAccess); - - [DllImport(Libraries.Kernel32, EntryPoint = "CreateSemaphoreExW", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern SafeWaitHandle CreateSemaphoreEx(IntPtr lpSemaphoreAttributes, int lInitialCount, int lMaximumCount, string lpName, uint dwFlags, uint dwDesiredAccess); - - [DllImport(Libraries.Kernel32, EntryPoint = "CreateMutexExW", SetLastError = true, CharSet = CharSet.Unicode)] - internal extern static SafeWaitHandle CreateMutexEx(IntPtr lpMutexAttributes, string lpName, uint dwFlags, uint dwDesiredAccess); - - [DllImport(Libraries.Kernel32, EntryPoint = "OpenEventW", SetLastError = true, CharSet = CharSet.Unicode)] - internal extern static SafeWaitHandle OpenEvent(uint dwDesiredAccess, bool bInheritHandle, string lpName); - - [DllImport(Libraries.Kernel32, EntryPoint = "OpenSemaphoreW", SetLastError = true, CharSet = CharSet.Unicode)] - internal extern static SafeWaitHandle OpenSemaphore(uint dwDesiredAccess, bool bInheritHandle, string lpName); - - [DllImport(Libraries.Kernel32, EntryPoint = "OpenMutexW", SetLastError = true, CharSet = CharSet.Unicode)] - internal extern static SafeWaitHandle OpenMutex(uint dwDesiredAccess, bool bInheritHandle, string lpName); - - [DllImport(Libraries.Kernel32)] - internal extern static bool ResetEvent(IntPtr hEvent); - - [DllImport(Libraries.Kernel32)] - internal extern static bool SetEvent(IntPtr hEvent); - - [DllImport(Libraries.Kernel32)] - internal extern static bool SetEvent(SafeWaitHandle hEvent); - - [DllImport(Libraries.Kernel32)] - internal extern static bool ReleaseSemaphore(IntPtr hSemaphore, int lReleaseCount, out int lpPreviousCount); - - [DllImport(Libraries.Kernel32)] - internal extern static bool ReleaseMutex(IntPtr hMutex); - [DllImport(Libraries.Kernel32)] internal extern static uint WaitForMultipleObjectsEx(uint nCount, IntPtr lpHandles, bool bWaitAll, uint dwMilliseconds, bool bAlertable); diff --git a/external/corert/src/Common/src/Interop/Windows/ole32/Interop.CoGetApartmentType.cs b/external/corert/src/Common/src/Interop/Windows/ole32/Interop.CoGetApartmentType.cs new file mode 100644 index 0000000000..a7aca2ab7b --- /dev/null +++ b/external/corert/src/Common/src/Interop/Windows/ole32/Interop.CoGetApartmentType.cs @@ -0,0 +1,36 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal enum APTTYPE : uint + { + APTTYPE_STA = 0x0u, + APTTYPE_MTA = 0x1u, + APTTYPE_NA = 0x2u, + APTTYPE_MAINSTA = 0x3u, + APTTYPE_CURRENT = 0xFFFFFFFFu, + } + + internal enum APTTYPEQUALIFIER : uint + { + APTTYPEQUALIFIER_NONE = 0x0u, + APTTYPEQUALIFIER_IMPLICIT_MTA = 0x1u, + APTTYPEQUALIFIER_NA_ON_MTA = 0x2u, + APTTYPEQUALIFIER_NA_ON_STA = 0x3u, + APTTYPEQUALIFIER_NA_ON_IMPLICIT_MTA = 0x4u, + APTTYPEQUALIFIER_NA_ON_MAINSTA = 0x5u, + APTTYPEQUALIFIER_APPLICATION_STA = 0x6u, + } + + internal static partial class Ole32 + { + [DllImport(Interop.Libraries.Ole32, ExactSpelling = true)] + internal extern static int CoGetApartmentType(out APTTYPE pAptType, out APTTYPEQUALIFIER pAptQualifier); + } +} diff --git a/external/corert/src/Common/src/Interop/Windows/ole32/Interop.CoInitializeEx.cs b/external/corert/src/Common/src/Interop/Windows/ole32/Interop.CoInitializeEx.cs new file mode 100644 index 0000000000..f953d5ec4a --- /dev/null +++ b/external/corert/src/Common/src/Interop/Windows/ole32/Interop.CoInitializeEx.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Ole32 + { + internal const uint COINIT_APARTMENTTHREADED = 2; + internal const uint COINIT_MULTITHREADED = 0; + + [DllImport(Interop.Libraries.Ole32, ExactSpelling = true)] + internal extern static int CoInitializeEx(IntPtr reserved, uint dwCoInit); + } +} diff --git a/external/corert/src/Common/src/Interop/Windows/ole32/Interop.CoUninitialize.cs b/external/corert/src/Common/src/Interop/Windows/ole32/Interop.CoUninitialize.cs new file mode 100644 index 0000000000..ae08366887 --- /dev/null +++ b/external/corert/src/Common/src/Interop/Windows/ole32/Interop.CoUninitialize.cs @@ -0,0 +1,16 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Ole32 + { + [DllImport(Interop.Libraries.Ole32, ExactSpelling = true)] + internal extern static int CoUninitialize(); + } +} diff --git a/external/corert/src/Common/src/System/Collections/Concurrent/ConcurrentUnifier.cs b/external/corert/src/Common/src/System/Collections/Concurrent/ConcurrentUnifier.cs index cc7edb0a40..bbb5959caa 100644 --- a/external/corert/src/Common/src/System/Collections/Concurrent/ConcurrentUnifier.cs +++ b/external/corert/src/Common/src/System/Collections/Concurrent/ConcurrentUnifier.cs @@ -102,7 +102,7 @@ namespace System.Collections.Concurrent // State of a key must never go from found to not found, and only one value may exist per key. Debug.Assert(checkedFound); if (default(V) == null) // No good way to do the "only one value" check for value types. - Debug.Assert(Object.ReferenceEquals(checkedValue, value)); + Debug.Assert(object.ReferenceEquals(checkedValue, value)); } } #endif //DEBUG diff --git a/external/corert/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierW.cs b/external/corert/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierW.cs index 8324b6c398..b2b70d8af3 100644 --- a/external/corert/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierW.cs +++ b/external/corert/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierW.cs @@ -112,7 +112,7 @@ namespace System.Collections.Concurrent // Since this DEBUG code is holding a strong reference to "value", state of a key must never go from found to not found, // and only one value may exist per key. Debug.Assert(checkedFound); - Debug.Assert(Object.ReferenceEquals(checkedValue, value)); + Debug.Assert(object.ReferenceEquals(checkedValue, value)); GC.KeepAlive(value); } } diff --git a/external/corert/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs b/external/corert/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs index 8aa21984db..5dfcab17ae 100644 --- a/external/corert/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs +++ b/external/corert/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs @@ -125,7 +125,7 @@ namespace System.Collections.Concurrent // Since this DEBUG code is holding a strong reference to "value", state of a key must never go from found to not found, // and only one value may exist per key. Debug.Assert(checkedFound); - Debug.Assert(Object.ReferenceEquals(checkedValue, value)); + Debug.Assert(object.ReferenceEquals(checkedValue, value)); GC.KeepAlive(value); } } diff --git a/external/corert/src/Common/src/System/Collections/Generic/LowLevelStack.cs b/external/corert/src/Common/src/System/Collections/Generic/LowLevelStack.cs new file mode 100644 index 0000000000..b193036a26 --- /dev/null +++ b/external/corert/src/Common/src/System/Collections/Generic/LowLevelStack.cs @@ -0,0 +1,161 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/*============================================================ +** +** +** Private version of Stack for internal System.Private.CoreLib use. This +** permits sharing more source between BCL and System.Private.CoreLib (as well as the +** fact that Stack is just a useful class in general.) +** +** This does not strive to implement the full api surface area +** (but any portion it does implement should match the real Stack's +** behavior.) +** +===========================================================*/ + +namespace System.Collections.Generic +{ + // Implements a variable-size Stack that uses an array of objects to store the + // elements. A Stack has a capacity, which is the allocated length + // of the internal array. As elements are added to a Stack, the capacity + // of the Stack is automatically increased as required by reallocating the + // internal array. + // + /// + /// LowLevelStack with no interface implementation to minimize both code and data size + /// Data size is smaller because there will be minimal virtual function table. + /// Code size is smaller because only functions called will be in the binary. + /// + internal class LowLevelStack + { + protected T[] _items; + protected int _size; + protected int _version; + + private static readonly T[] s_emptyArray = new T[0]; + + public LowLevelStack() + { + _items = s_emptyArray; + } + + public LowLevelStack(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity)); + + if (capacity == 0) + _items = s_emptyArray; + else + { + _size = capacity; + _items = new T[capacity]; + } + } + + public LowLevelStack(IEnumerable collection) + { + if (collection == null) + throw new ArgumentNullException(nameof(collection)); + + ICollection c = collection as ICollection; + if (c != null) + { + int count = c.Count; + if (count == 0) + { + _items = s_emptyArray; + } + else + { + _items = new T[count]; + c.CopyTo(_items, 0); + _size = count; + } + } + else + { + _size = 0; + _items = s_emptyArray; + + using (IEnumerator en = collection.GetEnumerator()) + { + while (en.MoveNext()) + { + Push(en.Current); + } + } + } + } + + public int Count + { + get + { + return _items.Length; + } + } + + public void Push(T item) + { + _size = _size + 1; + Array.Resize(ref _items, _size); + _items[_size - 1] = item; + _version++; + } + + public T Pop() + { + ThrowIfEmptyStack(); + + _size = _size - 1; + T item = _items[_size]; + Array.Resize(ref _items, _size); + _version++; + return item; + } + + public bool TryPop(out T result) + { + if (_size == 0) + { + result = default; + return false; + } + + _size = _size - 1; + result = _items[_size]; + Array.Resize(ref _items, _size); + _version++; + + return true; + } + + public T Peek() + { + ThrowIfEmptyStack(); + return _items[_size - 1]; + } + + public bool TryPeek(out T result) + { + if (_size == 0) + { + result = default; + return false; + } + + result = _items[_size - 1]; + _version++; + return true; + } + + private void ThrowIfEmptyStack() + { + if (_size == 0) + throw new InvalidOperationException(); + } + } +} diff --git a/external/corert/src/Common/src/System/CommonRuntimeTypes.cs b/external/corert/src/Common/src/System/CommonRuntimeTypes.cs index f4cfec4693..435a1867eb 100644 --- a/external/corert/src/Common/src/System/CommonRuntimeTypes.cs +++ b/external/corert/src/Common/src/System/CommonRuntimeTypes.cs @@ -37,28 +37,28 @@ namespace System internal static Type Void { get { return s_void; } } internal static Type MulticastDelegate { get { return s_multicastDelegate; } } - private static Type s_object = typeof(Object); + private static Type s_object = typeof(object); private static Type s_valuetype = typeof(ValueType); private static Type s_type = typeof(Type); private static Type s_attribute = typeof(Attribute); - private static Type s_string = typeof(String); + private static Type s_string = typeof(string); private static Type s_array = typeof(Array); private static Type s_enum = typeof(Enum); - private static Type s_boolean = typeof(Boolean); - private static Type s_char = typeof(Char); - private static Type s_byte = typeof(Byte); - private static Type s_sByte = typeof(SByte); - private static Type s_uInt16 = typeof(UInt16); - private static Type s_int16 = typeof(Int16); - private static Type s_uInt32 = typeof(UInt32); - private static Type s_int32 = typeof(Int32); - private static Type s_uInt64 = typeof(UInt64); - private static Type s_int64 = typeof(Int64); + private static Type s_boolean = typeof(bool); + private static Type s_char = typeof(char); + private static Type s_byte = typeof(byte); + private static Type s_sByte = typeof(sbyte); + private static Type s_uInt16 = typeof(ushort); + private static Type s_int16 = typeof(short); + private static Type s_uInt32 = typeof(uint); + private static Type s_int32 = typeof(int); + private static Type s_uInt64 = typeof(ulong); + private static Type s_int64 = typeof(long); private static Type s_uIntPtr = typeof(UIntPtr); private static Type s_intPtr = typeof(IntPtr); - private static Type s_single = typeof(Single); - private static Type s_double = typeof(Double); - private static Type s_decimal = typeof(Decimal); + private static Type s_single = typeof(float); + private static Type s_double = typeof(double); + private static Type s_decimal = typeof(decimal); private static Type s_datetime = typeof(DateTime); private static Type s_nullable = typeof(Nullable<>); private static Type s_void = typeof(void); diff --git a/external/corert/src/Common/src/System/Numerics/Hashing/HashHelpers.cs b/external/corert/src/Common/src/System/Numerics/Hashing/HashHelpers.cs index f017309a90..dd405eba78 100644 --- a/external/corert/src/Common/src/System/Numerics/Hashing/HashHelpers.cs +++ b/external/corert/src/Common/src/System/Numerics/Hashing/HashHelpers.cs @@ -8,7 +8,7 @@ namespace System.Numerics.Hashing internal static class HashHelpers { - public static readonly int RandomSeed = new Random().Next(Int32.MinValue, Int32.MaxValue); + public static readonly int RandomSeed = new Random().Next(int.MinValue, int.MaxValue); public static int Combine(int h1, int h2) { diff --git a/external/corert/src/Common/src/System/SR.cs b/external/corert/src/Common/src/System/SR.cs index 30462614f7..ef42e9a6b4 100644 --- a/external/corert/src/Common/src/System/SR.cs +++ b/external/corert/src/Common/src/System/SR.cs @@ -29,6 +29,10 @@ namespace System // This method is used to decide if we need to append the exception message parameters to the message when calling SR.Format. // by default it returns false. + // Native code generators can replace the value this returns based on user input at the time of native code generation. + // Marked as NoInlining because if this is used in an AoT compiled app that is not compiled into a single file, the user + // could compile each module with a different setting for this. We want to make sure there's a consistent behavior + // that doesn't depend on which native module this method got inlined into. [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { @@ -38,11 +42,14 @@ namespace System // Needed for debugger integration internal static string GetResourceString(string resourceKey) { - return GetResourceString(resourceKey, String.Empty); + return GetResourceString(resourceKey, string.Empty); } internal static string GetResourceString(string resourceKey, string defaultString) { + if (UsingResourceKeys()) + return defaultString ?? resourceKey; + string resourceString = null; try { resourceString = InternalGetResourceString(resourceKey); } catch (MissingManifestResourceException) { } @@ -139,10 +146,10 @@ namespace System { if (UsingResourceKeys()) { - return resourceFormat + String.Join(", ", args); + return resourceFormat + string.Join(", ", args); } - return String.Format(resourceFormat, args); + return string.Format(resourceFormat, args); } return resourceFormat; @@ -152,29 +159,29 @@ namespace System { if (UsingResourceKeys()) { - return String.Join(", ", resourceFormat, p1); + return string.Join(", ", resourceFormat, p1); } - return String.Format(resourceFormat, p1); + return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { - return String.Join(", ", resourceFormat, p1, p2); + return string.Join(", ", resourceFormat, p1, p2); } - return String.Format(resourceFormat, p1, p2); + return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { - return String.Join(", ", resourceFormat, p1, p2, p3); + return string.Join(", ", resourceFormat, p1, p2, p3); } - return String.Format(resourceFormat, p1, p2, p3); + return string.Format(resourceFormat, p1, p2, p3); } } } diff --git a/external/corert/src/Common/src/TypeSystem/Canon/CanonTypes.cs b/external/corert/src/Common/src/TypeSystem/Canon/CanonTypes.cs index ef8b601909..d84341b154 100644 --- a/external/corert/src/Common/src/TypeSystem/Canon/CanonTypes.cs +++ b/external/corert/src/Common/src/TypeSystem/Canon/CanonTypes.cs @@ -175,7 +175,7 @@ namespace Internal.TypeSystem } flags |= TypeFlags.HasFinalizerComputed; - flags |= TypeFlags.IsByRefLikeComputed; + flags |= TypeFlags.AttributeCacheComputed; return flags; } @@ -262,7 +262,7 @@ namespace Internal.TypeSystem } flags |= TypeFlags.HasFinalizerComputed; - flags |= TypeFlags.IsByRefLikeComputed; + flags |= TypeFlags.AttributeCacheComputed; return flags; } diff --git a/external/corert/src/Common/src/TypeSystem/CodeGen/TypeDesc.CodeGen.cs b/external/corert/src/Common/src/TypeSystem/CodeGen/TypeDesc.CodeGen.cs new file mode 100644 index 0000000000..9a5a1c8b28 --- /dev/null +++ b/external/corert/src/Common/src/TypeSystem/CodeGen/TypeDesc.CodeGen.cs @@ -0,0 +1,30 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace Internal.TypeSystem +{ + partial class TypeDesc + { + /// + /// Gets a value indicating whether this is a type that needs to be treated + /// specially. + /// + public bool IsIntrinsic + { + get + { + return (GetTypeFlags(TypeFlags.IsIntrinsic | TypeFlags.AttributeCacheComputed) & TypeFlags.IsIntrinsic) != 0; + } + } + } + + partial class InstantiatedType + { + partial void AddComputedIntrinsicFlag(ref TypeFlags flags) + { + if (_typeDef.IsIntrinsic) + flags |= TypeFlags.IsIntrinsic; + } + } +} diff --git a/external/corert/src/Common/src/TypeSystem/Common/ArrayType.cs b/external/corert/src/Common/src/TypeSystem/Common/ArrayType.cs index 22a9850123..eaa4547863 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/ArrayType.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/ArrayType.cs @@ -145,7 +145,7 @@ namespace Internal.TypeSystem flags |= TypeFlags.HasFinalizerComputed; - flags |= TypeFlags.IsByRefLikeComputed; + flags |= TypeFlags.AttributeCacheComputed; return flags; } diff --git a/external/corert/src/Common/src/TypeSystem/Common/ByRefType.cs b/external/corert/src/Common/src/TypeSystem/Common/ByRefType.cs index 164925f9df..6d19845945 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/ByRefType.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/ByRefType.cs @@ -37,7 +37,7 @@ namespace Internal.TypeSystem flags |= TypeFlags.HasFinalizerComputed; - flags |= TypeFlags.IsByRefLikeComputed; + flags |= TypeFlags.AttributeCacheComputed; return flags; } diff --git a/external/corert/src/Common/src/TypeSystem/Common/DefType.FieldLayout.cs b/external/corert/src/Common/src/TypeSystem/Common/DefType.FieldLayout.cs index 4977018128..7f56386079 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/DefType.FieldLayout.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/DefType.FieldLayout.cs @@ -55,7 +55,8 @@ namespace Internal.TypeSystem { public StaticsBlock NonGcStatics; public StaticsBlock GcStatics; - public StaticsBlock ThreadStatics; + public StaticsBlock ThreadNonGcStatics; + public StaticsBlock ThreadGcStatics; } ThreadSafeFlags _fieldLayoutFlags; @@ -217,10 +218,10 @@ namespace Internal.TypeSystem } /// - /// How many bytes must be allocated to represent the (potentially GC visible) thread static - /// fields of this type. + /// How many bytes must be allocated to represent the non GC visible thread static fields + /// of this type. /// - public LayoutInt ThreadStaticFieldSize + public LayoutInt ThreadNonGcStaticFieldSize { get { @@ -228,7 +229,39 @@ namespace Internal.TypeSystem { ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizes); } - return _staticBlockInfo == null ? LayoutInt.Zero : _staticBlockInfo.ThreadStatics.Size; + return _staticBlockInfo == null ? LayoutInt.Zero : _staticBlockInfo.ThreadNonGcStatics.Size; + } + } + + /// + /// What is the alignment required for allocating the non GC visible thread static fields + /// of this type. + /// + public LayoutInt ThreadNonGcStaticFieldAlignment + { + get + { + if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedStaticRegionLayout)) + { + ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizes); + } + return _staticBlockInfo == null ? LayoutInt.Zero : _staticBlockInfo.ThreadNonGcStatics.LargestAlignment; + } + } + + /// + /// How many bytes must be allocated to represent the (potentially GC visible) thread static + /// fields of this type. + /// + public LayoutInt ThreadGcStaticFieldSize + { + get + { + if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedStaticRegionLayout)) + { + ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizes); + } + return _staticBlockInfo == null ? LayoutInt.Zero : _staticBlockInfo.ThreadGcStatics.Size; } } @@ -236,7 +269,7 @@ namespace Internal.TypeSystem /// What is the alignment required for allocating the (potentially GC visible) thread static /// fields of this type. /// - public LayoutInt ThreadStaticFieldAlignment + public LayoutInt ThreadGcStaticFieldAlignment { get { @@ -244,7 +277,7 @@ namespace Internal.TypeSystem { ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizes); } - return _staticBlockInfo == null ? LayoutInt.Zero : _staticBlockInfo.ThreadStatics.LargestAlignment; + return _staticBlockInfo == null ? LayoutInt.Zero : _staticBlockInfo.ThreadGcStatics.LargestAlignment; } } @@ -328,13 +361,15 @@ namespace Internal.TypeSystem if ((computedStaticLayout.NonGcStatics.Size != LayoutInt.Zero) || (computedStaticLayout.GcStatics.Size != LayoutInt.Zero) || - (computedStaticLayout.ThreadStatics.Size != LayoutInt.Zero)) + (computedStaticLayout.ThreadNonGcStatics.Size != LayoutInt.Zero) || + (computedStaticLayout.ThreadGcStatics.Size != LayoutInt.Zero)) { var staticBlockInfo = new StaticBlockInfo { NonGcStatics = computedStaticLayout.NonGcStatics, GcStatics = computedStaticLayout.GcStatics, - ThreadStatics = computedStaticLayout.ThreadStatics + ThreadNonGcStatics = computedStaticLayout.ThreadNonGcStatics, + ThreadGcStatics = computedStaticLayout.ThreadGcStatics }; _staticBlockInfo = staticBlockInfo; } diff --git a/external/corert/src/Common/src/TypeSystem/Common/FieldDesc.FieldLayout.cs b/external/corert/src/Common/src/TypeSystem/Common/FieldDesc.FieldLayout.cs index 4f095421c3..4452e8d6ee 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/FieldDesc.FieldLayout.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/FieldDesc.FieldLayout.cs @@ -33,16 +33,13 @@ namespace Internal.TypeSystem } /// - /// For static fields, represents whether or not the field is held in the GC or non GC statics region - /// Does not apply to thread static fields. + /// For static fields, represents whether or not the field is held in the GC or non GC statics region. /// public bool HasGCStaticBase { get { - // If this assert fires then make sure the caller checks the IsThreadStatic attribute - // of FieldDesc before checking its HasGCStaticBase property. - Debug.Assert(IsStatic && !IsThreadStatic); + Debug.Assert(IsStatic); return Context.ComputeHasGCStaticBase(this); } } diff --git a/external/corert/src/Common/src/TypeSystem/Common/FieldLayoutAlgorithm.cs b/external/corert/src/Common/src/TypeSystem/Common/FieldLayoutAlgorithm.cs index eee09f1b38..720c80a659 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/FieldLayoutAlgorithm.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/FieldLayoutAlgorithm.cs @@ -101,7 +101,8 @@ namespace Internal.TypeSystem { public StaticsBlock NonGcStatics; public StaticsBlock GcStatics; - public StaticsBlock ThreadStatics; + public StaticsBlock ThreadNonGcStatics; + public StaticsBlock ThreadGcStatics; /// /// If Offsets is non-null, then all field based layout is complete. diff --git a/external/corert/src/Common/src/TypeSystem/Common/FunctionPointerType.cs b/external/corert/src/Common/src/TypeSystem/Common/FunctionPointerType.cs index 5d50620d75..523b105d0f 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/FunctionPointerType.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/FunctionPointerType.cs @@ -67,7 +67,7 @@ namespace Internal.TypeSystem flags |= TypeFlags.HasFinalizerComputed; - flags |= TypeFlags.IsByRefLikeComputed; + flags |= TypeFlags.AttributeCacheComputed; return flags; } diff --git a/external/corert/src/Common/src/TypeSystem/Common/GenericParameterDesc.cs b/external/corert/src/Common/src/TypeSystem/Common/GenericParameterDesc.cs index d98497921d..4eff6c6cbc 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/GenericParameterDesc.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/GenericParameterDesc.cs @@ -164,7 +164,7 @@ namespace Internal.TypeSystem flags |= TypeFlags.HasGenericVarianceComputed; - flags |= TypeFlags.IsByRefLikeComputed; + flags |= TypeFlags.AttributeCacheComputed; return flags; } diff --git a/external/corert/src/Common/src/TypeSystem/Common/InstantiatedType.cs b/external/corert/src/Common/src/TypeSystem/Common/InstantiatedType.cs index c5ae6776e4..a777f223f0 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/InstantiatedType.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/InstantiatedType.cs @@ -79,6 +79,10 @@ namespace Internal.TypeSystem } } + // Type system implementations that support the notion of intrinsic types + // will provide an implementation that adds the flag if necessary. + partial void AddComputedIntrinsicFlag(ref TypeFlags flags); + protected override TypeFlags ComputeTypeFlags(TypeFlags mask) { TypeFlags flags = 0; @@ -104,12 +108,14 @@ namespace Internal.TypeSystem flags |= TypeFlags.HasFinalizer; } - if ((mask & TypeFlags.IsByRefLikeComputed) != 0) + if ((mask & TypeFlags.AttributeCacheComputed) != 0) { - flags |= TypeFlags.IsByRefLikeComputed; + flags |= TypeFlags.AttributeCacheComputed; if (_typeDef.IsByRefLike) flags |= TypeFlags.IsByRefLike; + + AddComputedIntrinsicFlag(ref flags); } return flags; diff --git a/external/corert/src/Common/src/TypeSystem/Common/MetadataFieldLayoutAlgorithm.cs b/external/corert/src/Common/src/TypeSystem/Common/MetadataFieldLayoutAlgorithm.cs index ab35f05485..94074e1d83 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/MetadataFieldLayoutAlgorithm.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/MetadataFieldLayoutAlgorithm.cs @@ -185,7 +185,8 @@ namespace Internal.TypeSystem ComputedStaticFieldLayout result; result.GcStatics = new StaticsBlock(); result.NonGcStatics = new StaticsBlock(); - result.ThreadStatics = new StaticsBlock(); + result.ThreadGcStatics = new StaticsBlock(); + result.ThreadNonGcStatics = new StaticsBlock(); if (numStaticFields == 0) { @@ -231,7 +232,12 @@ namespace Internal.TypeSystem private ref StaticsBlock GetStaticsBlockForField(ref ComputedStaticFieldLayout layout, FieldDesc field) { if (field.IsThreadStatic) - return ref layout.ThreadStatics; + { + if (field.HasGCStaticBase) + return ref layout.ThreadGcStatics; + else + return ref layout.ThreadNonGcStatics; + } else if (field.HasGCStaticBase) return ref layout.GcStatics; else @@ -293,7 +299,7 @@ namespace Internal.TypeSystem var layoutMetadata = type.GetClassLayout(); - int packingSize = ComputePackingSize(type); + int packingSize = ComputePackingSize(type, layoutMetadata); LayoutInt largestAlignmentRequired = LayoutInt.One; var offsets = new FieldAndOffset[numInstanceFields]; @@ -353,9 +359,11 @@ namespace Internal.TypeSystem // For types inheriting from another type, field offsets continue on from where they left off LayoutInt cumulativeInstanceFieldPos = ComputeBytesUsedInParentType(type); + var layoutMetadata = type.GetClassLayout(); + LayoutInt largestAlignmentRequirement = LayoutInt.One; int fieldOrdinal = 0; - int packingSize = ComputePackingSize(type); + int packingSize = ComputePackingSize(type, layoutMetadata); foreach (var field in type.GetFields()) { @@ -375,7 +383,6 @@ namespace Internal.TypeSystem if (type.IsValueType) { - var layoutMetadata = type.GetClassLayout(); cumulativeInstanceFieldPos = LayoutInt.Max(cumulativeInstanceFieldPos, new LayoutInt(layoutMetadata.Size)); } @@ -442,10 +449,8 @@ namespace Internal.TypeSystem return result; } - private static int ComputePackingSize(MetadataType type) + private static int ComputePackingSize(MetadataType type, ClassLayoutMetadata layoutMetadata) { - var layoutMetadata = type.GetClassLayout(); - // If a type contains pointers then the metadata specified packing size is ignored (On desktop this is disqualification from ManagedSequential) if (layoutMetadata.PackingSize == 0 || type.ContainsGCPointers) return type.Context.Target.DefaultPackingSize; diff --git a/external/corert/src/Common/src/TypeSystem/Common/MethodDesc.cs b/external/corert/src/Common/src/TypeSystem/Common/MethodDesc.cs index 74c48d8eba..7103433b0c 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/MethodDesc.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/MethodDesc.cs @@ -133,7 +133,32 @@ namespace Internal.TypeSystem return TypeHashingAlgorithms.ComputeMethodSignatureHashCode(_returnType.GetHashCode(), _parameters); } + public SignatureEnumerator GetEnumerator() + { + return new SignatureEnumerator(this); + } + public override TypeSystemContext Context => _returnType.Context; + + public struct SignatureEnumerator + { + private int _index; + private MethodSignature _signature; + + public SignatureEnumerator(MethodSignature signature) + { + _signature = signature; + _index = -1; + } + + public TypeDesc Current => _signature[_index]; + + public bool MoveNext() + { + _index++; + return _index < _signature.Length; + } + } } /// diff --git a/external/corert/src/Common/src/TypeSystem/Common/PointerType.cs b/external/corert/src/Common/src/TypeSystem/Common/PointerType.cs index e0cd681b2d..15e8adbde4 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/PointerType.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/PointerType.cs @@ -35,7 +35,7 @@ namespace Internal.TypeSystem flags |= TypeFlags.HasGenericVarianceComputed; flags |= TypeFlags.HasFinalizerComputed; - flags |= TypeFlags.IsByRefLikeComputed; + flags |= TypeFlags.AttributeCacheComputed; return flags; } diff --git a/external/corert/src/Common/src/TypeSystem/Common/TargetDetails.cs b/external/corert/src/Common/src/TypeSystem/Common/TargetDetails.cs index 31323e59b0..01ede185f6 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/TargetDetails.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/TargetDetails.cs @@ -18,7 +18,7 @@ namespace Internal.TypeSystem ARM64, X64, X86, - Wasm32 + Wasm32, } /// @@ -49,7 +49,11 @@ namespace Internal.TypeSystem /// /// Jit runtime ABI /// - Jit + Jit, + /// + /// Cross-platform portable C++ codegen + /// + CppCodegen, } /// @@ -102,6 +106,14 @@ namespace Internal.TypeSystem } } + public bool SupportsRelativePointers + { + get + { + return Abi != TargetAbi.CppCodegen; + } + } + /// /// Gets the maximum alignment to which something can be aligned /// @@ -128,17 +140,36 @@ namespace Internal.TypeSystem } /// - /// Gets the minimum required method alignment. + /// Gets the minimum required alignment for methods whose address is visible + /// to managed code. /// public int MinimumFunctionAlignment { get { // We use a minimum alignment of 4 irrespective of the platform. + // This is to prevent confusing the method address with a fat function pointer. return 4; } } + public int MinimumCodeAlignment + { + get + { + switch (Architecture) + { + case TargetArchitecture.ARM: + case TargetArchitecture.ARMEL: + return 2; + case TargetArchitecture.ARM64: + return 4; + default: + return 1; + } + } + } + public TargetDetails(TargetArchitecture architecture, TargetOS targetOS, TargetAbi abi) { Architecture = architecture; @@ -204,7 +235,6 @@ namespace Internal.TypeSystem { case TargetArchitecture.ARM: case TargetArchitecture.ARMEL: - case TargetArchitecture.Wasm32: // ARM supports two alignments for objects on the GC heap (4 byte and 8 byte) if (fieldAlignment.IsIndeterminate) return LayoutInt.Indeterminate; @@ -217,6 +247,7 @@ namespace Internal.TypeSystem case TargetArchitecture.ARM64: return new LayoutInt(8); case TargetArchitecture.X86: + case TargetArchitecture.Wasm32: return new LayoutInt(4); default: throw new NotSupportedException(); diff --git a/external/corert/src/Common/src/TypeSystem/Common/TypeDesc.cs b/external/corert/src/Common/src/TypeSystem/Common/TypeDesc.cs index a3bc755f22..d9110d148e 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/TypeDesc.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/TypeDesc.cs @@ -626,7 +626,7 @@ namespace Internal.TypeSystem { get { - return (GetTypeFlags(TypeFlags.IsByRefLike | TypeFlags.IsByRefLikeComputed) & TypeFlags.IsByRefLike) != 0; + return (GetTypeFlags(TypeFlags.IsByRefLike | TypeFlags.AttributeCacheComputed) & TypeFlags.IsByRefLike) != 0; } } } diff --git a/external/corert/src/Common/src/TypeSystem/Common/TypeFlags.cs b/external/corert/src/Common/src/TypeSystem/Common/TypeFlags.cs index c177cbe591..028a7356d2 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/TypeFlags.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/TypeFlags.cs @@ -57,7 +57,8 @@ namespace Internal.TypeSystem HasFinalizerComputed = 0x1000, HasFinalizer = 0x2000, - IsByRefLike = 0x4000, - IsByRefLikeComputed = 0x8000, + IsByRefLike = 0x04000, + AttributeCacheComputed = 0x08000, + IsIntrinsic = 0x10000, } } diff --git a/external/corert/src/Common/src/TypeSystem/Common/TypeSystemContext.cs b/external/corert/src/Common/src/TypeSystem/Common/TypeSystemContext.cs index 4f9dbb141d..23e2c07585 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/TypeSystemContext.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/TypeSystemContext.cs @@ -66,6 +66,13 @@ namespace Internal.TypeSystem return null; } + internal virtual ModuleDesc ResolveModule(ModuleDesc referencingModule, string fileName, bool throwIfNotFound = true) + { + if (throwIfNotFound) + throw new NotSupportedException(); + return null; + } + // // Array types // diff --git a/external/corert/src/Common/src/TypeSystem/Common/UniversalCanonLayoutAlgorithm.cs b/external/corert/src/Common/src/TypeSystem/Common/UniversalCanonLayoutAlgorithm.cs index f6c475abd5..42eb4197f8 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/UniversalCanonLayoutAlgorithm.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/UniversalCanonLayoutAlgorithm.cs @@ -45,7 +45,8 @@ namespace Internal.TypeSystem { NonGcStatics = new StaticsBlock() { Size = LayoutInt.Zero, LargestAlignment = LayoutInt.Zero }, GcStatics = new StaticsBlock() { Size = LayoutInt.Zero, LargestAlignment = LayoutInt.Zero }, - ThreadStatics = new StaticsBlock() { Size = LayoutInt.Zero, LargestAlignment = LayoutInt.Zero }, + ThreadNonGcStatics = new StaticsBlock() { Size = LayoutInt.Zero, LargestAlignment = LayoutInt.Zero }, + ThreadGcStatics = new StaticsBlock() { Size = LayoutInt.Zero, LargestAlignment = LayoutInt.Zero }, Offsets = Array.Empty() }; } diff --git a/external/corert/src/Common/src/TypeSystem/Common/Utilities/GCPointerMap.Algorithm.cs b/external/corert/src/Common/src/TypeSystem/Common/Utilities/GCPointerMap.Algorithm.cs index 188780b875..8f9a1cd346 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/Utilities/GCPointerMap.Algorithm.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/Utilities/GCPointerMap.Algorithm.cs @@ -52,6 +52,7 @@ namespace Internal.TypeSystem } } + Debug.Assert(builder.ToGCMap().Size * type.Context.Target.PointerSize >= type.GCStaticFieldSize.AsInt); return builder.ToGCMap(); } @@ -60,11 +61,11 @@ namespace Internal.TypeSystem /// public static GCPointerMap FromThreadStaticLayout(DefType type) { - GCPointerMapBuilder builder = new GCPointerMapBuilder(type.ThreadStaticFieldSize.AsInt, type.Context.Target.PointerSize); + GCPointerMapBuilder builder = new GCPointerMapBuilder(type.ThreadGcStaticFieldSize.AsInt, type.Context.Target.PointerSize); foreach (FieldDesc field in type.GetFields()) { - if (!field.IsStatic || field.HasRva || field.IsLiteral || !field.IsThreadStatic) + if (!field.IsStatic || field.HasRva || field.IsLiteral || !field.IsThreadStatic || !field.HasGCStaticBase) continue; TypeDesc fieldType = field.FieldType; @@ -84,6 +85,7 @@ namespace Internal.TypeSystem } } + Debug.Assert(builder.ToGCMap().Size * type.Context.Target.PointerSize >= type.ThreadGcStaticFieldSize.AsInt); return builder.ToGCMap(); } diff --git a/external/corert/src/Common/src/TypeSystem/Common/Utilities/GCPointerMap.cs b/external/corert/src/Common/src/TypeSystem/Common/Utilities/GCPointerMap.cs index 342e1f834d..30a4aab3e8 100644 --- a/external/corert/src/Common/src/TypeSystem/Common/Utilities/GCPointerMap.cs +++ b/external/corert/src/Common/src/TypeSystem/Common/Utilities/GCPointerMap.cs @@ -164,8 +164,9 @@ namespace Internal.TypeSystem public GCPointerMapBuilder(int numBytes, int pointerSize) { - // Don't care about the remainder - the remainder is not big enough to hold a GC pointer. - int numPointerSizedCells = numBytes / pointerSize; + // Align the size up. The size of the pointer map is used to infer the statics storage size that has + // to include space for non-GC statics smaller than pointer size. + int numPointerSizedCells = (numBytes + pointerSize - 1) / pointerSize; if (numPointerSizedCells > 0) { @@ -219,7 +220,7 @@ namespace Internal.TypeSystem public GCPointerMap ToGCMap() { Debug.Assert(_delta == 0); - return new GCPointerMap(_gcFlags, _limit / _pointerSize); + return new GCPointerMap(_gcFlags, (_limit + _pointerSize - 1) / _pointerSize); } public BitEnumerator GetEnumerator() diff --git a/external/corert/src/Common/src/TypeSystem/Ecma/EcmaModule.cs b/external/corert/src/Common/src/TypeSystem/Ecma/EcmaModule.cs index 14b3d51b49..37f82ca032 100644 --- a/external/corert/src/Common/src/TypeSystem/Ecma/EcmaModule.cs +++ b/external/corert/src/Common/src/TypeSystem/Ecma/EcmaModule.cs @@ -9,8 +9,6 @@ using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; -using Internal.TypeSystem; - namespace Internal.TypeSystem.Ecma { public partial class EcmaModule : ModuleDesc @@ -147,6 +145,10 @@ namespace Internal.TypeSystem.Ecma item = _module; break; + case HandleKind.ModuleReference: + item = _module.ResolveModuleReference((ModuleReferenceHandle)handle); + break; + default: throw new BadImageFormatException("Unknown metadata token type: " + handle.Kind); } @@ -165,6 +167,13 @@ namespace Internal.TypeSystem.Ecma } } + private object ResolveModuleReference(ModuleReferenceHandle handle) + { + ModuleReference moduleReference = _metadataReader.GetModuleReference(handle); + string fileName = _metadataReader.GetString(moduleReference.Name); + return Context.ResolveModule(this, fileName); + } + private LockFreeReaderHashtable _resolvedTokens; internal EcmaModule(TypeSystemContext context, PEReader peReader, MetadataReader metadataReader) diff --git a/external/corert/src/Common/src/TypeSystem/Ecma/EcmaType.cs b/external/corert/src/Common/src/TypeSystem/Ecma/EcmaType.cs index e2e840f8a6..de9f467c93 100644 --- a/external/corert/src/Common/src/TypeSystem/Ecma/EcmaType.cs +++ b/external/corert/src/Common/src/TypeSystem/Ecma/EcmaType.cs @@ -242,12 +242,28 @@ namespace Internal.TypeSystem.Ecma flags |= TypeFlags.HasFinalizer; } - if ((mask & TypeFlags.IsByRefLikeComputed) != 0) + if ((mask & TypeFlags.AttributeCacheComputed) != 0) { - flags |= TypeFlags.IsByRefLikeComputed; + MetadataReader reader = MetadataReader; + MetadataStringComparer stringComparer = reader.StringComparer; + bool isValueType = IsValueType; - if (IsValueType && HasCustomAttribute("System.Runtime.CompilerServices", "IsByRefLikeAttribute")) - flags |= TypeFlags.IsByRefLike; + flags |= TypeFlags.AttributeCacheComputed; + + foreach (CustomAttributeHandle attributeHandle in _typeDefinition.GetCustomAttributes()) + { + if (MetadataReader.GetAttributeNamespaceAndName(attributeHandle, out StringHandle namespaceHandle, out StringHandle nameHandle)) + { + if (isValueType && + stringComparer.Equals(nameHandle, "IsByRefLikeAttribute") && + stringComparer.Equals(namespaceHandle, "System.Runtime.CompilerServices")) + flags |= TypeFlags.IsByRefLike; + + if (stringComparer.Equals(nameHandle, "IntrinsicAttribute") && + stringComparer.Equals(namespaceHandle, "System.Runtime.CompilerServices")) + flags |= TypeFlags.IsIntrinsic; + } + } } return flags; diff --git a/external/corert/src/Common/src/TypeSystem/IL/DelegateInfo.cs b/external/corert/src/Common/src/TypeSystem/IL/DelegateInfo.cs index 5322fc6181..8b5fc4dfbd 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/DelegateInfo.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/DelegateInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; using System.Collections.Generic; using Internal.IL.Stubs; @@ -17,13 +18,19 @@ namespace Internal.IL /// public class DelegateInfo { - private TypeDesc _delegateType; + private readonly TypeDesc _delegateType; + private readonly DelegateFeature _supportedFeatures; private MethodSignature _signature; private MethodDesc _getThunkMethod; private DelegateThunkCollection _thunks; + public static bool SupportsDynamicInvoke(TypeSystemContext context) + { + return DynamicInvokeMethodThunk.SupportsDynamicInvoke(context); + } + /// /// Gets the synthetic methods that support this delegate type. /// @@ -78,6 +85,14 @@ namespace Internal.IL } } + public DelegateFeature SupportedFeatures + { + get + { + return _supportedFeatures; + } + } + /// /// Gets the type of the delegate. /// @@ -89,12 +104,13 @@ namespace Internal.IL } } - public DelegateInfo(TypeDesc delegateType) + public DelegateInfo(TypeDesc delegateType, DelegateFeature features) { Debug.Assert(delegateType.IsDelegate); Debug.Assert(delegateType.IsTypeDefinition); _delegateType = delegateType; + _supportedFeatures = features; } } @@ -119,11 +135,11 @@ namespace Internal.IL _openStaticThunk = new DelegateInvokeOpenStaticThunk(owningDelegate); _multicastThunk = new DelegateInvokeMulticastThunk(owningDelegate); _closedStaticThunk = new DelegateInvokeClosedStaticThunk(owningDelegate); - _invokeThunk = new DelegateDynamicInvokeThunk(owningDelegate); _closedInstanceOverGeneric = new DelegateInvokeInstanceClosedOverGenericMethodThunk(owningDelegate); // Methods that have a byref-like type in the signature cannot be invoked with the object array thunk. // We would need to box the parameter and these can't be boxed. + // Neither can be methods that have pointers in the signature. MethodSignature delegateSignature = owningDelegate.Signature; bool generateObjectArrayThunk = true; for (int i = 0; i < delegateSignature.Length; i++) @@ -136,19 +152,34 @@ namespace Internal.IL generateObjectArrayThunk = false; break; } + if (paramType.IsPointer || paramType.IsFunctionPointer) + { + generateObjectArrayThunk = false; + break; + } } TypeDesc normalizedReturnType = delegateSignature.ReturnType; if (normalizedReturnType.IsByRef) normalizedReturnType = ((ByRefType)normalizedReturnType).ParameterType; if (!normalizedReturnType.IsSignatureVariable && normalizedReturnType.IsByRefLike) generateObjectArrayThunk = false; + if (normalizedReturnType.IsPointer || normalizedReturnType.IsFunctionPointer) + generateObjectArrayThunk = false; - if (generateObjectArrayThunk) + if ((owningDelegate.SupportedFeatures & DelegateFeature.ObjectArrayThunk) != 0 && generateObjectArrayThunk) _invokeObjectArrayThunk = new DelegateInvokeObjectArrayThunk(owningDelegate); + // + // Check whether we have a reverse p/invoke thunk + // + if (!owningDelegate.Type.HasInstantiation && IsNativeCallingConventionCompatible(delegateSignature)) _reversePInvokeThunk = new DelegateReversePInvokeThunk(owningDelegate); + // + // Check whether we have an open instance thunk + // + if (delegateSignature.Length > 0) { TypeDesc firstParam = delegateSignature[0]; @@ -185,6 +216,16 @@ namespace Internal.IL } } + // + // Check whether we have a dynamic invoke stub + // + + if ((owningDelegate.SupportedFeatures & DelegateFeature.DynamicInvoke) != 0 && + DynamicInvokeMethodThunk.SupportsSignature(delegateSignature)) + { + var sig = new DynamicInvokeMethodSignature(delegateSignature); + _invokeThunk = owningDelegate.Type.Context.GetDynamicInvokeThunk(sig); + } } #region Temporary interop logic @@ -277,4 +318,11 @@ namespace Internal.IL ReversePinvokeThunk = 6, // This may not exist ObjectArrayThunk = 7, // This may not exist } + + [Flags] + public enum DelegateFeature + { + DynamicInvoke = 0x1, + ObjectArrayThunk = 0x2, + } } diff --git a/external/corert/src/Common/src/TypeSystem/IL/ILImporter.cs b/external/corert/src/Common/src/TypeSystem/IL/ILImporter.cs index fbfdac0723..9a28605a70 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/ILImporter.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/ILImporter.cs @@ -317,6 +317,7 @@ namespace Internal.IL private void ImportBasicBlocks() { _pendingBasicBlocks = _basicBlocks[0]; + _basicBlocks[0].State = BasicBlock.ImportState.IsPending; while (_pendingBasicBlocks != null) { BasicBlock basicBlock = _pendingBasicBlocks; diff --git a/external/corert/src/Common/src/TypeSystem/IL/ILProvider.cs b/external/corert/src/Common/src/TypeSystem/IL/ILProvider.cs index d12904f383..eb1747beb6 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/ILProvider.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/ILProvider.cs @@ -78,6 +78,16 @@ namespace Internal.IL return GetCanonTypeIntrinsic.EmitIL(method); } break; + case "EEType": + { + if (owningType.Namespace == "Internal.Runtime" && method.Name == "get_SupportsRelativePointers") + { + ILOpcode value = method.Context.Target.SupportsRelativePointers ? + ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0; + return new ILStubMethodIL(method, new byte[] { (byte)value, (byte)ILOpcode.ret }, Array.Empty(), null); + } + } + break; } return null; @@ -202,7 +212,7 @@ namespace Internal.IL TypeSystemContext context = elementType.Context; MetadataType helperType = context.SystemModule.GetKnownType("Internal.IntrinsicSupport", "EqualityComparerHelpers"); - MethodDesc methodToCall = null; + MethodDesc methodToCall; if (elementType.IsEnum) { methodToCall = helperType.GetKnownMethod("EnumOnlyEquals", null).MakeInstantiatedMethod(elementType); @@ -215,18 +225,19 @@ namespace Internal.IL { methodToCall = helperType.GetKnownMethod("StructOnlyEqualsIEquatable", null).MakeInstantiatedMethod(elementType); } - - if (methodToCall != null) + else { - return new ILStubMethodIL(method, new byte[] - { - (byte)ILOpcode.ldarg_0, - (byte)ILOpcode.ldarg_1, - (byte)ILOpcode.call, 1, 0, 0, 0, - (byte)ILOpcode.ret - }, - Array.Empty(), new object[] { methodToCall }); + methodToCall = helperType.GetKnownMethod("StructOnlyNormalEquals", null).MakeInstantiatedMethod(elementType); } + + return new ILStubMethodIL(method, new byte[] + { + (byte)ILOpcode.ldarg_0, + (byte)ILOpcode.ldarg_1, + (byte)ILOpcode.call, 1, 0, 0, 0, + (byte)ILOpcode.ret + }, + Array.Empty(), new object[] { methodToCall }); } } } @@ -246,7 +257,7 @@ namespace Internal.IL if (((MetadataType)method.OwningType).HasCustomAttribute("System.Runtime.InteropServices", "McgIntrinsicsAttribute")) { var name = method.Name; - if (name == "Call") + if (name == "Call" || name.StartsWith("StdCall")) { return CalliIntrinsic.EmitIL(method); } diff --git a/external/corert/src/Common/src/TypeSystem/IL/Stubs/CalliIntrinsic.cs b/external/corert/src/Common/src/TypeSystem/IL/Stubs/CalliIntrinsic.cs index 28ae8b621e..2a39b77795 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/Stubs/CalliIntrinsic.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/Stubs/CalliIntrinsic.cs @@ -18,7 +18,7 @@ namespace Internal.IL.Stubs { public static MethodIL EmitIL(MethodDesc target) { - Debug.Assert(target.Name == "Call"); + Debug.Assert(target.Name == "Call" || target.Name.StartsWith("StdCall")); Debug.Assert(target.Signature.Length > 0 && target.Signature[0] == target.Context.GetWellKnownType(WellKnownType.IntPtr)); @@ -44,7 +44,11 @@ namespace Internal.IL.Stubs parameters[i - 1] = template[i]; } - var signature = new MethodSignature(template.Flags, 0, returnType, parameters); + MethodSignatureFlags flags = template.Flags; + if (target.Name == "StdCall") + flags |= MethodSignatureFlags.UnmanagedCallingConventionStdCall; + + var signature = new MethodSignature(flags, 0, returnType, parameters); codeStream.Emit(ILOpcode.calli, emitter.NewToken(signature)); codeStream.Emit(ILOpcode.ret); diff --git a/external/corert/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Mangling.cs b/external/corert/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Mangling.cs new file mode 100644 index 0000000000..5bb37b622e --- /dev/null +++ b/external/corert/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Mangling.cs @@ -0,0 +1,28 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using Internal.TypeSystem; + +namespace Internal.IL.Stubs +{ + public partial class CalliMarshallingMethodThunk : IPrefixMangledSignature + { + MethodSignature IPrefixMangledSignature.BaseSignature + { + get + { + return _targetSignature; + } + } + + string IPrefixMangledSignature.Prefix + { + get + { + return "Calli"; + } + } + } +} diff --git a/external/corert/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs b/external/corert/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs new file mode 100644 index 0000000000..2ac126d110 --- /dev/null +++ b/external/corert/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.TypeSystem; + +namespace Internal.IL.Stubs +{ + // Functionality related to deterministic ordering of methods + partial class CalliMarshallingMethodThunk + { + protected internal override int ClassCode => 1594107963; + + protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + { + var otherMethod = (CalliMarshallingMethodThunk)other; + return comparer.Compare(_targetSignature, otherMethod._targetSignature); + } + } +} diff --git a/external/corert/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs b/external/corert/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs new file mode 100644 index 0000000000..11489bb831 --- /dev/null +++ b/external/corert/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs @@ -0,0 +1,96 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using Internal.TypeSystem; +using Internal.TypeSystem.Interop; +using Debug = System.Diagnostics.Debug; +using Internal.TypeSystem.Ecma; + +namespace Internal.IL.Stubs +{ + /// + /// Thunk to marshal calli PInvoke parameters and invoke the appropriate function pointer + /// + public partial class CalliMarshallingMethodThunk : ILStubMethod + { + private readonly MethodSignature _targetSignature; + private readonly InteropStateManager _interopStateManager; + private readonly TypeDesc _owningType; + + private MethodSignature _signature; + + public CalliMarshallingMethodThunk(MethodSignature targetSignature, TypeDesc owningType, + InteropStateManager interopStateManager) + { + _targetSignature = targetSignature; + _owningType = owningType; + _interopStateManager = interopStateManager; + } + + public MethodSignature TargetSignature + { + get + { + return _targetSignature; + } + } + + public override TypeSystemContext Context + { + get + { + return _owningType.Context; + } + } + + public override TypeDesc OwningType + { + get + { + return _owningType; + } + } + + public override MethodSignature Signature + { + get + { + if (_signature == null) + { + // Prepend fnptr argument to the signature + TypeDesc[] parameterTypes = new TypeDesc[_targetSignature.Length + 1]; + + for (int i = 0; i < _targetSignature.Length; i++) + parameterTypes[i] = _targetSignature[i]; + parameterTypes[parameterTypes.Length - 1] = Context.GetWellKnownType(WellKnownType.IntPtr); + + _signature = new MethodSignature(MethodSignatureFlags.Static, 0, _targetSignature.ReturnType, parameterTypes); + } + return _signature; + } + } + + public override string Name + { + get + { + return "CalliMarshallingMethodThunk"; + } + } + + public override bool IsPInvoke + { + get + { + return true; + } + } + + public override MethodIL EmitIL() + { + return PInvokeILEmitter.EmitIL(this, default(PInvokeILEmitterConfiguration), _interopStateManager); + } + } +} diff --git a/external/corert/src/Common/src/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Mangling.cs b/external/corert/src/Common/src/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Mangling.cs index 7813d0318e..bd140239c8 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Mangling.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Mangling.cs @@ -7,9 +7,6 @@ using Internal.TypeSystem; namespace Internal.IL.Stubs { - /// - /// contains functionality related to name mangling - /// public partial class DelegateMarshallingMethodThunk : IPrefixMangledType { TypeDesc IPrefixMangledType.BaseType diff --git a/external/corert/src/Common/src/TypeSystem/IL/Stubs/DelegateThunks.Sorting.cs b/external/corert/src/Common/src/TypeSystem/IL/Stubs/DelegateThunks.Sorting.cs index f30a11c9cb..d921c9c3b9 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/Stubs/DelegateThunks.Sorting.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/Stubs/DelegateThunks.Sorting.cs @@ -51,17 +51,6 @@ namespace Internal.IL.Stubs protected internal override int ClassCode => 1993292344; } - partial class DelegateDynamicInvokeThunk - { - protected internal override int ClassCode => -1127289330; - - protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) - { - var otherMethod = (DelegateDynamicInvokeThunk)other; - return comparer.Compare(_delegateInfo.Type, otherMethod._delegateInfo.Type); - } - } - partial class DelegateGetThunkMethodOverride { protected internal override int ClassCode => -321263379; diff --git a/external/corert/src/Common/src/TypeSystem/IL/Stubs/DelegateThunks.cs b/external/corert/src/Common/src/TypeSystem/IL/Stubs/DelegateThunks.cs index af8cb9a057..a4e4b88967 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/Stubs/DelegateThunks.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/Stubs/DelegateThunks.cs @@ -187,11 +187,20 @@ namespace Internal.IL.Stubs // Call a helper to get the actual method target codeStream.EmitLdArg(0); - codeStream.EmitLdArg(1); - if (boxThisType != null) + + if (Signature[0].IsByRef) { - codeStream.Emit(ILOpcode.box, emitter.NewToken(boxThisType)); + codeStream.Emit(ILOpcode.ldnull); } + else + { + codeStream.EmitLdArg(1); + if (boxThisType != null) + { + codeStream.Emit(ILOpcode.box, emitter.NewToken(boxThisType)); + } + } + codeStream.Emit(ILOpcode.call, emitter.NewToken(SystemDelegateType.GetKnownMethod("GetActualTargetFunctionPointer", null))); MethodSignature targetSignature = new MethodSignature(0, 0, Signature.ReturnType, parameters); @@ -555,14 +564,13 @@ namespace Internal.IL.Stubs codeStream.EmitLdc(i); codeStream.EmitLdArg(i + 1); - TypeDesc boxableParamType = DelegateDynamicInvokeThunk.ConvertToBoxableType(paramType); - ILToken boxableParamToken = emitter.NewToken(boxableParamType); + ILToken paramToken = emitter.NewToken(paramType); if (paramIsByRef) { - codeStream.Emit(ILOpcode.ldobj, boxableParamToken); + codeStream.Emit(ILOpcode.ldobj, paramToken); } - codeStream.Emit(ILOpcode.box, boxableParamToken); + codeStream.Emit(ILOpcode.box, paramToken); codeStream.Emit(ILOpcode.stelem_ref); } } @@ -616,16 +624,15 @@ namespace Internal.IL.Stubs if (paramType.IsByRef) { paramType = ((ByRefType)paramType).ParameterType; - TypeDesc boxableParamType = DelegateDynamicInvokeThunk.ConvertToBoxableType(paramType); - ILToken boxableParamToken = emitter.NewToken(boxableParamType); + ILToken paramToken = emitter.NewToken(paramType); // Update parameter codeStream.EmitLdArg(i + 1); codeStream.EmitLdLoc(argsLocal); codeStream.EmitLdc(i); codeStream.Emit(ILOpcode.ldelem_ref); - codeStream.Emit(ILOpcode.unbox_any, boxableParamToken); - codeStream.Emit(ILOpcode.stobj, boxableParamToken); + codeStream.Emit(ILOpcode.unbox_any, paramToken); + codeStream.Emit(ILOpcode.stobj, paramToken); } } // ilgen.Emit(OperationCode.Endfinally); @@ -635,9 +642,8 @@ namespace Internal.IL.Stubs if (hasReturnValue) { - TypeDesc boxableReturnType = DelegateDynamicInvokeThunk.ConvertToBoxableType(Signature.ReturnType); codeStream.EmitLdLoc(retLocal); - codeStream.Emit(ILOpcode.unbox_any, emitter.NewToken(boxableReturnType)); + codeStream.Emit(ILOpcode.unbox_any, emitter.NewToken(Signature.ReturnType)); } codeStream.Emit(ILOpcode.ret); @@ -654,213 +660,6 @@ namespace Internal.IL.Stubs } } - /// - /// Delegate thunk that supports Delegate.DynamicInvoke. This thunk has heavy dependencies on the - /// general dynamic invocation infrastructure in System.InvokeUtils and gets called from there - /// at runtime. See comments in System.InvokeUtils for a more thorough explanation. - /// - public sealed partial class DelegateDynamicInvokeThunk : ILStubMethod - { - private DelegateInfo _delegateInfo; - private MethodSignature _signature; - - public DelegateDynamicInvokeThunk(DelegateInfo delegateInfo) - { - _delegateInfo = delegateInfo; - } - - public override TypeSystemContext Context - { - get - { - return _delegateInfo.Type.Context; - } - } - - public override TypeDesc OwningType - { - get - { - return _delegateInfo.Type; - } - } - - public override MethodSignature Signature - { - get - { - if (_signature == null) - { - _signature = new MethodSignature(0, 0, - Context.GetWellKnownType(WellKnownType.Object), - new TypeDesc[] { - Context.GetWellKnownType(WellKnownType.Object), - Context.GetWellKnownType(WellKnownType.IntPtr), - ArgSetupStateType.MakeByRefType() }); - } - return _signature; - } - } - - public override Instantiation Instantiation - { - get - { - return Instantiation.Empty; - } - } - - public override string Name - { - get - { - return "DynamicInvokeImpl"; - } - } - - private MetadataType InvokeUtilsType - { - get - { - return Context.SystemModule.GetKnownType("System", "InvokeUtils"); - } - } - - private MetadataType ArgSetupStateType - { - get - { - return InvokeUtilsType.GetNestedType("ArgSetupState"); - } - } - - public override MethodIL EmitIL() - { - ILEmitter emitter = new ILEmitter(); - ILCodeStream argSetupStream = emitter.NewCodeStream(); - ILCodeStream callSiteSetupStream = emitter.NewCodeStream(); - - // This function will look like - // - // !For each parameter to the delegate - // !if (parameter is In Parameter) - // localX is TypeOfParameterX& - // ldtoken TypeOfParameterX - // call DynamicInvokeParamHelperIn(RuntimeTypeHandle) - // stloc localX - // !else - // localX is TypeOfParameter - // ldtoken TypeOfParameterX - // call DynamicInvokeParamHelperRef(RuntimeTypeHandle) - // stloc localX - - // ldarg.3 - // call DynamicInvokeArgSetupComplete(ref ArgSetupState) - - // *** Second instruction stream starts here *** - - // ldarg.1 // Load this pointer - // !For each parameter - // !if (parameter is In Parameter) - // ldloc localX - // ldobj TypeOfParameterX - // !else - // ldloc localX - // ldarg.1 - // calli ReturnType thiscall(TypeOfParameter1, ...) - // !if ((ReturnType == void) - // ldnull - // !else if (ReturnType is a byref) - // ldobj StripByRef(ReturnType) - // box StripByRef(ReturnType) - // !else - // box ReturnType - // ret - - callSiteSetupStream.EmitLdArg(1); - - MethodSignature delegateSignature = _delegateInfo.Signature; - - TypeDesc[] targetMethodParameters = new TypeDesc[delegateSignature.Length]; - - for (int paramIndex = 0; paramIndex < delegateSignature.Length; paramIndex++) - { - TypeDesc paramType = delegateSignature[paramIndex]; - TypeDesc localType = paramType; - - targetMethodParameters[paramIndex] = paramType; - - if (localType.IsByRef) - { - // Strip ByRef - localType = ((ByRefType)localType).ParameterType; - } - else - { - // Only if this is not a ByRef, convert the parameter type to something boxable. - // Everything but pointer types are boxable. - localType = ConvertToBoxableType(localType); - } - - ILLocalVariable local = emitter.NewLocal(localType.MakeByRefType()); - - callSiteSetupStream.EmitLdLoc(local); - - argSetupStream.Emit(ILOpcode.ldtoken, emitter.NewToken(localType)); - - if (paramType.IsByRef) - { - argSetupStream.Emit(ILOpcode.call, emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeParamHelperRef", null))); - } - else - { - argSetupStream.Emit(ILOpcode.call, emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeParamHelperIn", null))); - - callSiteSetupStream.Emit(ILOpcode.ldobj, emitter.NewToken(paramType)); - } - argSetupStream.EmitStLoc(local); - } - - argSetupStream.EmitLdArg(3); - argSetupStream.Emit(ILOpcode.call, emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeArgSetupComplete", null))); - - callSiteSetupStream.EmitLdArg(2); - - MethodSignature targetMethodSig = new MethodSignature(0, 0, delegateSignature.ReturnType, targetMethodParameters); - - callSiteSetupStream.Emit(ILOpcode.calli, emitter.NewToken(targetMethodSig)); - - if (delegateSignature.ReturnType.IsVoid) - { - callSiteSetupStream.Emit(ILOpcode.ldnull); - } - else if (delegateSignature.ReturnType.IsByRef) - { - TypeDesc targetType = ((ByRefType)delegateSignature.ReturnType).ParameterType; - callSiteSetupStream.Emit(ILOpcode.ldobj, emitter.NewToken(targetType)); - callSiteSetupStream.Emit(ILOpcode.box, emitter.NewToken(targetType)); - } - else - { - callSiteSetupStream.Emit(ILOpcode.box, emitter.NewToken(delegateSignature.ReturnType)); - } - - callSiteSetupStream.Emit(ILOpcode.ret); - - return emitter.Link(this); - } - - internal static TypeDesc ConvertToBoxableType(TypeDesc type) - { - if (type.IsPointer || type.IsFunctionPointer) - { - return type.Context.GetWellKnownType(WellKnownType.IntPtr); - } - - return type; - } - } - /// /// Synthetic method override of "IntPtr Delegate.GetThunk(Int32)". This method is injected /// into all delegate types and provides means for System.Delegate to access the various thunks @@ -939,7 +738,25 @@ namespace Internal.IL.Stubs { codeStream.EmitLabel(labels[(int)i]); - codeStream.Emit(ILOpcode.ldftn, emitter.NewToken(thunk.InstantiateAsOpen())); + if (i == DelegateThunkKind.DelegateInvokeThunk) + { + // Dynamic invoke thunk is special since we're calling into a shared helper + MethodDesc targetMethod; + if (thunk.HasInstantiation) + { + TypeDesc[] inst = DynamicInvokeMethodThunk.GetThunkInstantiationForMethod(_delegateInfo.Type.InstantiateAsOpen().GetMethod("Invoke", null)); + targetMethod = Context.GetInstantiatedMethod(thunk, new Instantiation(inst)); + } + else + { + targetMethod = thunk; + } + codeStream.Emit(ILOpcode.ldftn, emitter.NewToken(targetMethod)); + } + else + { + codeStream.Emit(ILOpcode.ldftn, emitter.NewToken(thunk.InstantiateAsOpen())); + } codeStream.Emit(ILOpcode.ret); } } diff --git a/external/corert/src/Common/src/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Sorting.cs b/external/corert/src/Common/src/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Sorting.cs index 9904331134..d9c937f058 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Sorting.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Sorting.cs @@ -12,9 +12,9 @@ namespace Internal.IL.Stubs // Functionality related to determinstic ordering of types partial class DynamicInvokeMethodThunk { - protected override int ClassCode => -1980933220; + protected internal override int ClassCode => -1980933220; - protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) { return CompareTo((DynamicInvokeMethodThunk)other); } @@ -25,13 +25,23 @@ namespace Internal.IL.Stubs if (result != 0) return result; - result = (_targetSignature.HasReturnValue ? 1 : 0) - (otherMethod._targetSignature.HasReturnValue ? 1 : 0); + DynamicInvokeMethodParameterKind thisReturnType = _targetSignature.ReturnType; + result = (int)thisReturnType - (int)otherMethod._targetSignature.ReturnType; + if (result != 0) + return result; + + result = _targetSignature.GetNumerOfReturnTypePointerIndirections() - otherMethod._targetSignature.GetNumerOfReturnTypePointerIndirections(); if (result != 0) return result; for (int i = 0; i < _targetSignature.Length; i++) { - result = (int)_targetSignature[i] - (int)otherMethod._targetSignature[i]; + DynamicInvokeMethodParameterKind thisParamType = _targetSignature[i]; + result = (int)thisParamType - (int)otherMethod._targetSignature[i]; + if (result != 0) + return result; + + result = _targetSignature.GetNumberOfParameterPointerIndirections(i) - otherMethod._targetSignature.GetNumberOfParameterPointerIndirections(i); if (result != 0) return result; } @@ -42,9 +52,9 @@ namespace Internal.IL.Stubs partial class DynamicInvokeThunkGenericParameter { - protected override int ClassCode => -234393261; + protected internal override int ClassCode => -234393261; - protected override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) + protected internal override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) { var otherType = (DynamicInvokeThunkGenericParameter)other; int result = Index - otherType.Index; @@ -55,4 +65,4 @@ namespace Internal.IL.Stubs } } } -} \ No newline at end of file +} diff --git a/external/corert/src/Common/src/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.cs b/external/corert/src/Common/src/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.cs index 68c89d880d..510b300c5d 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.cs @@ -18,7 +18,7 @@ namespace Internal.IL.Stubs /// dependencies on the general dynamic invocation infrastructure in System.InvokeUtils and gets called from there /// at runtime. See comments in System.InvokeUtils for a more thorough explanation. /// - internal partial class DynamicInvokeMethodThunk : ILStubMethod + public partial class DynamicInvokeMethodThunk : ILStubMethod { private TypeDesc _owningType; private DynamicInvokeMethodSignature _targetSignature; @@ -32,11 +32,127 @@ namespace Internal.IL.Stubs _targetSignature = signature; } - public static bool SupportsThunks(TypeSystemContext context) + internal static bool SupportsDynamicInvoke(TypeSystemContext context) { return context.SystemModule.GetType("System", "InvokeUtils", false) != null; } + private static TypeDesc UnwrapByRef(TypeDesc type) + { + if (type.IsByRef) + return ((ByRefType)type).ParameterType; + return type; + } + + public static bool SupportsSignature(MethodSignature signature) + { + // ---------------------------------------------------------------- + // TODO: function pointer types are odd: https://github.com/dotnet/corert/issues/1929 + // ---------------------------------------------------------------- + + if (UnwrapByRef(signature.ReturnType).IsFunctionPointer) + return false; + + for (int i = 0; i < signature.Length; i++) + if (UnwrapByRef(signature[i]).IsFunctionPointer) + return false; + + // ---------------------------------------------------------------- + // Methods that return ByRef-like types or take them by reference can't be reflection invoked + // ---------------------------------------------------------------- + + if (!signature.ReturnType.IsSignatureVariable && UnwrapByRef(signature.ReturnType).IsByRefLike) + return false; + + for (int i = 0; i < signature.Length; i++) + { + ByRefType paramType = signature[i] as ByRefType; + if (paramType != null && !paramType.ParameterType.IsSignatureVariable && UnwrapByRef(paramType.ParameterType).IsByRefLike) + return false; + } + + return true; + } + + public static TypeDesc[] GetThunkInstantiationForMethod(MethodDesc method) + { + MethodSignature sig = method.Signature; + + ParameterMetadata[] paramMetadata = null; + TypeDesc[] instantiation = new TypeDesc[sig.ReturnType.IsVoid ? sig.Length : sig.Length + 1]; + + for (int i = 0; i < sig.Length; i++) + { + TypeDesc parameterType = sig[i]; + if (parameterType.IsByRef) + { + // strip ByRefType off the parameter (the method already has ByRef in the signature) + parameterType = ((ByRefType)parameterType).ParameterType; + + // Strip off all the pointers. Pointers are not valid instantiation arguments and the thunk compensates for that + // by being specialized for the specific pointer depth. + while (parameterType.IsPointer) + parameterType = ((PointerType)parameterType).ParameterType; + } + else if (parameterType.IsPointer) + { + // Strip off all the pointers. Pointers are not valid instantiation arguments and the thunk compensates for that + // by being specialized for the specific pointer depth. + while (parameterType.IsPointer) + parameterType = ((PointerType)parameterType).ParameterType; + } + else if (parameterType.IsEnum) + { + // If the invoke method takes an enum as an input parameter and there is no default value for + // that paramter, we don't need to specialize on the exact enum type (we only need to specialize + // on the underlying integral type of the enum.) + if (paramMetadata == null) + paramMetadata = method.GetParameterMetadata(); + + bool hasDefaultValue = false; + foreach (var p in paramMetadata) + { + // Parameter metadata indexes are 1-based (0 is reserved for return "parameter") + if (p.Index == (i + 1) && p.HasDefault) + { + hasDefaultValue = true; + break; + } + } + + if (!hasDefaultValue) + parameterType = parameterType.UnderlyingType; + } + + instantiation[i] = parameterType; + } + + if (!sig.ReturnType.IsVoid) + { + TypeDesc returnType = sig.ReturnType; + + // strip ByRefType off the return type (the method already has ByRef in the signature) + if (returnType.IsByRef) + returnType = ((ByRefType)returnType).ParameterType; + + // If the invoke method return an object reference, we don't need to specialize on the + // exact type of the object reference, as the behavior is not different. + if ((returnType.IsDefType && !returnType.IsValueType) || returnType.IsArray) + { + returnType = method.Context.GetWellKnownType(WellKnownType.Object); + } + + // Strip off all the pointers. Pointers are not valid instantiation arguments and the thunk compensates for that + // by being specialized for the specific pointer depth. + while (returnType.IsPointer) + returnType = ((PointerType)returnType).ParameterType; + + instantiation[sig.Length] = returnType; + } + + return instantiation; + } + public override TypeSystemContext Context { get @@ -69,6 +185,14 @@ namespace Internal.IL.Stubs } } + public DynamicInvokeMethodSignature TargetSignature + { + get + { + return _targetSignature; + } + } + public override MethodSignature Signature { get @@ -121,13 +245,54 @@ namespace Internal.IL.Stubs { StringBuilder sb = new StringBuilder("InvokeRet"); - if (_targetSignature.HasReturnValue) - sb.Append('O'); - else - sb.Append('V'); + switch (_targetSignature.ReturnType) + { + case DynamicInvokeMethodParameterKind.None: + sb.Append('V'); + break; + case DynamicInvokeMethodParameterKind.Pointer: + sb.Append('P'); + for (int i = 0; i < _targetSignature.GetNumerOfReturnTypePointerIndirections() - 1; i++) + sb.Append('p'); + break; + case DynamicInvokeMethodParameterKind.Reference: + sb.Append("R"); + for (int i = 0; i < _targetSignature.GetNumerOfReturnTypePointerIndirections(); i++) + sb.Append('p'); + break; + case DynamicInvokeMethodParameterKind.Value: + sb.Append('O'); + break; + default: + Debug.Fail("Unreachable"); + break; + } for (int i = 0; i < _targetSignature.Length; i++) - sb.Append(_targetSignature[i] == DynamicInvokeMethodParameterKind.Value ? 'I' : 'R'); + { + switch (_targetSignature[i]) + { + case DynamicInvokeMethodParameterKind.Pointer: + sb.Append('P'); + + for (int j = 0; j < _targetSignature.GetNumberOfParameterPointerIndirections(i) - 1; j++) + sb.Append('p'); + + break; + case DynamicInvokeMethodParameterKind.Reference: + sb.Append("R"); + + for (int j = 0; j < _targetSignature.GetNumberOfParameterPointerIndirections(i); j++) + sb.Append('p'); + break; + case DynamicInvokeMethodParameterKind.Value: + sb.Append("I"); + break; + default: + Debug.Fail("Unreachable"); + break; + } + } return sb.ToString(); } @@ -139,6 +304,7 @@ namespace Internal.IL.Stubs ILCodeStream argSetupStream = emitter.NewCodeStream(); ILCodeStream thisCallSiteSetupStream = emitter.NewCodeStream(); ILCodeStream staticCallSiteSetupStream = emitter.NewCodeStream(); + ILCodeStream returnCodeStream = emitter.NewCodeStream(); // This function will look like // @@ -171,11 +337,7 @@ namespace Internal.IL.Stubs // ldloc localX // ldarg.1 // calli ReturnType thiscall(TypeOfParameter1, ...) - // !if ((ReturnType == void) - // ldnull - // !else - // box ReturnType - // ret + // br Process_return // *** Static call instruction stream starts here *** @@ -188,13 +350,30 @@ namespace Internal.IL.Stubs // ldloc localX // ldarg.1 // calli ReturnType (TypeOfParameter1, ...) + + // *** Return code stream starts here *** + + // Process_return: + // !if (ReturnType is Byref) + // dup + // brfalse ByRefNull + // ldobj ReturnType // !if ((ReturnType == void) // ldnull + // !elif (ReturnType is pointer) + // System.Reflection.Pointer.Box(ReturnType) // !else // box ReturnType // ret + // + // !if (ReturnType is ByRef) + // ByRefNull: + // pop + // call InvokeUtils.get_NullByRefValueSentinel + // ret ILCodeLabel lStaticCall = emitter.NewCodeLabel(); + ILCodeLabel lProcessReturn = emitter.NewCodeLabel(); thisCallSiteSetupStream.EmitLdArg(3); // targetIsThisCall thisCallSiteSetupStream.Emit(ILOpcode.brfalse, lStaticCall); staticCallSiteSetupStream.EmitLabel(lStaticCall); @@ -211,6 +390,11 @@ namespace Internal.IL.Stubs for (int paramIndex = 0; paramIndex < _targetSignature.Length; paramIndex++) { TypeDesc paramType = Context.GetSignatureVariable(paramIndex, true); + DynamicInvokeMethodParameterKind paramKind = _targetSignature[paramIndex]; + + for (int i = 0; i < _targetSignature.GetNumberOfParameterPointerIndirections(paramIndex); i++) + paramType = paramType.MakePointerType(); + ILToken tokParamType = emitter.NewToken(paramType); ILLocalVariable local = emitter.NewLocal(paramType.MakeByRefType()); @@ -219,7 +403,7 @@ namespace Internal.IL.Stubs argSetupStream.Emit(ILOpcode.ldtoken, tokParamType); - if (_targetSignature[paramIndex] == DynamicInvokeMethodParameterKind.Reference) + if (paramKind == DynamicInvokeMethodParameterKind.Reference) { argSetupStream.Emit(ILOpcode.call, tokDynamicInvokeParamHelperRef); @@ -243,30 +427,74 @@ namespace Internal.IL.Stubs thisCallSiteSetupStream.EmitLdArg(1); // methodToCall staticCallSiteSetupStream.EmitLdArg(1); // methodToCall - TypeDesc returnType = _targetSignature.HasReturnValue ? + DynamicInvokeMethodParameterKind returnKind = _targetSignature.ReturnType; + TypeDesc returnType = returnKind != DynamicInvokeMethodParameterKind.None ? Context.GetSignatureVariable(_targetSignature.Length, true) : Context.GetWellKnownType(WellKnownType.Void); + for (int i = 0; i < _targetSignature.GetNumerOfReturnTypePointerIndirections(); i++) + returnType = returnType.MakePointerType(); + + if (returnKind == DynamicInvokeMethodParameterKind.Reference) + returnType = returnType.MakeByRefType(); + MethodSignature thisCallMethodSig = new MethodSignature(0, 0, returnType, targetMethodSignature); thisCallSiteSetupStream.Emit(ILOpcode.calli, emitter.NewToken(thisCallMethodSig)); + thisCallSiteSetupStream.Emit(ILOpcode.br, lProcessReturn); MethodSignature staticCallMethodSig = new MethodSignature(MethodSignatureFlags.Static, 0, returnType, targetMethodSignature); staticCallSiteSetupStream.Emit(ILOpcode.calli, emitter.NewToken(staticCallMethodSig)); - if (_targetSignature.HasReturnValue) + returnCodeStream.EmitLabel(lProcessReturn); + + ILCodeLabel lByRefReturnNull = null; + + if (returnKind == DynamicInvokeMethodParameterKind.None) { - ILToken tokReturnType = emitter.NewToken(returnType); - thisCallSiteSetupStream.Emit(ILOpcode.box, tokReturnType); - staticCallSiteSetupStream.Emit(ILOpcode.box, tokReturnType); + returnCodeStream.Emit(ILOpcode.ldnull); } else { - thisCallSiteSetupStream.Emit(ILOpcode.ldnull); - staticCallSiteSetupStream.Emit(ILOpcode.ldnull); + TypeDesc returnTypeForBoxing = returnType; + + if (returnType.IsByRef) + { + // If this is a byref return, we need to dereference first + returnTypeForBoxing = ((ByRefType)returnType).ParameterType; + lByRefReturnNull = emitter.NewCodeLabel(); + returnCodeStream.Emit(ILOpcode.dup); + returnCodeStream.Emit(ILOpcode.brfalse, lByRefReturnNull); + returnCodeStream.Emit(ILOpcode.ldobj, emitter.NewToken(returnTypeForBoxing)); + } + + if (returnTypeForBoxing.IsPointer) + { + // Pointers box differently + returnCodeStream.Emit(ILOpcode.ldtoken, emitter.NewToken(returnTypeForBoxing)); + MethodDesc getTypeFromHandleMethod = + Context.SystemModule.GetKnownType("System", "Type").GetKnownMethod("GetTypeFromHandle", null); + returnCodeStream.Emit(ILOpcode.call, emitter.NewToken(getTypeFromHandleMethod)); + + MethodDesc pointerBoxMethod = + Context.SystemModule.GetKnownType("System.Reflection", "Pointer").GetKnownMethod("Box", null); + returnCodeStream.Emit(ILOpcode.call, emitter.NewToken(pointerBoxMethod)); + } + else + { + ILToken tokReturnType = emitter.NewToken(returnTypeForBoxing); + returnCodeStream.Emit(ILOpcode.box, tokReturnType); + } } - thisCallSiteSetupStream.Emit(ILOpcode.ret); - staticCallSiteSetupStream.Emit(ILOpcode.ret); + returnCodeStream.Emit(ILOpcode.ret); + + if (lByRefReturnNull != null) + { + returnCodeStream.EmitLabel(lByRefReturnNull); + returnCodeStream.Emit(ILOpcode.pop); + returnCodeStream.Emit(ILOpcode.call, emitter.NewToken(InvokeUtilsType.GetKnownMethod("get_NullByRefValueSentinel", null))); + returnCodeStream.Emit(ILOpcode.ret); + } return emitter.Link(this); } @@ -309,15 +537,18 @@ namespace Internal.IL.Stubs None, Value, Reference, + Pointer, } /// /// Wraps a to reduce it's fidelity. /// - internal struct DynamicInvokeMethodSignature : IEquatable + public struct DynamicInvokeMethodSignature : IEquatable { private MethodSignature _signature; + public TypeSystemContext Context => _signature.ReturnType.Context; + public bool HasReturnValue { get @@ -334,21 +565,66 @@ namespace Internal.IL.Stubs } } - public DynamicInvokeMethodParameterKind this[int index] + internal DynamicInvokeMethodParameterKind this[int index] { get { - return _signature[index].IsByRef ? - DynamicInvokeMethodParameterKind.Reference : - DynamicInvokeMethodParameterKind.Value; + TypeDesc type = _signature[index]; + + if (type.IsByRef) + return DynamicInvokeMethodParameterKind.Reference; + else if (type.IsPointer) + return DynamicInvokeMethodParameterKind.Pointer; + else + return DynamicInvokeMethodParameterKind.Value; + } + } + + public static int GetNumberOfIndirections(TypeDesc type) + { + // Strip byrefness off. This is to support "ref void**"-style signatures. + if (type.IsByRef) + type = ((ByRefType)type).ParameterType; + + int result = 0; + while (type.IsPointer) + { + result++; + type = ((PointerType)type).ParameterType; + } + + return result; + } + + public int GetNumberOfParameterPointerIndirections(int paramIndex) + { + return GetNumberOfIndirections(_signature[paramIndex]); + } + + public int GetNumerOfReturnTypePointerIndirections() + { + return GetNumberOfIndirections(_signature.ReturnType); + } + + internal DynamicInvokeMethodParameterKind ReturnType + { + get + { + TypeDesc type = _signature.ReturnType; + if (type.IsPointer) + return DynamicInvokeMethodParameterKind.Pointer; + else if (type.IsVoid) + return DynamicInvokeMethodParameterKind.None; + else if (type.IsByRef) + return DynamicInvokeMethodParameterKind.Reference; + else + return DynamicInvokeMethodParameterKind.Value; } } public DynamicInvokeMethodSignature(MethodSignature concreteSignature) { - // ByRef returns should have been filtered out elsewhere. We don't handle them - // because reflection can't invoke such methods. - Debug.Assert(!concreteSignature.ReturnType.IsByRef); + Debug.Assert(DynamicInvokeMethodThunk.SupportsSignature(concreteSignature)); _signature = concreteSignature; } @@ -359,7 +635,7 @@ namespace Internal.IL.Stubs public override int GetHashCode() { - int hashCode = HasReturnValue ? 17 : 23; + int hashCode = (int)this.ReturnType * 0x5498341 + 0x832424; for (int i = 0; i < Length; i++) { @@ -372,7 +648,11 @@ namespace Internal.IL.Stubs public bool Equals(DynamicInvokeMethodSignature other) { - if (HasReturnValue != other.HasReturnValue) + DynamicInvokeMethodParameterKind thisReturnKind = ReturnType; + if (thisReturnKind != other.ReturnType) + return false; + + if (GetNumerOfReturnTypePointerIndirections() != other.GetNumerOfReturnTypePointerIndirections()) return false; if (Length != other.Length) @@ -380,7 +660,11 @@ namespace Internal.IL.Stubs for (int i = 0; i < Length; i++) { - if (this[i] != other[i]) + DynamicInvokeMethodParameterKind thisParamKind = this[i]; + if (thisParamKind != other[i]) + return false; + + if (GetNumberOfParameterPointerIndirections(i) != other.GetNumberOfParameterPointerIndirections(i)) return false; } diff --git a/external/corert/src/Common/src/TypeSystem/IL/Stubs/ILEmitter.cs b/external/corert/src/Common/src/TypeSystem/IL/Stubs/ILEmitter.cs index 042636f41b..45627bd1d7 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/Stubs/ILEmitter.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/Stubs/ILEmitter.cs @@ -253,6 +253,8 @@ namespace Internal.IL.Stubs break; case TypeFlags.ValueType: case TypeFlags.Nullable: + case TypeFlags.SignatureMethodVariable: + case TypeFlags.SignatureTypeVariable: Emit(ILOpcode.ldobj, _emitter.NewToken(type)); break; default: diff --git a/external/corert/src/Common/src/TypeSystem/IL/Stubs/PInvokeILEmitter.cs b/external/corert/src/Common/src/TypeSystem/IL/Stubs/PInvokeILEmitter.cs index fa503b7427..7620bda5bc 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/Stubs/PInvokeILEmitter.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/Stubs/PInvokeILEmitter.cs @@ -40,12 +40,10 @@ namespace Internal.IL.Stubs // targetMethod could be either a PInvoke or a DelegateMarshallingMethodThunk // ForwardNativeFunctionWrapper method thunks are marked as PInvokes, so it is // important to check them first here so that we get the right flags. - // - DelegateMarshallingMethodThunk delegateThunk = _targetMethod as DelegateMarshallingMethodThunk; - - if (delegateThunk != null) + // + if (_targetMethod is DelegateMarshallingMethodThunk delegateMethod) { - _flags = ((EcmaType)delegateThunk.DelegateType).GetDelegatePInvokeFlags(); + _flags = ((EcmaType)delegateMethod.DelegateType).GetDelegatePInvokeFlags(); } else { @@ -57,9 +55,21 @@ namespace Internal.IL.Stubs private static Marshaller[] InitializeMarshallers(MethodDesc targetMethod, InteropStateManager interopStateManager, PInvokeFlags flags) { - bool isDelegate = targetMethod is DelegateMarshallingMethodThunk; - MethodSignature methodSig = isDelegate ? ((DelegateMarshallingMethodThunk)targetMethod).DelegateSignature : targetMethod.Signature; - MarshalDirection direction = isDelegate ? ((DelegateMarshallingMethodThunk)targetMethod).Direction: MarshalDirection.Forward; + MarshalDirection direction = MarshalDirection.Forward; + MethodSignature methodSig; + switch (targetMethod) + { + case DelegateMarshallingMethodThunk delegateMethod: + methodSig = delegateMethod.DelegateSignature; + direction = delegateMethod.Direction; + break; + case CalliMarshallingMethodThunk calliMethod: + methodSig = calliMethod.TargetSignature; + break; + default: + methodSig = targetMethod.Signature; + break; + } int indexOffset = 0; if (!methodSig.IsStatic && direction == MarshalDirection.Forward) { @@ -282,6 +292,27 @@ namespace Internal.IL.Stubs } } + private void EmitCalli(PInvokeILCodeStreams ilCodeStreams, CalliMarshallingMethodThunk calliThunk) + { + ILEmitter emitter = ilCodeStreams.Emitter; + ILCodeStream callsiteSetupCodeStream = ilCodeStreams.CallsiteSetupCodeStream; + + TypeDesc nativeReturnType = _marshallers[0].NativeParameterType; + TypeDesc[] nativeParameterTypes = new TypeDesc[_marshallers.Length - 1]; + + for (int i = 1; i < _marshallers.Length; i++) + { + nativeParameterTypes[i - 1] = _marshallers[i].NativeParameterType; + } + + MethodSignature nativeSig = new MethodSignature( + calliThunk.TargetSignature.Flags, 0, nativeReturnType, + nativeParameterTypes); + + callsiteSetupCodeStream.EmitLdArg(calliThunk.TargetSignature.Length); + callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(nativeSig)); + } + private MethodIL EmitIL() { PInvokeILCodeStreams pInvokeILCodeStreams = new PInvokeILCodeStreams(); @@ -295,20 +326,23 @@ namespace Internal.IL.Stubs } // make the call - DelegateMarshallingMethodThunk delegateMethod = _targetMethod as DelegateMarshallingMethodThunk; - if (delegateMethod != null) + switch (_targetMethod) { - EmitDelegateCall(delegateMethod, pInvokeILCodeStreams); - } - else - { - EmitPInvokeCall(pInvokeILCodeStreams); + case DelegateMarshallingMethodThunk delegateMethod: + EmitDelegateCall(delegateMethod, pInvokeILCodeStreams); + break; + case CalliMarshallingMethodThunk calliMethod: + EmitCalli(pInvokeILCodeStreams, calliMethod); + break; + default: + EmitPInvokeCall(pInvokeILCodeStreams); + break; } _marshallers[0].LoadReturnValue(unmarshallingCodestream); unmarshallingCodestream.Emit(ILOpcode.ret); - return new PInvokeILStubMethodIL((ILStubMethodIL)emitter.Link(_targetMethod), IsStubRequired()); + return new PInvokeILStubMethodIL((ILStubMethodIL)emitter.Link(_targetMethod), IsStubRequired()); } public static MethodIL EmitIL(MethodDesc method, @@ -342,11 +376,14 @@ namespace Internal.IL.Stubs return true; } - if (MarshalHelpers.UseLazyResolution(_targetMethod, _importMetadata.Module, - _pInvokeILEmitterConfiguration)) + if (_pInvokeILEmitterConfiguration != null) { - return true; + if (MarshalHelpers.UseLazyResolution(_targetMethod, _importMetadata.Module, _pInvokeILEmitterConfiguration)) + { + return true; + } } + if (_flags.SetLastError) { return true; diff --git a/external/corert/src/Common/src/TypeSystem/IL/Stubs/PInvokeLazyFixupField.cs b/external/corert/src/Common/src/TypeSystem/IL/Stubs/PInvokeLazyFixupField.cs index 650b244c13..dd4f182de1 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/Stubs/PInvokeLazyFixupField.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/Stubs/PInvokeLazyFixupField.cs @@ -109,5 +109,13 @@ namespace Internal.IL.Stubs { return false; } + + public override string Name + { + get + { + return _targetMethod.Name; + } + } } } diff --git a/external/corert/src/Common/src/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.cs b/external/corert/src/Common/src/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.cs index 2a2cae4e82..5aab575a28 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.cs @@ -72,6 +72,15 @@ namespace Internal.IL.Stubs } } + public override bool IsNoInlining + { + get + { + // This method does not have real IL body. NoInlining stops the JIT asking for it. + return true; + } + } + public override PInvokeMetadata GetPInvokeMethodMetadata() { return _declMethod.GetPInvokeMethodMetadata(); diff --git a/external/corert/src/Common/src/TypeSystem/IL/Stubs/StructMarshallingThunk.cs b/external/corert/src/Common/src/TypeSystem/IL/Stubs/StructMarshallingThunk.cs index 6625e3b9a0..e5360b37c4 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/Stubs/StructMarshallingThunk.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/Stubs/StructMarshallingThunk.cs @@ -14,7 +14,7 @@ namespace Internal.IL.Stubs public enum StructMarshallingThunkType : byte { ManagedToNative = 1, - NativeToManage = 2, + NativeToManaged = 2, Cleanup = 4 } @@ -72,19 +72,29 @@ namespace Internal.IL.Stubs { if (_signature == null) { - TypeDesc[] parameters; - if (ThunkType == StructMarshallingThunkType.Cleanup) + TypeDesc[] parameters = null; + switch (ThunkType) { - parameters = new TypeDesc[] { - NativeType.MakeByRefType() - }; - } - else - { - parameters = new TypeDesc[] { - ManagedType.MakeByRefType(), - NativeType.MakeByRefType() - }; + case StructMarshallingThunkType.ManagedToNative: + parameters = new TypeDesc[] { + ManagedType.IsValueType ? (TypeDesc)ManagedType.MakeByRefType() : ManagedType, + NativeType.MakeByRefType() + }; + break; + case StructMarshallingThunkType.NativeToManaged: + parameters = new TypeDesc[] { + NativeType.MakeByRefType(), + ManagedType.IsValueType ? (TypeDesc)ManagedType.MakeByRefType() : ManagedType + }; + break; + case StructMarshallingThunkType.Cleanup: + parameters = new TypeDesc[] { + NativeType.MakeByRefType() + }; + break; + default: + System.Diagnostics.Debug.Fail("Unexpected Struct marshalling thunk type"); + break; } _signature = new MethodSignature(MethodSignatureFlags.Static, 0, Context.GetWellKnownType(WellKnownType.Void), parameters); } @@ -100,7 +110,7 @@ namespace Internal.IL.Stubs { case StructMarshallingThunkType.ManagedToNative: return "ManagedToNative"; - case StructMarshallingThunkType.NativeToManage: + case StructMarshallingThunkType.NativeToManaged: return "NativeToManaged"; case StructMarshallingThunkType.Cleanup: return "Cleanup"; @@ -147,7 +157,7 @@ namespace Internal.IL.Stubs marshallers[index] = Marshaller.CreateMarshaller(field.FieldType, MarshallerType.Field, marshalAsDescriptors[index], - (ThunkType == StructMarshallingThunkType.NativeToManage) ? MarshalDirection.Reverse : MarshalDirection.Forward, + (ThunkType == StructMarshallingThunkType.NativeToManaged) ? MarshalDirection.Reverse : MarshalDirection.Forward, marshallers, _interopStateManager, index, @@ -204,9 +214,9 @@ namespace Internal.IL.Stubs { LoadFieldValueFromArg(0, managedField, pInvokeILCodeStreams); } - else if (ThunkType == StructMarshallingThunkType.NativeToManage) + else if (ThunkType == StructMarshallingThunkType.NativeToManaged) { - LoadFieldValueFromArg(1, nativeField, pInvokeILCodeStreams); + LoadFieldValueFromArg(0, nativeField, pInvokeILCodeStreams); } _marshallers[index++].EmitMarshallingIL(pInvokeILCodeStreams); @@ -215,9 +225,9 @@ namespace Internal.IL.Stubs { StoreFieldValueFromArg(1, nativeField, pInvokeILCodeStreams); } - else if (ThunkType == StructMarshallingThunkType.NativeToManage) + else if (ThunkType == StructMarshallingThunkType.NativeToManaged) { - StoreFieldValueFromArg(0, managedField, pInvokeILCodeStreams); + StoreFieldValueFromArg(1, managedField, pInvokeILCodeStreams); } } } diff --git a/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.DelegateInfo.cs b/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.DelegateInfo.cs index 4f186e2195..a835b47d0a 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.DelegateInfo.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.DelegateInfo.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Collections.Generic; using Internal.IL; @@ -13,6 +12,10 @@ namespace Internal.TypeSystem { private class DelegateInfoHashtable : LockFreeReaderHashtable { + private enum CoreLibSupportLevel { Unknown, Supported, Unsupported } + + private CoreLibSupportLevel _supportLevel; + protected override int GetKeyHashCode(TypeDesc key) { return key.GetHashCode(); @@ -31,7 +34,18 @@ namespace Internal.TypeSystem } protected override DelegateInfo CreateValueFromKey(TypeDesc key) { - return new DelegateInfo(key); + if (_supportLevel == CoreLibSupportLevel.Unknown) + { + // Check if the core library supports dynamic invoke. + _supportLevel = DelegateInfo.SupportsDynamicInvoke(key.Context) ? + CoreLibSupportLevel.Supported : CoreLibSupportLevel.Unsupported; + } + + DelegateFeature supportedFeatures = _supportLevel == CoreLibSupportLevel.Supported ? + DelegateFeature.DynamicInvoke | DelegateFeature.ObjectArrayThunk : 0; + + + return new DelegateInfo(key, supportedFeatures); } } diff --git a/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.DynamicInvoke.cs b/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.DynamicInvoke.cs new file mode 100644 index 0000000000..cdad3d9ef2 --- /dev/null +++ b/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.DynamicInvoke.cs @@ -0,0 +1,31 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.IL.Stubs; + +using Debug = System.Diagnostics.Debug; + +namespace Internal.TypeSystem +{ + partial class TypeSystemContext + { + private class DynamicInvokeThunkHashtable : LockFreeReaderHashtable + { + protected override bool CompareKeyToValue(DynamicInvokeMethodSignature key, DynamicInvokeMethodThunk value) => key.Equals(value.TargetSignature); + protected override bool CompareValueToValue(DynamicInvokeMethodThunk value1, DynamicInvokeMethodThunk value2) => value1.TargetSignature.Equals(value2.TargetSignature) && value1.OwningType == value2.OwningType; + protected override int GetKeyHashCode(DynamicInvokeMethodSignature key) => key.GetHashCode(); + protected override int GetValueHashCode(DynamicInvokeMethodThunk value) => value.TargetSignature.GetHashCode(); + protected override DynamicInvokeMethodThunk CreateValueFromKey(DynamicInvokeMethodSignature key) + { + return new DynamicInvokeMethodThunk(key.Context.GeneratedAssembly.GetGlobalModuleType(), key); + } + } + DynamicInvokeThunkHashtable _dynamicInvokeThunks = new DynamicInvokeThunkHashtable(); + + public MethodDesc GetDynamicInvokeThunk(DynamicInvokeMethodSignature signature) + { + return _dynamicInvokeThunks.GetOrCreateValue(signature); + } + } +} diff --git a/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.Sorting.cs b/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.Sorting.cs new file mode 100644 index 0000000000..5c3301262a --- /dev/null +++ b/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.Sorting.cs @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +namespace Internal.TypeSystem +{ + partial class TypeSystemContext + { + // Functionality related to determinstic ordering of types and members + partial class CompilerGeneratedType : MetadataType + { + protected internal override int ClassCode => -1036681447; + + protected internal override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) + { + // Should be a singleton + throw new NotSupportedException(); + } + } + } +} diff --git a/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.cs b/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.cs new file mode 100644 index 0000000000..5b3e596163 --- /dev/null +++ b/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.cs @@ -0,0 +1,252 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; + +using TypeHashingAlgorithms = Internal.NativeFormat.TypeHashingAlgorithms; +using Interlocked = System.Threading.Interlocked; +using AssemblyName = System.Reflection.AssemblyName; +using Debug = System.Diagnostics.Debug; + +namespace Internal.TypeSystem +{ + partial class TypeSystemContext + { + private ModuleDesc _generatedAssembly; + + public ModuleDesc GeneratedAssembly + { + get + { + if (_generatedAssembly == null) + { + Interlocked.CompareExchange(ref _generatedAssembly, new CompilerGeneratedAssembly(this), null); + } + + return _generatedAssembly; + } + } + + private class CompilerGeneratedAssembly : ModuleDesc, IAssemblyDesc + { + private MetadataType _globalModuleType; + + public CompilerGeneratedAssembly(TypeSystemContext context) + : base(context) + { + _globalModuleType = new CompilerGeneratedType(this, ""); + } + + public override IEnumerable GetAllTypes() + { + return Array.Empty(); + } + + public override MetadataType GetGlobalModuleType() + { + return _globalModuleType; + } + + public AssemblyName GetName() + { + return new AssemblyName("System.Private.CompilerGenerated"); + } + + public override MetadataType GetType(string nameSpace, string name, bool throwIfNotFound = true) + { + Debug.Fail("Resolving a TypeRef in the compiler generated assembly?"); + + if (throwIfNotFound) + ThrowHelper.ThrowTypeLoadException(nameSpace, name, this); + + return null; + } + } + + /// + /// A pseudo-type that owns helper methods generated by the compiler. + /// This type should never be allocated (we should never see an EEType for it). + /// + internal sealed partial class CompilerGeneratedType : MetadataType + { + private int _hashcode; + + public CompilerGeneratedType(ModuleDesc module, string name) + { + Module = module; + Name = name; + } + + public override TypeSystemContext Context + { + get + { + return Module.Context; + } + } + + public override string Name + { + get; + } + + public override string Namespace + { + get + { + return "Internal.CompilerGenerated"; + } + } + + public override int GetHashCode() + { + if (_hashcode != 0) + return _hashcode; + return InitializeHashCode(); + } + + private int InitializeHashCode() + { + string ns = Namespace; + var hashCodeBuilder = new TypeHashingAlgorithms.HashCodeBuilder(ns); + if (ns.Length > 0) + hashCodeBuilder.Append("."); + hashCodeBuilder.Append(Name); + _hashcode = hashCodeBuilder.ToHashCode(); + + return _hashcode; + } + + public override bool IsCanonicalSubtype(CanonicalFormKind policy) + { + Debug.Assert(!HasInstantiation, "Why is this generic?"); + return false; + } + + protected override TypeFlags ComputeTypeFlags(TypeFlags mask) + { + return TypeFlags.Class | + TypeFlags.HasGenericVarianceComputed | + TypeFlags.HasStaticConstructorComputed | + TypeFlags.HasFinalizerComputed | + TypeFlags.AttributeCacheComputed; + } + + public override ClassLayoutMetadata GetClassLayout() + { + return new ClassLayoutMetadata + { + Offsets = null, + PackingSize = 0, + Size = 0, + }; + } + + public override bool HasCustomAttribute(string attributeNamespace, string attributeName) + { + return false; + } + + public override IEnumerable GetNestedTypes() + { + return Array.Empty(); + } + + public override MetadataType GetNestedType(string name) + { + return null; + } + + protected override MethodImplRecord[] ComputeVirtualMethodImplsForType() + { + return Array.Empty(); + } + + public override MethodImplRecord[] FindMethodsImplWithMatchingDeclName(string name) + { + return Array.Empty(); + } + + public override ModuleDesc Module + { + get; + } + + public override PInvokeStringFormat PInvokeStringFormat + { + get + { + return PInvokeStringFormat.AutoClass; + } + } + + public override bool IsExplicitLayout + { + get + { + return false; + } + } + + public override bool IsSequentialLayout + { + get + { + return false; + } + } + + public override bool IsBeforeFieldInit + { + get + { + return false; + } + } + + public override MetadataType MetadataBaseType + { + get + { + // Since this type should never be allocated and only serves the purpose of grouping things, + // it can act like a type and have no base type. + return null; + } + } + + public override bool IsSealed + { + get + { + return true; + } + } + + public override bool IsAbstract + { + get + { + return false; + } + } + + public override DefType ContainingType + { + get + { + return null; + } + } + + public override DefType[] ExplicitlyImplementedInterfaces + { + get + { + return Array.Empty(); + } + } + } + } +} diff --git a/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.ValueTypeMethods.cs b/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.ValueTypeMethods.cs index a1487a5ac5..0b8b9cfde9 100644 --- a/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.ValueTypeMethods.cs +++ b/external/corert/src/Common/src/TypeSystem/IL/TypeSystemContext.ValueTypeMethods.cs @@ -37,9 +37,6 @@ namespace Internal.TypeSystem { MethodDesc getFieldHelperMethod = _valueTypeMethodHashtable.GetOrCreateValue((DefType)valueTypeDefinition); - // Check that System.ValueType has the method we're overriding. - Debug.Assert(valueTypeDefinition.BaseType.GetMethod(getFieldHelperMethod.Name, null) != null); - if (valueType != valueTypeDefinition) { yield return GetMethodForInstantiatedType(getFieldHelperMethod, (InstantiatedType)valueType); diff --git a/external/corert/src/Common/src/TypeSystem/Interop/IL/InlineArrayType.cs b/external/corert/src/Common/src/TypeSystem/Interop/IL/InlineArrayType.cs index d7412081f2..6f7c711b0c 100644 --- a/external/corert/src/Common/src/TypeSystem/Interop/IL/InlineArrayType.cs +++ b/external/corert/src/Common/src/TypeSystem/Interop/IL/InlineArrayType.cs @@ -219,7 +219,7 @@ namespace Internal.TypeSystem.Interop } flags |= TypeFlags.HasFinalizerComputed; - flags |= TypeFlags.IsByRefLikeComputed; + flags |= TypeFlags.AttributeCacheComputed; return flags; } diff --git a/external/corert/src/Common/src/TypeSystem/Interop/IL/MarshalHelpers.cs b/external/corert/src/Common/src/TypeSystem/Interop/IL/MarshalHelpers.cs index a65a6a3a6e..00ba8fda53 100644 --- a/external/corert/src/Common/src/TypeSystem/Interop/IL/MarshalHelpers.cs +++ b/external/corert/src/Common/src/TypeSystem/Interop/IL/MarshalHelpers.cs @@ -66,8 +66,13 @@ namespace Internal.TypeSystem.Interop typeDesc = typeDesc.GetParameterType(); } - if (typeDesc.Category != TypeFlags.ValueType) + typeDesc = typeDesc.UnderlyingType; + + // TODO: There are primitive types which require marshalling, such as bool, char. + if (typeDesc.IsPrimitive) + { return false; + } MetadataType type = typeDesc as MetadataType; if (type == null) diff --git a/external/corert/src/Common/src/TypeSystem/Interop/IL/Marshaller.cs b/external/corert/src/Common/src/TypeSystem/Interop/IL/Marshaller.cs index ef75539f16..d7e88915d1 100644 --- a/external/corert/src/Common/src/TypeSystem/Interop/IL/Marshaller.cs +++ b/external/corert/src/Common/src/TypeSystem/Interop/IL/Marshaller.cs @@ -718,6 +718,9 @@ namespace Internal.TypeSystem.Interop PropagateToByRefArg(_ilCodeStreams.UnmarshallingCodestream, _managedHome); } } + + // TODO This should be in finally block + // https://github.com/dotnet/corert/issues/6075 EmitCleanupManaged(_ilCodeStreams.UnmarshallingCodestream); } @@ -1634,9 +1637,9 @@ namespace Internal.TypeSystem.Interop } - class SafeHandleMarshaller : ReferenceMarshaller + class SafeHandleMarshaller : Marshaller { - protected override void AllocNativeToManaged(ILCodeStream codeStream) + private void AllocSafeHandle(ILCodeStream codeStream) { var ctor = ManagedType.GetParameterlessConstructor(); if (ctor == null) @@ -1651,11 +1654,29 @@ namespace Internal.TypeSystem.Interop codeStream.Emit(ILOpcode.ldstr, emitter.NewToken(String.Format("'{0}' does not have a default constructor. Subclasses of SafeHandle must have a default constructor to support marshaling a Windows HANDLE into managed code.", name))); codeStream.Emit(ILOpcode.newobj, emitter.NewToken(exceptionCtor)); codeStream.Emit(ILOpcode.throw_); + return; } - else - { - base.AllocNativeToManaged(codeStream); - } + + codeStream.Emit(ILOpcode.newobj, _ilCodeStreams.Emitter.NewToken(ctor)); + } + + protected override void EmitMarshalReturnValueManagedToNative() + { + ILEmitter emitter = _ilCodeStreams.Emitter; + ILCodeStream marshallingCodeStream = _ilCodeStreams.MarshallingCodeStream; + ILCodeStream returnValueMarshallingCodeStream = _ilCodeStreams.ReturnValueMarshallingCodeStream; + + SetupArgumentsForReturnValueMarshalling(); + + AllocSafeHandle(marshallingCodeStream); + StoreManagedValue(marshallingCodeStream); + + StoreNativeValue(returnValueMarshallingCodeStream); + + LoadManagedValue(returnValueMarshallingCodeStream); + LoadNativeValue(returnValueMarshallingCodeStream); + returnValueMarshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( + InteropTypes.GetSafeHandle(Context).GetKnownMethod("SetHandle", null))); } protected override void EmitMarshalArgumentManagedToNative() @@ -1672,42 +1693,13 @@ namespace Internal.TypeSystem.Interop PropagateFromByRefArg(marshallingCodeStream, _managedHome); } - // TODO: https://github.com/dotnet/corert/issues/3291 - // We don't support [IN,OUT] together yet, either IN or OUT. - if (Out && In) - { - throw new NotSupportedException("Marshalling an argument as both in and out not yet implemented"); - } - var safeHandleType = InteropTypes.GetSafeHandle(Context); - if (Out && IsManagedByRef) + if (In) { - // 1) If this is an output parameter we need to preallocate a SafeHandle to wrap the new native handle value. We - // must allocate this before the native call to avoid a failure point when we already have a native resource - // allocated. We must allocate a new SafeHandle even if we have one on input since both input and output native - // handles need to be tracked and released by a SafeHandle. - // 2) Initialize a local IntPtr that will be passed to the native call. - // 3) After the native call, the new handle value is written into the output SafeHandle and that SafeHandle - // is propagated back to the caller. - var vOutValue = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); - var vSafeHandle = emitter.NewLocal(ManagedType); - marshallingCodeStream.Emit(ILOpcode.newobj, emitter.NewToken(ManagedType.GetParameterlessConstructor())); - marshallingCodeStream.EmitStLoc(vSafeHandle); - _ilCodeStreams.CallsiteSetupCodeStream.EmitLdLoca(vOutValue); + if (IsManagedByRef) + PropagateFromByRefArg(marshallingCodeStream, _managedHome); - unmarshallingCodeStream.EmitLdLoc(vSafeHandle); - unmarshallingCodeStream.EmitLdLoc(vOutValue); - unmarshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( - safeHandleType.GetKnownMethod("SetHandle", null))); - - unmarshallingCodeStream.EmitLdLoc(vSafeHandle); - StoreManagedValue(unmarshallingCodeStream); - - PropagateToByRefArg(unmarshallingCodeStream, _managedHome); - } - else - { var vAddRefed = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Boolean)); LoadManagedValue(marshallingCodeStream); marshallingCodeStream.EmitLdLoca(vAddRefed); @@ -1719,44 +1711,56 @@ namespace Internal.TypeSystem.Interop safeHandleType.GetKnownMethod("DangerousGetHandle", null))); StoreNativeValue(marshallingCodeStream); - // TODO: This should be inside finally block and only executed it the handle was addrefed + // TODO: This should be inside finally block and only executed if the handle was addrefed + // https://github.com/dotnet/corert/issues/6075 LoadManagedValue(unmarshallingCodeStream); unmarshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( safeHandleType.GetKnownMethod("DangerousRelease", null))); - - LoadNativeArg(_ilCodeStreams.CallsiteSetupCodeStream); } - } + if (Out && IsManagedByRef) + { + // 1) If this is an output parameter we need to preallocate a SafeHandle to wrap the new native handle value. We + // must allocate this before the native call to avoid a failure point when we already have a native resource + // allocated. We must allocate a new SafeHandle even if we have one on input since both input and output native + // handles need to be tracked and released by a SafeHandle. + // 2) Initialize a local IntPtr that will be passed to the native call. + // 3) After the native call, the new handle value is written into the output SafeHandle and that SafeHandle + // is propagated back to the caller. + var vSafeHandle = emitter.NewLocal(ManagedType); + AllocSafeHandle(marshallingCodeStream); + marshallingCodeStream.EmitStLoc(vSafeHandle); - protected override void TransformNativeToManaged(ILCodeStream codeStream) - { - LoadManagedValue(codeStream); - LoadNativeValue(codeStream); - codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken( - InteropTypes.GetSafeHandle(Context).GetKnownMethod("SetHandle", null))); + var lSkipPropagation = emitter.NewCodeLabel(); + if (In) + { + // Propagate the value only if it has changed + ILLocalVariable vOriginalValue = emitter.NewLocal(NativeType); + LoadNativeValue(marshallingCodeStream); + marshallingCodeStream.EmitStLoc(vOriginalValue); + + unmarshallingCodeStream.EmitLdLoc(vOriginalValue); + LoadNativeValue(unmarshallingCodeStream); + unmarshallingCodeStream.Emit(ILOpcode.beq, lSkipPropagation); + } + + unmarshallingCodeStream.EmitLdLoc(vSafeHandle); + LoadNativeValue(unmarshallingCodeStream); + unmarshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( + safeHandleType.GetKnownMethod("SetHandle", null))); + + unmarshallingCodeStream.EmitLdArg(Index - 1); + unmarshallingCodeStream.EmitLdLoc(vSafeHandle); + unmarshallingCodeStream.EmitStInd(ManagedType); + + unmarshallingCodeStream.EmitLabel(lSkipPropagation); + } + + LoadNativeArg(callsiteCodeStream); } } - class ReferenceMarshaller : Marshaller - { - protected override void AllocNativeToManaged(ILCodeStream codeStream) - { - var emitter = _ilCodeStreams.Emitter; - var lNull = emitter.NewCodeLabel(); - - // Check for null - LoadNativeValue(codeStream); - codeStream.Emit(ILOpcode.brfalse, lNull); - - codeStream.Emit(ILOpcode.newobj, emitter.NewToken( - ManagedType.GetParameterlessConstructor())); - StoreManagedValue(codeStream); - codeStream.EmitLabel(lNull); - } - } - - class StringBuilderMarshaller : ReferenceMarshaller + class StringBuilderMarshaller : Marshaller { private bool _isAnsi; public StringBuilderMarshaller(bool isAnsi) @@ -1778,6 +1782,21 @@ namespace Internal.TypeSystem.Interop Context.GetHelperEntryPoint("InteropHelpers", "CoTaskMemFree"))); } + protected override void AllocNativeToManaged(ILCodeStream codeStream) + { + var emitter = _ilCodeStreams.Emitter; + var lNull = emitter.NewCodeLabel(); + + // Check for null + LoadNativeValue(codeStream); + codeStream.Emit(ILOpcode.brfalse, lNull); + + codeStream.Emit(ILOpcode.newobj, emitter.NewToken( + ManagedType.GetParameterlessConstructor())); + StoreManagedValue(codeStream); + codeStream.EmitLabel(lNull); + } + protected override void AllocManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; @@ -1877,8 +1896,8 @@ namespace Internal.TypeSystem.Interop protected override void TransformNativeToManaged(ILCodeStream codeStream) { - LoadManagedAddr(codeStream); LoadNativeAddr(codeStream); + LoadManagedAddr(codeStream); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken( InteropStateManager.GetStructMarshallingNativeToManagedThunk(ManagedType))); } @@ -2072,7 +2091,7 @@ namespace Internal.TypeSystem.Interop var managedElementType = ((ArrayType)ManagedType).ElementType; ILLocalVariable vLength = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); - codeStream.EmitLdArg(0); + codeStream.EmitLdArg(1); // load the length EmitElementCount(codeStream, MarshalDirection.Reverse); codeStream.EmitStLoc(vLength); @@ -2092,13 +2111,13 @@ namespace Internal.TypeSystem.Interop codeStream.EmitLabel(lLoopHeader); // load managed type - codeStream.EmitLdArg(0); + codeStream.EmitLdArg(1); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(_managedField)); codeStream.EmitLdLoc(vIndex); // load native type - codeStream.EmitLdArg(1); + codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldflda, emitter.NewToken(_nativeField)); codeStream.EmitLdLoc(vIndex); @@ -2172,9 +2191,9 @@ namespace Internal.TypeSystem.Interop ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream codeStream = _ilCodeStreams.UnmarshallingCodestream; - codeStream.EmitLdArg(0); - codeStream.EmitLdArg(1); + + codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldflda, emitter.NewToken(_nativeField)); codeStream.Emit(ILOpcode.conv_u); diff --git a/external/corert/src/Common/src/TypeSystem/Interop/IL/NativeStructType.cs b/external/corert/src/Common/src/TypeSystem/Interop/IL/NativeStructType.cs index 87fb167a68..41b80e1914 100644 --- a/external/corert/src/Common/src/TypeSystem/Interop/IL/NativeStructType.cs +++ b/external/corert/src/Common/src/TypeSystem/Interop/IL/NativeStructType.cs @@ -148,7 +148,6 @@ namespace Internal.TypeSystem.Interop public NativeStructType(ModuleDesc owningModule, MetadataType managedStructType, InteropStateManager interopStateManager) { Debug.Assert(managedStructType.IsTypeDefinition); - Debug.Assert(managedStructType.IsValueType); Debug.Assert(!managedStructType.IsGenericDefinition); Module = owningModule; @@ -301,7 +300,7 @@ namespace Internal.TypeSystem.Interop } flags |= TypeFlags.HasFinalizerComputed; - flags |= TypeFlags.IsByRefLikeComputed; + flags |= TypeFlags.AttributeCacheComputed; return flags; } diff --git a/external/corert/src/Common/src/TypeSystem/Interop/IL/PInvokeDelegateWrapper.cs b/external/corert/src/Common/src/TypeSystem/Interop/IL/PInvokeDelegateWrapper.cs index 3ff100bf47..5d95c84613 100644 --- a/external/corert/src/Common/src/TypeSystem/Interop/IL/PInvokeDelegateWrapper.cs +++ b/external/corert/src/Common/src/TypeSystem/Interop/IL/PInvokeDelegateWrapper.cs @@ -204,7 +204,7 @@ namespace Internal.TypeSystem.Interop } flags |= TypeFlags.HasFinalizerComputed; - flags |= TypeFlags.IsByRefLikeComputed; + flags |= TypeFlags.AttributeCacheComputed; return flags; } diff --git a/external/corert/src/Common/src/TypeSystem/Interop/InteropStateManager.cs b/external/corert/src/Common/src/TypeSystem/Interop/InteropStateManager.cs index aeed8f19a9..3e71c1382c 100644 --- a/external/corert/src/Common/src/TypeSystem/Interop/InteropStateManager.cs +++ b/external/corert/src/Common/src/TypeSystem/Interop/InteropStateManager.cs @@ -22,6 +22,7 @@ namespace Internal.TypeSystem private readonly PInvokeDelegateWrapperHashtable _pInvokeDelegateWrapperHashtable; private readonly InlineArrayHashTable _inlineArrayHashtable; private readonly PInvokeLazyFixupFieldHashtable _pInvokeLazyFixupFieldHashtable; + private readonly PInvokeCalliHashtable _pInvokeCalliHashtable; public InteropStateManager(ModuleDesc generatedAssembly) { @@ -33,6 +34,7 @@ namespace Internal.TypeSystem _pInvokeDelegateWrapperHashtable = new PInvokeDelegateWrapperHashtable(this, _generatedAssembly); _inlineArrayHashtable = new InlineArrayHashTable(this, _generatedAssembly); _pInvokeLazyFixupFieldHashtable = new PInvokeLazyFixupFieldHashtable(_generatedAssembly.GetGlobalModuleType()); + _pInvokeCalliHashtable = new PInvokeCalliHashtable(this, _generatedAssembly.GetGlobalModuleType()); } // // Delegate Marshalling Stubs @@ -155,8 +157,7 @@ namespace Internal.TypeSystem Debug.Assert(managedType is MetadataType); - - var methodKey = new StructMarshallingThunkKey((MetadataType)managedType, StructMarshallingThunkType.NativeToManage); + var methodKey = new StructMarshallingThunkKey((MetadataType)managedType, StructMarshallingThunkType.NativeToManaged); return _structMarshallingThunkHashtable.GetOrCreateValue(methodKey); } @@ -172,7 +173,6 @@ namespace Internal.TypeSystem Debug.Assert(managedType is MetadataType); - var methodKey = new StructMarshallingThunkKey((MetadataType)managedType, StructMarshallingThunkType.Cleanup); return _structMarshallingThunkHashtable.GetOrCreateValue(methodKey); } @@ -187,6 +187,11 @@ namespace Internal.TypeSystem return _pInvokeLazyFixupFieldHashtable.GetOrCreateValue(method); } + public MethodDesc GetPInvokeCalliStub(MethodSignature signature) + { + return _pInvokeCalliHashtable.GetOrCreateValue(signature); + } + private class NativeStructTypeHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(MetadataType key) @@ -473,5 +478,42 @@ namespace Internal.TypeSystem _owningType = owningType; } } + + private class PInvokeCalliHashtable : LockFreeReaderHashtable + { + private readonly InteropStateManager _interopStateManager; + private readonly TypeDesc _owningType; + + protected override int GetKeyHashCode(MethodSignature key) + { + return key.GetHashCode(); + } + + protected override int GetValueHashCode(CalliMarshallingMethodThunk value) + { + return value.TargetSignature.GetHashCode(); + } + + protected override bool CompareKeyToValue(MethodSignature key, CalliMarshallingMethodThunk value) + { + return key.Equals(value.TargetSignature); + } + + protected override bool CompareValueToValue(CalliMarshallingMethodThunk value1, CalliMarshallingMethodThunk value2) + { + return value1.TargetSignature.Equals(value2.TargetSignature); + } + + protected override CalliMarshallingMethodThunk CreateValueFromKey(MethodSignature key) + { + return new CalliMarshallingMethodThunk(key, _owningType, _interopStateManager); + } + + public PInvokeCalliHashtable(InteropStateManager interopStateManager, TypeDesc owningType) + { + _interopStateManager = interopStateManager; + _owningType = owningType; + } + } } } diff --git a/external/corert/src/Common/src/TypeSystem/Interop/MethodDesc.Interop.cs b/external/corert/src/Common/src/TypeSystem/Interop/MethodDesc.Interop.cs index 78e29e25e7..46f364cd9a 100644 --- a/external/corert/src/Common/src/TypeSystem/Interop/MethodDesc.Interop.cs +++ b/external/corert/src/Common/src/TypeSystem/Interop/MethodDesc.Interop.cs @@ -101,7 +101,7 @@ namespace Internal.TypeSystem ThrowOnUnmappableCharMask = 12288 } - public struct PInvokeFlags + public struct PInvokeFlags : IEquatable, IComparable { private PInvokeAttributes _attributes; public PInvokeAttributes Attributes @@ -279,7 +279,26 @@ namespace Internal.TypeSystem } } } - + + public int CompareTo(PInvokeFlags other) + { + return Attributes.CompareTo(other.Attributes); + } + + public bool Equals(PInvokeFlags other) + { + return Attributes == other.Attributes; + } + + public override bool Equals(object obj) + { + return obj is PInvokeFlags other && Equals(other); + } + + public override int GetHashCode() + { + return Attributes.GetHashCode(); + } } /// diff --git a/external/corert/src/Common/src/TypeSystem/Mangling/IPrefixMangledSignature.cs b/external/corert/src/Common/src/TypeSystem/Mangling/IPrefixMangledSignature.cs new file mode 100644 index 0000000000..3dabbc53a6 --- /dev/null +++ b/external/corert/src/Common/src/TypeSystem/Mangling/IPrefixMangledSignature.cs @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace Internal.TypeSystem +{ + /// + /// When implemented by a , instructs a name mangler to use the same mangled name + /// as another entity while prepending a specific prefix to that mangled name. + /// + public interface IPrefixMangledSignature + { + /// + /// Signature whose mangled name to use. + /// + MethodSignature BaseSignature { get; } + + /// + /// Prefix to apply when mangling. + /// + string Prefix { get; } + } +} diff --git a/external/corert/src/Common/src/TypeSystem/NativeFormat/NativeFormatMetadataUnit.cs b/external/corert/src/Common/src/TypeSystem/NativeFormat/NativeFormatMetadataUnit.cs index 298e8431e6..d4e9718eef 100644 --- a/external/corert/src/Common/src/TypeSystem/NativeFormat/NativeFormatMetadataUnit.cs +++ b/external/corert/src/Common/src/TypeSystem/NativeFormat/NativeFormatMetadataUnit.cs @@ -502,7 +502,7 @@ namespace Internal.TypeSystem.NativeFormat AssemblyBindResult bindResult; RuntimeAssemblyName assemblyName = AssemblyNameParser.Parse(assemblyNameString); Exception failureException; - if (!AssemblyBinderImplementation.Instance.Bind(assemblyName, out bindResult, out failureException)) + if (!AssemblyBinderImplementation.Instance.Bind(assemblyName, cacheMissedLookups: true, out bindResult, out failureException)) { throw failureException; } diff --git a/external/corert/src/Common/src/TypeSystem/NativeFormat/NativeFormatType.cs b/external/corert/src/Common/src/TypeSystem/NativeFormat/NativeFormatType.cs index 6b4cb59023..cde2d125ea 100644 --- a/external/corert/src/Common/src/TypeSystem/NativeFormat/NativeFormatType.cs +++ b/external/corert/src/Common/src/TypeSystem/NativeFormat/NativeFormatType.cs @@ -287,9 +287,9 @@ namespace Internal.TypeSystem.NativeFormat flags |= TypeFlags.HasFinalizer; } - if ((mask & TypeFlags.IsByRefLikeComputed) != 0) + if ((mask & TypeFlags.AttributeCacheComputed) != 0) { - flags |= TypeFlags.IsByRefLikeComputed; + flags |= TypeFlags.AttributeCacheComputed; if (IsValueType && HasCustomAttribute("System.Runtime.CompilerServices", "IsByRefLikeAttribute")) flags |= TypeFlags.IsByRefLike; diff --git a/external/corert/src/Common/src/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.cs b/external/corert/src/Common/src/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.cs index 096fb1c0b6..48abf82860 100644 --- a/external/corert/src/Common/src/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.cs +++ b/external/corert/src/Common/src/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.cs @@ -137,7 +137,7 @@ namespace Internal.TypeSystem flags |= _rawCanonType.GetTypeFlags(mask); } - if ((mask & TypeFlags.IsByRefLikeComputed) != 0) + if ((mask & TypeFlags.AttributeCacheComputed) != 0) { flags |= _rawCanonType.GetTypeFlags(mask); } diff --git a/external/corert/src/Common/src/TypeSystem/TypesDebugInfoWriter/DebugInfoWriter.cs b/external/corert/src/Common/src/TypeSystem/TypesDebugInfoWriter/DebugInfoWriter.cs index a2640d7572..2b6cef29fc 100644 --- a/external/corert/src/Common/src/TypeSystem/TypesDebugInfoWriter/DebugInfoWriter.cs +++ b/external/corert/src/Common/src/TypeSystem/TypesDebugInfoWriter/DebugInfoWriter.cs @@ -540,7 +540,8 @@ namespace Internal.TypeSystem.TypesDebugInfo return classTypeIndex; } - public uint GetCompleteClassTypeIndex(ClassTypeDescriptor classTypeDescriptor, ClassFieldsTypeDescriptor classFieldsTypeDescriptior, DataFieldDescriptor[] fields) + public uint GetCompleteClassTypeIndex(ClassTypeDescriptor classTypeDescriptor, ClassFieldsTypeDescriptor classFieldsTypeDescriptior, + DataFieldDescriptor[] fields, StaticDataFieldDescriptor[] statics) { FieldListInProgress fieldList = default(FieldListInProgress); if ((classTypeDescriptor.BaseClassId != 0) || (fields != null && fields.Length > 0) || (classTypeDescriptor.IsStruct == 0)) @@ -676,8 +677,8 @@ namespace Internal.TypeSystem.TypesDebugInfo uint recordSize = 12 + DebugInfoBlob.StringLengthEncoded(name); _blob.WriteWORD(checked((ushort)(_blob.DWORDAlignedSize(recordSize) - 2))); // don't include size of 'length' in 'length' _blob.WriteLeafKind(LeafKind.LF_MFUNC_ID); - _blob.WriteDWORD(memberIdDescriptor.MemberFunction); _blob.WriteDWORD(memberIdDescriptor.ParentClass); + _blob.WriteDWORD(memberIdDescriptor.MemberFunction); _blob.WriteString(name); _blob.AlignToDWORD(); VerifyBlobEligibleToBeBetweenRecords(); diff --git a/external/corert/src/Common/src/TypeSystem/TypesDebugInfoWriter/TypesDebugInfoWriter.cs b/external/corert/src/Common/src/TypeSystem/TypesDebugInfoWriter/TypesDebugInfoWriter.cs index dd57f19244..133a18d706 100644 --- a/external/corert/src/Common/src/TypeSystem/TypesDebugInfoWriter/TypesDebugInfoWriter.cs +++ b/external/corert/src/Common/src/TypeSystem/TypesDebugInfoWriter/TypesDebugInfoWriter.cs @@ -12,7 +12,8 @@ namespace Internal.TypeSystem.TypesDebugInfo uint GetClassTypeIndex(ClassTypeDescriptor classTypeDescriptor); - uint GetCompleteClassTypeIndex(ClassTypeDescriptor classTypeDescriptor, ClassFieldsTypeDescriptor classFieldsTypeDescriptor, DataFieldDescriptor[] fields); + uint GetCompleteClassTypeIndex(ClassTypeDescriptor classTypeDescriptor, ClassFieldsTypeDescriptor classFieldsTypeDescriptor, + DataFieldDescriptor[] fields, StaticDataFieldDescriptor[] statics); uint GetArrayTypeIndex(ClassTypeDescriptor classDescriptor, ArrayTypeDescriptor arrayTypeDescriprtor); @@ -22,6 +23,8 @@ namespace Internal.TypeSystem.TypesDebugInfo uint GetMemberFunctionId(MemberFunctionIdTypeDescriptor memberIdDescriptor); + uint GetPrimitiveTypeIndex(TypeDesc type); + string GetMangledName(TypeDesc type); } @@ -46,6 +49,7 @@ namespace Internal.TypeSystem.TypesDebugInfo public int IsStruct; public string Name; public uint BaseClassId; + public ulong InstanceSize; } [StructLayout(LayoutKind.Sequential)] @@ -56,6 +60,14 @@ namespace Internal.TypeSystem.TypesDebugInfo public string Name; } + [StructLayout(LayoutKind.Sequential)] + public struct StaticDataFieldDescriptor + { + public string StaticDataName; + public ulong StaticOffset; + public int IsStaticDataInObject; + } + [StructLayout(LayoutKind.Sequential)] public struct ClassFieldsTypeDescriptor { diff --git a/external/corert/src/Common/test-runtime/XUnit.Runtime.depproj b/external/corert/src/Common/test-runtime/XUnit.Runtime.depproj index 5f1674de36..0d3b67d6e9 100644 --- a/external/corert/src/Common/test-runtime/XUnit.Runtime.depproj +++ b/external/corert/src/Common/test-runtime/XUnit.Runtime.depproj @@ -5,32 +5,93 @@ This RID value doesn't really matter, since the assets we are copying are not RID specific, so defaulting to Windows here --> win-x64 - netcoreapp2.0 + netcoreapp2.1 true $(RuntimePath) + xunit.runner.console + xunit.console + xunit.runner.visualstudio + xunit.runner.visualstudio.dotnetcore.testadapter + microsoft.testplatform.testhost + testhost + + unknown $(NoWarn);NU1603 - - 1.0.3-prerelease-00921-01 + + $(XUnitPackageVersion) - - $(XunitNetcoreExtensionsVersion) + + $(XUnitPackageVersion) - - $(XunitNetcoreExtensionsVersion) + + $(MicrosoftDotNetXUnitExtensionsVersion) + + + $(XUnitPackageVersion) + + + $(MicrosoftDotNetTestSdkVersion) + + + $(MicrosoftDotNetTestSdkVersion) + + + $(MicrosoftDotNetTestSdkVersion) + + + 2.0.4 + + + 9.0.1 + + + + + + + false + $(XUnitRunnerPackageId) + $(XUnitPackageVersion) + + + false + $(XUnitTestAdapterPackageId) + $(XUnitPackageVersion) + + + false + $(TestPlatformHostPackageId) + $(MicrosoftDotNetTestSdkVersion) + + + - - - - - - - - + + + + + + + + + + + + + + + diff --git a/external/corert/src/Framework/Framework-native.depproj b/external/corert/src/Framework/Framework-native.depproj index cc3093531c..a83f57d931 100644 --- a/external/corert/src/Framework/Framework-native.depproj +++ b/external/corert/src/Framework/Framework-native.depproj @@ -6,8 +6,8 @@ - .NETCoreApp,Version=v2.0 - netcoreapp2.0 + .NETCoreApp,Version=v2.1 + netcoreapp2.1 $(NuPkgRid) true diff --git a/external/corert/src/Framework/Framework-uapaot.depproj b/external/corert/src/Framework/Framework-uapaot.depproj index ab8e28d15e..47fc83e40f 100644 --- a/external/corert/src/Framework/Framework-uapaot.depproj +++ b/external/corert/src/Framework/Framework-uapaot.depproj @@ -19,10 +19,13 @@ + + + + + - - diff --git a/external/corert/src/Framework/Framework.depproj b/external/corert/src/Framework/Framework.depproj index e994ff4256..d72b2e1a0b 100644 --- a/external/corert/src/Framework/Framework.depproj +++ b/external/corert/src/Framework/Framework.depproj @@ -5,8 +5,8 @@ - .NETCoreApp,Version=v2.1 - netcoreapp2.1 + .NETCoreApp,Version=v3.0 + netcoreapp3.0 $(NuPkgRid) true @@ -29,22 +29,30 @@ + + + + + - - + + - - - - + + + + + + + diff --git a/external/corert/src/ILCompiler.Build.Tasks/src/ComputeManagedAssemblies.cs b/external/corert/src/ILCompiler.Build.Tasks/src/ComputeManagedAssemblies.cs index 0e4998ecee..e1435b0c6a 100644 --- a/external/corert/src/ILCompiler.Build.Tasks/src/ComputeManagedAssemblies.cs +++ b/external/corert/src/ILCompiler.Build.Tasks/src/ComputeManagedAssemblies.cs @@ -24,7 +24,7 @@ namespace Build.Tasks } /// - /// The CoreRT-specific System.Private.* assemblies that must be used instead of the netcoreapp2.0 versions. + /// The CoreRT-specific System.Private.* assemblies that must be used instead of the netcoreapp2.1 versions. /// [Required] public ITaskItem[] SdkAssemblies diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/AnalysisBasedMetadataManager.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/AnalysisBasedMetadataManager.cs index 3a51c070d6..1f2224d5d8 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/AnalysisBasedMetadataManager.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/AnalysisBasedMetadataManager.cs @@ -25,16 +25,17 @@ namespace ILCompiler private readonly Dictionary _reflectableFields = new Dictionary(); public AnalysisBasedMetadataManager( - ModuleDesc generatedAssembly, CompilerTypeSystemContext typeSystemContext, MetadataBlockingPolicy blockingPolicy, + ManifestResourceBlockingPolicy resourceBlockingPolicy, string logFile, StackTraceEmissionPolicy stackTracePolicy, + DynamicInvokeThunkGenerationPolicy invokeThunkGenerationPolicy, IEnumerable modulesWithMetadata, IEnumerable> reflectableTypes, IEnumerable> reflectableMethods, IEnumerable> reflectableFields) - : base(generatedAssembly, typeSystemContext, blockingPolicy, logFile, stackTracePolicy) + : base(typeSystemContext, blockingPolicy, resourceBlockingPolicy, logFile, stackTracePolicy, invokeThunkGenerationPolicy) { _modulesWithMetadata = new List(modulesWithMetadata); diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/Compilation.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/Compilation.cs index d686a0d7b4..b697d30208 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/Compilation.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/Compilation.cs @@ -58,7 +58,7 @@ namespace ILCompiler foreach (var rootProvider in compilationRoots) rootProvider.AddCompilationRoots(rootingService); - MetadataType globalModuleGeneratedType = nodeFactory.CompilationModuleGroup.GeneratedAssembly.GetGlobalModuleType(); + MetadataType globalModuleGeneratedType = nodeFactory.TypeSystemContext.GeneratedAssembly.GetGlobalModuleType(); _typeGetTypeMethodThunks = new TypeGetTypeMethodThunkCache(globalModuleGeneratedType); _assemblyGetExecutingAssemblyMethodThunks = new AssemblyGetExecutingAssemblyMethodThunkCache(globalModuleGeneratedType); _methodBaseGetCurrentMethodThunks = new MethodBaseGetCurrentMethodThunkCache(); @@ -90,6 +90,12 @@ namespace ILCompiler public DelegateCreationInfo GetDelegateCtor(TypeDesc delegateType, MethodDesc target, bool followVirtualDispatch) { + // If we're creating a delegate to a virtual method that cannot be overriden, devirtualize. + // This is not just an optimization - it's required for correctness in the presence of sealed + // vtable slots. + if (followVirtualDispatch && (target.IsFinal || target.OwningType.IsSealed())) + followVirtualDispatch = false; + return DelegateCreationInfo.Create(delegateType, target, NodeFactory, followVirtualDispatch); } @@ -102,7 +108,7 @@ namespace ILCompiler { var pInvokeFixup = (PInvokeLazyFixupField)field; PInvokeMetadata metadata = pInvokeFixup.PInvokeMetadata; - return NodeFactory.PInvokeMethodFixup(metadata.Module, metadata.Name); + return NodeFactory.PInvokeMethodFixup(metadata.Module, metadata.Name, metadata.Flags); } else { @@ -360,7 +366,7 @@ namespace ILCompiler Debug.Assert(!type.IsGenericDefinition); MetadataType metadataType = type as MetadataType; - if (metadataType != null && metadataType.ThreadStaticFieldSize.AsInt > 0) + if (metadataType != null && metadataType.ThreadGcStaticFieldSize.AsInt > 0) { _graph.AddRoot(_factory.TypeThreadStaticIndex(metadataType), reason); @@ -413,7 +419,16 @@ namespace ILCompiler public void RootModuleMetadata(ModuleDesc module, string reason) { - _graph.AddRoot(_factory.ModuleMetadata(module), reason); + // RootModuleMetadata is kind of a hack - this is pretty much only used to force include + // type forwarders from assemblies metadata generator would normally not look at. + // This will go away when the temporary RD.XML parser goes away. + if (_factory.MetadataManager is UsageBasedMetadataManager) + _graph.AddRoot(_factory.ModuleMetadata(module), reason); + } + + public void RootReadOnlyDataBlob(byte[] data, int alignment, string reason, string exportName) + { + _graph.AddRoot(_factory.ReadOnlyDataBlob(exportName, data, alignment), reason); } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilationModuleGroup.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilationModuleGroup.cs index 8fa73ff20b..edc9b076a0 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilationModuleGroup.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilationModuleGroup.cs @@ -21,17 +21,6 @@ namespace ILCompiler public abstract class CompilationModuleGroup { - /// - /// Gets the synthetic assembly that holds types generated by the compiler as part of the compilation process. - /// Types and members that declare this module as their owning module are always generated. - /// - public ModuleDesc GeneratedAssembly { get; } - - public CompilationModuleGroup(TypeSystemContext context) - { - GeneratedAssembly = new CompilerGeneratedAssembly(context); - } - /// /// If true, "type" is in the set of input assemblies being compiled /// @@ -49,6 +38,10 @@ namespace ILCompiler /// public abstract bool ContainsMethodDictionary(MethodDesc method); /// + /// If true, "method" is imported from the set of reference assemblies + /// + public abstract bool ImportsMethod(MethodDesc method, bool unboxingStub); + /// /// If true, "type" is exported by the set of input assemblies being compiled /// public abstract ExportForm GetExportTypeForm(TypeDesc type); @@ -94,41 +87,5 @@ namespace ILCompiler /// accessed through the target platform's import mechanism (ie, Import Address Table on Windows) /// public abstract bool CanHaveReferenceThroughImportTable { get; } - - private class CompilerGeneratedAssembly : ModuleDesc, IAssemblyDesc - { - private MetadataType _globalModuleType; - - public CompilerGeneratedAssembly(TypeSystemContext context) - : base(context) - { - _globalModuleType = new CompilerGeneratedType(this, ""); - } - - public override IEnumerable GetAllTypes() - { - return Array.Empty(); - } - - public override MetadataType GetGlobalModuleType() - { - return _globalModuleType; - } - - public AssemblyName GetName() - { - return new AssemblyName("System.Private.CompilerGenerated"); - } - - public override MetadataType GetType(string nameSpace, string name, bool throwIfNotFound = true) - { - Debug.Fail("Resolving a TypeRef in the compiler generated assembly?"); - - if (throwIfNotFound) - ThrowHelper.ThrowTypeLoadException(nameSpace, name, this); - - return null; - } - } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerGeneratedType.Sorting.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerGeneratedType.Sorting.cs deleted file mode 100644 index 99457b98f3..0000000000 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerGeneratedType.Sorting.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; - -using Internal.TypeSystem; - -namespace ILCompiler -{ - // Functionality related to determinstic ordering of types and members - internal sealed partial class CompilerGeneratedType : MetadataType - { - protected override int ClassCode => -1036681447; - - protected override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) - { - // Should be a singleton - throw new NotSupportedException(); - } - } -} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerGeneratedType.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerGeneratedType.cs deleted file mode 100644 index 7bbd0aa454..0000000000 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerGeneratedType.cs +++ /dev/null @@ -1,198 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; - -using Internal.TypeSystem; - -using Debug = System.Diagnostics.Debug; -using TypeHashingAlgorithms = Internal.NativeFormat.TypeHashingAlgorithms; - -namespace ILCompiler -{ - /// - /// A pseudo-type that owns helper methods generated by the compiler. - /// This type should never be allocated (we should never see an EEType for it). - /// - internal sealed partial class CompilerGeneratedType : MetadataType - { - private int _hashcode; - - public CompilerGeneratedType(ModuleDesc module, string name) - { - Module = module; - Name = name; - } - - public override TypeSystemContext Context - { - get - { - return Module.Context; - } - } - - public override string Name - { - get; - } - - public override string Namespace - { - get - { - return "Internal.CompilerGenerated"; - } - } - - public override int GetHashCode() - { - if (_hashcode != 0) - return _hashcode; - return InitializeHashCode(); - } - - private int InitializeHashCode() - { - string ns = Namespace; - var hashCodeBuilder = new TypeHashingAlgorithms.HashCodeBuilder(ns); - if (ns.Length > 0) - hashCodeBuilder.Append("."); - hashCodeBuilder.Append(Name); - _hashcode = hashCodeBuilder.ToHashCode(); - - return _hashcode; - } - - public override bool IsCanonicalSubtype(CanonicalFormKind policy) - { - Debug.Assert(!HasInstantiation, "Why is this generic?"); - return false; - } - - protected override TypeFlags ComputeTypeFlags(TypeFlags mask) - { - return TypeFlags.Class | - TypeFlags.HasGenericVarianceComputed | - TypeFlags.HasStaticConstructorComputed | - TypeFlags.HasFinalizerComputed | - TypeFlags.IsByRefLikeComputed; - } - - public override ClassLayoutMetadata GetClassLayout() - { - return new ClassLayoutMetadata - { - Offsets = null, - PackingSize = 0, - Size = 0, - }; - } - - public override bool HasCustomAttribute(string attributeNamespace, string attributeName) - { - return false; - } - - public override IEnumerable GetNestedTypes() - { - return Array.Empty(); - } - - public override MetadataType GetNestedType(string name) - { - return null; - } - - protected override MethodImplRecord[] ComputeVirtualMethodImplsForType() - { - return Array.Empty(); - } - - public override MethodImplRecord[] FindMethodsImplWithMatchingDeclName(string name) - { - return Array.Empty(); - } - - public override ModuleDesc Module - { - get; - } - - public override PInvokeStringFormat PInvokeStringFormat - { - get - { - return PInvokeStringFormat.AutoClass; - } - } - - public override bool IsExplicitLayout - { - get - { - return false; - } - } - - public override bool IsSequentialLayout - { - get - { - return false; - } - } - - public override bool IsBeforeFieldInit - { - get - { - return false; - } - } - - public override MetadataType MetadataBaseType - { - get - { - // Since this type should never be allocated and only serves the purpose of grouping things, - // it can act like a type and have no base type. - return null; - } - } - - public override bool IsSealed - { - get - { - return true; - } - } - - public override bool IsAbstract - { - get - { - return false; - } - } - - public override DefType ContainingType - { - get - { - return null; - } - } - - public override DefType[] ExplicitlyImplementedInterfaces - { - get - { - return Array.Empty(); - } - } - } -} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerMetadataFieldLayoutAlgorithm.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerMetadataFieldLayoutAlgorithm.cs index 1d6d2c8708..48daeab708 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerMetadataFieldLayoutAlgorithm.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerMetadataFieldLayoutAlgorithm.cs @@ -7,6 +7,8 @@ using System.Collections.Generic; using Internal.TypeSystem; +using Debug = System.Diagnostics.Debug; + namespace ILCompiler { internal class CompilerMetadataFieldLayoutAlgorithm : MetadataFieldLayoutAlgorithm @@ -15,7 +17,7 @@ namespace ILCompiler { // GC statics start with a pointer to the "EEType" that signals the size and GCDesc to the GC layout.GcStatics.Size = context.Target.LayoutPointerSize; - layout.ThreadStatics.Size = context.Target.LayoutPointerSize; + layout.ThreadGcStatics.Size = context.Target.LayoutPointerSize; } protected override void FinalizeRuntimeSpecificStaticFieldLayout(TypeSystemContext context, ref ComputedStaticFieldLayout layout) @@ -26,10 +28,14 @@ namespace ILCompiler { layout.GcStatics.Size = LayoutInt.Zero; } - if (layout.ThreadStatics.Size == context.Target.LayoutPointerSize) + if (layout.ThreadGcStatics.Size == context.Target.LayoutPointerSize) { - layout.ThreadStatics.Size = LayoutInt.Zero; + layout.ThreadGcStatics.Size = LayoutInt.Zero; } + + // CoreRT makes no distinction between Gc / non-Gc thread statics. All are placed into ThreadGcStatics since thread statics + // are typically rare. + Debug.Assert(layout.ThreadNonGcStatics.Size == LayoutInt.Zero); } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.BoxedTypes.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.BoxedTypes.cs index 9b8bd363c8..71b9720fc1 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.BoxedTypes.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.BoxedTypes.cs @@ -290,7 +290,17 @@ namespace ILCompiler Module = owningModule; ValueTypeRepresented = valuetype; - BoxedValue = new BoxedValueField(this); + + // Unboxing thunks for byref-like types don't make sense. Byref-like types cannot be boxed. + // We still allow these to exist in the system, because it's easier than trying to prevent + // their creation. We create them as if they existed (in lieu of e.g. pointing all of them + // to the same __unreachable method body) so that the various places that store pointers to + // them because they want to be able to extract the target instance method can use the same + // mechanism they use for everything else at runtime. + // The main difference is that the "Boxed_ValueType" version has no fields. Reference types + // cannot have byref-like fields. + if (!valuetype.IsByRefLike) + BoxedValue = new BoxedValueField(this); } public override ClassLayoutMetadata GetClassLayout() => default(ClassLayoutMetadata); @@ -325,14 +335,14 @@ namespace ILCompiler } flags |= TypeFlags.HasFinalizerComputed; - flags |= TypeFlags.IsByRefLikeComputed; + flags |= TypeFlags.AttributeCacheComputed; return flags; } public override FieldDesc GetField(string name) { - if (name == BoxedValueFieldName) + if (name == BoxedValueFieldName && BoxedValue != null) return BoxedValue; return null; @@ -340,7 +350,10 @@ namespace ILCompiler public override IEnumerable GetFields() { - yield return BoxedValue; + if (BoxedValue != null) + return new FieldDesc[] { BoxedValue }; + + return Array.Empty(); } /// @@ -439,6 +452,15 @@ namespace ILCompiler public override MethodIL EmitIL() { + if (_owningType.BoxedValue == null) + { + // If this is the fake unboxing thunk for ByRef-like types, just make a method that throws. + return new ILStubMethodIL(this, + new byte[] { (byte)ILOpcode.ldnull, (byte)ILOpcode.throw_ }, + Array.Empty(), + Array.Empty()); + } + // Generate the unboxing stub. This loosely corresponds to following C#: // return BoxedValue.InstanceMethod(this.m_pEEType, [rest of parameters]) @@ -507,6 +529,15 @@ namespace ILCompiler public override MethodIL EmitIL() { + if (_owningType.BoxedValue == null) + { + // If this is the fake unboxing thunk for ByRef-like types, just make a method that throws. + return new ILStubMethodIL(this, + new byte[] { (byte)ILOpcode.ldnull, (byte)ILOpcode.throw_ }, + Array.Empty(), + Array.Empty()); + } + // Generate the unboxing stub. This loosely corresponds to following C#: // return BoxedValue.InstanceMethod([rest of parameters]) diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.Mangling.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.Mangling.cs index 720f061148..ace374f044 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.Mangling.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.Mangling.cs @@ -47,5 +47,24 @@ namespace ILCompiler } } } + + partial class UnboxingThunk : IPrefixMangledMethod + { + MethodDesc IPrefixMangledMethod.BaseMethod + { + get + { + return _targetMethod; + } + } + + string IPrefixMangledMethod.Prefix + { + get + { + return "unbox"; + } + } + } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.cs index 4feb7a5824..6f47105614 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.cs @@ -424,6 +424,9 @@ namespace ILCompiler { Debug.Assert(field.IsStatic); + if (field.IsThreadStatic) + return true; + TypeDesc fieldType = field.FieldType; if (fieldType.IsValueType) return ((DefType)fieldType).ContainsGCPointers; @@ -499,17 +502,23 @@ namespace ILCompiler // method table. public long UniversalCanonReflectionMethodRootHeuristic_InstantiationCount { get; } + // To avoid infinite generic recursion issues during debug type record generation, attempt to + // use canonical form for types with high generic complexity. + public long MaxGenericDepthOfDebugRecord { get; } + public SharedGenericsConfiguration() { UniversalCanonGVMReflectionRootHeuristic_InstantiationCount = 4; UniversalCanonGVMDepthHeuristic_NonCanonDepth = 2; UniversalCanonGVMDepthHeuristic_CanonDepth = 1; - // Unlike the GVM heuristics which are intended to kick in aggresively + // Unlike the GVM heuristics which are intended to kick in aggressively // this heuristic exists to make it so that a fair amount of generic // expansion is allowed. Numbers are chosen to allow a fairly large // amount of generic expansion before trimming. UniversalCanonReflectionMethodRootHeuristic_InstantiationCount = 1024; + + MaxGenericDepthOfDebugRecord = 15; } }; } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/CoreRTNameMangler.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/CoreRTNameMangler.cs index 86cac8dc03..8c5636c21a 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/CoreRTNameMangler.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/CoreRTNameMangler.cs @@ -331,7 +331,13 @@ namespace ILCompiler } else { + // This is a type definition. Since we didn't fall in the `is EcmaType` case above, + // it's likely a compiler-generated type. mangledName = SanitizeName(((DefType)type).GetFullName(), true); + + // Always generate a fully qualified name + if (_mangleForCplusPlus) + mangledName = "::" + mangledName; } break; } @@ -404,6 +410,35 @@ namespace ILCompiler return sb.ToUtf8String(); } + private Utf8String GetPrefixMangledSignatureName(IPrefixMangledSignature prefixMangledSignature) + { + Utf8StringBuilder sb = new Utf8StringBuilder(); + sb.Append(EnterNameScopeSequence).Append(prefixMangledSignature.Prefix).Append(ExitNameScopeSequence); + + var signature = prefixMangledSignature.BaseSignature; + sb.Append(signature.Flags.ToStringInvariant()); + + sb.Append(EnterNameScopeSequence); + + string sigRetTypeName = GetMangledTypeName(signature.ReturnType); + if (_mangleForCplusPlus) + sigRetTypeName = sigRetTypeName.Replace("::", "_"); + sb.Append(sigRetTypeName); + + for (int i = 0; i < signature.Length; i++) + { + sb.Append("__"); + string sigArgName = GetMangledTypeName(signature[i]); + if (_mangleForCplusPlus) + sigArgName = sigArgName.Replace("::", "_"); + sb.Append(sigArgName); + } + + sb.Append(ExitNameScopeSequence); + + return sb.ToUtf8String(); + } + private Utf8String GetPrefixMangledMethodName(IPrefixMangledMethod prefixMangledMetod) { Utf8StringBuilder sb = new Utf8StringBuilder(); @@ -491,6 +526,10 @@ namespace ILCompiler { utf8MangledName = GetPrefixMangledTypeName((IPrefixMangledType)method); } + else if (method is IPrefixMangledSignature) + { + utf8MangledName = GetPrefixMangledSignatureName((IPrefixMangledSignature)method); + } else { // Assume that Name is unique for all other methods diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayMapNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayMapNode.cs index 4f8c8ba46a..bd42d69ad9 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayMapNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayMapNode.cs @@ -78,6 +78,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.ArrayMapNode; + public override int ClassCode => (int)ObjectNodeOrder.ArrayMapNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayOfEmbeddedDataNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayOfEmbeddedDataNode.cs index 927710fad0..131ae249f7 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayOfEmbeddedDataNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayOfEmbeddedDataNode.cs @@ -108,6 +108,6 @@ namespace ILCompiler.DependencyAnalysis protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.ArrayOfEmbeddedDataNode; + public override int ClassCode => (int)ObjectNodeOrder.ArrayOfEmbeddedDataNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayOfEmbeddedPointersNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayOfEmbeddedPointersNode.cs index 45271af23b..3082f9ffcb 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayOfEmbeddedPointersNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayOfEmbeddedPointersNode.cs @@ -51,7 +51,7 @@ namespace ILCompiler.DependencyAnalysis protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.ArrayOfEmbeddedPointersNode; + public override int ClassCode => (int)ObjectNodeOrder.ArrayOfEmbeddedPointersNode; private class PointerIndirectionNodeComparer : IComparer> { @@ -96,7 +96,7 @@ namespace ILCompiler.DependencyAnalysis }; } - protected internal override int ClassCode => -66002498; + public override int ClassCode => -66002498; } private class EmbeddedPointerIndirectionWithSymbolNode : SimpleEmbeddedPointerIndirectionNode, ISymbolDefinitionNode diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayOfFrozenObjectsNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayOfFrozenObjectsNode.cs index 70349bdbf5..847eb27be6 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayOfFrozenObjectsNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ArrayOfFrozenObjectsNode.cs @@ -42,6 +42,6 @@ namespace ILCompiler.DependencyAnalysis builder.EmitZeroPointer(); } - protected internal override int ClassCode => -1771336339; + public override int ClassCode => -1771336339; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/AssemblyStubNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/AssemblyStubNode.cs index db568a3e8c..0bc9db8c6c 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/AssemblyStubNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/AssemblyStubNode.cs @@ -16,6 +16,12 @@ namespace ILCompiler.DependencyAnalysis { } + /// + /// Gets a value indicating whether the stub's address is visible from managed code + /// and could be a target of a managed calli. + /// + protected virtual bool IsVisibleFromManagedCode => true; + public override ObjectNodeSection Section => ObjectNodeSection.TextSection; public override bool StaticDependenciesAreComputed => true; @@ -26,19 +32,26 @@ namespace ILCompiler.DependencyAnalysis public override ObjectData GetData(NodeFactory factory, bool relocsOnly) { + // If the address is expected to be visible from managed code, we need to align + // at the managed code boundaries to prevent the stub from being confused with + // a fat fuction pointer. Otherwise we can align tighter. + int alignment = IsVisibleFromManagedCode ? + factory.Target.MinimumFunctionAlignment : + factory.Target.MinimumCodeAlignment; + switch (factory.Target.Architecture) { case TargetArchitecture.X64: X64.X64Emitter x64Emitter = new X64.X64Emitter(factory, relocsOnly); EmitCode(factory, ref x64Emitter, relocsOnly); - x64Emitter.Builder.RequireInitialAlignment(factory.Target.MinimumFunctionAlignment); + x64Emitter.Builder.RequireInitialAlignment(alignment); x64Emitter.Builder.AddSymbol(this); return x64Emitter.Builder.ToObjectData(); case TargetArchitecture.X86: X86.X86Emitter x86Emitter = new X86.X86Emitter(factory, relocsOnly); EmitCode(factory, ref x86Emitter, relocsOnly); - x86Emitter.Builder.RequireInitialAlignment(factory.Target.MinimumFunctionAlignment); + x86Emitter.Builder.RequireInitialAlignment(alignment); x86Emitter.Builder.AddSymbol(this); return x86Emitter.Builder.ToObjectData(); @@ -46,14 +59,14 @@ namespace ILCompiler.DependencyAnalysis case TargetArchitecture.ARMEL: ARM.ARMEmitter armEmitter = new ARM.ARMEmitter(factory, relocsOnly); EmitCode(factory, ref armEmitter, relocsOnly); - armEmitter.Builder.RequireInitialAlignment(factory.Target.MinimumFunctionAlignment); + armEmitter.Builder.RequireInitialAlignment(alignment); armEmitter.Builder.AddSymbol(this); return armEmitter.Builder.ToObjectData(); case TargetArchitecture.ARM64: ARM64.ARM64Emitter arm64Emitter = new ARM64.ARM64Emitter(factory, relocsOnly); EmitCode(factory, ref arm64Emitter, relocsOnly); - arm64Emitter.Builder.RequireInitialAlignment(factory.Target.MinimumFunctionAlignment); + arm64Emitter.Builder.RequireInitialAlignment(alignment); arm64Emitter.Builder.AddSymbol(this); return arm64Emitter.Builder.ToObjectData(); diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/BlobNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/BlobNode.cs index 5f2b27f5c4..083de9bded 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/BlobNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/BlobNode.cs @@ -42,9 +42,9 @@ namespace ILCompiler.DependencyAnalysis protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); #if !SUPPORT_JIT - protected internal override int ClassCode => -470351029; + public override int ClassCode => -470351029; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return _name.CompareTo(((BlobNode)other)._name); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/BlockReflectionTypeMapNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/BlockReflectionTypeMapNode.cs index 95fa4b07ea..b9ccd7b07b 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/BlockReflectionTypeMapNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/BlockReflectionTypeMapNode.cs @@ -83,6 +83,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.BlockReflectionTypeMapNode; + public override int ClassCode => (int)ObjectNodeOrder.BlockReflectionTypeMapNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CanonicalDefinitionEETypeNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CanonicalDefinitionEETypeNode.cs index 520781f538..d1538a4a9d 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CanonicalDefinitionEETypeNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CanonicalDefinitionEETypeNode.cs @@ -43,6 +43,6 @@ namespace ILCompiler.DependencyAnalysis // Canonical definition types will have their base size set to the minimum protected override int BaseSize => MinimumObjectSize; - protected internal override int ClassCode => -1851030036; + public override int ClassCode => -1851030036; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CanonicalEETypeNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CanonicalEETypeNode.cs index 2383df2315..945e49c39c 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CanonicalEETypeNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CanonicalEETypeNode.cs @@ -27,7 +27,6 @@ namespace ILCompiler.DependencyAnalysis Debug.Assert(type.IsCanonicalSubtype(CanonicalFormKind.Any)); Debug.Assert(type == type.ConvertToCanonForm(CanonicalFormKind.Specific)); Debug.Assert(!type.IsMdArray); - Debug.Assert(!type.IsByRefLike); } public override bool StaticDependenciesAreComputed => true; @@ -46,7 +45,7 @@ namespace ILCompiler.DependencyAnalysis DefType closestDefType = _type.GetClosestDefType(); - if (_type.RuntimeInterfaces.Length > 0) + if (InterfaceDispatchMapNode.MightHaveInterfaceDispatchMap(_type, factory)) dependencyList.Add(factory.InterfaceDispatchMap(_type), "Canonical interface dispatch map"); dependencyList.Add(factory.VTable(closestDefType), "VTable"); @@ -62,6 +61,15 @@ namespace ILCompiler.DependencyAnalysis AddDependenciesForUniversalGVMSupport(factory, _type, ref dependencyList); } + // Keep track of the default constructor map dependency for this type if it has a default constructor + MethodDesc defaultCtor = closestDefType.GetDefaultConstructor(); + if (defaultCtor != null) + { + dependencyList.Add(new DependencyListEntry( + factory.MethodEntrypoint(defaultCtor, closestDefType.IsValueType), + "DefaultConstructorNode")); + } + return dependencyList; } @@ -136,6 +144,6 @@ namespace ILCompiler.DependencyAnalysis base.ComputeValueTypeFieldPadding(); } - protected internal override int ClassCode => -1798018602; + public override int ClassCode => -1798018602; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ClassConstructorContextMap.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ClassConstructorContextMap.cs index 0624ee1c6f..1a62667dbf 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ClassConstructorContextMap.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ClassConstructorContextMap.cs @@ -81,6 +81,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.ClassConstructorContextMap; + public override int ClassCode => (int)ObjectNodeOrder.ClassConstructorContextMap; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ClonedConstructedEETypeNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ClonedConstructedEETypeNode.cs index d64319e907..7b7642938b 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ClonedConstructedEETypeNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ClonedConstructedEETypeNode.cs @@ -15,7 +15,7 @@ namespace ILCompiler.DependencyAnalysis protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler) + " cloned"; - public override ObjectNode NodeForLinkage(NodeFactory factory) => this; + public override ISymbolNode NodeForLinkage(NodeFactory factory) => this; // // A cloned type must be named differently than the type it is a clone of so the linker @@ -35,6 +35,6 @@ namespace ILCompiler.DependencyAnalysis objData.EmitPointerReloc(factory.NecessaryTypeSymbol(_type)); } - protected internal override int ClassCode => -288888778; + public override int ClassCode => -288888778; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CompilerComparer.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CompilerComparer.cs index 2a564335e1..250b327077 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CompilerComparer.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CompilerComparer.cs @@ -10,9 +10,9 @@ using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { - public class CompilerComparer : TypeSystemComparer, IComparer + public class CompilerComparer : TypeSystemComparer, IComparer { - public int Compare(ISortableSymbolNode x, ISortableSymbolNode y) + public int Compare(ISortableNode x, ISortableNode y) { if (x == y) { @@ -35,7 +35,7 @@ namespace ILCompiler.DependencyAnalysis else { Debug.Assert(x.GetType() != y.GetType()); - return codeX > codeY ? -1 : 1; + return codeY > codeX ? -1 : 1; } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ConstructedEETypeNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ConstructedEETypeNode.cs index a835bc1f70..d145a8d262 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ConstructedEETypeNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ConstructedEETypeNode.cs @@ -80,7 +80,7 @@ namespace ILCompiler.DependencyAnalysis DefType closestDefType = _type.GetClosestDefType(); - if (_type.RuntimeInterfaces.Length > 0) + if (InterfaceDispatchMapNode.MightHaveInterfaceDispatchMap(_type, factory)) { dependencyList.Add(factory.InterfaceDispatchMap(_type), "Interface dispatch map"); } @@ -115,6 +115,22 @@ namespace ILCompiler.DependencyAnalysis dependencyList.Add(factory.NativeLayout.TemplateTypeLayout(canonType), "Template Type Layout"); } + if (factory.TypeSystemContext.SupportsUniversalCanon) + { + foreach (var instantiationType in _type.Instantiation) + { + if (instantiationType.IsValueType) + { + // All valuetype generic parameters of a constructed type may be effectively constructed. This is generally not that + // critical, but in the presence of universal generics the compiler may generate a Box followed by calls to ToString, + // GetHashcode or Equals in ways that cannot otherwise be detected by dependency analysis. Thus force all struct type + // generic parameters to be considered constructed when walking dependencies of a constructed generic + dependencyList.Add(factory.ConstructedTypeSymbol(instantiationType.ConvertToCanonForm(CanonicalFormKind.Specific)), + "Struct generic parameters in constructed types may be assumed to be used as constructed in constructed generic types"); + } + } + } + // Generated type contains generic virtual methods that will get added to the GVM tables if (TypeGVMEntriesNode.TypeNeedsGVMTableEntries(_type)) { @@ -135,6 +151,15 @@ namespace ILCompiler.DependencyAnalysis factory.InteropStubManager.AddInterestingInteropConstructedTypeDependencies(ref dependencyList, factory, _type); + // Keep track of the default constructor map dependency for this type if it has a default constructor + MethodDesc defaultCtor = closestDefType.GetDefaultConstructor(); + if (defaultCtor != null) + { + dependencyList.Add(new DependencyListEntry( + factory.MethodEntrypoint(defaultCtor.GetCanonMethodTarget(CanonicalFormKind.Specific), closestDefType.IsValueType), + "DefaultConstructorNode")); + } + return dependencyList; } @@ -179,10 +204,6 @@ namespace ILCompiler.DependencyAnalysis if (type.IsCanonicalDefinitionType(CanonicalFormKind.Any)) return false; - // Byref-like types have interior pointers and cannot be heap allocated. - if (type.IsByRefLike) - return false; - // The global "" type can never be allocated. if (((MetadataType)type).IsModuleType) return false; @@ -199,6 +220,6 @@ namespace ILCompiler.DependencyAnalysis ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } - protected internal override int ClassCode => 590142654; + public override int ClassCode => 590142654; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/DefaultConstructorMapNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/DefaultConstructorMapNode.cs index 9f6735b880..bee2f4de66 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/DefaultConstructorMapNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/DefaultConstructorMapNode.cs @@ -14,43 +14,6 @@ using ILCompiler.DependencyAnalysisFramework; namespace ILCompiler.DependencyAnalysis { - /// - /// Dependency analysis node used to keep track of types needing an entry in the default - /// constructor map hashtable - /// - internal sealed class DefaultConstructorFromLazyNode : DependencyNodeCore - { - public TypeDesc TypeNeedingDefaultCtor { get; } - - public DefaultConstructorFromLazyNode(TypeDesc type) - { - Debug.Assert(!type.IsRuntimeDeterminedSubtype); - Debug.Assert(type == type.ConvertToCanonForm(CanonicalFormKind.Specific)); - Debug.Assert(type.GetDefaultConstructor() != null && !type.IsValueType); - - TypeNeedingDefaultCtor = type; - } - - public override bool HasDynamicDependencies => false; - public override bool HasConditionalStaticDependencies => false; - public override bool InterestingForDynamicDependencyAnalysis => false; - public override bool StaticDependenciesAreComputed => true; - protected override string GetName(NodeFactory factory) => "__DefaultConstructorFromLazyNode_" + factory.NameMangler.GetMangledTypeName(TypeNeedingDefaultCtor); - public override IEnumerable GetConditionalStaticDependencies(NodeFactory context) => null; - public override IEnumerable SearchDynamicDependencies(List> markedNodes, int firstNode, NodeFactory factory) => null; - - public override IEnumerable GetStaticDependencies(NodeFactory context) - { - yield return new DependencyListEntry( - context.MaximallyConstructableType(TypeNeedingDefaultCtor), - "DefaultConstructorNode type"); - - yield return new DependencyListEntry( - context.MethodEntrypoint(TypeNeedingDefaultCtor.GetDefaultConstructor(), TypeNeedingDefaultCtor.IsValueType), - "DefaultConstructorNode"); - } - } - /// /// DefaultConstructorMap blob, containing information on default constructor entrypoints of all types used /// by lazy generic instantiations. @@ -80,7 +43,7 @@ namespace ILCompiler.DependencyAnalysis public override bool StaticDependenciesAreComputed => true; protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.DefaultConstructorMapNode; + public override int ClassCode => (int)ObjectNodeOrder.DefaultConstructorMapNode; protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); @@ -96,19 +59,22 @@ namespace ILCompiler.DependencyAnalysis Section defaultConstructorHashtableSection = writer.NewSection(); defaultConstructorHashtableSection.Place(defaultConstructorHashtable); - foreach (var ctorNeeded in factory.MetadataManager.GetDefaultConstructorsNeeded()) + foreach (var type in factory.MetadataManager.GetTypesWithConstructedEETypes()) { - MethodDesc defaultCtor = ctorNeeded.TypeNeedingDefaultCtor.GetDefaultConstructor(); - Debug.Assert(defaultCtor != null); + MethodDesc defaultCtor = type.GetDefaultConstructor(); + if (defaultCtor == null) + continue; - ISymbolNode typeNode = factory.NecessaryTypeSymbol(ctorNeeded.TypeNeedingDefaultCtor); + defaultCtor = defaultCtor.GetCanonMethodTarget(CanonicalFormKind.Specific); + + ISymbolNode typeNode = factory.NecessaryTypeSymbol(type); ISymbolNode defaultCtorNode = factory.MethodEntrypoint(defaultCtor, false); Vertex vertex = writer.GetTuple( writer.GetUnsignedConstant(_externalReferences.GetIndex(typeNode)), writer.GetUnsignedConstant(_externalReferences.GetIndex(defaultCtorNode))); - int hashCode = ctorNeeded.TypeNeedingDefaultCtor.GetHashCode(); + int hashCode = type.GetHashCode(); defaultConstructorHashtable.Append((uint)hashCode, defaultConstructorHashtableSection.Place(vertex)); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/DelegateMarshallingStubMapNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/DelegateMarshallingStubMapNode.cs index 11318ad2f7..95f9588aa0 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/DelegateMarshallingStubMapNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/DelegateMarshallingStubMapNode.cs @@ -77,6 +77,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.DelegateMarshallingStubMapNode; + public override int ClassCode => (int)ObjectNodeOrder.DelegateMarshallingStubMapNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/DynamicInvokeTemplateDataNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/DynamicInvokeTemplateDataNode.cs index d18e2eb590..01070faa21 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/DynamicInvokeTemplateDataNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/DynamicInvokeTemplateDataNode.cs @@ -124,6 +124,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.DynamicInvokeTemplateDataNode; + public override int ClassCode => (int)ObjectNodeOrder.DynamicInvokeTemplateDataNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EETypeNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EETypeNode.cs index dc09feaf89..8db7d5547a 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EETypeNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EETypeNode.cs @@ -56,7 +56,7 @@ namespace ILCompiler.DependencyAnalysis /// | /// [Pointer Size] | Pointer to the generic argument and variance info (optional) /// - public partial class EETypeNode : ObjectNode, IExportableSymbolNode, IEETypeNode, ISymbolDefinitionNode + public partial class EETypeNode : ObjectNode, IExportableSymbolNode, IEETypeNode, ISymbolDefinitionNode, ISymbolNodeWithLinkage { protected TypeDesc _type; internal EETypeOptionalFieldsBuilder _optionalFieldsBuilder = new EETypeOptionalFieldsBuilder(); @@ -90,9 +90,9 @@ namespace ILCompiler.DependencyAnalysis return false; } - public override ObjectNode NodeForLinkage(NodeFactory factory) + public virtual ISymbolNode NodeForLinkage(NodeFactory factory) { - return (ObjectNode)factory.NecessaryTypeSymbol(_type); + return factory.NecessaryTypeSymbol(_type); } public ExportForm GetExportForm(NodeFactory factory) => factory.CompilationModuleGroup.GetExportTypeForm(Type); @@ -385,7 +385,19 @@ namespace ILCompiler.DependencyAnalysis if (EmitVirtualSlotsAndInterfaces) { + if (!_type.IsArrayTypeWithoutGenericInterfaces()) + { + // Sealed vtables have relative pointers, so to minimize size, we build sealed vtables for the canonical types + dependencies.Add(new DependencyListEntry(factory.SealedVTable(_type.ConvertToCanonForm(CanonicalFormKind.Specific)), "Sealed Vtable")); + } + AddVirtualMethodUseDependencies(dependencies, factory); + + // Also add the un-normalized vtable slices of implemented interfaces. + // This is important to do in the scanning phase so that the compilation phase can find + // vtable information for things like IEnumerator>. + foreach (TypeDesc intface in _type.RuntimeInterfaces) + dependencies.Add(factory.VTable(intface), "Interface vtable slice"); } if (factory.CompilationModuleGroup.PresenceOfEETypeImpliesAllMethodsOnType(_type)) @@ -470,6 +482,7 @@ namespace ILCompiler.DependencyAnalysis OutputFinalizerMethod(factory, ref objData); OutputOptionalFields(factory, ref objData); OutputNullableTypeParameter(factory, ref objData); + OutputSealedVTable(factory, relocsOnly, ref objData); OutputGenericInstantiationDetails(factory, ref objData); return objData.ToObjectData(); @@ -690,7 +703,7 @@ namespace ILCompiler.DependencyAnalysis } } - protected virtual void OutputVirtualSlots(NodeFactory factory, ref ObjectDataBuilder objData, TypeDesc implType, TypeDesc declType, TypeDesc templateType, bool relocsOnly) + private void OutputVirtualSlots(NodeFactory factory, ref ObjectDataBuilder objData, TypeDesc implType, TypeDesc declType, TypeDesc templateType, bool relocsOnly) { Debug.Assert(EmitVirtualSlotsAndInterfaces); @@ -759,6 +772,11 @@ namespace ILCompiler.DependencyAnalysis MethodDesc implMethod = implType.GetClosestDefType().FindVirtualFunctionTargetMethodOnObjectType(declMethod); + // Final NewSlot methods cannot be overridden, and therefore can be placed in the sealed-vtable to reduce the size of the vtable + // of this type and any type that inherits from it. + if (declMethod.CanMethodBeInSealedVTable() && !declType.IsArrayTypeWithoutGenericInterfaces()) + continue; + if (!implMethod.IsAbstract) { MethodDesc canonImplMethod = implMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); @@ -812,11 +830,32 @@ namespace ILCompiler.DependencyAnalysis } } + private void OutputSealedVTable(NodeFactory factory, bool relocsOnly, ref ObjectDataBuilder objData) + { + if (EmitVirtualSlotsAndInterfaces && !_type.IsArrayTypeWithoutGenericInterfaces()) + { + // Sealed vtables have relative pointers, so to minimize size, we build sealed vtables for the canonical types + SealedVTableNode sealedVTable = factory.SealedVTable(_type.ConvertToCanonForm(CanonicalFormKind.Specific)); + + if (sealedVTable.BuildSealedVTableSlots(factory, relocsOnly) && sealedVTable.NumSealedVTableEntries > 0) + { + if (factory.Target.SupportsRelativePointers) + objData.EmitReloc(sealedVTable, RelocType.IMAGE_REL_BASED_RELPTR32); + else + objData.EmitPointerReloc(sealedVTable); + } + } + } + private void OutputGenericInstantiationDetails(NodeFactory factory, ref ObjectDataBuilder objData) { if (_type.HasInstantiation && !_type.IsTypeDefinition) { - objData.EmitPointerRelocOrIndirectionReference(factory.NecessaryTypeSymbol(_type.GetTypeDefinition())); + IEETypeNode typeDefNode = factory.NecessaryTypeSymbol(_type.GetTypeDefinition()); + if (factory.Target.SupportsRelativePointers) + objData.EmitRelativeRelocOrIndirectionReference(typeDefNode); + else + objData.EmitPointerRelocOrIndirectionReference(typeDefNode); GenericCompositionDetails details; if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType) @@ -834,7 +873,11 @@ namespace ILCompiler.DependencyAnalysis else details = new GenericCompositionDetails(_type); - objData.EmitPointerReloc(factory.GenericComposition(details)); + ISymbolNode compositionNode = factory.GenericComposition(details); + if (factory.Target.SupportsRelativePointers) + objData.EmitReloc(compositionNode, RelocType.IMAGE_REL_BASED_RELPTR32); + else + objData.EmitPointerReloc(compositionNode); } } @@ -843,19 +886,19 @@ namespace ILCompiler.DependencyAnalysis /// protected internal virtual void ComputeOptionalEETypeFields(NodeFactory factory, bool relocsOnly) { - if (!relocsOnly && _type.RuntimeInterfaces.Length > 0 && factory.InterfaceDispatchMap(_type).Marked) + if (!relocsOnly && EmitVirtualSlotsAndInterfaces && InterfaceDispatchMapNode.MightHaveInterfaceDispatchMap(_type, factory)) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.DispatchMap, checked((uint)factory.InterfaceDispatchMapIndirection(Type).IndexFromBeginningOfArray)); } - ComputeRareFlags(factory); + ComputeRareFlags(factory, relocsOnly); ComputeNullableValueOffset(); if (!relocsOnly) ComputeICastableVirtualMethodSlots(factory); ComputeValueTypeFieldPadding(); } - void ComputeRareFlags(NodeFactory factory) + void ComputeRareFlags(NodeFactory factory, bool relocsOnly) { uint flags = 0; @@ -882,7 +925,12 @@ namespace ILCompiler.DependencyAnalysis flags |= (uint)EETypeRareFlags.RequiresAlign8Flag; } - if (metadataType != null && metadataType.IsHfa) + TargetArchitecture targetArch = _type.Context.Target.Architecture; + if (metadataType != null && + (targetArch == TargetArchitecture.ARM || + targetArch == TargetArchitecture.ARMEL || + targetArch == TargetArchitecture.ARM64) && + metadataType.IsHfa) { flags |= (uint)EETypeRareFlags.IsHFAFlag; } @@ -897,6 +945,13 @@ namespace ILCompiler.DependencyAnalysis flags |= (uint)EETypeRareFlags.IsByRefLikeFlag; } + if (EmitVirtualSlotsAndInterfaces && !_type.IsArrayTypeWithoutGenericInterfaces()) + { + SealedVTableNode sealedVTable = factory.SealedVTable(_type.ConvertToCanonForm(CanonicalFormKind.Specific)); + if (sealedVTable.BuildSealedVTableSlots(factory, relocsOnly) && sealedVTable.NumSealedVTableEntries > 0) + flags |= (uint)EETypeRareFlags.HasSealedVTableEntriesFlag; + } + if (flags != 0) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.RareFlags, flags); @@ -945,13 +1000,14 @@ namespace ILCompiler.DependencyAnalysis MethodDesc isInstMethodImpl = _type.ResolveInterfaceMethodTarget(isInstDecl); MethodDesc getImplTypeMethodImpl = _type.ResolveInterfaceMethodTarget(getImplTypeDecl); - int isInstMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, isInstMethodImpl); - int getImplTypeMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, getImplTypeMethodImpl); + int isInstMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, isInstMethodImpl, _type); + int getImplTypeMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, getImplTypeMethodImpl, _type); - Debug.Assert(isInstMethodSlot != -1 && getImplTypeMethodSlot != -1); - - _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ICastableIsInstSlot, (uint)isInstMethodSlot); - _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ICastableGetImplTypeSlot, (uint)getImplTypeMethodSlot); + // Slots are usually -1, since these methods are usually in the sealed vtable of the base type. + if (isInstMethodSlot != -1) + _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ICastableIsInstSlot, (uint)isInstMethodSlot); + if (getImplTypeMethodSlot != -1) + _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ICastableGetImplTypeSlot, (uint)getImplTypeMethodSlot); } } } @@ -1200,20 +1256,13 @@ namespace ILCompiler.DependencyAnalysis } } - protected internal override int ClassCode => 1521789141; + public override int ClassCode => 1521789141; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_type, ((EETypeNode)other)._type); } - int ISortableSymbolNode.ClassCode => ClassCode; - - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) - { - return CompareToImpl((ObjectNode)other, comparer); - } - private struct SlotCounter { private int _startBytes; diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EETypeOptionalFieldsNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EETypeOptionalFieldsNode.cs index 0cc9ef2056..dbcaf76cf3 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EETypeOptionalFieldsNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EETypeOptionalFieldsNode.cs @@ -51,7 +51,7 @@ namespace ILCompiler.DependencyAnalysis public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { ObjectDataBuilder objData = new ObjectDataBuilder(factory, relocsOnly); - objData.RequireInitialPointerAlignment(); + objData.RequireInitialAlignment(1); objData.AddSymbol(this); if (!relocsOnly) @@ -63,9 +63,9 @@ namespace ILCompiler.DependencyAnalysis return objData.ToObjectData(); } - protected internal override int ClassCode => 821718028; + public override int ClassCode => 821718028; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return SortableDependencyNode.CompareImpl(_owner, ((EETypeOptionalFieldsNode)other)._owner, comparer); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EmbeddedDataContainerNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EmbeddedDataContainerNode.cs index bc9d9975de..0cffffac19 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EmbeddedDataContainerNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EmbeddedDataContainerNode.cs @@ -26,9 +26,9 @@ namespace ILCompiler.DependencyAnalysis _endSymbol = new ObjectAndOffsetSymbolNode(this, 0, endSymbolMangledName, true); } - protected internal override int ClassCode => -1410622237; + public override int ClassCode => -1410622237; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return _startSymbolMangledName.CompareTo(((EmbeddedDataContainerNode)other)._startSymbolMangledName); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EmbeddedPointerIndirectionNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EmbeddedPointerIndirectionNode.cs index 766a737068..45d05c9bce 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EmbeddedPointerIndirectionNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/EmbeddedPointerIndirectionNode.cs @@ -47,9 +47,9 @@ namespace ILCompiler.DependencyAnalysis Target.AppendMangledName(nameMangler, sb); } - int ISortableSymbolNode.ClassCode => -2055384490; + public override int ClassCode => -2055384490; - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_targetNode, ((EmbeddedPointerIndirectionNode)other)._targetNode); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExactMethodInstantiationsNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExactMethodInstantiationsNode.cs index d1dffa4b02..b4bf6659e9 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExactMethodInstantiationsNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExactMethodInstantiationsNode.cs @@ -152,6 +152,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.ExactMethodInstantiationsNode; + public override int ClassCode => (int)ObjectNodeOrder.ExactMethodInstantiationsNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExternMethodSymbolNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExternMethodSymbolNode.cs index 7602151b97..8efd6fe273 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExternMethodSymbolNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExternMethodSymbolNode.cs @@ -28,5 +28,7 @@ namespace ILCompiler.DependencyAnalysis return _method; } } + + public override int ClassCode => -729061105; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExternSymbolNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExternSymbolNode.cs index f35a57d1c4..0aee4c8dbd 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExternSymbolNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExternSymbolNode.cs @@ -14,7 +14,7 @@ namespace ILCompiler.DependencyAnalysis /// /// Represents a symbol that is defined externally and statically linked to the output obj file. /// - public class ExternSymbolNode : DependencyNodeCore, ISortableSymbolNode + public class ExternSymbolNode : SortableDependencyNode, ISortableSymbolNode { private Utf8String _name; @@ -42,9 +42,9 @@ namespace ILCompiler.DependencyAnalysis public override IEnumerable SearchDynamicDependencies(List> markedNodes, int firstNode, NodeFactory factory) => null; #if !SUPPORT_JIT - int ISortableSymbolNode.ClassCode => 1092559304; + public override int ClassCode => 1092559304; - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return _name.CompareTo(((ExternSymbolNode)other)._name); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExternalReferencesTableNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExternalReferencesTableNode.cs index 84c17aab5a..d37a4be952 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExternalReferencesTableNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ExternalReferencesTableNode.cs @@ -123,9 +123,8 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.ExternalReferencesTableNode; - - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int ClassCode => (int)ObjectNodeOrder.ExternalReferencesTableNode; + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return string.Compare(_blobName, ((ExternalReferencesTableNode)other)._blobName); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/FatFunctionPointerNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/FatFunctionPointerNode.cs index a4127e63d3..3016536ce6 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/FatFunctionPointerNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/FatFunctionPointerNode.cs @@ -97,9 +97,9 @@ namespace ILCompiler.DependencyAnalysis return builder.ToObjectData(); } - protected internal override int ClassCode => 190463489; + public override int ClassCode => 190463489; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { var compare = _isUnboxingStub.CompareTo(((FatFunctionPointerNode)other)._isUnboxingStub); if (compare != 0) @@ -107,12 +107,5 @@ namespace ILCompiler.DependencyAnalysis return comparer.Compare(Method, ((FatFunctionPointerNode)other).Method); } - - int ISortableSymbolNode.ClassCode => ClassCode; - - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) - { - return CompareToImpl((ObjectNode)other, comparer); - } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/FrozenArrayNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/FrozenArrayNode.cs index 23b0992bde..8d210f5c19 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/FrozenArrayNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/FrozenArrayNode.cs @@ -101,9 +101,9 @@ namespace ILCompiler.DependencyAnalysis factory.FrozenSegmentRegion.AddEmbeddedObject(this); } - protected internal override int ClassCode => 1789429316; + public override int ClassCode => 1789429316; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return _preInitFieldInfo.CompareTo(((FrozenArrayNode)other)._preInitFieldInfo, comparer); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/FrozenStringNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/FrozenStringNode.cs index 1fa63fc515..f1b3467c25 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/FrozenStringNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/FrozenStringNode.cs @@ -91,9 +91,9 @@ namespace ILCompiler.DependencyAnalysis factory.FrozenSegmentRegion.AddEmbeddedObject(this); } - protected internal override int ClassCode => -1733946122; + public override int ClassCode => -1733946122; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return string.CompareOrdinal(_data, ((FrozenStringNode)other)._data); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticDescNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticDescNode.cs index 07d482d3e4..4ff2e737ad 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticDescNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticDescNode.cs @@ -13,7 +13,7 @@ using Debug = System.Diagnostics.Debug; namespace ILCompiler.DependencyAnalysis { - public class GCStaticDescNode : EmbeddedObjectNode, ISymbolDefinitionNode + public class GCStaticDescNode : EmbeddedObjectNode, ISymbolDefinitionNode, ISortableSymbolNode { private MetadataType _type; private GCPointerMap _gcMap; @@ -177,21 +177,23 @@ namespace ILCompiler.DependencyAnalysis return compare != 0 ? compare : comparer.Compare(_type, other._type); } - protected internal override int ClassCode => 2142332918; - - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public sealed override int ClassCode => 2142332918; + + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { - return comparer.Compare(_type, ((GCStaticDescNode)other)._type); + return CompareTo((GCStaticDescNode)other, comparer); } } public class GCStaticDescRegionNode : ArrayOfEmbeddedDataNode { - public GCStaticDescRegionNode(string startSymbolMangledName, string endSymbolMangledName) - : base(startSymbolMangledName, endSymbolMangledName, null) + public GCStaticDescRegionNode(string startSymbolMangledName, string endSymbolMangledName, IComparer nodeSorter) + : base(startSymbolMangledName, endSymbolMangledName, nodeSorter) { } + public override int ClassCode => 1312891560; + protected override void GetElementDataForNodes(ref ObjectDataBuilder builder, NodeFactory factory, bool relocsOnly) { int numSeries = 0; @@ -246,9 +248,9 @@ namespace ILCompiler.DependencyAnalysis return "Standalone" + _standaloneGCStaticDesc.GetMangledName(context.NameMangler); } - protected internal override int ClassCode => 2091208431; + public override int ClassCode => 2091208431; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return _standaloneGCStaticDesc.CompareTo(((StandaloneGCStaticDescRegionNode)other)._standaloneGCStaticDesc, comparer); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticEETypeNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticEETypeNode.cs index bea0665cd2..570974205c 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticEETypeNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticEETypeNode.cs @@ -69,7 +69,7 @@ namespace ILCompiler.DependencyAnalysis dataBuilder.AddSymbol(this); // +1 for SyncBlock (in CoreRT static size already includes EEType) - Debug.Assert(factory.Target.Abi == TargetAbi.CoreRT); + Debug.Assert(factory.Target.Abi == TargetAbi.CoreRT || factory.Target.Abi == TargetAbi.CppCodegen); int totalSize = (_gcMap.Size + 1) * _target.PointerSize; // We only need to check for containsPointers because ThreadStatics are always allocated @@ -101,9 +101,9 @@ namespace ILCompiler.DependencyAnalysis return dataBuilder.ToObjectData(); } - protected internal override int ClassCode => 1304929125; + public override int ClassCode => 1304929125; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return _gcMap.CompareTo(((GCStaticEETypeNode)other)._gcMap); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticsNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticsNode.cs index 814ea97568..39d886e5e5 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticsNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticsNode.cs @@ -12,7 +12,7 @@ using GCStaticRegionConstants = Internal.Runtime.GCStaticRegionConstants; namespace ILCompiler.DependencyAnalysis { - public class GCStaticsNode : ObjectNode, IExportableSymbolNode, ISortableSymbolNode + public class GCStaticsNode : ObjectNode, IExportableSymbolNode, ISortableSymbolNode, ISymbolNodeWithDebugInfo { private MetadataType _type; private List _preInitFieldInfos; @@ -34,6 +34,8 @@ namespace ILCompiler.DependencyAnalysis public int Offset => 0; public MetadataType Type => _type; + public IDebugInfo DebugInfo => NullTypeIndexDebugInfo.Instance; + public static string GetMangledName(TypeDesc type, NameMangler nameMangler) { return nameMangler.NodeMangler.GCStatics(type); @@ -63,7 +65,7 @@ namespace ILCompiler.DependencyAnalysis } dependencyList.Add(factory.GCStaticsRegion, "GCStatics Region"); - if (factory.Target.Abi == TargetAbi.CoreRT) + if (factory.Target.Abi != TargetAbi.ProjectN) { dependencyList.Add(GetGCStaticEETypeNode(factory), "GCStatic EEType"); if (_preInitFieldInfos != null) @@ -130,18 +132,11 @@ namespace ILCompiler.DependencyAnalysis } } - protected internal override int ClassCode => -522346696; + public override int ClassCode => -522346696; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_type, ((GCStaticsNode)other)._type); } - - int ISortableSymbolNode.ClassCode => ClassCode; - - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) - { - return CompareToImpl((ObjectNode)other, comparer); - } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticsPreInitDataNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticsPreInitDataNode.cs index 653a18fa0e..e78801952e 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticsPreInitDataNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GCStaticsPreInitDataNode.cs @@ -113,9 +113,9 @@ namespace ILCompiler.DependencyAnalysis return builder.ToObjectData(); } - protected internal override int ClassCode => 1148300665; + public override int ClassCode => 1148300665; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_type, ((GCStaticsPreInitDataNode)other)._type); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericCompositionNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericCompositionNode.cs index cff9f37463..8d4c161fc9 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericCompositionNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericCompositionNode.cs @@ -100,8 +100,8 @@ namespace ILCompiler.DependencyAnalysis protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); - protected internal override int ClassCode => -762680703; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int ClassCode => -762680703; + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return _details.CompareToImpl(((GenericCompositionNode)other)._details, comparer); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericDefinitionEETypeNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericDefinitionEETypeNode.cs index d40972210d..243d94cd66 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericDefinitionEETypeNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericDefinitionEETypeNode.cs @@ -76,6 +76,6 @@ namespace ILCompiler.DependencyAnalysis return dataBuilder.ToObjectData(); } - protected internal override int ClassCode => -160325006; + public override int ClassCode => -160325006; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericDictionaryNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericDictionaryNode.cs index 8ebdfa051a..211ac3a1f1 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericDictionaryNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericDictionaryNode.cs @@ -86,9 +86,9 @@ namespace ILCompiler.DependencyAnalysis return this.GetMangledName(factory.NameMangler); } - int ISortableSymbolNode.ClassCode => ClassCode; + public override int ClassCode => ClassCode; - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return CompareToImpl((ObjectNode)other, comparer); } @@ -134,11 +134,11 @@ namespace ILCompiler.DependencyAnalysis foreach (var arg in _owningType.Instantiation) { // Skip types that do not have a default constructor (not interesting). - if (arg.IsValueType || arg.GetDefaultConstructor() == null) + if (arg.IsValueType || arg.GetDefaultConstructor() == null || !ConstructedEETypeNode.CreationAllowed(arg)) continue; result.Add(new DependencyListEntry( - factory.DefaultConstructorFromLazy(arg.ConvertToCanonForm(CanonicalFormKind.Specific)), + factory.ConstructedTypeSymbol(arg.ConvertToCanonForm(CanonicalFormKind.Specific)), "Default constructor for lazy generics")); } } @@ -176,9 +176,9 @@ namespace ILCompiler.DependencyAnalysis _owningType = owningType; } - protected internal override int ClassCode => 889700584; + public override int ClassCode => 889700584; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_owningType, ((TypeGenericDictionaryNode)other)._owningType); } @@ -218,21 +218,21 @@ namespace ILCompiler.DependencyAnalysis foreach (var arg in _owningMethod.OwningType.Instantiation) { // Skip types that do not have a default constructor (not interesting). - if (arg.IsValueType || arg.GetDefaultConstructor() == null) + if (arg.IsValueType || arg.GetDefaultConstructor() == null || !ConstructedEETypeNode.CreationAllowed(arg)) continue; dependencies.Add(new DependencyListEntry( - factory.DefaultConstructorFromLazy(arg.ConvertToCanonForm(CanonicalFormKind.Specific)), + factory.ConstructedTypeSymbol(arg.ConvertToCanonForm(CanonicalFormKind.Specific)), "Default constructor for lazy generics")); } foreach (var arg in _owningMethod.Instantiation) { // Skip types that do not have a default constructor (not interesting). - if (arg.IsValueType || arg.GetDefaultConstructor() == null) + if (arg.IsValueType || arg.GetDefaultConstructor() == null || !ConstructedEETypeNode.CreationAllowed(arg)) continue; dependencies.Add(new DependencyListEntry( - factory.DefaultConstructorFromLazy(arg.ConvertToCanonForm(CanonicalFormKind.Specific)), + factory.ConstructedTypeSymbol(arg.ConvertToCanonForm(CanonicalFormKind.Specific)), "Default constructor for lazy generics")); } } @@ -277,9 +277,9 @@ namespace ILCompiler.DependencyAnalysis _owningMethod = owningMethod; } - protected internal override int ClassCode => -1245704203; + public override int ClassCode => -1245704203; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_owningMethod, ((MethodGenericDictionaryNode)other)._owningMethod); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericMethodsHashtableNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericMethodsHashtableNode.cs index bb6d875536..efbe77897a 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericMethodsHashtableNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericMethodsHashtableNode.cs @@ -126,6 +126,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.GenericMethodsHashtableNode; + public override int ClassCode => (int)ObjectNodeOrder.GenericMethodsHashtableNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericMethodsTemplateMap.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericMethodsTemplateMap.cs index 5f48eff374..c4a7432195 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericMethodsTemplateMap.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericMethodsTemplateMap.cs @@ -118,6 +118,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.GenericMethodsTemplateMap; + public override int ClassCode => (int)ObjectNodeOrder.GenericMethodsTemplateMap; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericTypesHashtableNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericTypesHashtableNode.cs index 0d9907e9fe..0bf0f38500 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericTypesHashtableNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericTypesHashtableNode.cs @@ -68,6 +68,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.GenericTypesHashtableNode; + public override int ClassCode => (int)ObjectNodeOrder.GenericTypesHashtableNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericTypesTemplateMap.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericTypesTemplateMap.cs index 812a2a3fb5..c01bfae129 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericTypesTemplateMap.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericTypesTemplateMap.cs @@ -160,6 +160,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.GenericTypesTemplateMap; + public override int ClassCode => (int)ObjectNodeOrder.GenericTypesTemplateMap; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericVirtualMethodTableNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericVirtualMethodTableNode.cs index 69e35880d9..18f727a693 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericVirtualMethodTableNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/GenericVirtualMethodTableNode.cs @@ -145,6 +145,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.GenericVirtualMethodTableNode; + public override int ClassCode => (int)ObjectNodeOrder.GenericVirtualMethodTableNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ILScanNodeFactory.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ILScanNodeFactory.cs index 6f061c02f6..3069c5f53d 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ILScanNodeFactory.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ILScanNodeFactory.cs @@ -63,7 +63,7 @@ namespace ILCompiler.DependencyAnalysis // 'this' and also provides an instantiation argument (we do a calling convention conversion). // We don't do this for generic instance methods though because they don't use the EEType // for the generic context anyway. - return new ScannedMethodNode(TypeSystemContext.GetSpecialUnboxingThunk(method, CompilationModuleGroup.GeneratedAssembly)); + return new ScannedMethodNode(TypeSystemContext.GetSpecialUnboxingThunk(method, TypeSystemContext.GeneratedAssembly)); } else { diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/IMethodCodeNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/IMethodCodeNode.cs index 8a5e8d7f48..3aaece4d17 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/IMethodCodeNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/IMethodCodeNode.cs @@ -14,5 +14,6 @@ namespace ILCompiler.DependencyAnalysis void InitializeEHInfo(ObjectNode.ObjectData ehInfo); void InitializeDebugLocInfos(DebugLocInfo[] debugLocInfos); void InitializeDebugVarInfos(DebugVarInfo[] debugVarInfos); + void InitializeDebugEHClauseInfos(DebugEHClauseInfo[] debugEHClauseInfos); } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/INodeWithCodeInfo.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/INodeWithCodeInfo.cs index 48b48e656f..c1b293b020 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/INodeWithCodeInfo.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/INodeWithCodeInfo.cs @@ -33,6 +33,22 @@ namespace ILCompiler.DependencyAnalysis } } + public struct DebugEHClauseInfo + { + public uint TryOffset; + public uint TryLength; + public uint HandlerOffset; + public uint HandlerLength; + + public DebugEHClauseInfo(uint tryOffset, uint tryLength, uint handlerOffset, uint handlerLength) + { + TryOffset = tryOffset; + TryLength = tryLength; + HandlerOffset = handlerOffset; + HandlerLength = handlerLength; + } + } + public interface INodeWithCodeInfo { FrameInfo[] FrameInfos @@ -45,6 +61,11 @@ namespace ILCompiler.DependencyAnalysis get; } + DebugEHClauseInfo[] DebugEHClauseInfos + { + get; + } + ObjectNode.ObjectData EHInfo { get; diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ISortableNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ISortableNode.cs new file mode 100644 index 0000000000..ac62439b07 --- /dev/null +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ISortableNode.cs @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace ILCompiler.DependencyAnalysis +{ + public interface ISortableNode + { +#if !SUPPORT_JIT + /// + /// Gets an identifier that is the same for all instances of this + /// descendant, but different from the of any other descendant. + /// + /// + /// This is really just a number, ideally produced by "new Random().Next(int.MinValue, int.MaxValue)". + /// If two manage to conflict (which is pretty unlikely), just make a new one... + /// + int ClassCode { get; } + + int CompareToImpl(ISortableNode other, CompilerComparer comparer); +#endif + } +} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ISymbolNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ISymbolNode.cs index af38e11d66..feca8b45e2 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ISymbolNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ISymbolNode.cs @@ -32,13 +32,19 @@ namespace ILCompiler.DependencyAnalysis bool RepresentsIndirectionCell { get; } } - - public interface ISortableSymbolNode : ISymbolNode + /// + /// Represents a symbol backed by a different symbol for object emission purposes. + /// + public interface ISymbolNodeWithLinkage : ISymbolNode + { + /// + /// Return a node that is used for linkage + /// + ISymbolNode NodeForLinkage(NodeFactory factory); + } + + public interface ISortableSymbolNode : ISymbolNode, ISortableNode { -#if !SUPPORT_JIT - int ClassCode { get; } - int CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer); -#endif } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ISymbolNodeWithDebugInfo.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ISymbolNodeWithDebugInfo.cs new file mode 100644 index 0000000000..971cf70166 --- /dev/null +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ISymbolNodeWithDebugInfo.cs @@ -0,0 +1,38 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using ILCompiler.DependencyAnalysisFramework; +using Internal.Text; + +namespace ILCompiler.DependencyAnalysis +{ + /// + /// Represents a symbol definition with debug info, i.e., the S_GDATA32 record. + /// + public interface ISymbolNodeWithDebugInfo : ISymbolDefinitionNode + { + IDebugInfo DebugInfo { get; } + } + + public interface IDebugInfo + { } + + public interface ITypeIndexDebugInfo : IDebugInfo + { + int TypeIndex { get; } + } + + public class NullTypeIndexDebugInfo : ITypeIndexDebugInfo + { + private NullTypeIndexDebugInfo() { } + + public int TypeIndex => 0; + + public static IDebugInfo Instance + { + get { return new NullTypeIndexDebugInfo(); } + } + } +} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ImportedEETypeSymbolNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ImportedEETypeSymbolNode.cs index 1918de4af4..e8138f95ee 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ImportedEETypeSymbolNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ImportedEETypeSymbolNode.cs @@ -31,5 +31,7 @@ namespace ILCompiler.DependencyAnalysis return _type; } } + + public override int ClassCode => 395643063; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/IndirectionExtensions.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/IndirectionExtensions.cs new file mode 100644 index 0000000000..9265f94f88 --- /dev/null +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/IndirectionExtensions.cs @@ -0,0 +1,36 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.Runtime; +using Internal.TypeSystem; + +using Debug = System.Diagnostics.Debug; + +namespace ILCompiler.DependencyAnalysis +{ + static class IndirectionExtensions + { + /// + /// Use this api to generate a reloc to a symbol that may be an indirection cell or not as a pointer + /// + /// symbol to reference + /// value to OR in to the reloc to represent to runtime code that this pointer is an indirection. Defaults to IndirectionConstants.IndirectionCellPointer + /// Delta from symbol start for value + public static void EmitPointerRelocOrIndirectionReference(ref this ObjectDataBuilder builder, ISymbolNode symbol, int delta = 0, int indirectionBit = IndirectionConstants.IndirectionCellPointer) + { + if (symbol.RepresentsIndirectionCell) + delta |= indirectionBit; + + builder.EmitReloc(symbol, (builder.TargetPointerSize == 8) ? RelocType.IMAGE_REL_BASED_DIR64 : RelocType.IMAGE_REL_BASED_HIGHLOW, delta); + } + + public static void EmitRelativeRelocOrIndirectionReference(ref this ObjectDataBuilder builder, ISymbolNode symbol, int delta = 0, int indirectionBit = IndirectionConstants.IndirectionCellPointer) + { + if (symbol.RepresentsIndirectionCell) + delta = delta | indirectionBit; + + builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_RELPTR32, delta); + } + } +} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/IndirectionNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/IndirectionNode.cs index 77bd897eac..f219869794 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/IndirectionNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/IndirectionNode.cs @@ -61,11 +61,11 @@ namespace ILCompiler.DependencyAnalysis return builder.ToObjectData(); } - protected internal override int ClassCode => -1401349230; + public override int ClassCode => -1401349230; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { - return comparer.Compare(this._indirectedNode, ((IndirectionNode)other)._indirectedNode); + return comparer.Compare(_indirectedNode, ((IndirectionNode)other)._indirectedNode); } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchCellNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchCellNode.cs index a5c49fc66c..4bcd902153 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchCellNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchCellNode.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Diagnostics; using Internal.Runtime; @@ -10,11 +11,15 @@ using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { - public class InterfaceDispatchCellNode : ObjectNode, ISymbolDefinitionNode + public class InterfaceDispatchCellNode : EmbeddedObjectNode, ISymbolDefinitionNode { private readonly MethodDesc _targetMethod; private readonly string _callSiteIdentifier; + internal MethodDesc TargetMethod => _targetMethod; + + internal string CallSiteIdentifier => _callSiteIdentifier; + public InterfaceDispatchCellNode(MethodDesc targetMethod, string callSiteIdentifier) { Debug.Assert(targetMethod.OwningType.IsInterface); @@ -27,7 +32,10 @@ namespace ILCompiler.DependencyAnalysis { sb.Append(GetMangledName(nameMangler, _targetMethod, _callSiteIdentifier)); } - public int Offset => 0; + + int ISymbolDefinitionNode.Offset => OffsetFromBeginningOfArray; + + int ISymbolNode.Offset => 0; public override bool IsShareable => false; @@ -45,11 +53,9 @@ namespace ILCompiler.DependencyAnalysis protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); - public override ObjectNodeSection Section => ObjectNodeSection.DataSection; - public override bool StaticDependenciesAreComputed => true; - protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFactory factory) + public override IEnumerable GetStaticDependencies(NodeFactory factory) { DependencyList result = new DependencyList(); @@ -59,18 +65,25 @@ namespace ILCompiler.DependencyAnalysis } factory.MetadataManager.GetDependenciesDueToVirtualMethodReflectability(ref result, factory, _targetMethod); - + + TargetArchitecture targetArchitecture = factory.Target.Architecture; + if (targetArchitecture == TargetArchitecture.ARM || + targetArchitecture == TargetArchitecture.ARMEL) + { + result.Add(factory.InitialInterfaceDispatchStub, "Initial interface dispatch stub"); + } + else + { + result.Add(factory.ExternSymbol("RhpInitialDynamicInterfaceDispatch"), "Initial interface dispatch stub"); + } + + result.Add(factory.NecessaryTypeSymbol(_targetMethod.OwningType), "Interface type"); + return result; } - public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) + public override void EncodeData(ref ObjectDataBuilder objData, NodeFactory factory, bool relocsOnly) { - ObjectDataBuilder objData = new ObjectDataBuilder(factory, relocsOnly); - // The interface dispatch cell has an alignment requirement of 2 * [Pointer size] as part of the - // synchronization mechanism of the two values in the runtime. - objData.RequireInitialAlignment(_targetMethod.Context.Target.PointerSize * 2); - objData.AddSymbol(this); - TargetArchitecture targetArchitecture = factory.Target.Architecture; if (targetArchitecture == TargetArchitecture.ARM || targetArchitecture == TargetArchitecture.ARMEL) @@ -101,22 +114,16 @@ namespace ILCompiler.DependencyAnalysis // 32 bits on targets whose pointer size is 64 bit. objData.EmitInt(0); } - - // End the run of dispatch cells - objData.EmitZeroPointer(); - - // Avoid consulting VTable slots until they're guaranteed complete during final data emission - if (!relocsOnly) - { - objData.EmitNaturalInt(VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, _targetMethod)); - } - - return objData.ToObjectData(); } - protected internal override int ClassCode => -2023802120; + protected override void OnMarked(NodeFactory factory) + { + factory.InterfaceDispatchCellSection.AddEmbeddedObject(this); + } - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int ClassCode => -2023802120; + + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { var compare = comparer.Compare(_targetMethod, ((InterfaceDispatchCellNode)other)._targetMethod); return compare != 0 ? compare : string.Compare(_callSiteIdentifier, ((InterfaceDispatchCellNode)other)._callSiteIdentifier); diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchCellSectionNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchCellSectionNode.cs new file mode 100644 index 0000000000..274a4254ae --- /dev/null +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchCellSectionNode.cs @@ -0,0 +1,132 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; + +using Internal.TypeSystem; + +using Debug = System.Diagnostics.Debug; + +namespace ILCompiler.DependencyAnalysis +{ + /// + /// Represents a section of the executable where interface dispatch cells and their slot information + /// is stored. + /// + public class InterfaceDispatchCellSectionNode : ArrayOfEmbeddedDataNode + { + public InterfaceDispatchCellSectionNode(NodeFactory factory) + : base("__InterfaceDispatchCellSection_Start", "__InterfaceDispatchCellSection_End", new DispatchCellComparer(factory)) + { + } + + protected override void GetElementDataForNodes(ref ObjectDataBuilder builder, NodeFactory factory, bool relocsOnly) + { + if (relocsOnly) + return; + + // The interface dispatch cell has an alignment requirement of 2 * [Pointer size] as part of the + // synchronization mechanism of the two values in the runtime. + builder.RequireInitialAlignment(factory.Target.PointerSize * 2); + + // This number chosen to be high enough that the cost of recording slot numbers is cheap. + const int InterfaceDispatchCellRunLength = 32; + + const int NoSlot = -1; + + // + // We emit the individual dispatch cells in groups. The purpose of the grouping is to save + // us the number of slots we need to emit. The grouping looks like this: + // + // DispatchCell1 + // DispatchCell2 + // ... + // DispatchCellN + // Null + // Slot of the above dispatch cells + // + int runLength = 0; + int currentSlot = NoSlot; + foreach (InterfaceDispatchCellNode node in NodesList) + { + MethodDesc targetMethod = node.TargetMethod; + int targetSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod, targetMethod.OwningType); + if (currentSlot == NoSlot) + { + // This is the first dispatch cell we're emitting + currentSlot = targetSlot; + } + else if (currentSlot != targetSlot || runLength == InterfaceDispatchCellRunLength) + { + // Make sure we are sorted + Debug.Assert(targetSlot >= currentSlot); + + // End the run of dispatch cells + builder.EmitZeroPointer(); + builder.EmitNaturalInt(currentSlot); + + currentSlot = targetSlot; + runLength = 0; + } + + node.InitializeOffsetFromBeginningOfArray(builder.CountBytes); + node.EncodeData(ref builder, factory, relocsOnly); + builder.AddSymbol(node); + + runLength++; + } + + if (runLength > 0) + { + // End the run of dispatch cells + builder.EmitZeroPointer(); + builder.EmitNaturalInt(currentSlot); + } + } + + public override int ClassCode => -1389343; + + /// + /// Comparer that groups interface dispatch cells by their slot number. + /// + private class DispatchCellComparer : IComparer + { + private readonly NodeFactory _factory; + private readonly TypeSystemComparer _comparer = new TypeSystemComparer(); + + public DispatchCellComparer(NodeFactory factory) + { + _factory = factory; + } + + public int Compare(InterfaceDispatchCellNode x, InterfaceDispatchCellNode y) + { + MethodDesc methodX = x.TargetMethod; + MethodDesc methodY = y.TargetMethod; + + // The primary purpose of this comparer is to sort everything by slot + int slotX = VirtualMethodSlotHelper.GetVirtualMethodSlot(_factory, methodX, methodX.OwningType); + int slotY = VirtualMethodSlotHelper.GetVirtualMethodSlot(_factory, methodY, methodY.OwningType); + + int result = slotX - slotY; + if (result != 0) + return result; + + // If slots are the same, compare the method and callsite identifier to get + // a deterministic order within the group. + result = _comparer.Compare(methodX, methodY); + if (result != 0) + return result; + + result = StringComparer.Ordinal.Compare(x.CallSiteIdentifier, y.CallSiteIdentifier); + if (result != 0) + return result; + + Debug.Assert(x == y); + return 0; + } + } + } +} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs index e2f6a6535f..2da7c8d02d 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs @@ -15,8 +15,14 @@ namespace ILCompiler.DependencyAnalysis { TypeDesc _type; - public InterfaceDispatchMapNode(TypeDesc type) + public InterfaceDispatchMapNode(NodeFactory factory, TypeDesc type) { + // Multidimensional arrays should not get a sealed vtable or a dispatch map. Runtime should use the + // sealed vtable and dispatch map of the System.Array basetype instead. + // Pointer arrays also follow the same path + Debug.Assert(!type.IsArrayTypeWithoutGenericInterfaces()); + Debug.Assert(MightHaveInterfaceDispatchMap(type, factory)); + _type = type; } @@ -57,14 +63,71 @@ namespace ILCompiler.DependencyAnalysis return result; } + /// + /// Gets a value indicating whether '' might have a non-empty dispatch map. + /// Note that this is only an approximation because we might not be able to take into account + /// whether the interface methods are actually used. + /// + public static bool MightHaveInterfaceDispatchMap(TypeDesc type, NodeFactory factory) + { + if (type.IsArrayTypeWithoutGenericInterfaces()) + return false; + + if (!type.IsArray && !type.IsDefType) + return false; + + TypeDesc declType = type.GetClosestDefType(); + + for (int interfaceIndex = 0; interfaceIndex < declType.RuntimeInterfaces.Length; interfaceIndex++) + { + DefType interfaceType = declType.RuntimeInterfaces[interfaceIndex]; + InstantiatedType interfaceOnDefinitionType = interfaceType.IsTypeDefinition ? + null : + (InstantiatedType)declType.GetTypeDefinition().RuntimeInterfaces[interfaceIndex]; + + IEnumerable slots; + + // If the vtable has fixed slots, we can query it directly. + // If it's a lazily built vtable, we might not be able to query slots + // just yet, so approximate by looking at all methods. + VTableSliceNode vtableSlice = factory.VTable(interfaceType); + if (vtableSlice.HasFixedSlots) + slots = vtableSlice.Slots; + else + slots = interfaceType.GetAllMethods(); + + foreach (MethodDesc slotMethod in slots) + { + MethodDesc declMethod = slotMethod; + if (interfaceOnDefinitionType != null) + declMethod = factory.TypeSystemContext.GetMethodForInstantiatedType(declMethod.GetTypicalMethodDefinition(), interfaceOnDefinitionType); + + if (declMethod.Signature.IsStatic) + continue; + + var implMethod = declType.GetTypeDefinition().ResolveInterfaceMethodToVirtualMethodOnType(declMethod); + if (implMethod != null) + return true; + } + } + + return false; + } + void EmitDispatchMap(ref ObjectDataBuilder builder, NodeFactory factory) { var entryCountReservation = builder.ReserveInt(); int entryCount = 0; - - for (int interfaceIndex = 0; interfaceIndex < _type.RuntimeInterfaces.Length; interfaceIndex++) + + TypeDesc declType = _type.GetClosestDefType(); + + // Catch any runtime interface collapsing. We shouldn't have any + Debug.Assert(declType.RuntimeInterfaces.Length == declType.GetTypeDefinition().RuntimeInterfaces.Length); + + for (int interfaceIndex = 0; interfaceIndex < declType.RuntimeInterfaces.Length; interfaceIndex++) { - var interfaceType = _type.RuntimeInterfaces[interfaceIndex]; + var interfaceType = declType.RuntimeInterfaces[interfaceIndex]; + var interfaceDefinitionType = declType.GetTypeDefinition().RuntimeInterfaces[interfaceIndex]; Debug.Assert(interfaceType.IsInterface); IReadOnlyList virtualSlots = factory.VTable(interfaceType).Slots; @@ -72,15 +135,26 @@ namespace ILCompiler.DependencyAnalysis for (int interfaceMethodSlot = 0; interfaceMethodSlot < virtualSlots.Count; interfaceMethodSlot++) { MethodDesc declMethod = virtualSlots[interfaceMethodSlot]; - var implMethod = _type.GetClosestDefType().ResolveInterfaceMethodToVirtualMethodOnType(declMethod); + if(!interfaceType.IsTypeDefinition) + declMethod = factory.TypeSystemContext.GetMethodForInstantiatedType(declMethod.GetTypicalMethodDefinition(), (InstantiatedType)interfaceDefinitionType); + + var implMethod = declType.GetTypeDefinition().ResolveInterfaceMethodToVirtualMethodOnType(declMethod); // Interface methods first implemented by a base type in the hierarchy will return null for the implMethod (runtime interface // dispatch will walk the inheritance chain). if (implMethod != null) { + TypeDesc implType = declType; + while (!implType.HasSameTypeDefinition(implMethod.OwningType)) + implType = implType.BaseType; + + MethodDesc targetMethod = implMethod; + if (!implType.IsTypeDefinition) + targetMethod = factory.TypeSystemContext.GetMethodForInstantiatedType(implMethod.GetTypicalMethodDefinition(), (InstantiatedType)implType); + builder.EmitShort(checked((short)interfaceIndex)); builder.EmitShort(checked((short)(interfaceMethodSlot + (interfaceType.HasGenericDictionarySlot() ? 1 : 0)))); - builder.EmitShort(checked((short)VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, implMethod))); + builder.EmitShort(checked((short)VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod, declType))); entryCount++; } } @@ -103,18 +177,11 @@ namespace ILCompiler.DependencyAnalysis return objData.ToObjectData(); } - protected internal override int ClassCode => 848664602; + public override int ClassCode => 848664602; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_type, ((InterfaceDispatchMapNode)other)._type); } - - int ISortableSymbolNode.ClassCode => ClassCode; - - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) - { - return CompareToImpl((ObjectNode)other, comparer); - } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceGenericVirtualMethodTableNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceGenericVirtualMethodTableNode.cs index 4418d2984f..38fc2bd52f 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceGenericVirtualMethodTableNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceGenericVirtualMethodTableNode.cs @@ -214,6 +214,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.InterfaceGenericVirtualMethodTableNode; + public override int ClassCode => (int)ObjectNodeOrder.InterfaceGenericVirtualMethodTableNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/JumpStubNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/JumpStubNode.cs index abc13496c7..811a1bea92 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/JumpStubNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/JumpStubNode.cs @@ -23,6 +23,6 @@ namespace ILCompiler.DependencyAnalysis protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); - protected internal override int ClassCode => 737788182; + public override int ClassCode => 737788182; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/LoopHijackFlagNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/LoopHijackFlagNode.cs index 69b1bd7649..46d92a2baf 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/LoopHijackFlagNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/LoopHijackFlagNode.cs @@ -35,7 +35,7 @@ namespace ILCompiler.DependencyAnalysis public override bool StaticDependenciesAreComputed => true; - protected internal override int ClassCode => -266743363; + public override int ClassCode => -266743363; public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MetadataNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MetadataNode.cs index 246e804cef..fda760c8ce 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MetadataNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MetadataNode.cs @@ -58,6 +58,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.MetadataNode; + public override int ClassCode => (int)ObjectNodeOrder.MetadataNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MethodAssociatedDataNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MethodAssociatedDataNode.cs index 46dacad9e5..262d0799ab 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MethodAssociatedDataNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MethodAssociatedDataNode.cs @@ -41,9 +41,9 @@ namespace ILCompiler.DependencyAnalysis public int Offset => 0; public override bool IsShareable => _methodNode.Method is InstantiatedMethod || EETypeNode.IsTypeNodeShareable(_methodNode.Method.OwningType); - protected internal override int ClassCode => 1055183914; + public override int ClassCode => 1055183914; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_methodNode, ((MethodAssociatedDataNode)other)._methodNode); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MethodCodeNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MethodCodeNode.cs index 69832904e2..fc0efb910a 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MethodCodeNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MethodCodeNode.cs @@ -24,6 +24,7 @@ namespace ILCompiler.DependencyAnalysis private ObjectData _ehInfo; private DebugLocInfo[] _debugLocInfos; private DebugVarInfo[] _debugVarInfos; + private DebugEHClauseInfo[] _debugEHClauseInfos; public MethodCodeNode(MethodDesc method) { @@ -140,6 +141,7 @@ namespace ILCompiler.DependencyAnalysis public DebugLocInfo[] DebugLocInfos => _debugLocInfos; public DebugVarInfo[] DebugVarInfos => _debugVarInfos; + public DebugEHClauseInfo[] DebugEHClauseInfos => _debugEHClauseInfos; public void InitializeDebugLocInfos(DebugLocInfo[] debugLocInfos) { @@ -153,18 +155,17 @@ namespace ILCompiler.DependencyAnalysis _debugVarInfos = debugVarInfos; } - protected internal override int ClassCode => 788492407; + public void InitializeDebugEHClauseInfos(DebugEHClauseInfo[] debugEHClauseInfos) + { + Debug.Assert(_debugEHClauseInfos == null); + _debugEHClauseInfos = debugEHClauseInfos; + } - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int ClassCode => 788492407; + + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_method, ((MethodCodeNode)other)._method); } - - int ISortableSymbolNode.ClassCode => ClassCode; - - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) - { - return CompareToImpl((ObjectNode)other, comparer); - } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ModulesSectionNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ModulesSectionNode.cs index ed629af325..895138a101 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ModulesSectionNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ModulesSectionNode.cs @@ -55,6 +55,6 @@ namespace ILCompiler.DependencyAnalysis return objData.ToObjectData(); } - protected internal override int ClassCode => -1225116970; + public override int ClassCode => -1225116970; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MrtImports.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MrtImports.cs index e7bce493e3..503667b2ea 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MrtImports.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MrtImports.cs @@ -23,42 +23,49 @@ namespace ILCompiler.DependencyAnalysis { public MrtImportedEETypeSymbolNode(TypeDesc type) : base(type) { } protected override sealed string GetNonImportedName(NameMangler nameMangler) => nameMangler.NodeMangler.EEType(Type); + public override int ClassCode => 126598072; } public sealed class MrtImportedGCStaticSymbolNode : MrtImportWithTypeSymbol { public MrtImportedGCStaticSymbolNode(TypeDesc type) : base(type) { } protected override sealed string GetNonImportedName(NameMangler nameMangler) => GCStaticsNode.GetMangledName(Type, nameMangler); + public override int ClassCode => 1974639431; } public sealed class MrtImportedNonGCStaticSymbolNode : MrtImportWithTypeSymbol { public MrtImportedNonGCStaticSymbolNode(TypeDesc type) : base(type) { } protected override sealed string GetNonImportedName(NameMangler nameMangler) => NonGCStaticsNode.GetMangledName(Type, nameMangler); + public override int ClassCode => 257546392; } public sealed class MrtImportedThreadStaticOffsetSymbolNode : MrtImportWithTypeSymbol { public MrtImportedThreadStaticOffsetSymbolNode(TypeDesc type) : base(type) { } protected override sealed string GetNonImportedName(NameMangler nameMangler) => ThreadStaticsOffsetNode.GetMangledName(nameMangler, Type); + public override int ClassCode => 1944978231; } public sealed class MrtImportedMethodDictionarySymbolNode : MrtImportWithMethodSymbol { public MrtImportedMethodDictionarySymbolNode(MethodDesc method) : base(method) { } protected override sealed string GetNonImportedName(NameMangler nameMangler) => nameMangler.NodeMangler.MethodGenericDictionary(Method); + public override int ClassCode => 925274757; } public sealed class MrtImportedMethodCodeSymbolNode : MrtImportWithMethodSymbol, IMethodNode { public MrtImportedMethodCodeSymbolNode(MethodDesc method) : base(method) { } protected override sealed string GetNonImportedName(NameMangler nameMangler) => nameMangler.GetMangledMethodName(Method).ToString(); + public override int ClassCode => -454606757; } public sealed class MrtImportedUnboxingMethodCodeSymbolNode : MrtImportWithMethodSymbol, IMethodNode { public MrtImportedUnboxingMethodCodeSymbolNode(MethodDesc method) : base(method) { } protected override sealed string GetNonImportedName(NameMangler nameMangler) => UnboxingStubNode.GetMangledName(nameMangler, Method); + public override int ClassCode => 1712079609; } public abstract class MrtImportWithTypeSymbol : MrtImportNode @@ -153,7 +160,7 @@ namespace ILCompiler.DependencyAnalysis public sealed override IEnumerable GetConditionalStaticDependencies(NodeFactory factory) => null; public sealed override IEnumerable SearchDynamicDependencies(List> markedNodes, int firstNode, NodeFactory factory) => null; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { MrtImportNode otherImportNode = (MrtImportNode)other; @@ -164,7 +171,7 @@ namespace ILCompiler.DependencyAnalysis return Ordinal - otherImportNode.Ordinal; } - protected internal override int ClassCode => 2017985192; + public override int ClassCode => 2017985192; public sealed override IEnumerable GetStaticDependencies(NodeFactory factory) { @@ -180,13 +187,6 @@ namespace ILCompiler.DependencyAnalysis _importTable.AddNode(this); } - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) - { - return CompareToImpl((SortableDependencyNode)other, comparer); - } - - int ISortableSymbolNode.ClassCode => this.ClassCode; - void ISymbolNode.AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { AppendMangledName(nameMangler, sb); diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MrtProcessedExportAddressTableNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MrtProcessedExportAddressTableNode.cs index 50c3e3a8f1..40c60b8bda 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MrtProcessedExportAddressTableNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MrtProcessedExportAddressTableNode.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Linq; using System.Collections.Generic; using Internal.Text; @@ -24,7 +25,8 @@ namespace ILCompiler.DependencyAnalysis _factory = factory; } - public event Action ReportExportedItem; + public event Func ReportExportedItem; + public event Func GetInitialExportOrdinal; public void AddExportableSymbol(IExportableSymbolNode exportableSymbol) { @@ -68,6 +70,13 @@ namespace ILCompiler.DependencyAnalysis builder.RequireInitialPointerAlignment(); builder.AddSymbol(this); + // + // Entries in the export table need to be sorted by ordinals. When compiling using baseline TOC files, we reuse + // the ordinals from the baseline for sorting, otherwise we start assigning new sequential ordinals. Export entries that do + // not exist in the baseline will get new sequential ordinals, but for determinism, they are also pre-sorted using the + // CompilerComparer logic + // + ISortableSymbolNode[] symbolNodes = new ISortableSymbolNode[_exportableSymbols.Count]; _exportableSymbols.CopyTo(symbolNodes); Array.Sort(symbolNodes, new CompilerComparer()); @@ -75,30 +84,29 @@ namespace ILCompiler.DependencyAnalysis builder.EmitInt(1); // Export table version 1 builder.EmitInt(symbolNodes.Length); // Count of exported symbols in this table - int index = 1; + uint index = GetInitialExportOrdinal == null ? 1 : GetInitialExportOrdinal(); + Dictionary symbolsOridnalMap = new Dictionary(); foreach (ISortableSymbolNode symbol in symbolNodes) { - builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32); - ReportExportedItem?.Invoke(index, (IExportableSymbolNode)symbol); - index++; + uint indexUsed = ReportExportedItem.Invoke(index, (IExportableSymbolNode)symbol); + symbolsOridnalMap.Add(indexUsed, symbol); + index += (indexUsed == index ? (uint)1 : 0); + } + + foreach (uint ordinal in symbolsOridnalMap.Keys.OrderBy(o => o)) + { + builder.EmitReloc(symbolsOridnalMap[ordinal], RelocType.IMAGE_REL_BASED_REL32); } return builder.ToObjectData(); } - protected internal override int ClassCode => 40423846; + public override int ClassCode => 40423846; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { Debug.Assert(Object.ReferenceEquals(other, this)); return 0; // There should only ever be one of these per dependency graph } - - int ISortableSymbolNode.ClassCode => ClassCode; - - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) - { - return CompareToImpl((ObjectNode)other, comparer); - } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MrtProcessedImportAddressTableNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MrtProcessedImportAddressTableNode.cs index e72126588c..c2c9b53d9e 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MrtProcessedImportAddressTableNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/MrtProcessedImportAddressTableNode.cs @@ -113,14 +113,7 @@ namespace ILCompiler.DependencyAnalysis return dependencies; } - protected internal override int ClassCode => -1145565068; - - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) - { - return CompareToImpl((SortableDependencyNode)other, comparer); - } - - int ISortableSymbolNode.ClassCode => this.ClassCode; + public override int ClassCode => -1145565068; void ISymbolNode.AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NativeLayoutInfoNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NativeLayoutInfoNode.cs index a73b9edc3b..2b61d0ff48 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NativeLayoutInfoNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NativeLayoutInfoNode.cs @@ -95,6 +95,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.NativeLayoutInfoNode; + public override int ClassCode => (int)ObjectNodeOrder.NativeLayoutInfoNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NativeLayoutSignatureNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NativeLayoutSignatureNode.cs index 2c1dd5f4dd..f4a0044ea7 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NativeLayoutSignatureNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NativeLayoutSignatureNode.cs @@ -85,9 +85,9 @@ namespace ILCompiler.DependencyAnalysis return objData.ToObjectData(); } - protected internal override int ClassCode => 1887049331; + public override int ClassCode => 1887049331; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { NativeLayoutSignatureNode otherSignature = (NativeLayoutSignatureNode)other; if (_identity is MethodDesc) @@ -118,4 +118,4 @@ namespace ILCompiler.DependencyAnalysis } } } -} \ No newline at end of file +} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NativeLayoutVertexNode.cs.REMOVED.git-id b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NativeLayoutVertexNode.cs.REMOVED.git-id index a535d50619..2e3e597c7b 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NativeLayoutVertexNode.cs.REMOVED.git-id +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NativeLayoutVertexNode.cs.REMOVED.git-id @@ -1 +1 @@ -2c9122d7c05284011fce591922f542b5ddef2fc1 \ No newline at end of file +d48937e59ebf43eda0930bff3447962cae5016dd \ No newline at end of file diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NecessaryCanonicalEETypeNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NecessaryCanonicalEETypeNode.cs index 2a72b509be..a55b62860a 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NecessaryCanonicalEETypeNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NecessaryCanonicalEETypeNode.cs @@ -27,6 +27,6 @@ namespace ILCompiler.DependencyAnalysis return _type.BaseType != null ? factory.NecessaryTypeSymbol(GetFullCanonicalTypeForCanonicalType(_type.BaseType)) : null; } - protected internal override int ClassCode => 1505000724; + public override int ClassCode => 1505000724; } -} \ No newline at end of file +} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NodeFactory.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NodeFactory.cs index 6bfbf947d5..26b0c703d4 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NodeFactory.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NodeFactory.cs @@ -14,7 +14,6 @@ using Internal.Text; using Internal.TypeSystem; using Internal.Runtime; using Internal.IL; -using Internal.NativeFormat; namespace ILCompiler.DependencyAnalysis { @@ -50,6 +49,7 @@ namespace ILCompiler.DependencyAnalysis MetadataManager = metadataManager; LazyGenericsPolicy = lazyGenericsPolicy; _importedNodeProvider = importedNodeProvider; + InterfaceDispatchCellSection = new InterfaceDispatchCellSectionNode(this); } public void SetMarkingComplete() @@ -282,9 +282,9 @@ namespace ILCompiler.DependencyAnalysis return new PInvokeModuleFixupNode(name); }); - _pInvokeMethodFixups = new NodeCache, PInvokeMethodFixupNode>((Tuple key) => + _pInvokeMethodFixups = new NodeCache, PInvokeMethodFixupNode>((Tuple key) => { - return new PInvokeMethodFixupNode(key.Item1, key.Item2); + return new PInvokeMethodFixupNode(key.Item1, key.Item2, key.Item3); }); _methodEntrypoints = new NodeCache(CreateMethodEntrypointNode); @@ -379,7 +379,12 @@ namespace ILCompiler.DependencyAnalysis _interfaceDispatchMaps = new NodeCache((TypeDesc type) => { - return new InterfaceDispatchMapNode(type); + return new InterfaceDispatchMapNode(this, type); + }); + + _sealedVtableNodes = new NodeCache((TypeDesc type) => + { + return new SealedVTableNode(type); }); _runtimeMethodHandles = new NodeCache((MethodDesc method) => @@ -474,11 +479,6 @@ namespace ILCompiler.DependencyAnalysis return new StringAllocatorMethodNode(constructor); }); - _defaultConstructorFromLazyNodes = new NodeCache(type => - { - return new DefaultConstructorFromLazyNode(type); - }); - NativeLayout = new NativeLayoutHelper(this); WindowsDebugData = new WindowsDebugDataHelper(this); } @@ -641,6 +641,13 @@ namespace ILCompiler.DependencyAnalysis return _readOnlyDataBlobs.GetOrAdd(new ReadOnlyDataBlobKey(name, blobData, alignment)); } + private NodeCache _sealedVtableNodes; + + internal SealedVTableNode SealedVTable(TypeDesc type) + { + return _sealedVtableNodes.GetOrAdd(type); + } + private NodeCache _interfaceDispatchMaps; internal InterfaceDispatchMapNode InterfaceDispatchMap(TypeDesc type) @@ -676,11 +683,11 @@ namespace ILCompiler.DependencyAnalysis return _pInvokeModuleFixups.GetOrAdd(moduleName); } - private NodeCache, PInvokeMethodFixupNode> _pInvokeMethodFixups; + private NodeCache, PInvokeMethodFixupNode> _pInvokeMethodFixups; - public PInvokeMethodFixupNode PInvokeMethodFixup(string moduleName, string entryPointName) + public PInvokeMethodFixupNode PInvokeMethodFixup(string moduleName, string entryPointName, PInvokeFlags flags) { - return _pInvokeMethodFixups.GetOrAdd(new Tuple(moduleName, entryPointName)); + return _pInvokeMethodFixups.GetOrAdd(Tuple.Create(moduleName, entryPointName, flags)); } private NodeCache _vTableNodes; @@ -788,12 +795,6 @@ namespace ILCompiler.DependencyAnalysis return _runtimeDeterminedMethods.GetOrAdd(method); } - private NodeCache _defaultConstructorFromLazyNodes; - internal DefaultConstructorFromLazyNode DefaultConstructorFromLazy(TypeDesc type) - { - return _defaultConstructorFromLazyNodes.GetOrAdd(type); - } - private static readonly string[][] s_helperEntrypointNames = new string[][] { new string[] { "System.Runtime.CompilerServices", "ClassConstructorRunner", "CheckStaticClassConstructionReturnGCStaticBase" }, new string[] { "System.Runtime.CompilerServices", "ClassConstructorRunner", "CheckStaticClassConstructionReturnNonGCStaticBase" }, @@ -911,6 +912,9 @@ namespace ILCompiler.DependencyAnalysis internal TypeMetadataNode TypeMetadata(MetadataType type) { + // These are only meaningful for UsageBasedMetadataManager. We should not have them + // in the dependency graph otherwise. + Debug.Assert(MetadataManager is UsageBasedMetadataManager); return _typesWithMetadata.GetOrAdd(type); } @@ -918,6 +922,9 @@ namespace ILCompiler.DependencyAnalysis internal MethodMetadataNode MethodMetadata(MethodDesc method) { + // These are only meaningful for UsageBasedMetadataManager. We should not have them + // in the dependency graph otherwise. + Debug.Assert(MetadataManager is UsageBasedMetadataManager); return _methodsWithMetadata.GetOrAdd(method); } @@ -925,6 +932,9 @@ namespace ILCompiler.DependencyAnalysis internal FieldMetadataNode FieldMetadata(FieldDesc field) { + // These are only meaningful for UsageBasedMetadataManager. We should not have them + // in the dependency graph otherwise. + Debug.Assert(MetadataManager is UsageBasedMetadataManager); return _fieldsWithMetadata.GetOrAdd(field); } @@ -932,6 +942,9 @@ namespace ILCompiler.DependencyAnalysis internal ModuleMetadataNode ModuleMetadata(ModuleDesc module) { + // These are only meaningful for UsageBasedMetadataManager. We should not have them + // in the dependency graph otherwise. + Debug.Assert(MetadataManager is UsageBasedMetadataManager); return _modulesWithMetadata.GetOrAdd(module); } @@ -1016,6 +1029,8 @@ namespace ILCompiler.DependencyAnalysis "__ImportTablesTableEnd", new SortableDependencyNode.ObjectNodeComparer(new CompilerComparer())); + public InterfaceDispatchCellSectionNode InterfaceDispatchCellSection { get; } + public ReadyToRunHeaderNode ReadyToRunHeader; public Dictionary NodeAliases = new Dictionary(); @@ -1035,6 +1050,7 @@ namespace ILCompiler.DependencyAnalysis graph.AddRoot(TypeManagerIndirection, "TypeManagerIndirection is always generated"); graph.AddRoot(DispatchMapTable, "DispatchMapTable is always generated"); graph.AddRoot(FrozenSegmentRegion, "FrozenSegmentRegion is always generated"); + graph.AddRoot(InterfaceDispatchCellSection, "Interface dispatch cell section is always generated"); if (Target.IsWindows) { // We need 2 delimiter symbols to bound the unboxing stubs region on Windows platforms (these symbols are diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NonExternMethodSymbolNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NonExternMethodSymbolNode.cs index 1b09590cac..6be5e9456f 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NonExternMethodSymbolNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NonExternMethodSymbolNode.cs @@ -18,7 +18,7 @@ namespace ILCompiler.DependencyAnalysis // When full analysis is fully supported, remove this class and field forever. public static bool EnableFullAnalysis = false; } - + /// /// Represents a symbol that is defined externally but modeled as a method /// in the DependencyAnalysis infrastructure during compilation that is compiled @@ -32,9 +32,10 @@ namespace ILCompiler.DependencyAnalysis ISymbolNode[] _funcletSymbols = Array.Empty(); bool _dependenciesQueried; bool _hasCompiledBody; + private HashSet _floatingGenericLookupResults; public NonExternMethodSymbolNode(NodeFactory factory, MethodDesc method, bool isUnboxing) - : base(isUnboxing ? UnboxingStubNode.GetMangledName(factory.NameMangler, method) : + : base(isUnboxing ? UnboxingStubNode.GetMangledName(factory.NameMangler, method) : factory.NameMangler.GetMangledMethodName(method)) { _isUnboxing = isUnboxing; @@ -101,6 +102,30 @@ namespace ILCompiler.DependencyAnalysis _funcletSymbols = funclets; } + public void DeferFloatingGenericLookup(GenericLookupResult lookupResult) + { + if (_floatingGenericLookupResults == null) + _floatingGenericLookupResults = new HashSet(); + _floatingGenericLookupResults.Add(lookupResult); + } + + protected override void OnMarked(NodeFactory factory) + { + // Commit all floating generic lookups associated with the method when the method + // is proved not dead. + if (_floatingGenericLookupResults != null) + { + Debug.Assert(_method.IsCanonicalMethod(CanonicalFormKind.Any)); + TypeSystemEntity canonicalOwner = _method.HasInstantiation ? (TypeSystemEntity)_method : (TypeSystemEntity)_method.OwningType; + DictionaryLayoutNode dictLayout = factory.GenericDictionaryLayout(canonicalOwner); + + foreach (var lookupResult in _floatingGenericLookupResults) + { + dictLayout.EnsureEntry(lookupResult); + } + } + } + public void AddCompilationDiscoveredDependency(IDependencyNode node, string reason) { Debug.Assert(!_dependenciesQueried); @@ -149,6 +174,15 @@ namespace ILCompiler.DependencyAnalysis return dependencies; } + public override int ClassCode => -2124588118; + + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) + { + NonExternMethodSymbolNode otherMethod = (NonExternMethodSymbolNode)other; + var result = _isUnboxing.CompareTo(otherMethod._isUnboxing); + return result != 0 ? result : comparer.Compare(_method, otherMethod._method); + } + private class FuncletSymbol : ISymbolNodeWithFuncletId { public FuncletSymbol(NonExternMethodSymbolNode methodSymbol, int funcletId) diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NonGCStaticsNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NonGCStaticsNode.cs index dc6ade07cb..ac2115d7c5 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NonGCStaticsNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NonGCStaticsNode.cs @@ -18,7 +18,7 @@ namespace ILCompiler.DependencyAnalysis /// with the class constructor context if the type has a class constructor that /// needs to be triggered before the type members can be accessed. /// - public class NonGCStaticsNode : ObjectNode, IExportableSymbolNode, ISortableSymbolNode + public class NonGCStaticsNode : ObjectNode, IExportableSymbolNode, ISortableSymbolNode, ISymbolNodeWithDebugInfo { private MetadataType _type; private NodeFactory _factory; @@ -69,6 +69,8 @@ namespace ILCompiler.DependencyAnalysis } } + public IDebugInfo DebugInfo => NullTypeIndexDebugInfo.Instance; + public override bool IsShareable => EETypeNode.IsTypeNodeShareable(_type); public MetadataType Type => _type; @@ -178,18 +180,11 @@ namespace ILCompiler.DependencyAnalysis return builder.ToObjectData(); } - protected internal override int ClassCode => -1173104872; + public override int ClassCode => -1173104872; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_type, ((NonGCStaticsNode)other)._type); } - - int ISortableSymbolNode.ClassCode => ClassCode; - - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) - { - return CompareToImpl((ObjectNode)other, comparer); - } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectDataBuilder.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectDataBuilder.cs index b42c3e382f..29fc23f983 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectDataBuilder.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectDataBuilder.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic; using Internal.TypeSystem; -using Internal.Runtime; using Debug = System.Diagnostics.Debug; @@ -293,20 +292,6 @@ namespace ILCompiler.DependencyAnalysis EmitReloc(symbol, (_target.PointerSize == 8) ? RelocType.IMAGE_REL_BASED_DIR64 : RelocType.IMAGE_REL_BASED_HIGHLOW, delta); } - /// - /// Use this api to generate a reloc to a symbol that may be an indirection cell or not as a pointer - /// - /// symbol to reference - /// value to OR in to the reloc to represent to runtime code that this pointer is an indirection. Defaults to IndirectionConstants.IndirectionCellPointer - /// Delta from symbol start for value - public void EmitPointerRelocOrIndirectionReference(ISymbolNode symbol, int indirectionBit = IndirectionConstants.IndirectionCellPointer, int delta = 0) - { - if (symbol.RepresentsIndirectionCell) - delta |= indirectionBit; - - EmitReloc(symbol, (_target.PointerSize == 8) ? RelocType.IMAGE_REL_BASED_DIR64 : RelocType.IMAGE_REL_BASED_HIGHLOW, delta); - } - public ObjectNode.ObjectData ToObjectData() { #if DEBUG diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectNode.cs index 6dcf96ae89..21490cadc3 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectNode.cs @@ -51,16 +51,6 @@ namespace ILCompiler.DependencyAnalysis return false; } - /// - /// Return a node that is used for linkage - /// - /// - /// - public virtual ObjectNode NodeForLinkage(NodeFactory factory) - { - return this; - } - public override bool HasConditionalStaticDependencies => false; public override bool HasDynamicDependencies => false; public override bool InterestingForDynamicDependencyAnalysis => false; diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectNodeSection.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectNodeSection.cs index 86c6a31789..e9eaf77c7a 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectNodeSection.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectNodeSection.cs @@ -46,7 +46,7 @@ namespace ILCompiler.DependencyAnalysis public static readonly ObjectNodeSection XDataSection = new ObjectNodeSection("xdata", SectionType.ReadOnly); public static readonly ObjectNodeSection DataSection = new ObjectNodeSection("data", SectionType.Writeable); public static readonly ObjectNodeSection ReadOnlyDataSection = new ObjectNodeSection("rdata", SectionType.ReadOnly); - public static readonly ObjectNodeSection FoldableReadOnlyDataSection = new ObjectNodeSection("rdata$ICF", SectionType.ReadOnly); + public static readonly ObjectNodeSection FoldableReadOnlyDataSection = new ObjectNodeSection("rdata$F", SectionType.ReadOnly); public static readonly ObjectNodeSection TextSection = new ObjectNodeSection("text", SectionType.Executable); public static readonly ObjectNodeSection TLSSection = new ObjectNodeSection("TLS", SectionType.Writeable); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectWriter.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectWriter.cs index 25242c8776..4a85d860d0 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectWriter.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ObjectWriter.cs @@ -194,16 +194,6 @@ namespace ILCompiler.DependencyAnalysis private static extern int EmitSymbolRef(IntPtr objWriter, byte[] symbolName, RelocType relocType, int delta); public int EmitSymbolRef(Utf8StringBuilder symbolName, RelocType relocType, int delta = 0) { - if (_targetPlatform.Architecture != TargetArchitecture.ARMEL && _targetPlatform.Architecture != TargetArchitecture.ARM) - { - // Workaround for ObjectWriter's lack of support for IMAGE_REL_BASED_RELPTR32 - // https://github.com/dotnet/corert/issues/3278 - if (relocType == RelocType.IMAGE_REL_BASED_RELPTR32) - { - relocType = RelocType.IMAGE_REL_BASED_REL32; - delta = checked(delta + sizeof(int)); - } - } return EmitSymbolRef(_nativeObjectWriter, symbolName.Append('\0').UnderlyingArray, relocType, delta); } @@ -275,7 +265,12 @@ namespace ILCompiler.DependencyAnalysis private static extern uint GetClassTypeIndex(IntPtr objWriter, ClassTypeDescriptor classTypeDescriptor); [DllImport(NativeObjectWriterFileName)] - private static extern uint GetCompleteClassTypeIndex(IntPtr objWriter, ClassTypeDescriptor classTypeDescriptor, ClassFieldsTypeDescriptor classFieldsTypeDescriptior, DataFieldDescriptor[] fields); + private static extern uint GetCompleteClassTypeIndex(IntPtr objWriter, ClassTypeDescriptor classTypeDescriptor, + ClassFieldsTypeDescriptor classFieldsTypeDescriptior, DataFieldDescriptor[] fields, + StaticDataFieldDescriptor[] statics); + + [DllImport(NativeObjectWriterFileName)] + private static extern uint GetPrimitiveTypeIndex(IntPtr objWriter, int type); [DllImport(NativeObjectWriterFileName)] private static extern void EmitARMFnStart(IntPtr objWriter); @@ -316,9 +311,16 @@ namespace ILCompiler.DependencyAnalysis return GetClassTypeIndex(_nativeObjectWriter, classTypeDescriptor); } - public uint GetCompleteClassTypeIndex(ClassTypeDescriptor classTypeDescriptor, ClassFieldsTypeDescriptor classFieldsTypeDescriptior, DataFieldDescriptor[] fields) + public uint GetCompleteClassTypeIndex(ClassTypeDescriptor classTypeDescriptor, ClassFieldsTypeDescriptor classFieldsTypeDescriptior, + DataFieldDescriptor[] fields, StaticDataFieldDescriptor[] statics) { - return GetCompleteClassTypeIndex(_nativeObjectWriter, classTypeDescriptor, classFieldsTypeDescriptior, fields); + return GetCompleteClassTypeIndex(_nativeObjectWriter, classTypeDescriptor, classFieldsTypeDescriptior, fields, statics); + } + + public uint GetPrimitiveTypeIndex(TypeDesc type) + { + Debug.Assert(type.IsPrimitive, "it is not a primitive type"); + return GetPrimitiveTypeIndex(_nativeObjectWriter, (int)type.Category); } [DllImport(NativeObjectWriterFileName)] @@ -372,10 +374,42 @@ namespace ILCompiler.DependencyAnalysis } [DllImport(NativeObjectWriterFileName)] - private static extern void EmitDebugFunctionInfo(IntPtr objWriter, byte[] methodName, int methodSize); - public void EmitDebugFunctionInfo(int methodSize) + private static extern void EmitDebugEHClause(IntPtr objWriter, UInt32 TryOffset, UInt32 TryLength, UInt32 HandlerOffset, UInt32 HandlerLength); + + public void EmitDebugEHClause(DebugEHClauseInfo ehClause) { - EmitDebugFunctionInfo(_nativeObjectWriter, _currentNodeZeroTerminatedName.UnderlyingArray, methodSize); + EmitDebugEHClause(_nativeObjectWriter, ehClause.TryOffset, ehClause.TryLength, ehClause.HandlerOffset, ehClause.HandlerLength); + } + + public void EmitDebugEHClauseInfo(ObjectNode node) + { + var nodeWithCodeInfo = node as INodeWithCodeInfo; + if (nodeWithCodeInfo != null) + { + DebugEHClauseInfo[] clauses = nodeWithCodeInfo.DebugEHClauseInfos; + if (clauses != null) + { + foreach (var clause in clauses) + { + EmitDebugEHClause(clause); + } + } + } + } + + [DllImport(NativeObjectWriterFileName)] + private static extern void EmitDebugFunctionInfo(IntPtr objWriter, byte[] methodName, int methodSize, UInt32 methodTypeIndex); + public void EmitDebugFunctionInfo(ObjectNode node, int methodSize) + { + uint methodTypeIndex = 0; + + var methodNode = node as IMethodNode; + if (methodNode != null) + { + methodTypeIndex = _userDefinedTypeDescriptor.GetMethodFunctionIdTypeIndex(methodNode.Method); + } + + EmitDebugFunctionInfo(_nativeObjectWriter, _currentNodeZeroTerminatedName.UnderlyingArray, methodSize, methodTypeIndex); } [DllImport(NativeObjectWriterFileName)] @@ -699,12 +733,21 @@ namespace ILCompiler.DependencyAnalysis List cfis; if (_offsetToCfis.TryGetValue(offset, out cfis)) { - foreach (byte[] cfi in cfis) + if (forArm) { - if (forArm) - EmitARMExIdxCode(offset, cfi); - else + // Unwind insts are generated in the object file in the reversed order on arm, + // so we should reverse the cfi list + for (int index = cfis.Count - 1; index >= 0; index--) + { + EmitARMExIdxCode(offset, cfis[index]); + } + } + else + { + foreach (byte[] cfi in cfis) + { EmitCFICode(offset, cfi); + } } } } @@ -1113,13 +1156,9 @@ namespace ILCompiler.DependencyAnalysis if (objectWriter.HasFunctionDebugInfo()) { - if (factory.Target.OperatingSystem == TargetOS.Windows) - { - // Build debug local var info. - // It currently supports only Windows CodeView format. - objectWriter.EmitDebugVarInfo(node); - } - objectWriter.EmitDebugFunctionInfo(nodeContents.Data.Length); + objectWriter.EmitDebugVarInfo(node); + objectWriter.EmitDebugEHClauseInfo(node); + objectWriter.EmitDebugFunctionInfo(node, nodeContents.Data.Length); } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/PInvokeMethodFixupNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/PInvokeMethodFixupNode.cs index 797032e3eb..c7707b23a8 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/PInvokeMethodFixupNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/PInvokeMethodFixupNode.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Runtime.InteropServices; using Internal.Text; using Internal.TypeSystem; @@ -16,11 +17,13 @@ namespace ILCompiler.DependencyAnalysis { private string _moduleName; private string _entryPointName; + private PInvokeFlags _flags; - public PInvokeMethodFixupNode(string moduleName, string entryPointName) + public PInvokeMethodFixupNode(string moduleName, string entryPointName, PInvokeFlags flags) { _moduleName = moduleName; _entryPointName = entryPointName; + _flags = flags; } public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) @@ -29,6 +32,13 @@ namespace ILCompiler.DependencyAnalysis sb.Append(_moduleName); sb.Append("__"); sb.Append(_entryPointName); + if(!_flags.ExactSpelling) + { + sb.Append("__"); + sb.Append(_flags.CharSet.ToString()); + } + sb.Append("__"); + sb.Append(((int)_flags.Attributes).ToString()); } public int Offset => 0; public override bool IsShareable => true; @@ -72,16 +82,22 @@ namespace ILCompiler.DependencyAnalysis // Module fixup cell builder.EmitPointerReloc(factory.PInvokeModuleFixup(_moduleName)); + builder.EmitInt(_flags.ExactSpelling ? 0 : (int)_flags.CharSet); + return builder.ToObjectData(); } - protected internal override int ClassCode => -1592006940; + public override int ClassCode => -1592006940; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { - var compare = string.Compare(_moduleName, ((PInvokeMethodFixupNode)other)._moduleName); - if (compare != 0) - return compare; + var flagsCompare = _flags.CompareTo(((PInvokeMethodFixupNode)other)._flags); + if (flagsCompare != 0) + return flagsCompare; + + var moduleCompare = string.Compare(_moduleName, ((PInvokeMethodFixupNode)other)._moduleName); + if (moduleCompare != 0) + return moduleCompare; return string.Compare(_entryPointName, ((PInvokeMethodFixupNode)other)._entryPointName); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/PInvokeModuleFixupNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/PInvokeModuleFixupNode.cs index bf83f13b1b..784f791baa 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/PInvokeModuleFixupNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/PInvokeModuleFixupNode.cs @@ -50,9 +50,9 @@ namespace ILCompiler.DependencyAnalysis return builder.ToObjectData(); } - protected internal override int ClassCode => 159930099; + public override int ClassCode => 159930099; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return string.Compare(_moduleName, ((PInvokeModuleFixupNode)other)._moduleName); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReadyToRunGenericHelperNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReadyToRunGenericHelperNode.cs index ddd1479b27..f68ccbf0a5 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReadyToRunGenericHelperNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReadyToRunGenericHelperNode.cs @@ -63,6 +63,8 @@ namespace ILCompiler.DependencyAnalysis } } + protected override bool IsVisibleFromManagedCode => false; + protected sealed override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); public override bool IsShareable => true; @@ -206,7 +208,7 @@ namespace ILCompiler.DependencyAnalysis return conditionalDependencies; } - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { var compare = _id.CompareTo(((ReadyToRunGenericHelperNode)other)._id); if (compare != 0) @@ -272,7 +274,7 @@ namespace ILCompiler.DependencyAnalysis AppendLookupSignatureMangledName(nameMangler, sb); } - protected internal override int ClassCode => 1055354299; + public override int ClassCode => 1055354299; } public partial class ReadyToRunGenericLookupFromTypeNode : ReadyToRunGenericHelperNode @@ -294,6 +296,6 @@ namespace ILCompiler.DependencyAnalysis AppendLookupSignatureMangledName(nameMangler, sb); } - protected internal override int ClassCode => 913214059; + public override int ClassCode => 913214059; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReadyToRunHeaderNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReadyToRunHeaderNode.cs index 6c2fd6d735..fa8e6ed265 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReadyToRunHeaderNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReadyToRunHeaderNode.cs @@ -128,6 +128,6 @@ namespace ILCompiler.DependencyAnalysis return builder.ToObjectData(); } - protected internal override int ClassCode => -534800244; + public override int ClassCode => -534800244; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReadyToRunHelperNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReadyToRunHelperNode.cs index 7b941ec850..76f4785a41 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReadyToRunHelperNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReadyToRunHelperNode.cs @@ -80,16 +80,24 @@ namespace ILCompiler.DependencyAnalysis } break; case ReadyToRunHelperId.VirtualCall: + case ReadyToRunHelperId.ResolveVirtualFunction: { // Make sure we aren't trying to callvirt Object.Finalize MethodDesc method = (MethodDesc)target; if (method.IsFinalizer) ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramCallVirtFinalize, method); + + // Method should be in fully canonical form. Otherwise we're being wasteful and generate more + // helpers than needed. + Debug.Assert(!method.IsCanonicalMethod(CanonicalFormKind.Any) || + method.GetCanonMethodTarget(CanonicalFormKind.Specific) == method); } break; } } + protected override bool IsVisibleFromManagedCode => false; + protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); public ReadyToRunHelperId Id => _id; @@ -221,9 +229,9 @@ namespace ILCompiler.DependencyAnalysis } #if !SUPPORT_JIT - protected internal override int ClassCode => -911637948; + public override int ClassCode => -911637948; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { var compare = _id.CompareTo(((ReadyToRunHelperNode)other)._id); if (compare != 0) diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReflectionFieldMapNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReflectionFieldMapNode.cs index 93bf599792..7c062d0687 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReflectionFieldMapNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReflectionFieldMapNode.cs @@ -187,6 +187,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.ReflectionFieldMapNode; + public override int ClassCode => (int)ObjectNodeOrder.ReflectionFieldMapNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReflectionInvokeMapNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReflectionInvokeMapNode.cs index 73a95d2e5d..2304902a55 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReflectionInvokeMapNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReflectionInvokeMapNode.cs @@ -189,6 +189,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.ReflectionInvokeMapNode; + public override int ClassCode => (int)ObjectNodeOrder.ReflectionInvokeMapNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReflectionVirtualInvokeMapNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReflectionVirtualInvokeMapNode.cs index 2b5f45090e..0b256dbf1e 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReflectionVirtualInvokeMapNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ReflectionVirtualInvokeMapNode.cs @@ -218,7 +218,7 @@ namespace ILCompiler.DependencyAnalysis else { // Get the declaring method for slot on the instantiated declaring type - int slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, declaringMethodForSlot, factory.Target.Abi != TargetAbi.ProjectN); + int slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, declaringMethodForSlot, declaringMethodForSlot.OwningType, factory.Target.Abi != TargetAbi.ProjectN); Debug.Assert(slot != -1); vertex = writer.GetTuple( @@ -242,6 +242,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.ReflectionVirtualInvokeMapNode; + public override int ClassCode => (int)ObjectNodeOrder.ReflectionVirtualInvokeMapNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ResourceDataNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ResourceDataNode.cs index cc9dd6a2ce..b425283deb 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ResourceDataNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ResourceDataNode.cs @@ -98,6 +98,11 @@ namespace ILCompiler.DependencyAnalysis } string resourceName = module.MetadataReader.GetString(resource.Name); + + // Check if emitting the manifest resource is blocked by policy. + if (factory.MetadataManager.IsManifestResourceBlocked(module, resourceName)) + continue; + string assemblyName = module.GetName().FullName; BlobReader reader = resourceDirectory.GetReader((int)resource.Offset, resourceDirectory.Length - (int)resource.Offset); int length = (int)reader.ReadUInt32(); @@ -143,7 +148,7 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.ResourceDataNode; + public override int ClassCode => (int)ObjectNodeOrder.ResourceDataNode; } /// diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ResourceIndexNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ResourceIndexNode.cs index 4ad4a3b897..bd1243f4a1 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ResourceIndexNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ResourceIndexNode.cs @@ -97,6 +97,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.ResourceIndexNode; + public override int ClassCode => (int)ObjectNodeOrder.ResourceIndexNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeDecodableJumpStub.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeDecodableJumpStub.cs index d4d8e06ffd..1fba7e459e 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeDecodableJumpStub.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeDecodableJumpStub.cs @@ -50,18 +50,11 @@ namespace ILCompiler.DependencyAnalysis protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); - protected internal override int ClassCode => 532434339; + public override int ClassCode => 532434339; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(WrappedMethodIndirectionCellNode, ((RuntimeDecodableJumpStubNode)other).WrappedMethodIndirectionCellNode); } - - int ISortableSymbolNode.ClassCode => ClassCode; - - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) - { - return CompareToImpl((ObjectNode)other, comparer); - } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeDeterminedMethodNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeDeterminedMethodNode.cs index d3a3672eaf..e9ac8a8d7e 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeDeterminedMethodNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeDeterminedMethodNode.cs @@ -62,9 +62,9 @@ namespace ILCompiler.DependencyAnalysis public override IEnumerable SearchDynamicDependencies(List> markedNodes, int firstNode, NodeFactory factory) => null; public override IEnumerable GetConditionalStaticDependencies(NodeFactory factory) => null; - int ISortableSymbolNode.ClassCode => 258139501; + int ISortableNode.ClassCode => 258139501; - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) + int ISortableNode.CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_canonicalMethodNode, ((RuntimeDeterminedMethodNode)other)._canonicalMethodNode); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeFieldHandleNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeFieldHandleNode.cs index 57a4018fd8..c5eaeddfe9 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeFieldHandleNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeFieldHandleNode.cs @@ -29,10 +29,20 @@ namespace ILCompiler.DependencyAnalysis } public int Offset => 0; protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); - public override ObjectNodeSection Section => ObjectNodeSection.ReadOnlyDataSection; public override bool IsShareable => false; public override bool StaticDependenciesAreComputed => true; + public override ObjectNodeSection Section + { + get + { + if (_targetField.Context.Target.IsWindows) + return ObjectNodeSection.ReadOnlyDataSection; + else + return ObjectNodeSection.DataSection; + } + } + private static Utf8String s_NativeLayoutSignaturePrefix = new Utf8String("__RFHSignature_"); protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFactory factory) @@ -55,9 +65,9 @@ namespace ILCompiler.DependencyAnalysis return objData.ToObjectData(); } - protected internal override int ClassCode => -1326215725; + public override int ClassCode => -1326215725; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_targetField, ((RuntimeFieldHandleNode)other)._targetField); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeImportMethodNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeImportMethodNode.cs index 909edfae4e..796ffce389 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeImportMethodNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeImportMethodNode.cs @@ -10,7 +10,7 @@ namespace ILCompiler.DependencyAnalysis /// /// Represents a method that is imported from the runtime library. /// - public class RuntimeImportMethodNode : ExternSymbolNode, IMethodNode + public class RuntimeImportMethodNode : ExternSymbolNode, IMethodNode, IExportableSymbolNode { private MethodDesc _method; @@ -27,5 +27,27 @@ namespace ILCompiler.DependencyAnalysis return _method; } } + + public ExportForm GetExportForm(NodeFactory factory) + { + // Force non-fake exports for RuntimeImportMethods that have '*' as their module. ('*' means the method is + // REALLY a reference to the linked in native code) + if (((EcmaMethod)_method).GetRuntimeImportDllName() == "*") + { + ExportForm exportForm = factory.CompilationModuleGroup.GetExportMethodForm(_method, false); + if (exportForm == ExportForm.ByName) + return ExportForm.None; // Method symbols exported by name are naturally handled by the linker + return exportForm; + } + + return ExportForm.None; + } + + public override int ClassCode => -1173492615; + + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) + { + return comparer.Compare(_method, ((RuntimeImportMethodNode)other)._method); + } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeMethodHandleNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeMethodHandleNode.cs index c40987f3cc..39884096ac 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeMethodHandleNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RuntimeMethodHandleNode.cs @@ -35,10 +35,20 @@ namespace ILCompiler.DependencyAnalysis } public int Offset => 0; protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); - public override ObjectNodeSection Section => ObjectNodeSection.ReadOnlyDataSection; public override bool IsShareable => false; public override bool StaticDependenciesAreComputed => true; + public override ObjectNodeSection Section + { + get + { + if (_targetMethod.Context.Target.IsWindows) + return ObjectNodeSection.ReadOnlyDataSection; + else + return ObjectNodeSection.DataSection; + } + } + protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFactory factory) { DependencyList dependencies = null; @@ -70,9 +80,9 @@ namespace ILCompiler.DependencyAnalysis return objData.ToObjectData(); } - protected internal override int ClassCode => -274400625; + public override int ClassCode => -274400625; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_targetMethod, ((RuntimeMethodHandleNode)other)._targetMethod); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs index cce88f8108..1db0a59484 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs @@ -60,7 +60,7 @@ namespace ILCompiler.DependencyAnalysis // 'this' and also provides an instantiation argument (we do a calling convention conversion). // We don't do this for generic instance methods though because they don't use the EEType // for the generic context anyway. - return new MethodCodeNode(TypeSystemContext.GetSpecialUnboxingThunk(method, CompilationModuleGroup.GeneratedAssembly)); + return new MethodCodeNode(TypeSystemContext.GetSpecialUnboxingThunk(method, TypeSystemContext.GeneratedAssembly)); } else { diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ScannedMethodNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ScannedMethodNode.cs index 43d27c3443..4dfd012668 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ScannedMethodNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ScannedMethodNode.cs @@ -63,9 +63,9 @@ namespace ILCompiler.DependencyAnalysis public override bool HasDynamicDependencies => false; public override bool HasConditionalStaticDependencies => false; - int ISortableSymbolNode.ClassCode => -1381809560; + int ISortableNode.ClassCode => -1381809560; - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) + int ISortableNode.CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(Method, ((ScannedMethodNode)other).Method); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SealedVTableNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SealedVTableNode.cs new file mode 100644 index 0000000000..dac6d8dbc8 --- /dev/null +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SealedVTableNode.cs @@ -0,0 +1,170 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + + +using System; +using System.Collections.Generic; +using System.Diagnostics; + +using Internal.Text; +using Internal.TypeSystem; + +namespace ILCompiler.DependencyAnalysis +{ + public class SealedVTableNode : ObjectNode, ISymbolDefinitionNode + { + private readonly TypeDesc _type; + private List _sealedVTableEntries; + + public SealedVTableNode(TypeDesc type) + { + // Multidimensional arrays should not get a sealed vtable or a dispatch map. Runtime should use the + // sealed vtable and dispatch map of the System.Array basetype instead. + // Pointer arrays also follow the same path + Debug.Assert(!type.IsArrayTypeWithoutGenericInterfaces()); + Debug.Assert(!type.IsRuntimeDeterminedSubtype); + + _type = type; + } + + protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); + + public override ObjectNodeSection Section => _type.Context.Target.IsWindows ? ObjectNodeSection.FoldableReadOnlyDataSection : ObjectNodeSection.DataSection; + + public virtual void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) + { + sb.Append(nameMangler.CompilationUnitPrefix + "__SealedVTable_" + nameMangler.NodeMangler.EEType(_type)); + } + + int ISymbolNode.Offset => 0; + int ISymbolDefinitionNode.Offset => 0; + public override bool IsShareable => EETypeNode.IsTypeNodeShareable(_type); + public override bool StaticDependenciesAreComputed => true; + + /// + /// Returns the number of sealed vtable slots on the type. This API should only be called after successfully + /// building the sealed vtable slots. + /// + public int NumSealedVTableEntries + { + get + { + if (_sealedVTableEntries == null) + throw new NotSupportedException(); + + return _sealedVTableEntries.Count; + } + } + + /// + /// Returns the slot of a method in the sealed vtable, or -1 if not found. This API should only be called after + /// successfully building the sealed vtable slots. + /// + public int ComputeSealedVTableSlot(MethodDesc method) + { + if (_sealedVTableEntries == null) + throw new NotSupportedException(); + + for (int i = 0; i < _sealedVTableEntries.Count; i++) + { + if (_sealedVTableEntries[i] == method) + return i; + } + + return -1; + } + + public bool BuildSealedVTableSlots(NodeFactory factory, bool relocsOnly) + { + // Sealed vtable already built + if (_sealedVTableEntries != null) + return true; + + TypeDesc declType = _type.GetClosestDefType(); + + // It's only okay to touch the actual list of slots if we're in the final emission phase + // or the vtable is not built lazily. + if (relocsOnly && !factory.VTable(declType).HasFixedSlots) + return false; + + _sealedVTableEntries = new List(); + + IReadOnlyList virtualSlots = factory.VTable(declType).Slots; + + for (int i = 0; i < virtualSlots.Count; i++) + { + MethodDesc implMethod = declType.FindVirtualFunctionTargetMethodOnObjectType(virtualSlots[i]); + + if (implMethod.CanMethodBeInSealedVTable()) + _sealedVTableEntries.Add(implMethod); + } + + // Catch any runtime interface collapsing. We shouldn't have any + Debug.Assert(declType.RuntimeInterfaces.Length == declType.GetTypeDefinition().RuntimeInterfaces.Length); + + for (int interfaceIndex = 0; interfaceIndex < declType.RuntimeInterfaces.Length; interfaceIndex++) + { + var interfaceType = declType.RuntimeInterfaces[interfaceIndex]; + var interfaceDefinitionType = declType.GetTypeDefinition().RuntimeInterfaces[interfaceIndex]; + + virtualSlots = factory.VTable(interfaceType).Slots; + + for (int interfaceMethodSlot = 0; interfaceMethodSlot < virtualSlots.Count; interfaceMethodSlot++) + { + MethodDesc declMethod = virtualSlots[interfaceMethodSlot]; + if (!interfaceType.IsTypeDefinition) + declMethod = factory.TypeSystemContext.GetMethodForInstantiatedType(declMethod.GetTypicalMethodDefinition(), (InstantiatedType)interfaceDefinitionType); + + var implMethod = declType.GetTypeDefinition().ResolveInterfaceMethodToVirtualMethodOnType(declMethod); + + // Interface methods first implemented by a base type in the hierarchy will return null for the implMethod (runtime interface + // dispatch will walk the inheritance chain). + if (implMethod != null && implMethod.CanMethodBeInSealedVTable() && !implMethod.OwningType.HasSameTypeDefinition(declType)) + { + TypeDesc implType = declType; + while (!implType.HasSameTypeDefinition(implMethod.OwningType)) + implType = implType.BaseType; + + MethodDesc targetMethod = implMethod; + if (!implType.IsTypeDefinition) + targetMethod = factory.TypeSystemContext.GetMethodForInstantiatedType(implMethod.GetTypicalMethodDefinition(), (InstantiatedType)implType); + + _sealedVTableEntries.Add(targetMethod); + } + } + } + + return true; + } + + public override ObjectData GetData(NodeFactory factory, bool relocsOnly) + { + ObjectDataBuilder objData = new ObjectDataBuilder(factory, relocsOnly); + objData.RequireInitialAlignment(4); + objData.AddSymbol(this); + + if (BuildSealedVTableSlots(factory, relocsOnly)) + { + for (int i = 0; i < _sealedVTableEntries.Count; i++) + { + MethodDesc canonImplMethod = _sealedVTableEntries[i].GetCanonMethodTarget(CanonicalFormKind.Specific); + IMethodNode relocTarget = factory.MethodEntrypoint(canonImplMethod, _sealedVTableEntries[i].OwningType.IsValueType); + + if (factory.Target.SupportsRelativePointers) + objData.EmitReloc(relocTarget, RelocType.IMAGE_REL_BASED_RELPTR32); + else + objData.EmitPointerReloc(relocTarget); + } + } + + return objData.ToObjectData(); + } + + public override int ClassCode => 1632890252; + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) + { + return comparer.Compare(_type, ((SealedVTableNode)other)._type); + } + } +} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ShadowConcreteMethodNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ShadowConcreteMethodNode.cs index 40d7cc978a..5f1eef5b8b 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ShadowConcreteMethodNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ShadowConcreteMethodNode.cs @@ -20,7 +20,7 @@ namespace ILCompiler.DependencyAnalysis /// method body, as if it was generated. The node acts as a symbol for the canonical /// method for convenience. /// - public class ShadowConcreteMethodNode : DependencyNodeCore, IMethodNode + public class ShadowConcreteMethodNode : DependencyNodeCore, IMethodNode, ISymbolNodeWithLinkage { /// /// Gets the canonical method body that defines the dependencies of this node. @@ -53,6 +53,11 @@ namespace ILCompiler.DependencyAnalysis CanonicalMethodNode = canonicalMethod; } + public ISymbolNode NodeForLinkage(NodeFactory factory) + { + return CanonicalMethodNode; + } + public override IEnumerable GetStaticDependencies(NodeFactory factory) { DependencyList dependencies = new DependencyList(); @@ -99,9 +104,9 @@ namespace ILCompiler.DependencyAnalysis public sealed override IEnumerable SearchDynamicDependencies(List> markedNodes, int firstNode, NodeFactory factory) => null; public sealed override IEnumerable GetConditionalStaticDependencies(NodeFactory factory) => null; - int ISortableSymbolNode.ClassCode => -1440570971; + int ISortableNode.ClassCode => -1440570971; - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) + int ISortableNode.CompareToImpl(ISortableNode other, CompilerComparer comparer) { var compare = comparer.Compare(Method, ((ShadowConcreteMethodNode)other).Method); if (compare != 0) diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ShadowConcreteUnboxingThunkNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ShadowConcreteUnboxingThunkNode.cs index fe973fdb3e..9a1dae9172 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ShadowConcreteUnboxingThunkNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ShadowConcreteUnboxingThunkNode.cs @@ -70,9 +70,9 @@ namespace ILCompiler.DependencyAnalysis public sealed override IEnumerable SearchDynamicDependencies(List> markedNodes, int firstNode, NodeFactory factory) => null; public sealed override IEnumerable GetConditionalStaticDependencies(NodeFactory factory) => null; - int ISortableSymbolNode.ClassCode => -501699818; + int ISortableNode.ClassCode => -501699818; - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) + int ISortableNode.CompareToImpl(ISortableNode other, CompilerComparer comparer) { var compare = comparer.Compare(Method, ((ShadowConcreteUnboxingThunkNode)other).Method); if (compare != 0) diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SortableDependencyNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SortableDependencyNode.cs index 521a5bf459..f65c5b602a 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SortableDependencyNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SortableDependencyNode.cs @@ -12,7 +12,7 @@ using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { - public abstract class SortableDependencyNode : DependencyNodeCore + public abstract class SortableDependencyNode : DependencyNodeCore, ISortableNode { #if !SUPPORT_JIT /// @@ -29,10 +29,10 @@ namespace ILCompiler.DependencyAnalysis /// This is really just a number, ideally produced by "new Random().Next(int.MinValue, int.MaxValue)". /// If two manage to conflict (which is pretty unlikely), just make a new one... /// - protected internal abstract int ClassCode { get; } - + public abstract int ClassCode { get; } + // Note to implementers: the type of `other` is actually the same as the type of `this`. - protected internal virtual int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public virtual int CompareToImpl(ISortableNode other, CompilerComparer comparer) { throw new NotImplementedException("Multiple nodes of this type are not supported"); } @@ -75,12 +75,18 @@ namespace ILCompiler.DependencyAnalysis BlockReflectionTypeMapNode, StaticsInfoHashtableNode, ReflectionVirtualInvokeMapNode, - ExternalReferencesTableNode, ArrayOfEmbeddedPointersNode, DefaultConstructorMapNode, + ExternalReferencesTableNode, StackTraceEmbeddedMetadataNode, StackTraceMethodMappingNode, - ArrayOfEmbeddedDataNode + ArrayOfEmbeddedDataNode, + WindowsDebugNeedTypeIndicesStoreNode, + WindowsDebugMethodSignatureMapSectionNode, + WindowsDebugTypeSignatureMapSectionNode, + WindowsDebugManagedNativeDictionaryInfoSectionNode, + WindowsDebugTypeRecordsSectionNode, + WindowsDebugPseudoAssemblySectionNode, } public class EmbeddedObjectNodeComparer : IComparer @@ -159,7 +165,7 @@ namespace ILCompiler.DependencyAnalysis else { Debug.Assert(x.GetType() != y.GetType()); - return codeX - codeY; + return codeY > codeX ? -1 : 1; } } else diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StackTraceEmbeddedMetadataNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StackTraceEmbeddedMetadataNode.cs index b1ab09a295..39c62fcb08 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StackTraceEmbeddedMetadataNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StackTraceEmbeddedMetadataNode.cs @@ -38,7 +38,7 @@ namespace ILCompiler.DependencyAnalysis public int Offset => 0; protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.StackTraceEmbeddedMetadataNode; + public override int ClassCode => (int)ObjectNodeOrder.StackTraceEmbeddedMetadataNode; public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StackTraceMethodMappingNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StackTraceMethodMappingNode.cs index de12c6f923..d9c13b19cd 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StackTraceMethodMappingNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StackTraceMethodMappingNode.cs @@ -31,7 +31,7 @@ namespace ILCompiler.DependencyAnalysis public int Offset => 0; protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.StackTraceMethodMappingNode; + public override int ClassCode => (int)ObjectNodeOrder.StackTraceMethodMappingNode; public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StaticsInfoHashtableNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StaticsInfoHashtableNode.cs index 14b81d92ed..d1ea7d3d4a 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StaticsInfoHashtableNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StaticsInfoHashtableNode.cs @@ -70,7 +70,7 @@ namespace ILCompiler.DependencyAnalysis dependencies.Add(factory.Indirection(factory.TypeNonGCStaticsSymbol(metadataType)), "Non-GC statics indirection for StaticsInfoHashtable"); } - if (metadataType.ThreadStaticFieldSize.AsInt > 0) + if (metadataType.ThreadGcStaticFieldSize.AsInt > 0) { if (factory.Target.Abi == TargetAbi.ProjectN) { @@ -116,7 +116,7 @@ namespace ILCompiler.DependencyAnalysis ISymbolNode nonGCStaticIndirection = factory.Indirection(factory.TypeNonGCStaticsSymbol(metadataType)); bag.AppendUnsigned(BagElementKind.NonGcStaticData, _nativeStaticsReferences.GetIndex(nonGCStaticIndirection)); } - if (metadataType.ThreadStaticFieldSize.AsInt > 0) + if (metadataType.ThreadGcStaticFieldSize.AsInt > 0) { if (factory.Target.Abi == TargetAbi.ProjectN) { @@ -148,6 +148,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.StaticsInfoHashtableNode; + public override int ClassCode => (int)ObjectNodeOrder.StaticsInfoHashtableNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StringAllocatorMethodNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StringAllocatorMethodNode.cs index fe9528040a..4e68d5536e 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StringAllocatorMethodNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StringAllocatorMethodNode.cs @@ -73,9 +73,9 @@ namespace ILCompiler.DependencyAnalysis protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); - int ISortableSymbolNode.ClassCode => 1991750873; + int ISortableNode.ClassCode => 1991750873; - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) + int ISortableNode.CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_allocationMethod, ((StringAllocatorMethodNode)other)._allocationMethod); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StructMarshallingStubMapNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StructMarshallingStubMapNode.cs index 604e250760..d4d5664fd0 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StructMarshallingStubMapNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/StructMarshallingStubMapNode.cs @@ -71,7 +71,7 @@ namespace ILCompiler.DependencyAnalysis writer.GetUnsignedConstant(_externalReferences.GetIndex(factory.MethodEntrypoint(structEntry.UnmarshallingThunk))), writer.GetUnsignedConstant(_externalReferences.GetIndex(factory.MethodEntrypoint(structEntry.CleanupThunk)))); - uint size = (uint)nativeType.InstanceByteCount.AsInt; + uint size = (uint)nativeType.InstanceFieldSize.AsInt; uint mask = (uint)(nativeType.Fields.Length << 1) | (uint)(nativeType.HasInvalidLayout ? 1 : 0); Vertex data = writer.GetTuple( @@ -106,6 +106,6 @@ namespace ILCompiler.DependencyAnalysis } protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.StructMarshallingStubMapNode; + public override int ClassCode => (int)ObjectNodeOrder.StructMarshallingStubMapNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_ARM/ARMDebug.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_ARM/ARMDebug.cs index 0a1cd06391..b0d8ab2eea 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_ARM/ARMDebug.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_ARM/ARMDebug.cs @@ -9,6 +9,7 @@ namespace ILCompiler.DependencyAnalysis { public static class ARMDebug { + [System.Diagnostics.Conditional("DEBUG")] public static void EmitNYIAssert(NodeFactory factory, ref ARMEmitter encoder, string message, [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = null, [System.Runtime.CompilerServices.CallerMemberName] string memberName = null, @@ -21,6 +22,7 @@ namespace ILCompiler.DependencyAnalysis encoder.EmitJMP(NYI_Assert); } + [System.Diagnostics.Conditional("DEBUG")] public static void EmitHelperNYIAssert(NodeFactory factory, ref ARMEmitter encoder, ReadyToRunHelperId hId, [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = null, [System.Runtime.CompilerServices.CallerMemberName] string memberName = null, diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_ARM/ARMInitialInterfaceDispatchStubNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_ARM/ARMInitialInterfaceDispatchStubNode.cs index 1c201ebe35..7e1793acfd 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_ARM/ARMInitialInterfaceDispatchStubNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_ARM/ARMInitialInterfaceDispatchStubNode.cs @@ -52,6 +52,6 @@ namespace ILCompiler.DependencyAnalysis throw new NotImplementedException(); } - protected internal override int ClassCode => 588185132; + public override int ClassCode => 588185132; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_ARM/ARMReadyToRunHelperNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_ARM/ARMReadyToRunHelperNode.cs index d4bf28b316..a05365715d 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_ARM/ARMReadyToRunHelperNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_ARM/ARMReadyToRunHelperNode.cs @@ -33,13 +33,14 @@ namespace ILCompiler.DependencyAnalysis MethodDesc targetMethod = (MethodDesc)Target; Debug.Assert(!targetMethod.OwningType.IsInterface); + Debug.Assert(!targetMethod.CanMethodBeInSealedVTable()); int pointerSize = factory.Target.PointerSize; int slot = 0; if (!relocsOnly) { - slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod); + slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod, targetMethod.OwningType); Debug.Assert(slot != -1); } @@ -162,11 +163,13 @@ namespace ILCompiler.DependencyAnalysis if (target.TargetNeedsVTableLookup) { + Debug.Assert(!target.TargetMethod.CanMethodBeInSealedVTable()); + encoder.EmitLDR(encoder.TargetRegister.Arg2, encoder.TargetRegister.Arg1); int slot = 0; if (!relocsOnly) - slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, target.TargetMethod); + slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, target.TargetMethod, target.TargetMethod.OwningType); Debug.Assert(slot != -1); encoder.EmitLDR(encoder.TargetRegister.Arg2, encoder.TargetRegister.Arg2, @@ -212,7 +215,9 @@ namespace ILCompiler.DependencyAnalysis encoder.EmitLDR(encoder.TargetRegister.Result, encoder.TargetRegister.Arg0); - int slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod); + Debug.Assert(!targetMethod.CanMethodBeInSealedVTable()); + + int slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod, targetMethod.OwningType); Debug.Assert(slot != -1); encoder.EmitLDR(encoder.TargetRegister.Result, encoder.TargetRegister.Result, ((short)(EETypeNode.GetVTableOffset(factory.Target.PointerSize) + (slot * factory.Target.PointerSize)))); diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_X64/X64Emitter.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_X64/X64Emitter.cs index 09ebadeaad..662867f99e 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_X64/X64Emitter.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_X64/X64Emitter.cs @@ -88,6 +88,20 @@ namespace ILCompiler.DependencyAnalysis.X64 } } + public void EmitJE(ISymbolNode symbol) + { + if (symbol.RepresentsIndirectionCell) + { + throw new NotImplementedException(); + } + else + { + Builder.EmitByte(0x0f); + Builder.EmitByte(0x84); + Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32); + } + } + public void EmitINT3() { Builder.EmitByte(0xCC); diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_X64/X64ReadyToRunHelperNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_X64/X64ReadyToRunHelperNode.cs index 614c171e62..dbe8319c8e 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_X64/X64ReadyToRunHelperNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/Target_X64/X64ReadyToRunHelperNode.cs @@ -32,6 +32,7 @@ namespace ILCompiler.DependencyAnalysis MethodDesc targetMethod = (MethodDesc)Target; Debug.Assert(!targetMethod.OwningType.IsInterface); + Debug.Assert(!targetMethod.CanMethodBeInSealedVTable()); AddrMode loadFromThisPtr = new AddrMode(encoder.TargetRegister.Arg0, null, 0, 0, AddrModeSize.Int64); encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromThisPtr); @@ -41,7 +42,7 @@ namespace ILCompiler.DependencyAnalysis int slot = 0; if (!relocsOnly) { - slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod); + slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod, targetMethod.OwningType); Debug.Assert(slot != -1); } Debug.Assert(((INodeWithDebugInfo)this).DebugLocInfos[1].NativeOffset == encoder.Builder.CountBytes); @@ -126,7 +127,11 @@ namespace ILCompiler.DependencyAnalysis else { encoder.EmitLEAQ(encoder.TargetRegister.Arg2, factory.TypeNonGCStaticsSymbol(target), - NonGCStaticsNode.GetClassConstructorContextStorageSize(factory.Target, target)); - // TODO: performance optimization - inline the check verifying whether we need to trigger the cctor + + AddrMode initialized = new AddrMode(encoder.TargetRegister.Arg2, null, factory.Target.PointerSize, 0, AddrModeSize.Int32); + encoder.EmitCMP(ref initialized, 1); + encoder.EmitJE(factory.HelperEntrypoint(HelperEntrypoint.GetThreadStaticBaseForType)); + encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnThreadStaticBase)); } } @@ -167,12 +172,14 @@ namespace ILCompiler.DependencyAnalysis if (target.TargetNeedsVTableLookup) { + Debug.Assert(!target.TargetMethod.CanMethodBeInSealedVTable()); + AddrMode loadFromThisPtr = new AddrMode(encoder.TargetRegister.Arg1, null, 0, 0, AddrModeSize.Int64); encoder.EmitMOV(encoder.TargetRegister.Arg2, ref loadFromThisPtr); int slot = 0; if (!relocsOnly) - slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, target.TargetMethod); + slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, target.TargetMethod, target.TargetMethod.OwningType); Debug.Assert(slot != -1); AddrMode loadFromSlot = new AddrMode(encoder.TargetRegister.Arg2, null, EETypeNode.GetVTableOffset(factory.Target.PointerSize) + (slot * factory.Target.PointerSize), 0, AddrModeSize.Int64); @@ -214,7 +221,9 @@ namespace ILCompiler.DependencyAnalysis AddrMode loadFromThisPtr = new AddrMode(encoder.TargetRegister.Arg0, null, 0, 0, AddrModeSize.Int64); encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromThisPtr); - int slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod); + Debug.Assert(!targetMethod.CanMethodBeInSealedVTable()); + + int slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod, targetMethod.OwningType); Debug.Assert(slot != -1); AddrMode loadFromSlot = new AddrMode(encoder.TargetRegister.Result, null, EETypeNode.GetVTableOffset(factory.Target.PointerSize) + (slot * factory.Target.PointerSize), 0, AddrModeSize.Int64); encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromSlot); diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ThreadStaticsIndexNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ThreadStaticsIndexNode.cs index f350c2cfba..fbfe07f9ea 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ThreadStaticsIndexNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ThreadStaticsIndexNode.cs @@ -82,19 +82,12 @@ namespace ILCompiler.DependencyAnalysis return objData.ToObjectData(); } - protected internal override int ClassCode => -968500265; + public override int ClassCode => -968500265; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return string.Compare(_prefix, ((ThreadStaticsIndexNode)other)._prefix); } - - int ISortableSymbolNode.ClassCode => ClassCode; - - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) - { - return CompareToImpl((ObjectNode)other, comparer); - } } // The data structure used by the OS loader to load TLS chunks. @@ -182,9 +175,9 @@ namespace ILCompiler.DependencyAnalysis return objData.ToObjectData(); } - protected internal override int ClassCode => -754150753; + public override int ClassCode => -754150753; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return string.Compare(_prefix, ((ThreadStaticsDirectoryNode)other)._prefix); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ThreadStaticsNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ThreadStaticsNode.cs index 357dde0fe9..80c497e2c2 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ThreadStaticsNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ThreadStaticsNode.cs @@ -20,7 +20,7 @@ namespace ILCompiler.DependencyAnalysis public ThreadStaticsNode(MetadataType type, NodeFactory factory) { - Debug.Assert(factory.Target.Abi == TargetAbi.CoreRT); + Debug.Assert(factory.Target.Abi == TargetAbi.CoreRT || factory.Target.Abi == TargetAbi.CppCodegen); _type = type; } @@ -76,9 +76,9 @@ namespace ILCompiler.DependencyAnalysis builder.EmitPointerReloc(GetGCStaticEETypeNode(factory)); } - protected internal override int ClassCode => 2091208431; + public override int ClassCode => 2091208431; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_type, ((ThreadStaticsNode)other)._type); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ThreadStaticsOffsetNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ThreadStaticsOffsetNode.cs index 096ebe98aa..5eb2f7525b 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ThreadStaticsOffsetNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ThreadStaticsOffsetNode.cs @@ -74,18 +74,11 @@ namespace ILCompiler.DependencyAnalysis builder.EmitReloc(factory.TypeThreadStaticsSymbol(_type), RelocType.IMAGE_REL_SECREL); } - protected internal override int ClassCode => 419394032; + public sealed override int ClassCode => 419394032; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_type, ((ThreadStaticsOffsetNode)other)._type); } - - int ISortableSymbolNode.ClassCode => 419394032; - - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) - { - return CompareToImpl((SortableDependencyNode)other, comparer); - } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeManagerIndirectionNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeManagerIndirectionNode.cs index 4199c29fbe..7a7c4b797b 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeManagerIndirectionNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeManagerIndirectionNode.cs @@ -34,6 +34,6 @@ namespace ILCompiler.DependencyAnalysis return objData.ToObjectData(); } - protected internal override int ClassCode => -2028598574; + public override int ClassCode => -2028598574; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeMetadataMapNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeMetadataMapNode.cs index 75012d6e8e..469d86dd5b 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeMetadataMapNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeMetadataMapNode.cs @@ -53,12 +53,9 @@ namespace ILCompiler.DependencyAnalysis foreach (var mappingEntry in factory.MetadataManager.GetTypeDefinitionMapping(factory)) { - if (!factory.CompilationModuleGroup.ContainsType(mappingEntry.Entity)) - continue; - // Types that don't have EETypes don't need mapping table entries because there's no risk of them // not unifying to the same System.Type at runtime. - if (!factory.MetadataManager.TypeGeneratesEEType(mappingEntry.Entity)) + if (!factory.MetadataManager.TypeGeneratesEEType(mappingEntry.Entity) && !factory.CompilationModuleGroup.ShouldReferenceThroughImportTable(mappingEntry.Entity)) continue; // Go with a necessary type symbol. It will be upgraded to a constructed one if a constructed was emitted. @@ -82,6 +79,6 @@ namespace ILCompiler.DependencyAnalysis protected internal override int Phase => (int)ObjectNodePhase.Ordered; - protected internal override int ClassCode => (int)ObjectNodeOrder.TypeMetadataMapNode; + public override int ClassCode => (int)ObjectNodeOrder.TypeMetadataMapNode; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeMetadataNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeMetadataNode.cs index a8416afad0..39ad01e9f1 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeMetadataNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeMetadataNode.cs @@ -51,6 +51,23 @@ namespace ILCompiler.DependencyAnalysis dependencies.Add(factory.MethodMetadata(_type.GetMethod("Invoke", null)), "Delegate invoke method metadata"); } + // If the user asked for complete metadata to be generated for all types that are getting metadata, ensure that. + var mdManager = (UsageBasedMetadataManager)factory.MetadataManager; + if ((mdManager._generationOptions & UsageBasedMetadataGenerationOptions.CompleteTypesOnly) != 0) + { + foreach (MethodDesc method in _type.GetMethods()) + { + if (!mdManager.IsReflectionBlocked(method)) + dependencies.Add(factory.MethodMetadata(method), "Complete metadata for type"); + } + + foreach (FieldDesc field in _type.GetFields()) + { + if (!mdManager.IsReflectionBlocked(field)) + dependencies.Add(factory.FieldMetadata(field), "Complete metadata for type"); + } + } + return dependencies; } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeThreadStaticIndexNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeThreadStaticIndexNode.cs index 11ac06f2c5..2c20841bb2 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeThreadStaticIndexNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/TypeThreadStaticIndexNode.cs @@ -67,9 +67,9 @@ namespace ILCompiler.DependencyAnalysis return objData.ToObjectData(); } - protected internal override int ClassCode => -149601250; + public override int ClassCode => -149601250; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_type, ((TypeThreadStaticIndexNode)other)._type); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UnboxingStubNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UnboxingStubNode.cs index d0cb80ba38..ae39c5074b 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UnboxingStubNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UnboxingStubNode.cs @@ -70,19 +70,12 @@ namespace ILCompiler.DependencyAnalysis protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); - protected internal override int ClassCode => -1846923013; + public override int ClassCode => -1846923013; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(Method, ((UnboxingStubNode)other).Method); } - - int ISortableSymbolNode.ClassCode => ClassCode; - - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) - { - return CompareToImpl((ObjectNode)other, comparer); - } } // @@ -122,9 +115,9 @@ namespace ILCompiler.DependencyAnalysis return objData.ToObjectData(); } - protected internal override int ClassCode => 1102274050; + public override int ClassCode => 1102274050; - protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return _isEndSymbol.CompareTo(((WindowsUnboxingStubsRegionNode)other)._isEndSymbol); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcDictionaryLayoutNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcDictionaryLayoutNode.cs deleted file mode 100644 index d268fa17bd..0000000000 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcDictionaryLayoutNode.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Diagnostics; - -using Internal.TypeSystem; - -using ILCompiler.DependencyAnalysisFramework; - -namespace ILCompiler.DependencyAnalysis -{ - /// - /// Represents the layout of the generic dictionary associated with a given canonical - /// generic type or generic method. Maintains a bag of associated - /// with the canonical entity. - /// - /// - /// The generic dictionary doesn't have any dependent nodes because - /// are runtime-determined - the concrete dependency depends on the generic context the canonical - /// entity is instantiated with. - /// - public partial class UtcDictionaryLayoutNode : DictionaryLayoutNode - { - public override bool HasFixedSlots - { - get - { - return false; - } - } - - public UtcDictionaryLayoutNode(TypeSystemEntity owningMethodOrType) : base(owningMethodOrType) - { - - } - -#if !PROJECTN - public override void EnsureEntry(GenericLookupResult lookupResult) => throw new NotImplementedException(); - public override int GetSlotForEntry(GenericLookupResult entry) => throw new NotImplementedException(); - public override IEnumerable Entries => throw new NotImplementedException(); - public override ICollection GetTemplateEntries(NodeFactory factory) => throw new NotImplementedException(); - public override void EmitDictionaryData(ref ObjectDataBuilder builder, NodeFactory factory, GenericDictionaryNode dictionary, bool fixedLayoutOnly) => throw new NotImplementedException(); -#endif - } -} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcNodeFactory.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcNodeFactory.cs index 776ca6a2b9..80aec11b0b 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcNodeFactory.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcNodeFactory.cs @@ -59,7 +59,7 @@ namespace ILCompiler return null; } - private static MetadataManager PickMetadataManager(CompilerTypeSystemContext context, CompilationModuleGroup compilationModuleGroup, IEnumerable inputModules, IEnumerable inputMetadataOnlyAssemblies, string metadataFile) + private static MetadataManager PickMetadataManager(CompilerTypeSystemContext context, CompilationModuleGroup compilationModuleGroup, IEnumerable inputModules, IEnumerable inputMetadataOnlyAssemblies, string metadataFile, bool emitStackTraceMetadata, bool disableExceptionMessages, bool disableInvokeThunks) { if (metadataFile == null) { @@ -67,7 +67,28 @@ namespace ILCompiler } else { - return new PrecomputedMetadataManager(compilationModuleGroup, context, FindMetadataDescribingModuleInInputSet(inputModules), inputModules, inputMetadataOnlyAssemblies, ReadBytesFromFile(metadataFile), new UtcStackTraceEmissionPolicy()); + // Set Policies according to passed arguments + StackTraceEmissionPolicy stackTraceEmissionPolicy; + if (emitStackTraceMetadata) + { + stackTraceEmissionPolicy = new UtcStackTraceEmissionPolicy(); + } + else + { + stackTraceEmissionPolicy = new NoStackTraceEmissionPolicy(); + } + + ManifestResourceBlockingPolicy resourceBlockingPolicy; + if (disableExceptionMessages) + { + resourceBlockingPolicy = new FrameworkStringResourceBlockingPolicy(); + } + else + { + resourceBlockingPolicy = new NoManifestResourceBlockingPolicy(); + } + + return new PrecomputedMetadataManager(compilationModuleGroup, context, FindMetadataDescribingModuleInInputSet(inputModules), inputModules, inputMetadataOnlyAssemblies, ReadBytesFromFile(metadataFile), stackTraceEmissionPolicy , resourceBlockingPolicy, disableInvokeThunks); } } @@ -86,11 +107,14 @@ namespace ILCompiler string outputFile, UTCNameMangler nameMangler, bool buildMRT, + bool emitStackTraceMetadata, + bool disableExceptionMessages, + bool allowInvokeThunks, DictionaryLayoutProvider dictionaryLayoutProvider, ImportedNodeProvider importedNodeProvider) : base(context, compilationModuleGroup, - PickMetadataManager(context, compilationModuleGroup, inputModules, inputMetadataOnlyAssemblies, metadataFile), + PickMetadataManager(context, compilationModuleGroup, inputModules, inputMetadataOnlyAssemblies, metadataFile, emitStackTraceMetadata, disableExceptionMessages, allowInvokeThunks), NewEmptyInteropStubManager(context, compilationModuleGroup), nameMangler, new AttributeDrivenLazyGenericsPolicy(), @@ -159,6 +183,7 @@ namespace ILCompiler graph.AddRoot(EagerCctorTable, "EagerCctorTable is always generated"); graph.AddRoot(DispatchMapTable, "DispatchMapTable is always generated"); graph.AddRoot(FrozenSegmentRegion, "FrozenSegmentRegion is always generated"); + graph.AddRoot(InterfaceDispatchCellSection, "Interface dispatch cell section is always generated"); graph.AddRoot(TypeManagerIndirection, "ModuleManagerIndirection is always generated"); graph.AddRoot(GCStaticsRegion, "GC StaticsRegion is always generated"); graph.AddRoot(GCStaticDescRegion, "GC Static Desc is always generated"); @@ -212,12 +237,21 @@ namespace ILCompiler { if (method.HasCustomAttribute("System.Runtime", "RuntimeImportAttribute")) { - return new RuntimeImportMethodNode(method); + RuntimeImportMethodNode runtimeImportMethod = new RuntimeImportMethodNode(method); + + // If the method is imported from either the current module or the runtime, reference it directly + if (CompilationModuleGroup.ContainsMethodBody(method, false)) + return runtimeImportMethod; + // If the method is imported from the runtime but not a managed assembly, reference it directly + else if (!CompilationModuleGroup.ImportsMethod(method, false)) + return runtimeImportMethod; + + // If the method is imported from a managed assembly, reference it via an import cell } - - if (CompilationModuleGroup.ContainsMethodBody(method, false)) + else { - return NonExternMethodSymbol(method, false); + if (CompilationModuleGroup.ContainsMethodBody(method, false)) + return NonExternMethodSymbol(method, false); } return _importedNodeProvider.ImportedMethodCodeNode(this, method, false); @@ -251,16 +285,18 @@ namespace ILCompiler public GCStaticDescRegionNode GCStaticDescRegion = new GCStaticDescRegionNode( CompilationUnitPrefix + "__GCStaticDescStart", - CompilationUnitPrefix + "__GCStaticDescEnd"); + CompilationUnitPrefix + "__GCStaticDescEnd", + new SortableDependencyNode.EmbeddedObjectNodeComparer(new CompilerComparer())); public GCStaticDescRegionNode ThreadStaticGCDescRegion = new GCStaticDescRegionNode( CompilationUnitPrefix + "__ThreadStaticGCDescStart", - CompilationUnitPrefix + "__ThreadStaticGCDescEnd"); + CompilationUnitPrefix + "__ThreadStaticGCDescEnd", + new SortableDependencyNode.EmbeddedObjectNodeComparer(new CompilerComparer())); public ArrayOfEmbeddedDataNode ThreadStaticsOffsetRegion = new ArrayOfEmbeddedDataNode( CompilationUnitPrefix + "__ThreadStaticOffsetRegionStart", CompilationUnitPrefix + "__ThreadStaticOffsetRegionEnd", - null); + new SortableDependencyNode.EmbeddedObjectNodeComparer(new CompilerComparer())); public ThreadStaticsIndexNode ThreadStaticsIndex; @@ -348,14 +384,6 @@ namespace ILCompiler return ReadOnlyDataBlob(NameMangler.GetMangledFieldName(field), ((EcmaField)field).GetFieldRvaData(), Target.PointerSize); } - public class UtcDictionaryLayoutProvider : DictionaryLayoutProvider - { - public override DictionaryLayoutNode GetLayout(TypeSystemEntity methodOrType) - { - return new UtcDictionaryLayoutNode(methodOrType); - } - } - public ISymbolNode LoopHijackFlagSymbol() { return LoopHijackFlag; diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcThreadStaticsNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcThreadStaticsNode.cs index 3aeadde412..9647ef5626 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcThreadStaticsNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcThreadStaticsNode.cs @@ -7,7 +7,7 @@ using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { - public class UtcThreadStaticsNode : ObjectNode, ISymbolDefinitionNode + public class UtcThreadStaticsNode : ObjectNode, ISymbolDefinitionNode, ISymbolNodeWithDebugInfo, ISortableSymbolNode { private MetadataType _type; @@ -26,6 +26,8 @@ namespace ILCompiler.DependencyAnalysis public int Offset => 0; public MetadataType Type => _type; + public IDebugInfo DebugInfo => NullTypeIndexDebugInfo.Instance; + public static string GetMangledName(TypeDesc type, NameMangler nameMangler) { return nameMangler.NodeMangler.ThreadStatics(type); @@ -56,11 +58,16 @@ namespace ILCompiler.DependencyAnalysis { ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); builder.RequireInitialPointerAlignment(); - builder.EmitZeros(_type.ThreadStaticFieldSize.AsInt); + builder.EmitZeros(_type.ThreadGcStaticFieldSize.AsInt); builder.AddSymbol(this); return builder.ToObjectData(); } - protected internal override int ClassCode => -1421136129; + public sealed override int ClassCode => -1421136129; + + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) + { + return comparer.Compare(_type, ((UtcThreadStaticsNode)other)._type); + } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugILImagesSection.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugILImagesSection.cs index 5ac16bbb38..284e4fe17f 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugILImagesSection.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugILImagesSection.cs @@ -30,7 +30,7 @@ namespace ILCompiler.DependencyAnalysis public int Offset => 0; - protected internal override int ClassCode => 2051656903; + public override int ClassCode => 2051656903; public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugManagedNativeDictionaryInfoSection.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugManagedNativeDictionaryInfoSection.cs index 5d3ebd6e7b..79c176034f 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugManagedNativeDictionaryInfoSection.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugManagedNativeDictionaryInfoSection.cs @@ -30,7 +30,8 @@ namespace ILCompiler.DependencyAnalysis public int Offset => 0; - protected internal override int ClassCode => 1502860768; + protected internal override int Phase => (int)ObjectNodePhase.Ordered; + public override int ClassCode => (int)ObjectNodeOrder.WindowsDebugManagedNativeDictionaryInfoSectionNode; public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugMergedAssemblyRecordsSection.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugMergedAssemblyRecordsSection.cs index 49f75a1006..d16f9cc5b8 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugMergedAssemblyRecordsSection.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugMergedAssemblyRecordsSection.cs @@ -31,7 +31,7 @@ namespace ILCompiler.DependencyAnalysis public int Offset => 0; - protected internal override int ClassCode => -1250136545; + public override int ClassCode => -1250136545; public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugMethodInfoSection.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugMethodInfoSection.cs index 7d4396fc72..9a8d8e765d 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugMethodInfoSection.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugMethodInfoSection.cs @@ -102,7 +102,7 @@ namespace ILCompiler.DependencyAnalysis // find virtual method slot. MethodDesc declaringMethodForSlot = MetadataVirtualMethodAlgorithm.FindSlotDefiningMethodForVirtualMethod(md.GetTypicalMethodDefinition()); - int slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, declaringMethodForSlot); + int slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, declaringMethodForSlot, type); if (slot != -1 && !methodList.ContainsKey(methodToken)) methodList.Add(methodToken, slot); } @@ -150,6 +150,6 @@ namespace ILCompiler.DependencyAnalysis return "___DebugMethodInfoSection"; } - protected internal override int ClassCode => 513099721; + public override int ClassCode => 513099721; } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugMethodMapSection.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugMethodMapSection.cs index c351d54e87..9ff8978046 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugMethodMapSection.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugMethodMapSection.cs @@ -30,7 +30,8 @@ namespace ILCompiler.DependencyAnalysis public int Offset => 0; - protected internal override int ClassCode => -2063194124; + protected internal override int Phase => (int)ObjectNodePhase.Ordered; + public override int ClassCode => (int)ObjectNodeOrder.WindowsDebugMethodSignatureMapSectionNode; public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { @@ -178,9 +179,6 @@ namespace ILCompiler.DependencyAnalysis if (relocsOnly) return new ObjectData(Array.Empty(), Array.Empty(), 1, new ISymbolDefinitionNode[] { this }); - if (factory.WindowsDebugData.DebugTypeRecordsSection != null) - factory.WindowsDebugData.DebugTypeRecordsSection.Neuter(); - List relocations = new List(); DebugInfoBlob debugData = GetDebugMethodRVAToTokenMap(factory.WindowsDebugData.DebugPseudoAssemblySection.PseudoAssembly, factory.MetadataManager.GetCompiledMethodBodies(), out relocations); diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugNeedTypeIndicesStoreNode.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugNeedTypeIndicesStoreNode.cs index 71435021ca..3aa7335d89 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugNeedTypeIndicesStoreNode.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugNeedTypeIndicesStoreNode.cs @@ -21,7 +21,8 @@ namespace ILCompiler.DependencyAnalysis public int Offset => 0; - protected internal override int ClassCode => 1275723356; + protected internal override int Phase => (int)ObjectNodePhase.Ordered; + public override int ClassCode => (int)ObjectNodeOrder.WindowsDebugNeedTypeIndicesStoreNode; public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugPseudoAssemblySection.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugPseudoAssemblySection.cs index 7f393b2d40..6780d06850 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugPseudoAssemblySection.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugPseudoAssemblySection.cs @@ -29,7 +29,8 @@ namespace ILCompiler.DependencyAnalysis public int Offset => 0; - protected internal override int ClassCode => 920778380; + protected internal override int Phase => (int)ObjectNodePhase.Ordered; + public override int ClassCode => (int)ObjectNodeOrder.WindowsDebugPseudoAssemblySectionNode; public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugTypeRecordsSection.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugTypeRecordsSection.cs index 660559ccb4..e74e0a077b 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugTypeRecordsSection.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugTypeRecordsSection.cs @@ -33,7 +33,8 @@ namespace ILCompiler.DependencyAnalysis public int Offset => 0; - protected internal override int ClassCode => -2081034825; + protected internal override int Phase => (int)ObjectNodePhase.Ordered; + public override int ClassCode => (int)ObjectNodeOrder.WindowsDebugTypeRecordsSectionNode; public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { @@ -73,9 +74,10 @@ namespace ILCompiler.DependencyAnalysis return _dbgInfoWriter.GetClassTypeIndex(classTypeDescriptor); } - uint ITypesDebugInfoWriter.GetCompleteClassTypeIndex(ClassTypeDescriptor classTypeDescriptor, ClassFieldsTypeDescriptor classFieldsTypeDescriptior, DataFieldDescriptor[] fields) + uint ITypesDebugInfoWriter.GetCompleteClassTypeIndex(ClassTypeDescriptor classTypeDescriptor, ClassFieldsTypeDescriptor classFieldsTypeDescriptior, + DataFieldDescriptor[] fields, StaticDataFieldDescriptor[] statics) { - return _dbgInfoWriter.GetCompleteClassTypeIndex(classTypeDescriptor, classFieldsTypeDescriptior, fields); + return _dbgInfoWriter.GetCompleteClassTypeIndex(classTypeDescriptor, classFieldsTypeDescriptior, fields, statics); } uint ITypesDebugInfoWriter.GetArrayTypeIndex(ClassTypeDescriptor classDescriptor, ArrayTypeDescriptor arrayTypeDescriptor) @@ -98,6 +100,11 @@ namespace ILCompiler.DependencyAnalysis return _dbgInfoWriter.GetMemberFunctionId(memberIdDescriptor); } + uint ITypesDebugInfoWriter.GetPrimitiveTypeIndex(TypeDesc type) + { + return PrimitiveTypeDescriptor.GetPrimitiveTypeIndex(type); + } + string ITypesDebugInfoWriter.GetMangledName(TypeDesc type) { return _nodeFactory.NameMangler.GetMangledTypeName(type); diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugTypeSignatureMapSection.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugTypeSignatureMapSection.cs index 0ec387d9cf..a5aaea9b74 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugTypeSignatureMapSection.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/WindowsDebugTypeSignatureMapSection.cs @@ -31,7 +31,8 @@ namespace ILCompiler.DependencyAnalysis public int Offset => 0; - protected internal override int ClassCode => 1029840999; + protected internal override int Phase => (int)ObjectNodePhase.Ordered; + public override int ClassCode => (int)ObjectNodeOrder.WindowsDebugTypeSignatureMapSectionNode; public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { @@ -129,9 +130,6 @@ namespace ILCompiler.DependencyAnalysis if (relocsOnly) return new ObjectData(Array.Empty(), Array.Empty(), 1, new ISymbolDefinitionNode[] { this }); - if (factory.WindowsDebugData.DebugTypeRecordsSection != null) - factory.WindowsDebugData.DebugTypeRecordsSection.Neuter(); - DebugInfoBlob debugData = GetDebugTypeIndexToTokenMap(factory.WindowsDebugData.DebugPseudoAssemblySection.PseudoAssembly, factory.WindowsDebugData.UserDefinedTypeDescriptor.CompleteKnownTypes); return new ObjectData(debugData.ToArray(), Array.Empty(), 1, new ISymbolDefinitionNode[] { this }); diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/DynamicInvokeThunkGenerationPolicy.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/DynamicInvokeThunkGenerationPolicy.cs new file mode 100644 index 0000000000..e4f3f67d75 --- /dev/null +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/DynamicInvokeThunkGenerationPolicy.cs @@ -0,0 +1,48 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.TypeSystem; + +namespace ILCompiler +{ + /// + /// Controls the way calling convention conversion is performed in + /// + /// scenarios. + /// + public abstract class DynamicInvokeThunkGenerationPolicy + { + /// + /// Gets a value indicating whether reflection-invokable method '' + /// should get a static calling convention conversion thunk. Static calling convention + /// conversion thunks speed up reflection invoke of the method at the cost of extra code generation. + /// + public abstract bool HasStaticInvokeThunk(MethodDesc targetMethod); + } + + /// + /// A thunk generation policy that generates no static invocation thunks. + /// + public sealed class NoDynamicInvokeThunkGenerationPolicy : DynamicInvokeThunkGenerationPolicy + { + public override bool HasStaticInvokeThunk(MethodDesc targetMethod) => false; + } + + /// + /// A thunk generation policy that uses static invocation thunks whenever possible. + /// + public sealed class DefaultDynamicInvokeThunkGenerationPolicy : DynamicInvokeThunkGenerationPolicy + { + public override bool HasStaticInvokeThunk(MethodDesc targetMethod) + { + // Place an upper limit on how many parameters a method can have to still get a static stub. + // From the past experience, methods taking 8000+ parameters get a stub that can hit various limitations + // in the codegen. On Project N, we were limited to 256 parameters because of MDIL limitations. + // We don't have such limitations here, but it's a nice round number. + // Reflection invoke will still work, but will go through the calling convention converter. + + return targetMethod.Signature.Length <= 256; + } + } +} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/EmptyMetadataManager.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/EmptyMetadataManager.cs index 2ae0536691..16d547abec 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/EmptyMetadataManager.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/EmptyMetadataManager.cs @@ -17,7 +17,7 @@ namespace ILCompiler public override bool SupportsReflection => false; public EmptyMetadataManager(CompilerTypeSystemContext typeSystemContext) - : base(typeSystemContext, new FullyBlockedMetadataPolicy()) + : base(typeSystemContext, new FullyBlockedMetadataPolicy(), new FullyBlockedManifestResourcePolicy(), new NoDynamicInvokeThunkGenerationPolicy()) { } @@ -61,15 +61,6 @@ namespace ILCompiler stackTraceMapping = new List>(); } - /// - /// Is there a reflection invoke stub for a method that is invokable? - /// - public override bool HasReflectionInvokeStubForInvokableMethod(MethodDesc method) - { - Debug.Assert(IsReflectionInvokable(method)); - return false; - } - /// /// Gets a stub that can be used to reflection-invoke a method with a given signature. /// @@ -108,5 +99,13 @@ namespace ILCompiler return true; } } + + private sealed class FullyBlockedManifestResourcePolicy : ManifestResourceBlockingPolicy + { + public override bool IsManifestResourceBlocked(ModuleDesc module, string resourceName) + { + return true; + } + } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/FrameworkStringResourceBlockingPolicy.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/FrameworkStringResourceBlockingPolicy.cs new file mode 100644 index 0000000000..dd53aa0242 --- /dev/null +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/FrameworkStringResourceBlockingPolicy.cs @@ -0,0 +1,91 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; + +using Internal.TypeSystem; +using Internal.TypeSystem.Ecma; + +namespace ILCompiler +{ + /// + /// A resource blocking policy that blocks RESX resources in framework assemblies. + /// This is useful for size-conscious scenarios where the conveniece of having + /// proper exception messages in framework-throw exceptions is not important. + /// + public sealed class FrameworkStringResourceBlockingPolicy : ManifestResourceBlockingPolicy + { + public override bool IsManifestResourceBlocked(ModuleDesc module, string resourceName) + { + // The embedded RESX files all have names that end with .resources, so use that as the initial filter. + if (!resourceName.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) + return false; + + // Assuming multimodule and non-ecma assemblies are unsupported + EcmaModule ecmaModule = (EcmaModule)module; + + // If this is not a framework assembly, no resources are blocked + if (!IsFrameworkAssembly(ecmaModule)) + return false; + + MetadataReader reader = ecmaModule.MetadataReader; + + // We have a resource in the framework assembly. Now check if this is a RESX + foreach (ManifestResourceHandle resourceHandle in reader.ManifestResources) + { + ManifestResource resource = reader.GetManifestResource(resourceHandle); + if (reader.StringComparer.Equals(resource.Name, resourceName) && + resource.Implementation.IsNil) + { + PEMemoryBlock resourceDirectory = + ecmaModule.PEReader.GetSectionData(ecmaModule.PEReader.PEHeaders.CorHeader.ResourcesDirectory.RelativeVirtualAddress); + BlobReader blob = resourceDirectory.GetReader((int)resource.Offset, resourceDirectory.Length - (int)resource.Offset); + int length = (int)blob.ReadUInt32(); + if (length > 4) + { + // Check for magic bytes that correspond to RESX + if (blob.ReadUInt32() == 0xBEEFCACE) + return true; + } + } + } + + return false; + } + + /// + /// Gets a value indicating whether '' is a framework assembly. + /// + private static bool IsFrameworkAssembly(EcmaModule module) + { + MetadataReader reader = module.MetadataReader; + + // We look for [assembly:AssemblyMetadata(".NETFrameworkAssembly", "")] + + foreach (CustomAttributeHandle attributeHandle in reader.GetAssemblyDefinition().GetCustomAttributes()) + { + if (!reader.GetAttributeNamespaceAndName(attributeHandle, out StringHandle namespaceHandle, out StringHandle nameHandle)) + continue; + + if (!reader.StringComparer.Equals(namespaceHandle, "System.Reflection") || + !reader.StringComparer.Equals(nameHandle, "AssemblyMetadataAttribute")) + continue; + + var attributeTypeProvider = new CustomAttributeTypeProvider(module); + CustomAttribute attribute = reader.GetCustomAttribute(attributeHandle); + CustomAttributeValue decodedAttribute = attribute.DecodeValue(attributeTypeProvider); + + if (decodedAttribute.FixedArguments.Length != 2) + continue; + + if (decodedAttribute.FixedArguments[0].Value is string s && s == ".NETFrameworkAssembly") + return true; + } + + return false; + } + } +} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/GeneratingMetadataManager.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/GeneratingMetadataManager.cs index b01a4bb5f3..044842f810 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/GeneratingMetadataManager.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/GeneratingMetadataManager.cs @@ -9,14 +9,11 @@ using System.Text; using Internal.IL.Stubs; using Internal.TypeSystem; -using Internal.TypeSystem.Ecma; using Internal.Metadata.NativeFormat.Writer; using ILCompiler.Metadata; using ILCompiler.DependencyAnalysis; -using Debug = System.Diagnostics.Debug; - namespace ILCompiler { /// @@ -26,20 +23,16 @@ namespace ILCompiler { protected readonly string _metadataLogFile; protected readonly StackTraceEmissionPolicy _stackTraceEmissionPolicy; - private readonly Dictionary _dynamicInvokeThunks; private readonly ModuleDesc _generatedAssembly; - public GeneratingMetadataManager(ModuleDesc generatedAssembly, CompilerTypeSystemContext typeSystemContext, MetadataBlockingPolicy blockingPolicy, string logFile, StackTraceEmissionPolicy stackTracePolicy) - : base(typeSystemContext, blockingPolicy) + public GeneratingMetadataManager(CompilerTypeSystemContext typeSystemContext, MetadataBlockingPolicy blockingPolicy, + ManifestResourceBlockingPolicy resourceBlockingPolicy, string logFile, StackTraceEmissionPolicy stackTracePolicy, + DynamicInvokeThunkGenerationPolicy invokeThunkGenerationPolicy) + : base(typeSystemContext, blockingPolicy, resourceBlockingPolicy, invokeThunkGenerationPolicy) { _metadataLogFile = logFile; _stackTraceEmissionPolicy = stackTracePolicy; - _generatedAssembly = generatedAssembly; - - if (DynamicInvokeMethodThunk.SupportsThunks(typeSystemContext)) - { - _dynamicInvokeThunks = new Dictionary(); - } + _generatedAssembly = typeSystemContext.GeneratedAssembly; } public sealed override bool WillUseMetadataTokenToReferenceMethod(MethodDesc method) @@ -175,41 +168,14 @@ namespace ILCompiler /// protected abstract IEnumerable GetFieldsWithRuntimeMapping(); - /// - /// Is there a reflection invoke stub for a method that is invokable? - /// - public sealed override bool HasReflectionInvokeStubForInvokableMethod(MethodDesc method) - { - Debug.Assert(IsReflectionInvokable(method)); - - if (_dynamicInvokeThunks == null) - return false; - - // Place an upper limit on how many parameters a method can have to still get a static stub. - // From the past experience, methods taking 8000+ parameters get a stub that can hit various limitations - // in the codegen. On Project N, we were limited to 256 parameters because of MDIL limitations. - // We don't have such limitations here, but it's a nice round number. - // Reflection invoke will still work, but will go through the calling convention converter. - - return method.Signature.Length <= 256; - } - /// /// Gets a stub that can be used to reflection-invoke a method with a given signature. /// public sealed override MethodDesc GetCanonicalReflectionInvokeStub(MethodDesc method) { - TypeSystemContext context = method.Context; - var sig = method.Signature; - // Get a generic method that can be used to invoke method with this shape. - MethodDesc thunk; - var lookupSig = new DynamicInvokeMethodSignature(sig); - if (!_dynamicInvokeThunks.TryGetValue(lookupSig, out thunk)) - { - thunk = new DynamicInvokeMethodThunk(_generatedAssembly.GetGlobalModuleType(), lookupSig); - _dynamicInvokeThunks.Add(lookupSig, thunk); - } + var lookupSig = new DynamicInvokeMethodSignature(method.Signature); + MethodDesc thunk = _typeSystemContext.GetDynamicInvokeThunk(lookupSig); return InstantiateCanonicalDynamicInvokeMethodForMethod(thunk, method); } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/ILScannerBuilder.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/ILScannerBuilder.cs index 340c5603a9..2202f93d6d 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/ILScannerBuilder.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/ILScannerBuilder.cs @@ -53,7 +53,7 @@ namespace ILCompiler public IILScanner ToILScanner() { - var interopStubManager = new CompilerGeneratedInteropStubManager(_compilationGroup, _context, new InteropStateManager(_compilationGroup.GeneratedAssembly)); + var interopStubManager = new CompilerGeneratedInteropStubManager(_compilationGroup, _context, new InteropStateManager(_context.GeneratedAssembly)); var nodeFactory = new ILScanNodeFactory(_context, _compilationGroup, _metadataManager, interopStubManager, _nameMangler); DependencyAnalyzerBase graph = _dependencyTrackingLevel.CreateDependencyGraph(nodeFactory); diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/ILStreamReader.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/ILStreamReader.cs index 8facc05f74..badf0151aa 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/ILStreamReader.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/ILStreamReader.cs @@ -179,9 +179,9 @@ namespace Internal.Compiler try { tokenResolved = TryReadLdtoken(out token); - entity = tokenResolved ?(TypeSystemEntity)_methodIL.GetObject(token) : null; + entity = tokenResolved ? (TypeSystemEntity)_methodIL.GetObject(token) : null; } - catch (TypeSystemException.TypeLoadException) + catch (TypeSystemException) { tokenResolved = false; entity = null; diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/IRootingServiceProvider.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/IRootingServiceProvider.cs index 0895464ccd..1a462e9fcd 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/IRootingServiceProvider.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/IRootingServiceProvider.cs @@ -18,5 +18,6 @@ namespace ILCompiler void RootNonGCStaticBaseForType(TypeDesc type, string reason); void RootVirtualMethodForReflection(MethodDesc method, string reason); void RootModuleMetadata(ModuleDesc module, string reason); + void RootReadOnlyDataBlob(byte[] data, int alignment, string reason, string exportName); } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/LibraryInitializers.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/LibraryInitializers.cs index cf9222cb85..e970fdd767 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/LibraryInitializers.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/LibraryInitializers.cs @@ -2,12 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Collections.Generic; using Internal.TypeSystem; -using AssemblyName = System.Reflection.AssemblyName; using Debug = System.Diagnostics.Debug; namespace ILCompiler @@ -17,37 +15,22 @@ namespace ILCompiler /// public sealed class LibraryInitializers { - private const string ClassLibraryPlaceHolderString = "*ClassLibrary*"; private const string LibraryInitializerContainerNamespaceName = "Internal.Runtime.CompilerHelpers"; private const string LibraryInitializerContainerTypeName = "LibraryInitializer"; private const string LibraryInitializerMethodName = "InitializeLibrary"; - private static readonly LibraryInitializerInfo[] s_assembliesWithLibraryInitializers = - { - new LibraryInitializerInfo(ClassLibraryPlaceHolderString), - new LibraryInitializerInfo("System.Private.TypeLoader"), - new LibraryInitializerInfo("System.Private.Reflection.Execution"), - new LibraryInitializerInfo("System.Private.DeveloperExperience.Console"), - new LibraryInitializerInfo("System.Private.Interop"), - new LibraryInitializerInfo("System.Private.StackTraceMetadata"), - }; - private List _libraryInitializerMethods; private readonly TypeSystemContext _context; - private readonly bool _isCppCodeGen; + private IReadOnlyCollection _librariesWithInitializers; - public LibraryInitializers(TypeSystemContext context, bool isCppCodeGen) + public LibraryInitializers(TypeSystemContext context, IEnumerable librariesWithInitalizers) { _context = context; - // - // We should not care which code-gen is being used but for the time being - // this can be useful to workaround CppCodeGen bugs. - // - _isCppCodeGen = isCppCodeGen; + _librariesWithInitializers = new List(librariesWithInitalizers); } - public IList LibraryInitializerMethods + public IReadOnlyCollection LibraryInitializerMethods { get { @@ -64,18 +47,8 @@ namespace ILCompiler _libraryInitializerMethods = new List(); - foreach (var entry in s_assembliesWithLibraryInitializers) + foreach (var assembly in _librariesWithInitializers) { - if (_isCppCodeGen && !entry.UseWithCppCodeGen) - continue; - - ModuleDesc assembly = entry.Assembly == ClassLibraryPlaceHolderString - ? _context.SystemModule - : _context.ResolveAssembly(new AssemblyName(entry.Assembly), false); - - if (assembly == null) - continue; - TypeDesc containingType = assembly.GetType(LibraryInitializerContainerNamespaceName, LibraryInitializerContainerTypeName, false); if (containingType == null) continue; @@ -87,17 +60,5 @@ namespace ILCompiler _libraryInitializerMethods.Add(initializerMethod); } } - - private sealed class LibraryInitializerInfo - { - public string Assembly { get; } - public bool UseWithCppCodeGen { get; } - - public LibraryInitializerInfo(string assembly, bool useWithCppCodeGen = true) - { - Assembly = assembly; - UseWithCppCodeGen = useWithCppCodeGen; - } - } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/MainMethodRootProvider.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/MainMethodRootProvider.cs index 4df659ad83..2b716787bf 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/MainMethodRootProvider.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/MainMethodRootProvider.cs @@ -22,9 +22,9 @@ namespace ILCompiler public const string ManagedEntryPointMethodName = "__managed__Main"; private EcmaModule _module; - private IList _libraryInitializers; + private IReadOnlyCollection _libraryInitializers; - public MainMethodRootProvider(EcmaModule module, IList libraryInitializers) + public MainMethodRootProvider(EcmaModule module, IReadOnlyCollection libraryInitializers) { _module = module; _libraryInitializers = libraryInitializers; diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/ManifestResourceBlockingPolicy.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/ManifestResourceBlockingPolicy.cs new file mode 100644 index 0000000000..9f61db5bda --- /dev/null +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/ManifestResourceBlockingPolicy.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.TypeSystem; + +namespace ILCompiler +{ + /// + /// Represents a manifest resource blocking policy. The policy dictates whether manifest resources should + /// be generated into the executable. + /// + public abstract class ManifestResourceBlockingPolicy + { + /// + /// Returns true if manifest resource with name '' in module '' + /// is reflection blocked. + /// + public abstract bool IsManifestResourceBlocked(ModuleDesc module, string resourceName); + } +} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/MetadataManager.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/MetadataManager.cs index 2c2c6123bd..31526a097e 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/MetadataManager.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/MetadataManager.cs @@ -42,6 +42,8 @@ namespace ILCompiler protected readonly CompilerTypeSystemContext _typeSystemContext; protected readonly MetadataBlockingPolicy _blockingPolicy; + protected readonly ManifestResourceBlockingPolicy _resourceBlockingPolicy; + protected readonly DynamicInvokeThunkGenerationPolicy _dynamicInvokeThunkGenerationPolicy; private List _cctorContextsGenerated = new List(); private HashSet _typesWithEETypesGenerated = new HashSet(); @@ -50,16 +52,18 @@ namespace ILCompiler private HashSet _genericDictionariesGenerated = new HashSet(); private HashSet _methodBodiesGenerated = new HashSet(); private List _typeGVMEntries = new List(); - private HashSet _defaultConstructorsNeeded = new HashSet(); internal NativeLayoutInfoNode NativeLayoutInfo { get; private set; } internal DynamicInvokeTemplateDataNode DynamicInvokeTemplateData { get; private set; } public virtual bool SupportsReflection => true; - public MetadataManager(CompilerTypeSystemContext typeSystemContext, MetadataBlockingPolicy blockingPolicy) + public MetadataManager(CompilerTypeSystemContext typeSystemContext, MetadataBlockingPolicy blockingPolicy, + ManifestResourceBlockingPolicy resourceBlockingPolicy, DynamicInvokeThunkGenerationPolicy dynamicInvokeThunkGenerationPolicy) { _typeSystemContext = typeSystemContext; _blockingPolicy = blockingPolicy; + _resourceBlockingPolicy = resourceBlockingPolicy; + _dynamicInvokeThunkGenerationPolicy = dynamicInvokeThunkGenerationPolicy; } public void AttachToDependencyGraph(DependencyAnalyzerBase graph) @@ -205,12 +209,6 @@ namespace ILCompiler { _genericDictionariesGenerated.Add(dictionaryNode); } - - var ctorFromLazyGenericsNode = obj as DefaultConstructorFromLazyNode; - if (ctorFromLazyGenericsNode != null) - { - _defaultConstructorsNeeded.Add(ctorFromLazyGenericsNode); - } } /// @@ -218,60 +216,10 @@ namespace ILCompiler /// public virtual bool IsReflectionInvokable(MethodDesc method) { - return IsMethodSignatureSupportedInReflectionInvoke(method) + return Internal.IL.Stubs.DynamicInvokeMethodThunk.SupportsSignature(method.Signature) && IsMethodSupportedInReflectionInvoke(method); } - protected bool IsMethodSignatureSupportedInReflectionInvoke(MethodDesc method) - { - var signature = method.Signature; - - // ---------------------------------------------------------------- - // TODO: support for methods returning pointer types - https://github.com/dotnet/corert/issues/2113 - // ---------------------------------------------------------------- - - if (signature.ReturnType.IsPointer) - return false; - - for (int i = 0; i < signature.Length; i++) - if (signature[i].IsByRef && ((ByRefType)signature[i]).ParameterType.IsPointer) - return false; - - // ---------------------------------------------------------------- - // TODO: function pointer types are odd: https://github.com/dotnet/corert/issues/1929 - // ---------------------------------------------------------------- - - if (signature.ReturnType.IsFunctionPointer) - return false; - - for (int i = 0; i < signature.Length; i++) - if (signature[i].IsFunctionPointer) - return false; - - // ---------------------------------------------------------------- - // Methods with ByRef returns can't be reflection invoked - // ---------------------------------------------------------------- - - if (signature.ReturnType.IsByRef) - return false; - - // ---------------------------------------------------------------- - // Methods that return ByRef-like types or take them by reference can't be reflection invoked - // ---------------------------------------------------------------- - - if (signature.ReturnType.IsByRefLike) - return false; - - for (int i = 0; i < signature.Length; i++) - { - ByRefType paramType = signature[i] as ByRefType; - if (paramType != null && paramType.ParameterType.IsByRefLike) - return false; - } - - return true; - } - protected bool IsMethodSupportedInReflectionInvoke(MethodDesc method) { TypeDesc owningType = method.OwningType; @@ -430,7 +378,11 @@ namespace ILCompiler /// /// Given that a method is invokable, does there exist a reflection invoke stub? /// - public abstract bool HasReflectionInvokeStubForInvokableMethod(MethodDesc method); + public bool HasReflectionInvokeStubForInvokableMethod(MethodDesc method) + { + Debug.Assert(IsReflectionInvokable(method)); + return _dynamicInvokeThunkGenerationPolicy.HasStaticInvokeThunk(method); + } /// /// Given that a method is invokable, if it is inserted into the reflection invoke table @@ -470,65 +422,7 @@ namespace ILCompiler // Instantiate the generic thunk over the parameters and the return type of the target method // - ParameterMetadata[] paramMetadata = null; - TypeDesc[] instantiation = new TypeDesc[sig.ReturnType.IsVoid ? sig.Length : sig.Length + 1]; - Debug.Assert(thunk.Instantiation.Length == instantiation.Length); - for (int i = 0; i < sig.Length; i++) - { - TypeDesc parameterType = sig[i]; - if (parameterType.IsByRef) - { - // strip ByRefType off the parameter (the method already has ByRef in the signature) - parameterType = ((ByRefType)parameterType).ParameterType; - - Debug.Assert(!parameterType.IsPointer); // TODO: support for methods returning pointer types - https://github.com/dotnet/corert/issues/2113 - } - else if (parameterType.IsPointer || parameterType.IsFunctionPointer) - { - // For pointer typed parameters, instantiate the method over IntPtr - parameterType = context.GetWellKnownType(WellKnownType.IntPtr); - } - else if (parameterType.IsEnum) - { - // If the invoke method takes an enum as an input parameter and there is no default value for - // that paramter, we don't need to specialize on the exact enum type (we only need to specialize - // on the underlying integral type of the enum.) - if (paramMetadata == null) - paramMetadata = method.GetParameterMetadata(); - - bool hasDefaultValue = false; - foreach (var p in paramMetadata) - { - // Parameter metadata indexes are 1-based (0 is reserved for return "parameter") - if (p.Index == (i + 1) && p.HasDefault) - { - hasDefaultValue = true; - break; - } - } - - if (!hasDefaultValue) - parameterType = parameterType.UnderlyingType; - } - - instantiation[i] = parameterType; - } - - if (!sig.ReturnType.IsVoid) - { - TypeDesc returnType = sig.ReturnType; - Debug.Assert(!returnType.IsByRef); - - // If the invoke method return an object reference, we don't need to specialize on the - // exact type of the object reference, as the behavior is not different. - if ((returnType.IsDefType && !returnType.IsValueType) || returnType.IsArray) - { - returnType = context.GetWellKnownType(WellKnownType.Object); - } - - instantiation[sig.Length] = returnType; - } - + TypeDesc[] instantiation = Internal.IL.Stubs.DynamicInvokeMethodThunk.GetThunkInstantiationForMethod(method); Debug.Assert(thunk.Instantiation.Length == instantiation.Length); // Check if at least one of the instantiation arguments is a universal canonical type, and if so, we @@ -683,11 +577,6 @@ namespace ILCompiler return _methodBodiesGenerated; } - internal IEnumerable GetDefaultConstructorsNeeded() - { - return _defaultConstructorsNeeded; - } - internal bool TypeGeneratesEEType(TypeDesc type) { return _typesWithEETypesGenerated.Contains(type); @@ -777,6 +666,11 @@ namespace ILCompiler return _blockingPolicy.IsBlocked(typicalMethodDefinition); } + public bool IsManifestResourceBlocked(ModuleDesc module, string resourceName) + { + return _resourceBlockingPolicy.IsManifestResourceBlocked(module, resourceName); + } + public bool CanGenerateMetadata(MetadataType type) { return (GetMetadataCategory(type) & MetadataCategory.Description) != 0; diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/MethodExtensions.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/MethodExtensions.cs index 15070a4b4e..fd274af789 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/MethodExtensions.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/MethodExtensions.cs @@ -30,6 +30,26 @@ namespace ILCompiler return null; } + public static string GetRuntimeImportDllName(this EcmaMethod This) + { + var decoded = This.GetDecodedCustomAttribute("System.Runtime", "RuntimeImportAttribute"); + if (decoded == null) + return null; + + var decodedValue = decoded.Value; + + if (decodedValue.FixedArguments.Length == 2) + return (string)decodedValue.FixedArguments[0].Value; + + foreach (var argument in decodedValue.NamedArguments) + { + if (argument.Name == "DllName") + return (string)argument.Value; + } + + return null; + } + public static string GetRuntimeExportName(this EcmaMethod This) { var decoded = This.GetDecodedCustomAttribute("System.Runtime", "RuntimeExportAttribute"); @@ -113,5 +133,19 @@ namespace ILCompiler return false; } + + /// + /// Determine whether a method can go into the sealed vtable of a type. Such method must be a sealed virtual + /// method that is not overriding any method on a base type. + /// Given that such methods can never be overridden in any derived type, we can + /// save space in the vtable of a type, and all of its derived types by not emitting these methods in their vtables, + /// and storing them in a separate table on the side. This is especially beneficial for all array types, + /// since all of their collection interface methods are sealed and implemented on the System.Array and + /// System.Array<T> base types, and therefore we can minimize the vtable sizes of all derived array types. + /// + public static bool CanMethodBeInSealedVTable(this MethodDesc method) + { + return method.IsFinal && method.IsNewSlot; + } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/MultiFileCompilationModuleGroup.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/MultiFileCompilationModuleGroup.cs index 9541e4285e..842ddefadb 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/MultiFileCompilationModuleGroup.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/MultiFileCompilationModuleGroup.cs @@ -17,12 +17,11 @@ namespace ILCompiler private HashSet _compilationModuleSet; public MultiFileCompilationModuleGroup(TypeSystemContext context, IEnumerable compilationModuleSet) - : base(context) { _compilationModuleSet = new HashSet(compilationModuleSet); // The fake assembly that holds compiler generated types is part of the compilation. - _compilationModuleSet.Add(this.GeneratedAssembly); + _compilationModuleSet.Add(context.GeneratedAssembly); } public sealed override bool ContainsType(TypeDesc type) @@ -59,6 +58,11 @@ namespace ILCompiler return ContainsMethodBody(method, false); } + public sealed override bool ImportsMethod(MethodDesc method, bool unboxingStub) + { + return false; + } + public sealed override ExportForm GetExportTypeForm(TypeDesc type) { return ExportForm.None; diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/NativeLibraryInitializerRootProvider.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/NativeLibraryInitializerRootProvider.cs index d7460d45ac..4079a902b8 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/NativeLibraryInitializerRootProvider.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/NativeLibraryInitializerRootProvider.cs @@ -20,10 +20,10 @@ namespace ILCompiler /// public const string ManagedEntryPointMethodName = "__managed__Startup"; - private EcmaModule _module; - private IList _libraryInitializers; + private ModuleDesc _module; + private IReadOnlyCollection _libraryInitializers; - public NativeLibraryInitializerRootProvider(EcmaModule module, IList libraryInitializers) + public NativeLibraryInitializerRootProvider(ModuleDesc module, IReadOnlyCollection libraryInitializers) { _module = module; _libraryInitializers = libraryInitializers; diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/NoManifestResourceBlockingPolicy.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/NoManifestResourceBlockingPolicy.cs new file mode 100644 index 0000000000..fd58d0e5bf --- /dev/null +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/NoManifestResourceBlockingPolicy.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.TypeSystem; + +namespace ILCompiler +{ + /// + /// A blocking policy that doesn't block any manifest resources. + /// + public sealed class NoManifestResourceBlockingPolicy : ManifestResourceBlockingPolicy + { + public override bool IsManifestResourceBlocked(ModuleDesc module, string resourceName) + { + return false; + } + } +} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/NoMetadataBlockingPolicy.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/NoMetadataBlockingPolicy.cs new file mode 100644 index 0000000000..af0c073b9a --- /dev/null +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/NoMetadataBlockingPolicy.cs @@ -0,0 +1,51 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.TypeSystem; +using Internal.TypeSystem.Ecma; + +namespace ILCompiler +{ + /// + /// Represents a metadata blocking policy that doesn't block any metadata. + /// + public sealed class NoMetadataBlockingPolicy : MetadataBlockingPolicy + { + public override bool IsBlocked(MetadataType type) => !(type is EcmaType); + + public override bool IsBlocked(FieldDesc field) => !(field is EcmaField); + + private MetadataType _arrayOfTType; + private MetadataType InitializeArrayOfTType(TypeSystemEntity contextEntity) + { + _arrayOfTType = contextEntity.Context.SystemModule.GetType("System", "Array`1"); + return _arrayOfTType; + } + private MetadataType GetArrayOfTType(TypeSystemEntity contextEntity) + { + if (_arrayOfTType != null) + { + return _arrayOfTType; + } + return InitializeArrayOfTType(contextEntity); + } + + public override bool IsBlocked(MethodDesc method) + { + if (method is EcmaMethod ecmaMethod) + { + // Methods on Array`1 are implementation details that implement the generic interfaces on + // arrays. They should not generate metadata or be reflection invokable. + // We can get rid of this special casing if we make these methods stop being regular EcmaMethods + // with Array as their owning type + if (ecmaMethod.OwningType == GetArrayOfTType(ecmaMethod)) + return true; + + return false; + } + + return true; + } + } +} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/PrecomputedMetadataManager.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/PrecomputedMetadataManager.cs index 0e333d323d..a005fa3799 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/PrecomputedMetadataManager.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/PrecomputedMetadataManager.cs @@ -33,6 +33,7 @@ namespace ILCompiler public ImmutableArray LocalMetadataModules = ImmutableArray.Empty; public ImmutableArray ExternalMetadataModules = ImmutableArray.Empty; public List TypesWithStrongMetadataMappings = new List(); + public Dictionary WeakReflectedTypeMappings = new Dictionary(); public Dictionary AllTypeMappings = new Dictionary(); public Dictionary MethodMappings = new Dictionary(); public Dictionary FieldMappings = new Dictionary(); @@ -62,9 +63,15 @@ namespace ILCompiler IEnumerable compilationModules, IEnumerable inputMetadataOnlyAssemblies, byte[] metadataBlob, - StackTraceEmissionPolicy stackTraceEmissionPolicy) - : base(typeSystemContext, new AttributeSpecifiedBlockingPolicy()) + StackTraceEmissionPolicy stackTraceEmissionPolicy, + ManifestResourceBlockingPolicy resourceBlockingPolicy, + bool disableInvokeThunks) + : base(typeSystemContext, new AttributeSpecifiedBlockingPolicy(), resourceBlockingPolicy, + disableInvokeThunks ? (DynamicInvokeThunkGenerationPolicy)new NoDynamicInvokeThunkGenerationPolicy() : new PrecomputedDynamicInvokeThunkGenerationPolicy()) { + // Need to do this dance because C# won't let us access `this` in the `base()` expression above. Sigh. + (_dynamicInvokeThunkGenerationPolicy as PrecomputedDynamicInvokeThunkGenerationPolicy)?.SetParentWorkaround(this); + _compilationModuleGroup = group; _metadataDescribingModule = metadataDescribingModule; _compilationModules = new HashSet(compilationModules); @@ -400,7 +407,7 @@ namespace ILCompiler MethodIL weakMethodIL = ilProvider.GetMethodIL(weakMetadataMethod); Dictionary weakMethodMappings = new Dictionary(); Dictionary weakFieldMappings = new Dictionary(); - ReadMetadataMethod(weakMethodIL, result.AllTypeMappings, weakMethodMappings, weakFieldMappings, metadataModules); + ReadMetadataMethod(weakMethodIL, result.WeakReflectedTypeMappings, weakMethodMappings, weakFieldMappings, metadataModules); if ((weakMethodMappings.Count > 0) || (weakFieldMappings.Count > 0)) { // the format does not permit weak field/method mappings @@ -538,7 +545,7 @@ namespace ILCompiler } } - if (metadataType.ThreadStaticFieldSize.AsInt > 0) + if (metadataType.ThreadGcStaticFieldSize.AsInt > 0) { dependencies.Add(((UtcNodeFactory)factory).TypeThreadStaticsOffsetSymbol(metadataType), "Thread statics for ReflectionFieldMap entry"); } @@ -706,7 +713,7 @@ namespace ILCompiler continue; int token; - if (loadedMetadata.AllTypeMappings.TryGetValue(definition, out token)) + if (loadedMetadata.AllTypeMappings.TryGetValue(definition, out token) || loadedMetadata.WeakReflectedTypeMappings.TryGetValue(definition, out token)) { typeMappings.Add(new MetadataMapping(definition, token)); } @@ -739,6 +746,14 @@ namespace ILCompiler AddFieldMapping(field, canonicalFieldsAddedToMap, fieldMappings); } + foreach (var typeMapping in loadedMetadata.WeakReflectedTypeMappings) + { + // Imported types that are also declared as weak reflected types need to be added to the TypeMap table, but only if they are also + // reachable from static compilation (node marked in the dependency analysis graph) + if (factory.CompilationModuleGroup.ShouldReferenceThroughImportTable(typeMapping.Key) && factory.NecessaryTypeSymbol(typeMapping.Key).Marked) + typeMappings.Add(new MetadataMapping(typeMapping.Key, typeMapping.Value)); + } + stackTraceMapping = GenerateStackTraceMetadata(factory); } @@ -893,38 +908,6 @@ namespace ILCompiler return dynamicInvokeMapTable; } - /// - /// Is there a reflection invoke stub for a method that is invokable? - /// - public override bool HasReflectionInvokeStubForInvokableMethod(MethodDesc method) - { - Debug.Assert(IsReflectionInvokable(method)); - - if (!ProjectNDependencyBehavior.EnableFullAnalysis) - { - if (method.IsCanonicalMethod(CanonicalFormKind.Any)) - return false; - } - else - { - if (method.IsCanonicalMethod(CanonicalFormKind.Universal)) - return false; - } - - MethodDesc reflectionInvokeStub = GetCanonicalReflectionInvokeStub(method); - - if (reflectionInvokeStub == null) - return false; - - // TODO: Generate DynamicInvokeTemplateMap dependencies correctly. For now, force all canonical stubs to go through the - // calling convention converter interpreter path. - if (reflectionInvokeStub.IsSharedByGenericInstantiations) - return false; - - return true; - } - - /// /// Gets a stub that can be used to reflection-invoke a method with a given signature. /// @@ -1040,5 +1023,45 @@ namespace ILCompiler public bool IsBlocked(MethodDesc methodDef) => false; public ModuleDesc GetModuleOfType(MetadataType typeDef) => typeDef.Module; } + + private sealed class PrecomputedDynamicInvokeThunkGenerationPolicy : DynamicInvokeThunkGenerationPolicy + { + private PrecomputedMetadataManager _parent; + + public PrecomputedDynamicInvokeThunkGenerationPolicy() + { + } + + public void SetParentWorkaround(PrecomputedMetadataManager parent) + { + _parent = parent; + } + + public override bool HasStaticInvokeThunk(MethodDesc method) + { + if (!ProjectNDependencyBehavior.EnableFullAnalysis) + { + if (method.IsCanonicalMethod(CanonicalFormKind.Any)) + return false; + } + else + { + if (method.IsCanonicalMethod(CanonicalFormKind.Universal)) + return false; + } + + MethodDesc reflectionInvokeStub = _parent.GetCanonicalReflectionInvokeStub(method); + + if (reflectionInvokeStub == null) + return false; + + // TODO: Generate DynamicInvokeTemplateMap dependencies correctly. For now, force all canonical stubs to go through the + // calling convention converter interpreter path. + if (reflectionInvokeStub.IsSharedByGenericInstantiations) + return false; + + return true; + } + } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/RuntimeConfigurationRootProvider.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/RuntimeConfigurationRootProvider.cs new file mode 100644 index 0000000000..e4be79fc19 --- /dev/null +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/RuntimeConfigurationRootProvider.cs @@ -0,0 +1,58 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; + +namespace ILCompiler +{ + /// + /// A root provider that provides a runtime configuration blob that influences runtime behaviors. + /// See RhConfigValues.h for allowed values. + /// + public class RuntimeConfigurationRootProvider : ICompilationRootProvider + { + private readonly IEnumerable _runtimeOptions; + + public RuntimeConfigurationRootProvider(IEnumerable runtimeOptions) + { + _runtimeOptions = runtimeOptions; + } + + void ICompilationRootProvider.AddCompilationRoots(IRootingServiceProvider rootProvider) + { + rootProvider.RootReadOnlyDataBlob(GetRuntimeOptionsBlob(), 4, "Runtime configuration information", "g_compilerEmbeddedSettingsBlob"); + } + + protected byte[] GetRuntimeOptionsBlob() + { + const int HeaderSize = 4; + + ArrayBuilder options = new ArrayBuilder(); + + // Reserve space for the header + options.ZeroExtend(HeaderSize); + + foreach (string option in _runtimeOptions) + { + byte[] optionBytes = System.Text.Encoding.ASCII.GetBytes(option); + options.Append(optionBytes); + + // Emit a null to separate the next option + options.Add(0); + } + + byte[] result = options.ToArray(); + + int length = options.Count - HeaderSize; + + // Encode the size of the blob into the header + result[0] = (byte)length; + result[1] = (byte)(length >> 8); + result[2] = (byte)(length >> 0x10); + result[3] = (byte)(length >> 0x18); + + return result; + } + } +} diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/RyuJitCompilationBuilder.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/RyuJitCompilationBuilder.cs index 773560798c..f02559b4eb 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/RyuJitCompilationBuilder.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/RyuJitCompilationBuilder.cs @@ -86,7 +86,7 @@ namespace ILCompiler jitFlagBuilder.Add(CorJitFlag.CORJIT_FLAG_FEATURE_SIMD); } - var interopStubManager = new CompilerGeneratedInteropStubManager(_compilationGroup, _context, new InteropStateManager(_compilationGroup.GeneratedAssembly)); + var interopStubManager = new CompilerGeneratedInteropStubManager(_compilationGroup, _context, new InteropStateManager(_context.GeneratedAssembly)); var factory = new RyuJitNodeFactory(_context, _compilationGroup, _metadataManager, interopStubManager, _nameMangler, _vtableSliceProvider, _dictionaryLayoutProvider); var jitConfig = new JitConfigProvider(jitFlagBuilder.ToArray(), _ryujitOptions); diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/SimdHelper.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/SimdHelper.cs index 3f523b18da..53f606c57f 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/SimdHelper.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/SimdHelper.cs @@ -17,19 +17,27 @@ namespace ILCompiler { private ModuleDesc[] _simdModulesCached; - public bool IsInSimdModule(TypeDesc type) + public bool IsSimdType(TypeDesc type) { - if (type is MetadataType) + if (type is MetadataType metadataType) { if (_simdModulesCached == null) { InitializeSimdModules(type); } - ModuleDesc typeModule = ((MetadataType)type).Module; + ModuleDesc typeModule = metadataType.Module; foreach (ModuleDesc simdModule in _simdModulesCached) if (typeModule == simdModule) return true; + + if (metadataType.IsIntrinsic) + { + string name = metadataType.Name; + if ((name == "Vector`1" || name == "Vector") && + metadataType.Namespace == "System.Numerics") + return true; + } } return false; @@ -54,7 +62,7 @@ namespace ILCompiler public bool IsVectorOfT(TypeDesc type) { - return IsInSimdModule(type) + return IsSimdType(type) && ((MetadataType)type).Name == "Vector`1" && ((MetadataType)type).Namespace == "System.Numerics"; } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/SingleFileCompilationModuleGroup.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/SingleFileCompilationModuleGroup.cs index ba4c23d79b..90a0043be2 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/SingleFileCompilationModuleGroup.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/SingleFileCompilationModuleGroup.cs @@ -10,11 +10,6 @@ namespace ILCompiler { public class SingleFileCompilationModuleGroup : CompilationModuleGroup { - public SingleFileCompilationModuleGroup(TypeSystemContext context) - : base(context) - { - } - public override bool ContainsType(TypeDesc type) { return true; @@ -36,6 +31,11 @@ namespace ILCompiler return ContainsMethodBody(method, false); } + public override bool ImportsMethod(MethodDesc method, bool unboxingStub) + { + return false; + } + public override ExportForm GetExportTypeForm(TypeDesc type) { return ExportForm.None; diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/SingleMethodCompilationModuleGroup.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/SingleMethodCompilationModuleGroup.cs index 61f220e094..9a14352173 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/SingleMethodCompilationModuleGroup.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/SingleMethodCompilationModuleGroup.cs @@ -17,7 +17,6 @@ namespace ILCompiler private MethodDesc _method; public SingleMethodCompilationModuleGroup(MethodDesc method) - : base(method.Context) { _method = method; } @@ -51,6 +50,11 @@ namespace ILCompiler return false; } + public override bool ImportsMethod(MethodDesc method, bool unboxingStub) + { + return false; + } + public override ExportForm GetExportTypeForm(TypeDesc type) { return ExportForm.None; diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/TypeExtensions.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/TypeExtensions.cs index 5cf56d1724..99b0de66ce 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/TypeExtensions.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/TypeExtensions.cs @@ -31,14 +31,11 @@ namespace ILCompiler { if (type.IsArray) { - var arrayType = (ArrayType)type; - TypeDesc elementType = arrayType.ElementType; - if (arrayType.IsSzArray && !elementType.IsPointer && !elementType.IsFunctionPointer) - { - MetadataType arrayShadowType = type.Context.SystemModule.GetKnownType("System", "Array`1"); - return arrayShadowType.MakeInstantiatedType(elementType); - } - return type.Context.GetWellKnownType(WellKnownType.Array); + if (type.IsArrayTypeWithoutGenericInterfaces()) + return type.Context.GetWellKnownType(WellKnownType.Array); + + MetadataType arrayShadowType = type.Context.SystemModule.GetKnownType("System", "Array`1"); + return arrayShadowType.MakeInstantiatedType(((ArrayType)type).ElementType); } Debug.Assert(type is DefType); @@ -183,5 +180,19 @@ namespace ILCompiler return false; } + + /// + /// Determines whether an array type does implements the generic collection interfaces. This is the case + /// for multi-dimensional arrays, and arrays of pointers. + /// + public static bool IsArrayTypeWithoutGenericInterfaces(this TypeDesc type) + { + if (!type.IsArray) + return false; + + var arrayType = (ArrayType)type; + TypeDesc elementType = arrayType.ElementType; + return type.IsMdArray || elementType.IsPointer || elementType.IsFunctionPointer; + } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/UsageBasedMetadataManager.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/UsageBasedMetadataManager.cs index b5845786c8..312a1a1923 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/UsageBasedMetadataManager.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/UsageBasedMetadataManager.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; using System.Collections.Generic; using Internal.TypeSystem; @@ -23,6 +24,7 @@ namespace ILCompiler { private readonly CompilationModuleGroup _compilationModuleGroup; + internal readonly UsageBasedMetadataGenerationOptions _generationOptions; private readonly bool _hasPreciseFieldUsageInformation; private readonly List _modulesWithMetadata = new List(); @@ -34,13 +36,17 @@ namespace ILCompiler CompilationModuleGroup group, CompilerTypeSystemContext typeSystemContext, MetadataBlockingPolicy blockingPolicy, + ManifestResourceBlockingPolicy resourceBlockingPolicy, string logFile, - StackTraceEmissionPolicy stackTracePolicy) - : base(group.GeneratedAssembly, typeSystemContext, blockingPolicy, logFile, stackTracePolicy) + StackTraceEmissionPolicy stackTracePolicy, + DynamicInvokeThunkGenerationPolicy invokeThunkGenerationPolicy, + UsageBasedMetadataGenerationOptions generationOptions) + : base(typeSystemContext, blockingPolicy, resourceBlockingPolicy, logFile, stackTracePolicy, invokeThunkGenerationPolicy) { // We use this to mark places that would behave differently if we tracked exact fields used. _hasPreciseFieldUsageInformation = false; _compilationModuleGroup = group; + _generationOptions = generationOptions; } protected override void Graph_NewMarkedNode(DependencyNodeCore obj) @@ -353,8 +359,8 @@ namespace ILCompiler } } - return new AnalysisBasedMetadataManager(_compilationModuleGroup.GeneratedAssembly, - _typeSystemContext, _blockingPolicy, _metadataLogFile, _stackTraceEmissionPolicy, + return new AnalysisBasedMetadataManager( + _typeSystemContext, _blockingPolicy, _resourceBlockingPolicy, _metadataLogFile, _stackTraceEmissionPolicy, _dynamicInvokeThunkGenerationPolicy, _modulesWithMetadata, reflectableTypes.ToEnumerable(), reflectableMethods.ToEnumerable(), reflectableFields.ToEnumerable()); } @@ -438,4 +444,21 @@ namespace ILCompiler } } } + + [Flags] + public enum UsageBasedMetadataGenerationOptions + { + None = 0, + + /// + /// Specifies that complete metadata should be generated for types. + /// + /// + /// If this option is set, generated metadata will no longer be pay for play, + /// and a certain class of bugs will disappear (APIs returning "member doesn't + /// exist" at runtime, even though the member exists and we just didn't generate the metadata). + /// Reflection blocking still applies. + /// + CompleteTypesOnly = 1, + } } diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/UserDefinedTypeDescriptor.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/UserDefinedTypeDescriptor.cs index c91a1f08ed..7427c49815 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/UserDefinedTypeDescriptor.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/UserDefinedTypeDescriptor.cs @@ -81,7 +81,9 @@ namespace ILCompiler descriptor.ReturnType = GetVariableTypeIndex(DebuggerCanonicalize(signature.ReturnType)); descriptor.ThisAdjust = 0; descriptor.CallingConvention = 0x4; // Near fastcall - descriptor.TypeIndexOfThisPointer = signature.IsStatic ? (uint)PrimitiveTypeDescriptor.TYPE_ENUM.T_VOID : GetThisTypeIndex(method.OwningType); + descriptor.TypeIndexOfThisPointer = signature.IsStatic ? + GetPrimitiveTypeIndex(method.OwningType.Context.GetWellKnownType(WellKnownType.Void)) : + GetThisTypeIndex(method.OwningType); descriptor.ContainingClass = GetTypeIndex(method.OwningType, true); try @@ -139,7 +141,7 @@ namespace ILCompiler uint variableTypeIndex = 0; if (type.IsPrimitive) { - variableTypeIndex = PrimitiveTypeDescriptor.GetPrimitiveTypeIndex(type); + variableTypeIndex = GetPrimitiveTypeIndex(type); } else { @@ -180,6 +182,10 @@ namespace ILCompiler variableTypeIndex = GetEnumTypeIndex(type); GetTypeIndex(type, false); // Ensure regular structure record created + + _enumTypes[type] = variableTypeIndex; + + return variableTypeIndex; } variableTypeIndex = GetTypeIndex(type, needsCompleteIndex); @@ -290,7 +296,7 @@ namespace ILCompiler EnumTypeDescriptor enumTypeDescriptor = new EnumTypeDescriptor { ElementCount = (ulong)fieldsDescriptors.Count, - ElementType = PrimitiveTypeDescriptor.GetPrimitiveTypeIndex(defType.UnderlyingType), + ElementType = GetPrimitiveTypeIndex(defType.UnderlyingType), Name = _objectWriter.GetMangledName(type), }; EnumRecordTypeDescriptor[] typeRecords = new EnumRecordTypeDescriptor[enumTypeDescriptor.ElementCount]; @@ -381,33 +387,69 @@ namespace ILCompiler return 0; } - TypeDesc GetFieldDebugType(FieldDesc field) + bool ShouldUseCanonicalTypeRecord(TypeDesc type) { - TypeDesc type = field.FieldType; - // TODO: check the type's generic complexity - if (NodeFactory.LazyGenericsPolicy.UsesLazyGenerics(type)) + return type.GetGenericDepth() > NodeFactory.TypeSystemContext.GenericsConfig.MaxGenericDepthOfDebugRecord; + } + + TypeDesc GetDebugType(TypeDesc type) + { + TypeDesc typeGenericComplexityInfo = type; + + // Strip off pointer, array, and byref details. + while (typeGenericComplexityInfo is ParameterizedType paramType) { + typeGenericComplexityInfo = paramType.ParameterType; + } + + // Types that have some canonical subtypes types should always be represented in normalized canonical form to the binder. + // Also, to avoid infinite generic recursion issues, attempt to use canonical form for fields with high generic complexity. + if (type.IsCanonicalSubtype(CanonicalFormKind.Specific) || (typeGenericComplexityInfo is DefType defType) && ShouldUseCanonicalTypeRecord(defType)) { type = type.ConvertToCanonForm(CanonicalFormKind.Specific); + + // Re-check if the canonical subtype has acceptable generic complexity + typeGenericComplexityInfo = type; + + while (typeGenericComplexityInfo is ParameterizedType paramType) { + typeGenericComplexityInfo = paramType.ParameterType; + } + + if ((typeGenericComplexityInfo is DefType canonDefType) && ShouldUseCanonicalTypeRecord(canonDefType)) + { + type = type.ConvertToCanonForm(CanonicalFormKind.Universal); + } } return type; } + TypeDesc GetFieldDebugType(FieldDesc field) + { + return GetDebugType(field.FieldType); + } + private uint GetClassTypeIndex(TypeDesc type, bool needsCompleteType) { - DefType defType = type as DefType; + TypeDesc debugType = GetDebugType(type); + DefType defType = debugType as DefType; System.Diagnostics.Debug.Assert(defType != null, "GetClassTypeIndex was called with non def type"); ClassTypeDescriptor classTypeDescriptor = new ClassTypeDescriptor { IsStruct = type.IsValueType ? 1 : 0, - Name = _objectWriter.GetMangledName(type), - BaseClassId = 0 + Name = _objectWriter.GetMangledName(defType), + BaseClassId = 0, + InstanceSize = 0 }; uint typeIndex = _objectWriter.GetClassTypeIndex(classTypeDescriptor); _knownTypes[type] = typeIndex; + if (!defType.InstanceByteCount.IsIndeterminate) + { + classTypeDescriptor.InstanceSize = (ulong)defType.InstanceByteCount.AsInt; + } + if (type.HasBaseType && !type.IsValueType) { classTypeDescriptor.BaseClassId = GetTypeIndex(defType.BaseType, true); @@ -417,6 +459,12 @@ namespace ILCompiler List nonGcStaticFields = new List(); List gcStaticFields = new List(); List threadStaticFields = new List(); + List staticsDescs = new List(); + + string nonGcStaticDataName = NodeFactory.NameMangler.NodeMangler.NonGCStatics(type); + string gcStaticDataName = NodeFactory.NameMangler.NodeMangler.GCStatics(type); + string threadStaticDataName = NodeFactory.NameMangler.NodeMangler.ThreadStatics(type); + bool IsCoreRTAbi = Abi == TargetAbi.CoreRT; bool isCanonical = defType.IsCanonicalSubtype(CanonicalFormKind.Any); @@ -439,6 +487,30 @@ namespace ILCompiler if (fieldDesc.IsStatic) { + if (NodeFactory.Target.OperatingSystem != TargetOS.Windows) + { + StaticDataFieldDescriptor staticDesc = new StaticDataFieldDescriptor + { + StaticOffset = (ulong)fieldOffsetEmit + }; + + // Mark field as static + field.Offset = 0xFFFFFFFF; + + if (fieldDesc.IsThreadStatic) { + staticDesc.StaticDataName = threadStaticDataName; + staticDesc.IsStaticDataInObject = IsCoreRTAbi ? 1 : 0; + } else if (fieldDesc.HasGCStaticBase) { + staticDesc.StaticDataName = gcStaticDataName; + staticDesc.IsStaticDataInObject = IsCoreRTAbi ? 1 : 0; + } else { + staticDesc.StaticDataName = nonGcStaticDataName; + staticDesc.IsStaticDataInObject = 0; + } + + staticsDescs.Add(staticDesc); + } + if (fieldDesc.IsThreadStatic) threadStaticFields.Add(field); else if (fieldDesc.HasGCStaticBase) @@ -452,9 +524,18 @@ namespace ILCompiler } } - InsertStaticFieldRegionMember(fieldsDescs, defType, nonGcStaticFields, WindowsNodeMangler.NonGCStaticMemberName, "__type_" + WindowsNodeMangler.NonGCStaticMemberName, false); - InsertStaticFieldRegionMember(fieldsDescs, defType, gcStaticFields, WindowsNodeMangler.GCStaticMemberName, "__type_" + WindowsNodeMangler.GCStaticMemberName, Abi == TargetAbi.CoreRT); - InsertStaticFieldRegionMember(fieldsDescs, defType, threadStaticFields, WindowsNodeMangler.ThreadStaticMemberName, "__type_" + WindowsNodeMangler.ThreadStaticMemberName, Abi == TargetAbi.CoreRT); + if (NodeFactory.Target.OperatingSystem == TargetOS.Windows) + { + InsertStaticFieldRegionMember(fieldsDescs, defType, nonGcStaticFields, WindowsNodeMangler.NonGCStaticMemberName, "__type_" + WindowsNodeMangler.NonGCStaticMemberName, false); + InsertStaticFieldRegionMember(fieldsDescs, defType, gcStaticFields, WindowsNodeMangler.GCStaticMemberName, "__type_" + WindowsNodeMangler.GCStaticMemberName, IsCoreRTAbi); + InsertStaticFieldRegionMember(fieldsDescs, defType, threadStaticFields, WindowsNodeMangler.ThreadStaticMemberName, "__type_" + WindowsNodeMangler.ThreadStaticMemberName, IsCoreRTAbi); + } + else + { + fieldsDescs.AddRange(nonGcStaticFields); + fieldsDescs.AddRange(gcStaticFields); + fieldsDescs.AddRange(threadStaticFields); + } DataFieldDescriptor[] fields = new DataFieldDescriptor[fieldsDescs.Count]; for (int i = 0; i < fieldsDescs.Count; ++i) @@ -462,15 +543,21 @@ namespace ILCompiler fields[i] = fieldsDescs[i]; } + StaticDataFieldDescriptor[] statics = new StaticDataFieldDescriptor[staticsDescs.Count]; + for (int i = 0; i < staticsDescs.Count; ++i) + { + statics[i] = staticsDescs[i]; + } + LayoutInt elementSize = defType.GetElementSize(); int elementSizeEmit = elementSize.IsIndeterminate ? 0xBAAD : elementSize.AsInt; ClassFieldsTypeDescriptor fieldsDescriptor = new ClassFieldsTypeDescriptor { Size = (ulong)elementSizeEmit, - FieldsCount = fieldsDescs.Count + FieldsCount = fieldsDescs.Count, }; - uint completeTypeIndex = _objectWriter.GetCompleteClassTypeIndex(classTypeDescriptor, fieldsDescriptor, fields); + uint completeTypeIndex = _objectWriter.GetCompleteClassTypeIndex(classTypeDescriptor, fieldsDescriptor, fields, statics); _completeKnownTypes[type] = completeTypeIndex; if (needsCompleteType) @@ -502,7 +589,7 @@ namespace ILCompiler classTypeDescriptor.BaseClassId = GetTypeIndex(defType.Context.GetWellKnownType(WellKnownType.Object), true); } - uint staticFieldRegionTypeIndex = _objectWriter.GetCompleteClassTypeIndex(classTypeDescriptor, fieldsDescriptor, staticFields.ToArray()); + uint staticFieldRegionTypeIndex = _objectWriter.GetCompleteClassTypeIndex(classTypeDescriptor, fieldsDescriptor, staticFields.ToArray(), null); uint staticFieldRegionSymbolTypeIndex = staticFieldRegionTypeIndex; // This means that access to this static region is done via a double indirection @@ -530,6 +617,21 @@ namespace ILCompiler } } + private uint GetPrimitiveTypeIndex(TypeDesc type) + { + Debug.Assert(type.IsPrimitive, "it is not a primitive type"); + + uint typeIndex; + + if (_primitiveTypes.TryGetValue(type, out typeIndex)) + return typeIndex; + + typeIndex = _objectWriter.GetPrimitiveTypeIndex(type); + _primitiveTypes[type] = typeIndex; + + return typeIndex; + } + private ITypesDebugInfoWriter _objectWriter; private Dictionary _knownTypes = new Dictionary(); private Dictionary _completeKnownTypes = new Dictionary(); @@ -538,6 +640,7 @@ namespace ILCompiler private Dictionary _enumTypes = new Dictionary(); private Dictionary _byRefTypes = new Dictionary(); private Dictionary _thisTypes = new Dictionary(); + private Dictionary _primitiveTypes = new Dictionary(); private Dictionary _methodIndices = new Dictionary(); private Dictionary _methodIdIndices = new Dictionary(); diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/UtcNameMangler.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/UtcNameMangler.cs index 6eaf70a75b..5a0aa6515d 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/UtcNameMangler.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/UtcNameMangler.cs @@ -40,15 +40,19 @@ namespace ILCompiler private ImportExportOrdinals _importOrdinals; private ImportExportOrdinals _exportOrdinals; + private Dictionary _inputModuleIndices; + private bool HasImport { get; set; } private bool HasExport { get; set; } + private bool BuildingClassLib { get; } - public UTCNameMangler(bool hasImport, bool hasExport, ImportExportOrdinals ordinals) : base(new UtcNodeMangler()) + public UTCNameMangler(bool hasImport, bool hasExport, ImportExportOrdinals ordinals, TypeSystemContext context, List inputModules, bool buildingClassLib) : base(new UtcNodeMangler()) { // Do not support both imports and exports for one module Debug.Assert(!hasImport || !hasExport); HasImport = hasImport; HasExport = hasExport; + BuildingClassLib = buildingClassLib; if (hasImport) { @@ -59,11 +63,35 @@ namespace ILCompiler _exportOrdinals = ordinals; } + _inputModuleIndices = new Dictionary(); + for (int i = 0; i < inputModules.Count; i++) + _inputModuleIndices[inputModules[i]] = i; + // Use SHA256 hash here to provide a high degree of uniqueness to symbol names without requiring them to be long // This hash function provides an exceedingly high likelihood that no two strings will be given equal symbol names // This is not considered used for security purpose; however collisions would be highly unfortunate as they will cause compilation // failure. _sha256 = SHA256.Create(); + + // Special case primitive types and use shortened names. This reduces string sizes in symbol names, and reduces the overall native memory + // usage of the compiler + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.Void), "void"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.Boolean), "bool"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.Char), "char"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.SByte), "sbyte"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.Byte), "byte"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.Int16), "short"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.UInt16), "ushort"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.Int32), "int"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.UInt32), "uint"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.Int64), "long"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.UInt64), "ulong"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.Single), "float"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.Double), "double"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.Object), "object"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.String), "string"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.IntPtr), "IntPtr"); + _mangledTypeNames = _mangledTypeNames.Add(context.GetWellKnownType(WellKnownType.UIntPtr), "UIntPtr"); } private bool GetMethodOrdinal(MethodDesc method, out uint ordinal) @@ -157,6 +185,15 @@ namespace ILCompiler continue; } + if (sb != null) + { + if (c == '[' || c == ']' || c == '&' || c == '*' || c == '$' || c == '<' || c == '>') + { + sb.Append(c); + continue; + } + } + if (sb == null) sb = new StringBuilder(s, 0, i, s.Length); @@ -167,6 +204,13 @@ namespace ILCompiler continue; } + if (c == '$' && i == 0) + { + // '$' is used at the begining of the string as assembly identifiers (ex: $0_, similar to ProjectN) + sb.Append(c); + continue; + } + // Everything else is replaced by underscore. // TODO: We assume that there won't be collisions with our own or C++ built-in identifiers. sb.Append("_"); @@ -254,6 +298,20 @@ namespace ILCompiler return EnterNameScopeSequence + name + ExitNameScopeSequence; } + private string ComputeMangledModuleName(EcmaAssembly module) + { + // Do not prepend the module prefix when building pntestcl because the prefix is unknown + // when building an app against pntestcl. + if (!BuildingClassLib) + { + int index; + if (_inputModuleIndices.TryGetValue(module, out index)) + return "$" + index; + } + + return SanitizeName(module.GetName().Name); + } + /// /// If given is an precompute its mangled type name /// along with all the other types from the same module as . @@ -268,7 +326,7 @@ namespace ILCompiler { EcmaType ecmaType = (EcmaType)type; - string prependAssemblyName = SanitizeName(((EcmaAssembly)ecmaType.EcmaModule).GetName().Name); + string prependAssemblyName = ComputeMangledModuleName((EcmaAssembly)ecmaType.EcmaModule); var deduplicator = new HashSet(); @@ -280,6 +338,15 @@ namespace ILCompiler { foreach (MetadataType t in ((EcmaType)type).EcmaModule.GetAllTypes()) { + if (_mangledTypeNames.ContainsKey(t)) + { + Debug.Assert( + (t.Category & TypeFlags.CategoryMask) <= TypeFlags.Double || + t == type.Context.GetWellKnownType(WellKnownType.Object) || + t == type.Context.GetWellKnownType(WellKnownType.String)); + continue; + } + string name = t.GetFullName(); // Include encapsulating type @@ -290,8 +357,7 @@ namespace ILCompiler containingType = containingType.ContainingType; } - name = SanitizeName(name, true); - name = prependAssemblyName + "_" + name; + name = SanitizeName(prependAssemblyName + "_" + name, true); // Ensure that name is unique and update our tables accordingly. name = DisambiguateName(name, deduplicator); @@ -310,22 +376,22 @@ namespace ILCompiler { case TypeFlags.Array: case TypeFlags.SzArray: - mangledName = GetMangledTypeName(((ArrayType)type).ElementType) + "__"; + mangledName = GetMangledTypeName(((ArrayType)type).ElementType); if (type.IsMdArray) { - mangledName += NestMangledName("ArrayRank" + ((ArrayType)type).Rank.ToStringInvariant()); + mangledName += "[md" + ((ArrayType)type).Rank.ToString() + "]"; } else { - mangledName += NestMangledName("Array"); + mangledName += "[]"; } break; case TypeFlags.ByRef: - mangledName = GetMangledTypeName(((ByRefType)type).ParameterType) + NestMangledName("ByRef"); + mangledName = GetMangledTypeName(((ByRefType)type).ParameterType) + "&"; break; case TypeFlags.Pointer: - mangledName = GetMangledTypeName(((PointerType)type).ParameterType) + NestMangledName("Pointer"); + mangledName = GetMangledTypeName(((PointerType)type).ParameterType) + "*"; break; default: diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/VirtualMethodCallHelper.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/VirtualMethodCallHelper.cs index 27b1198c6e..19da1f6aed 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/VirtualMethodCallHelper.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/VirtualMethodCallHelper.cs @@ -16,29 +16,74 @@ namespace ILCompiler /// Given a virtual method decl, return its VTable slot if the method is used on its containing type. /// Return -1 if the virtual method is not used. /// - public static int GetVirtualMethodSlot(NodeFactory factory, MethodDesc method, bool countDictionarySlots = true) + public static int GetVirtualMethodSlot(NodeFactory factory, MethodDesc method, TypeDesc implType, bool countDictionarySlots = true) { - // TODO: More efficient lookup of the slot - TypeDesc owningType = method.OwningType; - int baseSlots = GetNumberOfBaseSlots(factory, owningType, countDictionarySlots); - - // For types that have a generic dictionary, the introduced virtual method slots are - // prefixed with a pointer to the generic dictionary. - if (owningType.HasGenericDictionarySlot() && countDictionarySlots) - baseSlots++; - - IReadOnlyList virtualSlots = factory.VTable(owningType).Slots; - int methodSlot = -1; - for (int slot = 0; slot < virtualSlots.Count; slot++) + if (method.CanMethodBeInSealedVTable()) { - if (virtualSlots[slot] == method) - { - methodSlot = slot; - break; - } - } + // If the method is a sealed newslot method, it will be put in the sealed vtable instead of the type's vtable. In this + // case, the slot index return should be the index in the sealed vtable, plus the total number of vtable slots. - return methodSlot == -1 ? -1 : baseSlots + methodSlot; + // First, make sure we are not attempting to resolve the slot of a sealed vtable method on a special array type, which + // does not get any sealed vtable entries + Debug.Assert(!implType.IsArrayTypeWithoutGenericInterfaces()); + + // Ensure the sealed vtable is built before computing the slot + factory.SealedVTable(implType).BuildSealedVTableSlots(factory, relocsOnly: false /* GetVirtualMethodSlot is called in the final emission phase */); + + int sealedVTableSlot = factory.SealedVTable(implType).ComputeSealedVTableSlot(method); + if (sealedVTableSlot == -1) + return -1; + + // Now compute the total number of vtable slots that would exist on the type + int baseSlots = GetNumberOfBaseSlots(factory, implType, countDictionarySlots); + + // For types that have a generic dictionary, the introduced virtual method slots are + // prefixed with a pointer to the generic dictionary. + if (implType.HasGenericDictionarySlot() && countDictionarySlots) + baseSlots++; + + int numVTableSlots = baseSlots; + IReadOnlyList virtualSlots = factory.VTable(implType).Slots; + for (int slot = 0; slot < virtualSlots.Count; slot++) + { + if (virtualSlots[slot].CanMethodBeInSealedVTable()) + continue; + numVTableSlots++; + } + + return numVTableSlots + sealedVTableSlot; + } + else + { + // TODO: More efficient lookup of the slot + TypeDesc owningType = method.OwningType; + int baseSlots = GetNumberOfBaseSlots(factory, owningType, countDictionarySlots); + + // For types that have a generic dictionary, the introduced virtual method slots are + // prefixed with a pointer to the generic dictionary. + if (owningType.HasGenericDictionarySlot() && countDictionarySlots) + baseSlots++; + + IReadOnlyList virtualSlots = factory.VTable(owningType).Slots; + int methodSlot = -1; + int numSealedVTableEntries = 0; + for (int slot = 0; slot < virtualSlots.Count; slot++) + { + if (virtualSlots[slot].CanMethodBeInSealedVTable()) + { + numSealedVTableEntries++; + continue; + } + + if (virtualSlots[slot] == method) + { + methodSlot = slot; + break; + } + } + + return methodSlot == -1 ? -1 : baseSlots + methodSlot - numSealedVTableEntries; + } } private static int GetNumberOfBaseSlots(NodeFactory factory, TypeDesc owningType, bool countDictionarySlots) @@ -83,7 +128,13 @@ namespace ILCompiler baseSlots++; IReadOnlyList baseVirtualSlots = factory.VTable(baseType).Slots; - baseSlots += baseVirtualSlots.Count; + foreach (var vtableMethod in baseVirtualSlots) + { + // Methods in the sealed vtable should be excluded from the count + if (vtableMethod.CanMethodBeInSealedVTable()) + continue; + baseSlots++; + } baseType = baseType.BaseType; templateBaseType = templateBaseType.BaseType; diff --git a/external/corert/src/ILCompiler.Compiler/src/Compiler/WindowsNodeMangler.cs b/external/corert/src/ILCompiler.Compiler/src/Compiler/WindowsNodeMangler.cs index 81f5e1592a..0c3d3163af 100644 --- a/external/corert/src/ILCompiler.Compiler/src/Compiler/WindowsNodeMangler.cs +++ b/external/corert/src/ILCompiler.Compiler/src/Compiler/WindowsNodeMangler.cs @@ -47,7 +47,10 @@ namespace ILCompiler public sealed override string ThreadStatics(TypeDesc type) { - return NameMangler.CompilationUnitPrefix + NameMangler.GetMangledTypeName(type) + "::" + ThreadStaticMemberName; + if (type.Context.Target.Abi == TargetAbi.ProjectN) + return NameMangler.GetMangledTypeName(type) + "::" + ThreadStaticMemberName; + else + return NameMangler.CompilationUnitPrefix + NameMangler.GetMangledTypeName(type) + "::" + ThreadStaticMemberName; } public sealed override string TypeGenericDictionary(TypeDesc type) diff --git a/external/corert/src/ILCompiler.Compiler/src/IL/ILImporter.Scanner.cs b/external/corert/src/ILCompiler.Compiler/src/IL/ILImporter.Scanner.cs index 009dc068bb..9468e25f1f 100644 --- a/external/corert/src/ILCompiler.Compiler/src/IL/ILImporter.Scanner.cs +++ b/external/corert/src/ILCompiler.Compiler/src/IL/ILImporter.Scanner.cs @@ -19,6 +19,7 @@ namespace Internal.IL partial class ILImporter { private readonly MethodIL _methodIL; + private readonly MethodIL _canonMethodIL; private readonly ILScanner _compilation; private readonly ILScanNodeFactory _factory; @@ -84,6 +85,8 @@ namespace Internal.IL _ilBytes = methodIL.GetILBytes(); + _canonMethodIL = methodIL; + // Get the runtime determined method IL so that this works right in shared code // and tokens in shared code resolve to runtime determined types. MethodIL uninstantiatiedMethodIL = methodIL.GetMethodILDefinition(); @@ -266,11 +269,10 @@ namespace Internal.IL private void ImportCall(ILOpcode opcode, int token) { - // Strip runtime determined characteristics off of the method (because that's how RyuJIT operates) + // We get both the canonical and runtime determined form - JitInterface mostly operates + // on the canonical form. var runtimeDeterminedMethod = (MethodDesc)_methodIL.GetObject(token); - MethodDesc method = runtimeDeterminedMethod; - if (runtimeDeterminedMethod.IsRuntimeDeterminedExactMethod) - method = runtimeDeterminedMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); + var method = (MethodDesc)_canonMethodIL.GetObject(token); if (method.IsRawPInvoke()) { @@ -354,10 +356,14 @@ namespace Internal.IL } } - if (method.OwningType.IsDelegate && method.Name == "Invoke") + if (method.OwningType.IsDelegate && method.Name == "Invoke" && + opcode != ILOpcode.ldftn && opcode != ILOpcode.ldvirtftn) { - // TODO: might not want to do this if scanning for reflection. - // This is expanded as an intrinsic, not a function call. + // This call is expanded as an intrinsic; it's not an actual function call. + // Before codegen realizes this is an intrinsic, it might still ask questions about + // the vtable of this virtual method, so let's make sure it's marked in the scanner's + // dependency graph. + _dependencies.Add(_factory.VTable(method.OwningType), reason); return; } diff --git a/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/PInvokeILProvider.cs b/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/PInvokeILProvider.cs index 4aec04036d..7ae483dbcc 100644 --- a/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/PInvokeILProvider.cs +++ b/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/PInvokeILProvider.cs @@ -29,5 +29,10 @@ namespace Internal.IL { return PInvokeILEmitter.EmitIL(method, _pInvokeILEmitterConfiguration, _interopStateManager); } + + public MethodDesc GetCalliStub(MethodSignature signature) + { + return _interopStateManager.GetPInvokeCalliStub(signature); + } } } diff --git a/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/StartupCode/AppContextInitializerMethod.Sorting.cs b/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/StartupCode/AppContextInitializerMethod.Sorting.cs new file mode 100644 index 0000000000..67a2b612ca --- /dev/null +++ b/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/StartupCode/AppContextInitializerMethod.Sorting.cs @@ -0,0 +1,22 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.TypeSystem; + +using Debug = System.Diagnostics.Debug; + +namespace Internal.IL.Stubs.StartupCode +{ + partial class AppContextInitializerMethod + { + protected override int ClassCode => 15749517; + + protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + { + // Should be a singleton + Debug.Assert(this == other); + return 0; + } + } +} diff --git a/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/StartupCode/AppContextInitializerMethod.cs b/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/StartupCode/AppContextInitializerMethod.cs new file mode 100644 index 0000000000..2c2d3a51a5 --- /dev/null +++ b/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/StartupCode/AppContextInitializerMethod.cs @@ -0,0 +1,83 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; + +using Internal.TypeSystem; + +namespace Internal.IL.Stubs.StartupCode +{ + public sealed partial class AppContextInitializerMethod : ILStubMethod + { + private TypeDesc _owningType; + private MethodSignature _signature; + private IReadOnlyCollection _switches; + + public AppContextInitializerMethod(TypeDesc owningType, IEnumerable switches) + { + _owningType = owningType; + _switches = new List(switches); + } + + public override TypeSystemContext Context + { + get + { + return _owningType.Context; + } + } + + public override TypeDesc OwningType + { + get + { + return _owningType; + } + } + + public override string Name + { + get + { + return "SetAppContextSwitches"; + } + } + + public override MethodIL EmitIL() + { + ILEmitter emitter = new ILEmitter(); + ILCodeStream codeStream = emitter.NewCodeStream(); + + MetadataType appContextType = Context.SystemModule.GetKnownType("System", "AppContext"); + MethodDesc setSwitchMethod = appContextType.GetKnownMethod("SetSwitch", null); + ILToken setSwitchToken = emitter.NewToken(setSwitchMethod); + + foreach (string switchName in _switches) + { + codeStream.Emit(ILOpcode.ldstr, emitter.NewToken(switchName)); + codeStream.EmitLdc(1); + codeStream.Emit(ILOpcode.call, setSwitchToken); + } + + codeStream.Emit(ILOpcode.ret); + + return emitter.Link(this); + } + + public override MethodSignature Signature + { + get + { + if (_signature == null) + { + _signature = new MethodSignature(MethodSignatureFlags.Static, 0, + Context.GetWellKnownType(WellKnownType.Void), + TypeDesc.EmptyTypes); + } + + return _signature; + } + } + } +} diff --git a/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/StartupCode/NativeLibraryStartupMethod.cs b/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/StartupCode/NativeLibraryStartupMethod.cs index 80bd691a01..b04e5e9888 100644 --- a/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/StartupCode/NativeLibraryStartupMethod.cs +++ b/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/StartupCode/NativeLibraryStartupMethod.cs @@ -17,9 +17,9 @@ namespace Internal.IL.Stubs.StartupCode { private TypeDesc _owningType; private MethodSignature _signature; - private IList _libraryInitializers; + private IReadOnlyCollection _libraryInitializers; - public NativeLibraryStartupMethod(TypeDesc owningType, IList libraryInitializers) + public NativeLibraryStartupMethod(TypeDesc owningType, IReadOnlyCollection libraryInitializers) { _owningType = owningType; _libraryInitializers = libraryInitializers; diff --git a/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/StartupCode/StartupCodeMainMethod.cs b/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/StartupCode/StartupCodeMainMethod.cs index f994a1d0aa..fd16383f5d 100644 --- a/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/StartupCode/StartupCodeMainMethod.cs +++ b/external/corert/src/ILCompiler.Compiler/src/IL/Stubs/StartupCode/StartupCodeMainMethod.cs @@ -21,9 +21,9 @@ namespace Internal.IL.Stubs.StartupCode private TypeDesc _owningType; private MainMethodWrapper _mainMethod; private MethodSignature _signature; - private IList _libraryInitializers; + private IReadOnlyCollection _libraryInitializers; - public StartupCodeMainMethod(TypeDesc owningType, MethodDesc mainMethod, IList libraryInitializers) + public StartupCodeMainMethod(TypeDesc owningType, MethodDesc mainMethod, IReadOnlyCollection libraryInitializers) { _owningType = owningType; _mainMethod = new MainMethodWrapper(owningType, mainMethod); diff --git a/external/corert/src/ILCompiler.Compiler/src/ILCompiler.Compiler.csproj b/external/corert/src/ILCompiler.Compiler/src/ILCompiler.Compiler.csproj index a29a5cd10f..be2d84a431 100644 --- a/external/corert/src/ILCompiler.Compiler/src/ILCompiler.Compiler.csproj +++ b/external/corert/src/ILCompiler.Compiler/src/ILCompiler.Compiler.csproj @@ -58,9 +58,6 @@ IL\Stubs\ComparerIntrinsics.cs - - IL\Stubs\DynamicInvokeMethodThunk.Sorting.cs - IL\Stubs\GetCanonTypeIntrinsic.cs @@ -73,9 +70,6 @@ IL\Stubs\DelegateMethodILEmitter.cs - - IL\Stubs\DynamicInvokeMethodThunk.cs - IL\Stubs\EETypePtrOfIntrinsic.cs @@ -100,8 +94,6 @@ - - @@ -110,6 +102,8 @@ + + @@ -132,14 +126,21 @@ + + + + + + + @@ -280,9 +281,9 @@ - + @@ -335,6 +336,7 @@ + @@ -359,6 +361,8 @@ + + diff --git a/external/corert/src/ILCompiler.Compiler/tests/DependencyGraphTests.cs b/external/corert/src/ILCompiler.Compiler/tests/DependencyGraphTests.cs index c4ace726b8..a0a60efda5 100644 --- a/external/corert/src/ILCompiler.Compiler/tests/DependencyGraphTests.cs +++ b/external/corert/src/ILCompiler.Compiler/tests/DependencyGraphTests.cs @@ -64,7 +64,7 @@ namespace ILCompiler.Compiler.Tests // var context = (CompilerTypeSystemContext)method.Context; - CompilationModuleGroup compilationGroup = new SingleFileCompilationModuleGroup(context); + CompilationModuleGroup compilationGroup = new SingleFileCompilationModuleGroup(); CompilationBuilder builder = new RyuJitCompilationBuilder(context, compilationGroup); IILScanner scanner = builder.GetILScannerBuilder() diff --git a/external/corert/src/ILCompiler.Compiler/tests/DevirtualizationTests.cs b/external/corert/src/ILCompiler.Compiler/tests/DevirtualizationTests.cs index 6b320fb171..0ebda0cbc9 100644 --- a/external/corert/src/ILCompiler.Compiler/tests/DevirtualizationTests.cs +++ b/external/corert/src/ILCompiler.Compiler/tests/DevirtualizationTests.cs @@ -32,7 +32,7 @@ namespace ILCompiler.Compiler.Tests private DevirtualizationManager GetDevirtualizationManagerFromScan(MethodDesc method) { - CompilationModuleGroup compilationGroup = new SingleFileCompilationModuleGroup(_context); + CompilationModuleGroup compilationGroup = new SingleFileCompilationModuleGroup(); CompilationBuilder builder = new RyuJitCompilationBuilder(_context, compilationGroup); IILScanner scanner = builder.GetILScannerBuilder() diff --git a/external/corert/src/ILCompiler.Compiler/tests/ILCompiler.Compiler.Tests.Assets/ILCompiler.Compiler.Tests.Assets.csproj b/external/corert/src/ILCompiler.Compiler/tests/ILCompiler.Compiler.Tests.Assets/ILCompiler.Compiler.Tests.Assets.csproj index 44d852d96c..a463d125f9 100644 --- a/external/corert/src/ILCompiler.Compiler/tests/ILCompiler.Compiler.Tests.Assets/ILCompiler.Compiler.Tests.Assets.csproj +++ b/external/corert/src/ILCompiler.Compiler/tests/ILCompiler.Compiler.Tests.Assets/ILCompiler.Compiler.Tests.Assets.csproj @@ -4,7 +4,7 @@ Library ILCompiler.Compiler.Tests.Assets false - false + true diff --git a/external/corert/src/ILCompiler.Compiler/tests/ILCompiler.Compiler.Tests.csproj b/external/corert/src/ILCompiler.Compiler/tests/ILCompiler.Compiler.Tests.csproj index 6e2a7f7f4e..797bb79fed 100644 --- a/external/corert/src/ILCompiler.Compiler/tests/ILCompiler.Compiler.Tests.csproj +++ b/external/corert/src/ILCompiler.Compiler/tests/ILCompiler.Compiler.Tests.csproj @@ -4,11 +4,14 @@ Library ILCompiler.Compiler.Tests ILCompiler.Compiler.Tests - netstandard1.3 + netstandard2.0 - - $(XunitNetcoreExtensionsVersion) + + $(XUnitPackageVersion) + + + $(MicrosoftDotNetXUnitExtensionsVersion) diff --git a/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/CppCodegenCompilationBuilder.cs b/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/CppCodegenCompilationBuilder.cs index 8b4fe63601..0068f2da84 100644 --- a/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/CppCodegenCompilationBuilder.cs +++ b/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/CppCodegenCompilationBuilder.cs @@ -31,7 +31,7 @@ namespace ILCompiler public override ICompilation ToCompilation() { - var interopStubManager = new CompilerGeneratedInteropStubManager(_compilationGroup, _context, new InteropStateManager(_compilationGroup.GeneratedAssembly)); + var interopStubManager = new CompilerGeneratedInteropStubManager(_compilationGroup, _context, new InteropStateManager(_context.GeneratedAssembly)); CppCodegenNodeFactory factory = new CppCodegenNodeFactory(_context, _compilationGroup, _metadataManager, interopStubManager, _nameMangler, _vtableSliceProvider, _dictionaryLayoutProvider); DependencyAnalyzerBase graph = CreateDependencyGraph(factory); diff --git a/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/DependencyAnalysis/CppCodegenNodeFactory.cs b/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/DependencyAnalysis/CppCodegenNodeFactory.cs index baf0339aa5..d282e1f270 100644 --- a/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/DependencyAnalysis/CppCodegenNodeFactory.cs +++ b/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/DependencyAnalysis/CppCodegenNodeFactory.cs @@ -40,8 +40,7 @@ namespace ILCompiler.DependencyAnalysis protected override IMethodNode CreateUnboxingStubNode(MethodDesc method) { - // TODO: this is wrong: this returns an assembly stub node - return new UnboxingStubNode(method, Target); + return new CppUnboxingStubNode(method); } protected override ISymbolNode CreateReadyToRunHelperNode(ReadyToRunHelperKey helperCall) diff --git a/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/DependencyAnalysis/CppMethodCodeNode.cs b/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/DependencyAnalysis/CppMethodCodeNode.cs index 70a138649e..49f610ef45 100644 --- a/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/DependencyAnalysis/CppMethodCodeNode.cs +++ b/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/DependencyAnalysis/CppMethodCodeNode.cs @@ -76,9 +76,9 @@ namespace ILCompiler.DependencyAnalysis public override IEnumerable GetConditionalStaticDependencies(NodeFactory factory) => null; public override IEnumerable SearchDynamicDependencies(List> markedNodes, int firstNode, NodeFactory factory) => null; - int ISortableSymbolNode.ClassCode => 1643555522; + int ISortableNode.ClassCode => 1643555522; - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) + int ISortableNode.CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_method, ((CppMethodCodeNode)other)._method); } diff --git a/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/DependencyAnalysis/CppUnboxingStubNode.cs b/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/DependencyAnalysis/CppUnboxingStubNode.cs new file mode 100644 index 0000000000..a47dca6db6 --- /dev/null +++ b/external/corert/src/ILCompiler.CppCodeGen/src/Compiler/DependencyAnalysis/CppUnboxingStubNode.cs @@ -0,0 +1,68 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.Diagnostics; + +using ILCompiler.DependencyAnalysisFramework; + +using Internal.Text; +using Internal.TypeSystem; + +namespace ILCompiler.DependencyAnalysis +{ + internal class CppUnboxingStubNode : DependencyNodeCore, IMethodNode + { + public CppUnboxingStubNode(MethodDesc method) + { + Debug.Assert(method.OwningType.IsValueType && !method.Signature.IsStatic); + Method = method; + } + + public MethodDesc Method { get; } + + public int ClassCode => 17864523; + + public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) + { + sb.Append("unbox_").Append(nameMangler.GetMangledMethodName(Method)); + } + + public int CompareToImpl(ISortableNode other, CompilerComparer comparer) + { + return comparer.Compare(this.Method, ((CppUnboxingStubNode)other).Method); + } + + public override IEnumerable GetStaticDependencies(NodeFactory factory) + { + return new DependencyListEntry[] { + new DependencyListEntry(factory.MethodEntrypoint(Method), "Target of unboxing") }; + } + + protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); + + public static string GetMangledName(NameMangler nameMangler, MethodDesc method) + { + return "unbox_" + nameMangler.GetMangledMethodName(method); + } + + public override bool StaticDependenciesAreComputed => true; + public override bool HasDynamicDependencies => false; + public override bool InterestingForDynamicDependencyAnalysis => false; + public override bool HasConditionalStaticDependencies => false; + + public int Offset => throw new System.NotImplementedException(); + + public bool RepresentsIndirectionCell => throw new System.NotImplementedException(); + + public override IEnumerable GetConditionalStaticDependencies(NodeFactory context) + { + return null; + } + public override IEnumerable SearchDynamicDependencies(List> markedNodes, int firstNode, NodeFactory context) + { + return null; + } + } +} diff --git a/external/corert/src/ILCompiler.CppCodeGen/src/CppCodeGen/CppWriter.cs b/external/corert/src/ILCompiler.CppCodeGen/src/CppCodeGen/CppWriter.cs index ef08550b7b..c813492bf4 100644 --- a/external/corert/src/ILCompiler.CppCodeGen/src/CppCodeGen/CppWriter.cs +++ b/external/corert/src/ILCompiler.CppCodeGen/src/CppCodeGen/CppWriter.cs @@ -15,6 +15,8 @@ using Internal.Text; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; +using Debug = System.Diagnostics.Debug; + namespace ILCompiler.CppCodeGen { internal class CppWriter @@ -586,12 +588,6 @@ namespace ILCompiler.CppCodeGen if (explicitLayout || hasSize) { - if (classLayoutMetadata.Size > 0) - { - sb.AppendLine(); - sb.Append("struct { char __sizePadding[" + classLayoutMetadata.Size + "]; };"); - } - if (!explicitLayout) { sb.Exdent(); @@ -599,6 +595,12 @@ namespace ILCompiler.CppCodeGen sb.Append("};"); } + if (classLayoutMetadata.Size > 0) + { + sb.AppendLine(); + sb.Append("struct { char __sizePadding[" + classLayoutMetadata.Size + "]; };"); + } + sb.Exdent(); sb.AppendLine(); sb.Append("};"); @@ -797,42 +799,61 @@ namespace ILCompiler.CppCodeGen } } } + + bool generateMethod = !(node is BlobNode); + string pointerType = node is EETypeNode ? "MethodTable * " : "void* "; - nodeCode.Append(pointerType); - if (node is EETypeNode) + if (generateMethod) { - nodeCode.Append(GetCppMethodDeclarationName((node as EETypeNode).Type, "__getMethodTable")); + nodeCode.Append(pointerType); + if (node is EETypeNode) + { + nodeCode.Append(GetCppMethodDeclarationName((node as EETypeNode).Type, "__getMethodTable")); + } + else + { + string mangledName = ((ISymbolNode)node).GetMangledName(factory.NameMangler); + + // Rename generic composition and optional fields nodes to avoid name clash with types + bool shouldReplaceNamespaceQualifier = node is GenericCompositionNode || node is EETypeOptionalFieldsNode || node is SealedVTableNode; + nodeCode.Append(shouldReplaceNamespaceQualifier ? mangledName.Replace("::", "_") : mangledName); + } + nodeCode.Append("()"); + nodeCode.AppendLine(); + nodeCode.Append("{"); + nodeCode.Indent(); + nodeCode.AppendLine(); + nodeCode.Append("static "); } else { - string mangledName = ((ISymbolNode)node).GetMangledName(factory.NameMangler); - - // Rename generic composition and optional fields nodes to avoid name clash with types - bool shouldReplaceNamespaceQualifier = node is GenericCompositionNode || node is EETypeOptionalFieldsNode; - nodeCode.Append(shouldReplaceNamespaceQualifier ? mangledName.Replace("::", "_") : mangledName); + nodeCode.Append("extern \"C\" "); } - nodeCode.Append("()"); - nodeCode.AppendLine(); - nodeCode.Append("{"); - nodeCode.Indent(); - nodeCode.AppendLine(); - nodeCode.Append("static struct {"); + nodeCode.Append("struct {"); nodeCode.AppendLine(); nodeCode.Append(GetCodeForNodeStruct(nodeDataSections, node)); nodeCode.AppendLine(); - nodeCode.Append("} mt = {"); + + if (generateMethod) + nodeCode.Append("} mt = {"); + else + nodeCode.Append(" } " + ((ISymbolNode)node).GetMangledName(factory.NameMangler) + " = {"); nodeCode.Append(GetCodeForNodeData(nodeDataSections, relocs, nodeData.Data, node, offset, factory)); nodeCode.Append("};"); - nodeCode.AppendLine(); - nodeCode.Append("return ( "); - nodeCode.Append(pointerType); - nodeCode.Append(")&mt;"); - nodeCode.Exdent(); - nodeCode.AppendLine(); - nodeCode.Append("}"); + + if (generateMethod) + { + nodeCode.AppendLine(); + nodeCode.Append("return ( "); + nodeCode.Append(pointerType); + nodeCode.Append(")&mt;"); + nodeCode.Exdent(); + nodeCode.AppendLine(); + nodeCode.Append("}"); + } nodeCode.AppendLine(); return nodeCode.ToString(); } @@ -882,10 +903,15 @@ namespace ILCompiler.CppCodeGen relocCode.Append("()"); } // Node is either an non-emitted type or a generic composition - both are ignored for CPP codegen - else if ((reloc.Target is TypeManagerIndirectionNode || reloc.Target is InterfaceDispatchMapNode || reloc.Target is EETypeOptionalFieldsNode || reloc.Target is GenericCompositionNode) && !(reloc.Target as ObjectNode).ShouldSkipEmittingObjectNode(factory)) + else if ((reloc.Target is TypeManagerIndirectionNode || + reloc.Target is InterfaceDispatchMapNode || + reloc.Target is EETypeOptionalFieldsNode || + reloc.Target is GenericCompositionNode || + reloc.Target is SealedVTableNode + ) && !(reloc.Target as ObjectNode).ShouldSkipEmittingObjectNode(factory)) { string mangledTargetName = reloc.Target.GetMangledName(factory.NameMangler); - bool shouldReplaceNamespaceQualifier = reloc.Target is GenericCompositionNode || reloc.Target is EETypeOptionalFieldsNode; + bool shouldReplaceNamespaceQualifier = reloc.Target is GenericCompositionNode || reloc.Target is EETypeOptionalFieldsNode || reloc.Target is SealedVTableNode; relocCode.Append(shouldReplaceNamespaceQualifier ? mangledTargetName.Replace("::", "_") : mangledTargetName); relocCode.Append("()"); } @@ -894,12 +920,12 @@ namespace ILCompiler.CppCodeGen { relocCode.Append("dispatchMapModule"); } - else if(reloc.Target is UnboxingStubNode) + else if(reloc.Target is CppUnboxingStubNode) { - var method = reloc.Target as UnboxingStubNode; + var method = reloc.Target as CppUnboxingStubNode; relocCode.Append("(void*)&"); - relocCode.Append(GetCppMethodDeclarationName(method.Method.OwningType, UnboxingStubNode.GetMangledName(factory.NameMangler, method.Method), false)); + relocCode.Append(GetCppMethodDeclarationName(method.Method.OwningType, method.GetMangledName(factory.NameMangler), false)); } else { @@ -1011,26 +1037,30 @@ namespace ILCompiler.CppCodeGen //RTR header needs to be declared after all modules have already been output string rtrHeader = string.Empty; - // GetData stabilizes the indices of the embedded objects. This must be done manually - // for C++ codegen since we don't currently emit the DispatchMapTable node directly. - factory.DispatchMapTable.GetData(factory, false); - // Iterate through nodes foreach (var node in nodeIterator.GetNodes()) { if (node is EETypeNode) OutputTypeNode(node as EETypeNode, factory, typeDefinitions, methodTables); - else if ((node is EETypeOptionalFieldsNode || node is TypeManagerIndirectionNode || node is GenericCompositionNode) && !(node as ObjectNode).ShouldSkipEmittingObjectNode(factory)) + else if ((node is EETypeOptionalFieldsNode || + node is TypeManagerIndirectionNode || + node is GenericCompositionNode || + node is BlobNode || + node is SealedVTableNode) && !(node as ObjectNode).ShouldSkipEmittingObjectNode(factory)) additionalNodes.Append(GetCodeForObjectNode(node as ObjectNode, factory)); - else if (node is InterfaceDispatchMapNode) + else if (node is ArrayOfEmbeddedPointersNode dispatchMap) { - dispatchPointers.Append("(void *)"); - dispatchPointers.Append(((ISymbolNode)node).GetMangledName(factory.NameMangler)); - dispatchPointers.Append("(),"); - dispatchPointers.AppendLine(); - dispatchMapCount++; - additionalNodes.Append(GetCodeForObjectNode(node as ObjectNode, factory)); - + var dispatchMapData = dispatchMap.GetData(factory, false); + Debug.Assert(dispatchMapData.Relocs.Length == dispatchMapData.Data.Length / factory.Target.PointerSize); + foreach (Relocation reloc in dispatchMapData.Relocs) + { + dispatchPointers.Append("(void *)"); + dispatchPointers.Append(reloc.Target.GetMangledName(factory.NameMangler)); + dispatchPointers.Append("(),"); + dispatchPointers.AppendLine(); + dispatchMapCount++; + additionalNodes.Append(GetCodeForObjectNode(reloc.Target as ObjectNode, factory)); + } } else if (node is ReadyToRunHeaderNode) rtrHeader = GetCodeForReadyToRunHeader(node as ReadyToRunHeaderNode, factory); @@ -1202,23 +1232,15 @@ namespace ILCompiler.CppCodeGen if (typeNode is ConstructedEETypeNode) { - IReadOnlyList virtualSlots = _compilation.NodeFactory.VTable(nodeType.GetClosestDefType()).Slots; + DefType closestDefType = nodeType.GetClosestDefType(); - int baseSlots = 0; - var baseType = nodeType.BaseType; - while (baseType != null) - { - IReadOnlyList baseVirtualSlots = _compilation.NodeFactory.VTable(baseType).Slots; - if (baseVirtualSlots != null) - baseSlots += baseVirtualSlots.Count; - baseType = baseType.BaseType; - } + IReadOnlyList virtualSlots = _compilation.NodeFactory.VTable(closestDefType).Slots; - for (int slot = 0; slot < virtualSlots.Count; slot++) + foreach (MethodDesc slot in virtualSlots) { - MethodDesc virtualMethod = virtualSlots[slot]; typeDefinitions.AppendLine(); - typeDefinitions.Append(GetCodeForVirtualMethod(virtualMethod, baseSlots + slot)); + int slotNumber = VirtualMethodSlotHelper.GetVirtualMethodSlot(_compilation.NodeFactory, slot, closestDefType); + typeDefinitions.Append(GetCodeForVirtualMethod(slot, slotNumber)); } if (nodeType.IsDelegate) @@ -1242,7 +1264,7 @@ namespace ILCompiler.CppCodeGen typeDefinitions.AppendLine(); AppendCppMethodDeclaration(typeDefinitions, m, false); typeDefinitions.AppendLine(); - AppendCppMethodDeclaration(typeDefinitions, m, false, null, null, UnboxingStubNode.GetMangledName(factory.NameMangler, m)); + AppendCppMethodDeclaration(typeDefinitions, m, false, null, null, CppUnboxingStubNode.GetMangledName(factory.NameMangler, m)); } } @@ -1274,7 +1296,7 @@ namespace ILCompiler.CppCodeGen rtrHeader.Append(GetCodeForObjectNode(headerNode, factory)); rtrHeader.AppendLine(); - rtrHeader.Append("void* RtRHeaderWrapper() {"); + rtrHeader.Append("extern \"C\" void* RtRHeaderWrapper() {"); rtrHeader.Indent(); rtrHeader.AppendLine(); rtrHeader.Append("static struct {"); @@ -1342,13 +1364,13 @@ namespace ILCompiler.CppCodeGen /// /// The unboxing stub node to be output /// The buffer in which to write out the C++ code - private void OutputUnboxingStubNode(UnboxingStubNode unboxingStubNode) + private void OutputUnboxingStubNode(CppUnboxingStubNode unboxingStubNode) { Out.WriteLine(); CppGenerationBuffer sb = new CppGenerationBuffer(); sb.AppendLine(); - AppendCppMethodDeclaration(sb, unboxingStubNode.Method, true, null, null, UnboxingStubNode.GetMangledName(_compilation.NameMangler, unboxingStubNode.Method)); + AppendCppMethodDeclaration(sb, unboxingStubNode.Method, true, null, null, unboxingStubNode.GetMangledName(_compilation.NameMangler)); sb.AppendLine(); sb.Append("{"); sb.Indent(); @@ -1405,8 +1427,8 @@ namespace ILCompiler.CppCodeGen { if (node is CppMethodCodeNode) OutputMethodNode(node as CppMethodCodeNode); - else if (node is UnboxingStubNode) - OutputUnboxingStubNode(node as UnboxingStubNode); + else if (node is CppUnboxingStubNode) + OutputUnboxingStubNode(node as CppUnboxingStubNode); } Out.Dispose(); diff --git a/external/corert/src/ILCompiler.CppCodeGen/src/CppCodeGen/ILToCppImporter.cs b/external/corert/src/ILCompiler.CppCodeGen/src/CppCodeGen/ILToCppImporter.cs index ae062dad6f..33ab17d76f 100644 --- a/external/corert/src/ILCompiler.CppCodeGen/src/CppCodeGen/ILToCppImporter.cs +++ b/external/corert/src/ILCompiler.CppCodeGen/src/CppCodeGen/ILToCppImporter.cs @@ -1003,8 +1003,9 @@ namespace Internal.IL if (IsTypeName(method, "System", "ByReference`1")) { var thisRef = _stack.Pop(); - - PushExpression(StackValueKind.ValueType, ((ExpressionEntry)thisRef).Name + "->_value", method.Signature.ReturnType); + PushExpression(StackValueKind.ByRef, + String.Concat("(", GetSignatureTypeNameAndAddReference(method.Signature.ReturnType), ")", ((ExpressionEntry)thisRef).Name, "->_value"), + method.Signature.ReturnType); return true; } break; @@ -1151,7 +1152,7 @@ namespace Internal.IL { // TODO: Null checks - if (method.IsVirtual) + if (method.IsVirtual && !method.IsFinal && !method.OwningType.IsSealed()) { // TODO: Full resolution of virtual methods if (!method.IsNewSlot) @@ -2613,7 +2614,8 @@ namespace Internal.IL private void ImportUnalignedPrefix(byte alignment) { - throw new NotImplementedException(); + // TODO: + // throw new NotImplementedException(); } private void ImportVolatilePrefix() diff --git a/external/corert/src/ILCompiler.CppCodeGen/src/ILCompiler.CppCodeGen.csproj b/external/corert/src/ILCompiler.CppCodeGen/src/ILCompiler.CppCodeGen.csproj index 1ef83f8bdd..80a2a51f20 100644 --- a/external/corert/src/ILCompiler.CppCodeGen/src/ILCompiler.CppCodeGen.csproj +++ b/external/corert/src/ILCompiler.CppCodeGen/src/ILCompiler.CppCodeGen.csproj @@ -32,6 +32,7 @@ + diff --git a/external/corert/src/ILCompiler.DependencyAnalysisFramework/tests/DependencyAnalysisFrameworkTests.cs b/external/corert/src/ILCompiler.DependencyAnalysisFramework/tests/DependencyAnalysisFrameworkTests.cs index 3902999406..3b9cfc80e5 100644 --- a/external/corert/src/ILCompiler.DependencyAnalysisFramework/tests/DependencyAnalysisFrameworkTests.cs +++ b/external/corert/src/ILCompiler.DependencyAnalysisFramework/tests/DependencyAnalysisFrameworkTests.cs @@ -50,8 +50,8 @@ namespace ILCompiler.DependencyAnalysisFramework.Tests testGraph.AddRoot("A", "A is root"); List results = testGraph.AnalysisResults; - Assert.True(results.Contains("A")); - Assert.True(results.Contains("B")); + Assert.Contains("A", results); + Assert.Contains("B", results); }); } @@ -64,9 +64,9 @@ namespace ILCompiler.DependencyAnalysisFramework.Tests testGraph.AddRoot("A", "A is root"); List results = testGraph.AnalysisResults; - Assert.True(results.Contains("A")); - Assert.False(results.Contains("B")); - Assert.False(results.Contains("C")); + Assert.Contains("A", results); + Assert.DoesNotContain("B", results); + Assert.DoesNotContain("C", results); Assert.True(results.Count == 1); }); } @@ -81,9 +81,9 @@ namespace ILCompiler.DependencyAnalysisFramework.Tests testGraph.AddRoot("C", "C is root"); List results = testGraph.AnalysisResults; - Assert.True(results.Contains("A")); - Assert.True(results.Contains("B")); - Assert.True(results.Contains("C")); + Assert.Contains("A", results); + Assert.Contains("B", results); + Assert.Contains("C", results); Assert.True(results.Count == 3); }); } diff --git a/external/corert/src/ILCompiler.DependencyAnalysisFramework/tests/ILCompiler.DependencyAnalysisFramework.Tests.csproj b/external/corert/src/ILCompiler.DependencyAnalysisFramework/tests/ILCompiler.DependencyAnalysisFramework.Tests.csproj index 37f6e2a402..a352c7c0c6 100644 --- a/external/corert/src/ILCompiler.DependencyAnalysisFramework/tests/ILCompiler.DependencyAnalysisFramework.Tests.csproj +++ b/external/corert/src/ILCompiler.DependencyAnalysisFramework/tests/ILCompiler.DependencyAnalysisFramework.Tests.csproj @@ -4,7 +4,7 @@ Library ILCompiler.DependencyAnalysisFramework.Tests ILCompiler.DependencyAnalysisFramework.Tests - netstandard1.3 + netstandard2.0 @@ -13,8 +13,11 @@ 1.3.1 - - $(XunitNetcoreExtensionsVersion) + + $(XUnitPackageVersion) + + + $(MicrosoftDotNetXUnitExtensionsVersion) diff --git a/external/corert/src/ILCompiler.MetadataTransform/src/ILCompiler/Metadata/Transform.CustomAttribute.cs b/external/corert/src/ILCompiler.MetadataTransform/src/ILCompiler/Metadata/Transform.CustomAttribute.cs index ecf9532e75..31f61c5e8e 100644 --- a/external/corert/src/ILCompiler.MetadataTransform/src/ILCompiler/Metadata/Transform.CustomAttribute.cs +++ b/external/corert/src/ILCompiler.MetadataTransform/src/ILCompiler/Metadata/Transform.CustomAttribute.cs @@ -117,16 +117,16 @@ namespace ILCompiler.Metadata return new ConstantUInt64Value { Value = (ulong)value }; } - if (type.IsString) - { - return HandleString((string)value); - } - if (value == null) { return new ConstantReferenceValue(); } + if (type.IsString) + { + return HandleString((string)value); + } + if (type.IsSzArray) { return HandleCustomAttributeConstantArray( diff --git a/external/corert/src/ILCompiler.MetadataTransform/tests/ExplicitScopeTests.cs b/external/corert/src/ILCompiler.MetadataTransform/tests/ExplicitScopeTests.cs index 6745b23eef..dad6f4e735 100644 --- a/external/corert/src/ILCompiler.MetadataTransform/tests/ExplicitScopeTests.cs +++ b/external/corert/src/ILCompiler.MetadataTransform/tests/ExplicitScopeTests.cs @@ -57,7 +57,7 @@ namespace MetadataTransformTests return scope; } - public void CheckTypeDefinitionForProperWinRTHome(TypeDefinition typeDefinition, string module) + private void CheckTypeDefinitionForProperWinRTHome(TypeDefinition typeDefinition, string module) { ScopeDefinition scope = GetScopeDefinitionOfType(typeDefinition); Assert.Equal(module, scope.Name.Value); @@ -66,7 +66,7 @@ namespace MetadataTransformTests } - public void CheckTypeReferenceForProperWinRTHome(TypeReference typeReference, string module) + private void CheckTypeReferenceForProperWinRTHome(TypeReference typeReference, string module) { ScopeReference scope = GetScopeReferenceOfType(typeReference); Assert.Equal(module, scope.Name.Value); diff --git a/external/corert/src/ILCompiler.MetadataTransform/tests/ILCompiler.MetadataTransform.Tests.csproj b/external/corert/src/ILCompiler.MetadataTransform/tests/ILCompiler.MetadataTransform.Tests.csproj index 9de4e1df79..1a3d8e52ab 100644 --- a/external/corert/src/ILCompiler.MetadataTransform/tests/ILCompiler.MetadataTransform.Tests.csproj +++ b/external/corert/src/ILCompiler.MetadataTransform/tests/ILCompiler.MetadataTransform.Tests.csproj @@ -4,11 +4,14 @@ Library ILCompiler.MetadataTransform.Tests MetadataTransformTests - netstandard1.3 + netstandard2.0 - - $(XunitNetcoreExtensionsVersion) + + $(XUnitPackageVersion) + + + $(MicrosoftDotNetXUnitExtensionsVersion) diff --git a/external/corert/src/ILCompiler.MetadataTransform/tests/ILMetadataAssembly/ILMetadataAssembly.ilproj b/external/corert/src/ILCompiler.MetadataTransform/tests/ILMetadataAssembly/ILMetadataAssembly.ilproj index 8e383e0670..63712c1f40 100644 --- a/external/corert/src/ILCompiler.MetadataTransform/tests/ILMetadataAssembly/ILMetadataAssembly.ilproj +++ b/external/corert/src/ILCompiler.MetadataTransform/tests/ILMetadataAssembly/ILMetadataAssembly.ilproj @@ -5,7 +5,7 @@ Library ILMetadataAssembly - false + true diff --git a/external/corert/src/ILCompiler.MetadataTransform/tests/PrimaryMetadataAssembly/PrimaryMetadataAssembly.csproj b/external/corert/src/ILCompiler.MetadataTransform/tests/PrimaryMetadataAssembly/PrimaryMetadataAssembly.csproj index 82b325adfc..a64f834304 100644 --- a/external/corert/src/ILCompiler.MetadataTransform/tests/PrimaryMetadataAssembly/PrimaryMetadataAssembly.csproj +++ b/external/corert/src/ILCompiler.MetadataTransform/tests/PrimaryMetadataAssembly/PrimaryMetadataAssembly.csproj @@ -5,7 +5,7 @@ PrimaryMetadataAssembly false true - false + true diff --git a/external/corert/src/ILCompiler.MetadataTransform/tests/SampleMetadataAssembly/SampleMetadataAssembly.csproj b/external/corert/src/ILCompiler.MetadataTransform/tests/SampleMetadataAssembly/SampleMetadataAssembly.csproj index 04ff2298d9..796a387b68 100644 --- a/external/corert/src/ILCompiler.MetadataTransform/tests/SampleMetadataAssembly/SampleMetadataAssembly.csproj +++ b/external/corert/src/ILCompiler.MetadataTransform/tests/SampleMetadataAssembly/SampleMetadataAssembly.csproj @@ -4,7 +4,7 @@ Library SampleMetadataAssembly false - false + true diff --git a/external/corert/src/ILCompiler.MetadataTransform/tests/SampleWinRTMetadataAssembly/SampleWinRTMetadataAssembly.csproj b/external/corert/src/ILCompiler.MetadataTransform/tests/SampleWinRTMetadataAssembly/SampleWinRTMetadataAssembly.csproj index 5149824077..e228feb1fb 100644 --- a/external/corert/src/ILCompiler.MetadataTransform/tests/SampleWinRTMetadataAssembly/SampleWinRTMetadataAssembly.csproj +++ b/external/corert/src/ILCompiler.MetadataTransform/tests/SampleWinRTMetadataAssembly/SampleWinRTMetadataAssembly.csproj @@ -4,7 +4,7 @@ Library SampleWinRTMetadataAssembly false - false + true diff --git a/external/corert/src/ILCompiler.MetadataTransform/tests/SimpleTests.cs b/external/corert/src/ILCompiler.MetadataTransform/tests/SimpleTests.cs index b1d6d06a65..e3035321e2 100644 --- a/external/corert/src/ILCompiler.MetadataTransform/tests/SimpleTests.cs +++ b/external/corert/src/ILCompiler.MetadataTransform/tests/SimpleTests.cs @@ -10,6 +10,8 @@ using Cts = Internal.TypeSystem; using Xunit; +#pragma warning disable xUnit2013 // Do not use Assert.Equal() to check for collection size + namespace MetadataTransformTests { public class SimpleTests diff --git a/external/corert/src/ILCompiler.MetadataTransform/tests/WindowsWinRTMetadataAssembly/WindowsWinRTMetadataAssembly.csproj b/external/corert/src/ILCompiler.MetadataTransform/tests/WindowsWinRTMetadataAssembly/WindowsWinRTMetadataAssembly.csproj index d6f36ace18..05853a005a 100644 --- a/external/corert/src/ILCompiler.MetadataTransform/tests/WindowsWinRTMetadataAssembly/WindowsWinRTMetadataAssembly.csproj +++ b/external/corert/src/ILCompiler.MetadataTransform/tests/WindowsWinRTMetadataAssembly/WindowsWinRTMetadataAssembly.csproj @@ -4,7 +4,7 @@ Library WindowsWinRTMetadataAssembly false - false + true diff --git a/external/corert/src/ILCompiler.MetadataWriter/src/Internal/Metadata/NativeFormat/Writer/NativeFormatWriterGen.cs.REMOVED.git-id b/external/corert/src/ILCompiler.MetadataWriter/src/Internal/Metadata/NativeFormat/Writer/NativeFormatWriterGen.cs.REMOVED.git-id index 8fd73e4b2e..3c72a095c2 100644 --- a/external/corert/src/ILCompiler.MetadataWriter/src/Internal/Metadata/NativeFormat/Writer/NativeFormatWriterGen.cs.REMOVED.git-id +++ b/external/corert/src/ILCompiler.MetadataWriter/src/Internal/Metadata/NativeFormat/Writer/NativeFormatWriterGen.cs.REMOVED.git-id @@ -1 +1 @@ -d503e858e2d9a50147fcbccf8e82790bb64c2dfc \ No newline at end of file +d4e199c70726180c23c103b11ad8e53a68ae6d37 \ No newline at end of file diff --git a/external/corert/src/ILCompiler.TypeSystem/src/ILCompiler.TypeSystem.csproj b/external/corert/src/ILCompiler.TypeSystem/src/ILCompiler.TypeSystem.csproj index c9b2ef2bfd..ec7b134e6e 100644 --- a/external/corert/src/ILCompiler.TypeSystem/src/ILCompiler.TypeSystem.csproj +++ b/external/corert/src/ILCompiler.TypeSystem/src/ILCompiler.TypeSystem.csproj @@ -82,6 +82,9 @@ TypeSystem\CodeGen\TargetDetails.CodeGen.cs + + TypeSystem\CodeGen\TypeDesc.CodeGen.cs + Utilities\AlignmentHelper.cs @@ -355,12 +358,15 @@ IL\DelegateInfo.cs - - IL\Stubs\DelegateMarshallingMethodThunk.Sorting.cs - IL\Stubs\DelegateThunks.Sorting.cs + + IL\Stubs\DynamicInvokeMethodThunk.cs + + + IL\Stubs\DynamicInvokeMethodThunk.Sorting.cs + IL\Stubs\EnumThunks.cs @@ -388,6 +394,15 @@ IL\TypeSystemContext.DelegateInfo.cs + + IL\TypeSystemContext.DynamicInvoke.cs + + + IL\TypeSystemContext.GeneratedAssembly.cs + + + IL\TypeSystemContext.GeneratedAssembly.Sorting.cs + IL\EcmaMethodIL.cs @@ -457,12 +472,24 @@ IL\Stubs\DebuggerSteppingHelpers.cs + + IL\Stubs\CalliMarshallingMethodThunk.cs + + + IL\Stubs\CalliMarshallingMethodThunk.Mangling.cs + + + IL\Stubs\CalliMarshallingMethodThunk.Sorting.cs + IL\Stubs\DelegateMarshallingMethodThunk.cs IL\Stubs\DelegateMarshallingMethodThunk.Mangling.cs + + IL\Stubs\DelegateMarshallingMethodThunk.Sorting.cs + IL\Stubs\ForwardDelegateCreationThunk.cs @@ -544,6 +571,9 @@ TypeSystem\Mangling\IPrefixMangledType.cs + + TypeSystem\Mangling\IPrefixMangledSignature.cs + Utilities\ArrayBuilder.cs diff --git a/external/corert/src/ILCompiler.TypeSystem/src/Utilities/UniqueTypeNameFormatter.cs b/external/corert/src/ILCompiler.TypeSystem/src/Utilities/UniqueTypeNameFormatter.cs index 62d4cc4112..5da415a469 100644 --- a/external/corert/src/ILCompiler.TypeSystem/src/Utilities/UniqueTypeNameFormatter.cs +++ b/external/corert/src/ILCompiler.TypeSystem/src/Utilities/UniqueTypeNameFormatter.cs @@ -120,7 +120,7 @@ namespace Internal.TypeSystem protected override void AppendNameForNestedType(StringBuilder sb, DefType nestedType, DefType containingType) { - AppendNameForNamespaceType(sb, containingType); + AppendName(sb, containingType); sb.Append('+'); diff --git a/external/corert/src/ILCompiler.TypeSystem/tests/CoreTestAssembly/CoreTestAssembly.csproj b/external/corert/src/ILCompiler.TypeSystem/tests/CoreTestAssembly/CoreTestAssembly.csproj index 447bf566f6..efdb81aa49 100644 --- a/external/corert/src/ILCompiler.TypeSystem/tests/CoreTestAssembly/CoreTestAssembly.csproj +++ b/external/corert/src/ILCompiler.TypeSystem/tests/CoreTestAssembly/CoreTestAssembly.csproj @@ -5,7 +5,7 @@ CoreTestAssembly false true - false + true diff --git a/external/corert/src/ILCompiler.TypeSystem/tests/GCPointerMapTests.cs b/external/corert/src/ILCompiler.TypeSystem/tests/GCPointerMapTests.cs index cc075cc12e..7193a800bd 100644 --- a/external/corert/src/ILCompiler.TypeSystem/tests/GCPointerMapTests.cs +++ b/external/corert/src/ILCompiler.TypeSystem/tests/GCPointerMapTests.cs @@ -35,19 +35,19 @@ namespace TypeSystemTests { var map = GCPointerMap.FromInstanceLayout(classWithArrayFields); - Assert.Equal(map.Size, 3); + Assert.Equal(3, map.Size); Assert.Equal("011", map.ToString()); } { var map = GCPointerMap.FromInstanceLayout(classWithStringField); - Assert.Equal(map.Size, 4); + Assert.Equal(4, map.Size); Assert.Equal("0010", map.ToString()); } { var map = GCPointerMap.FromInstanceLayout(mixedStruct); - Assert.Equal(map.Size, 5); + Assert.Equal(5, map.Size); Assert.Equal("01001", map.ToString()); } @@ -60,19 +60,19 @@ namespace TypeSystemTests { var map = GCPointerMap.FromInstanceLayout(doubleMixedStructLayout); - Assert.Equal(map.Size, 10); + Assert.Equal(10, map.Size); Assert.Equal("0100101001", map.ToString()); } { var map = GCPointerMap.FromInstanceLayout(explicitlyFarPointer); - Assert.Equal(map.Size, 117); + Assert.Equal(117, map.Size); Assert.Equal("100000000000000000000000000000000000000000000000000000000000000010000000000000001000000000000000000000000000000001001", map.ToString()); } { var map = GCPointerMap.FromInstanceLayout(struct32GcPointers); - Assert.Equal(map.Size, 32); + Assert.Equal(32, map.Size); Assert.Equal("11111111111111111111111111111111", map.ToString()); } } @@ -82,20 +82,17 @@ namespace TypeSystemTests { MetadataType mixedStaticClass = _testModule.GetType("GCPointerMap", "MixedStaticClass"); var map = GCPointerMap.FromStaticLayout(mixedStaticClass); - Assert.Equal(map.Size, 12); + Assert.Equal(12, map.Size); Assert.Equal("010100101001", map.ToString()); } -#if false - // TODO: enable when IsThreadStatic stops lying [Fact] public void TestThreadStaticMap() { MetadataType mixedThreadStaticClass = _testModule.GetType("GCPointerMap", "MixedThreadStaticClass"); var map = GCPointerMap.FromThreadStaticLayout(mixedThreadStaticClass); - Assert.Equal(map.Size, 14); + Assert.Equal(14, map.Size); Assert.Equal("00010010100110", map.ToString()); } -#endif } } diff --git a/external/corert/src/ILCompiler.TypeSystem/tests/GenericTypeAndMethodTests.cs b/external/corert/src/ILCompiler.TypeSystem/tests/GenericTypeAndMethodTests.cs index 66698ff0b7..ddfe97e26b 100644 --- a/external/corert/src/ILCompiler.TypeSystem/tests/GenericTypeAndMethodTests.cs +++ b/external/corert/src/ILCompiler.TypeSystem/tests/GenericTypeAndMethodTests.cs @@ -33,8 +33,7 @@ namespace TypeSystemTests // Verify that we get just type definitions. Assert.NotNull(t); Assert.True(t.IsTypeDefinition); - Assert.NotNull(t.Instantiation); - Assert.Equal(t.Instantiation.Length, 1); + Assert.Equal(1, t.Instantiation.Length); Assert.True(t.Instantiation[0].IsTypeDefinition); // Verify that we got a method definition @@ -50,14 +49,13 @@ namespace TypeSystemTests // Verify properties of the instantiated type Assert.NotNull(instantiatedType); Assert.False(instantiatedType.IsTypeDefinition); - Assert.NotNull(instantiatedType.Instantiation); - Assert.Equal(instantiatedType.Instantiation.Length, 1); - Assert.Equal(instantiatedType.Instantiation[0], _context.GetWellKnownType(WellKnownType.Int32)); + Assert.Equal(1, instantiatedType.Instantiation.Length); + Assert.Equal(_context.GetWellKnownType(WellKnownType.Int32), instantiatedType.Instantiation[0]); // Verify that we get an instantiated method with the proper signature MethodDesc fooInstantiatedMethod = instantiatedType.GetMethods().First(m => m.Name == "Foo"); Assert.False(fooInstantiatedMethod.IsTypicalMethodDefinition); - Assert.Equal(fooInstantiatedMethod.Signature.ReturnType, _context.GetWellKnownType(WellKnownType.Int32)); + Assert.Equal(_context.GetWellKnownType(WellKnownType.Int32), fooInstantiatedMethod.Signature.ReturnType); Assert.Same(fooInstantiatedMethod.GetTypicalMethodDefinition(), fooMethod); // This is not a generic method, so they should be the same Assert.Same(fooInstantiatedMethod.GetMethodDefinition(), fooInstantiatedMethod); @@ -137,16 +135,16 @@ namespace TypeSystemTests InstantiatedType genericOfIntString = genericOpenType.MakeInstantiatedType(intType, stringType); InstantiatedType genericOfIntObject = genericOpenType.MakeInstantiatedType(intType, objectType); - Assert.Equal(true, genericOfCharObject.IsConstructedOverType(new TypeDesc[] { charType })); - Assert.Equal(true, genericOfCharObject.IsConstructedOverType(new TypeDesc[] { objectType })); - Assert.Equal(false, genericOfCharObject.IsConstructedOverType(new TypeDesc[] { intType })); - Assert.Equal(false, genericOfCharObject.IsConstructedOverType(new TypeDesc[] { stringType })); - Assert.Equal(false, genericOfCharObject.IsConstructedOverType(new TypeDesc[] { genericOpenType })); + Assert.True(genericOfCharObject.IsConstructedOverType(new TypeDesc[] { charType })); + Assert.True(genericOfCharObject.IsConstructedOverType(new TypeDesc[] { objectType })); + Assert.False(genericOfCharObject.IsConstructedOverType(new TypeDesc[] { intType })); + Assert.False(genericOfCharObject.IsConstructedOverType(new TypeDesc[] { stringType })); + Assert.False(genericOfCharObject.IsConstructedOverType(new TypeDesc[] { genericOpenType })); - Assert.Equal(true, genericOfCharString.IsConstructedOverType(new TypeDesc[] { charType })); - Assert.Equal(false, genericOfCharString.IsConstructedOverType(new TypeDesc[] { objectType })); - Assert.Equal(false, genericOfCharString.IsConstructedOverType(new TypeDesc[] { intType })); - Assert.Equal(true, genericOfCharString.IsConstructedOverType(new TypeDesc[] { stringType })); + Assert.True(genericOfCharString.IsConstructedOverType(new TypeDesc[] { charType })); + Assert.False(genericOfCharString.IsConstructedOverType(new TypeDesc[] { objectType })); + Assert.False(genericOfCharString.IsConstructedOverType(new TypeDesc[] { intType })); + Assert.True(genericOfCharString.IsConstructedOverType(new TypeDesc[] { stringType })); // Test direct replacement TypeDesc testDirectReplaceAllTypes = genericOfCharObject.ReplaceTypesInConstructionOfType(new TypeDesc[] { charType, objectType }, new TypeDesc[] { intType, stringType }); @@ -197,8 +195,8 @@ namespace TypeSystemTests TypeDesc testReplaceTypeInPointer = charPointer.ReplaceTypesInConstructionOfType(new TypeDesc[] { charType }, new TypeDesc[] { intType }); Assert.Equal(intPointer, testReplaceTypeInPointer); - Assert.Equal(true, charPointer.IsConstructedOverType(new TypeDesc[] { charType })); - Assert.Equal(false, charPointer.IsConstructedOverType(new TypeDesc[] { intType })); + Assert.True(charPointer.IsConstructedOverType(new TypeDesc[] { charType })); + Assert.False(charPointer.IsConstructedOverType(new TypeDesc[] { intType })); // Test byref TypeDesc charByRef = _context.GetByRefType(charType); @@ -206,13 +204,13 @@ namespace TypeSystemTests TypeDesc testReplaceTypeInByRef = charByRef.ReplaceTypesInConstructionOfType(new TypeDesc[] { charType }, new TypeDesc[] { intType }); Assert.Equal(intByRef, testReplaceTypeInByRef); - Assert.Equal(true, charByRef.IsConstructedOverType(new TypeDesc[] { charType })); - Assert.Equal(false, charByRef.IsConstructedOverType(new TypeDesc[] { intType })); + Assert.True(charByRef.IsConstructedOverType(new TypeDesc[] { charType })); + Assert.False(charByRef.IsConstructedOverType(new TypeDesc[] { intType })); // Test replace type entirely TypeDesc testReplaceTypeEntirely = charByRef.ReplaceTypesInConstructionOfType(new TypeDesc[] { charByRef }, new TypeDesc[] { intByRef }); Assert.Equal(intByRef, testReplaceTypeEntirely); - Assert.Equal(true, charByRef.IsConstructedOverType(new TypeDesc[] { charByRef })); + Assert.True(charByRef.IsConstructedOverType(new TypeDesc[] { charByRef })); } [Fact] @@ -273,4 +271,4 @@ namespace TypeSystemTests Assert.Equal(getMethodOnMDCharArray, testArrayMethodCase); } } -} \ No newline at end of file +} diff --git a/external/corert/src/ILCompiler.TypeSystem/tests/ILTestAssembly/ILTestAssembly.ilproj b/external/corert/src/ILCompiler.TypeSystem/tests/ILTestAssembly/ILTestAssembly.ilproj index 5d65099c49..bce9574f96 100644 --- a/external/corert/src/ILCompiler.TypeSystem/tests/ILTestAssembly/ILTestAssembly.ilproj +++ b/external/corert/src/ILCompiler.TypeSystem/tests/ILTestAssembly/ILTestAssembly.ilproj @@ -4,7 +4,7 @@ Library ILTestAssembly - false + true diff --git a/external/corert/src/ILCompiler.TypeSystem/tests/TestMetadataFieldLayoutAlgorithm.cs b/external/corert/src/ILCompiler.TypeSystem/tests/TestMetadataFieldLayoutAlgorithm.cs index a3dd93a221..ba96e1c7da 100644 --- a/external/corert/src/ILCompiler.TypeSystem/tests/TestMetadataFieldLayoutAlgorithm.cs +++ b/external/corert/src/ILCompiler.TypeSystem/tests/TestMetadataFieldLayoutAlgorithm.cs @@ -15,7 +15,7 @@ namespace TypeSystemTests { // GC statics start with a pointer to the "EEType" that signals the size and GCDesc to the GC layout.GcStatics.Size = context.Target.LayoutPointerSize; - layout.ThreadStatics.Size = context.Target.LayoutPointerSize; + layout.ThreadGcStatics.Size = context.Target.LayoutPointerSize; } protected override void FinalizeRuntimeSpecificStaticFieldLayout(TypeSystemContext context, ref ComputedStaticFieldLayout layout) @@ -26,9 +26,9 @@ namespace TypeSystemTests { layout.GcStatics.Size = LayoutInt.Zero; } - if (layout.ThreadStatics.Size == context.Target.LayoutPointerSize) + if (layout.ThreadGcStatics.Size == context.Target.LayoutPointerSize) { - layout.ThreadStatics.Size = LayoutInt.Zero; + layout.ThreadGcStatics.Size = LayoutInt.Zero; } } } diff --git a/external/corert/src/ILCompiler.TypeSystem/tests/TestTypeSystemContext.cs b/external/corert/src/ILCompiler.TypeSystem/tests/TestTypeSystemContext.cs index 005d98fee8..5661b1a872 100644 --- a/external/corert/src/ILCompiler.TypeSystem/tests/TestTypeSystemContext.cs +++ b/external/corert/src/ILCompiler.TypeSystem/tests/TestTypeSystemContext.cs @@ -110,6 +110,9 @@ namespace TypeSystemTests { Debug.Assert(field.IsStatic); + if (field.IsThreadStatic) + return true; + TypeDesc fieldType = field.FieldType; if (fieldType.IsValueType) return ((DefType)fieldType).ContainsGCPointers; diff --git a/external/corert/src/ILCompiler.TypeSystem/tests/TypeSystem.Tests.csproj b/external/corert/src/ILCompiler.TypeSystem/tests/TypeSystem.Tests.csproj index 3c4e785164..cd4d34c182 100644 --- a/external/corert/src/ILCompiler.TypeSystem/tests/TypeSystem.Tests.csproj +++ b/external/corert/src/ILCompiler.TypeSystem/tests/TypeSystem.Tests.csproj @@ -4,16 +4,16 @@ Library TypeSystem.Tests TypeSystem.Tests - netstandard1.3 + netstandard2.0 $(NoWarn);NU1603 - - $(XunitNetcoreExtensionsVersion) + + $(XUnitPackageVersion) - - $(XunitNetcoreExtensionsVersion) + + $(MicrosoftDotNetXUnitExtensionsVersion) 1.4.2 diff --git a/external/corert/src/ILCompiler.TypeSystem/tests/UniversalGenericFieldLayoutTests.cs b/external/corert/src/ILCompiler.TypeSystem/tests/UniversalGenericFieldLayoutTests.cs index 938828c795..8258cadf94 100644 --- a/external/corert/src/ILCompiler.TypeSystem/tests/UniversalGenericFieldLayoutTests.cs +++ b/external/corert/src/ILCompiler.TypeSystem/tests/UniversalGenericFieldLayoutTests.cs @@ -200,8 +200,8 @@ namespace TypeSystemTests Assert.Equal(LayoutInt.Zero, context.UniversalCanonType.GCStaticFieldSize); Assert.Equal(LayoutInt.Zero, context.UniversalCanonType.NonGCStaticFieldAlignment); Assert.Equal(LayoutInt.Zero, context.UniversalCanonType.NonGCStaticFieldSize); - Assert.Equal(LayoutInt.Zero, context.UniversalCanonType.ThreadStaticFieldAlignment); - Assert.Equal(LayoutInt.Zero, context.UniversalCanonType.ThreadStaticFieldSize); + Assert.Equal(LayoutInt.Zero, context.UniversalCanonType.ThreadGcStaticFieldAlignment); + Assert.Equal(LayoutInt.Zero, context.UniversalCanonType.ThreadGcStaticFieldSize); } [Fact] public void TestLayoutOfUniversalCanonType() @@ -268,7 +268,7 @@ namespace TypeSystemTests Assert.Equal(LayoutInt.Indeterminate, genOfUUU.GetFields().ElementAt(2).Offset); } - public void TestIndeterminatedNestedStructFieldPerContext(TypeSystemContext context, ModuleDesc testModule, out InstantiatedType genOfIntNestedInt, out InstantiatedType genOfLongNestedInt) + private void TestIndeterminatedNestedStructFieldPerContext(TypeSystemContext context, ModuleDesc testModule, out InstantiatedType genOfIntNestedInt, out InstantiatedType genOfLongNestedInt) { // Given a struct with all field universal, what is the layout? MetadataType tGen = testModule.GetType("GenericTypes", "GenStruct`3"); @@ -310,7 +310,7 @@ namespace TypeSystemTests Assert.Equal(LayoutInt.Indeterminate, genOfLongNestedInt.InstanceByteAlignment); } - public void AssertClassIndeterminateSize(TypeSystemContext context, MetadataType type, LayoutInt expectedIndeterminateByteAlignment) + private void AssertClassIndeterminateSize(TypeSystemContext context, MetadataType type, LayoutInt expectedIndeterminateByteAlignment) { Assert.Equal(context.Target.LayoutPointerSize, type.InstanceFieldAlignment); Assert.Equal(context.Target.LayoutPointerSize, type.InstanceFieldSize); diff --git a/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/DebugMetadata.cs b/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/DebugMetadata.cs new file mode 100644 index 0000000000..30780db65e --- /dev/null +++ b/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/DebugMetadata.cs @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Text; +using LLVMSharp; + +namespace ILCompiler.WebAssembly +{ + class DebugMetadata + { + public DebugMetadata(LLVMMetadataRef file, LLVMMetadataRef compileUnit) + { + File = file; + CompileUnit = compileUnit; + } + + public LLVMMetadataRef CompileUnit { get; } + public LLVMMetadataRef File { get; } + } +} diff --git a/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/EvaluationStack.cs b/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/EvaluationStack.cs index 92c1919764..44b947ccd7 100644 --- a/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/EvaluationStack.cs +++ b/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/EvaluationStack.cs @@ -199,7 +199,7 @@ namespace Internal.IL else if (kind == StackValueKind.Int64) return ValueAsInt64(builder, signExtend); else if (kind == StackValueKind.Float) - return ValueAsType(LLVM.FloatType(), builder); + return ValueAsType(LLVM.DoubleType(), builder); else if (kind == StackValueKind.NativeInt || kind == StackValueKind.ByRef || kind == StackValueKind.ObjRef) return ValueAsInt32(builder, false); else @@ -239,7 +239,7 @@ namespace Internal.IL /// Create a new copy of current entry. /// /// A new instance of the same type as the current entry. - public abstract StackEntry Duplicate(); + public abstract StackEntry Duplicate(LLVMBuilderRef builder); } /// @@ -298,7 +298,7 @@ namespace Internal.IL } } - public override StackEntry Duplicate() + public override StackEntry Duplicate(LLVMBuilderRef builder) { return new Int32ConstantEntry(Value, Type); } @@ -333,7 +333,7 @@ namespace Internal.IL { } - public override StackEntry Duplicate() + public override StackEntry Duplicate(LLVMBuilderRef builder) { return new Int64ConstantEntry(Value, Type); } @@ -397,7 +397,7 @@ namespace Internal.IL return LLVM.ConstReal(type, Value); } - public override StackEntry Duplicate() + public override StackEntry Duplicate(LLVMBuilderRef builder) { return new FloatConstantEntry(Value, Type); } @@ -425,7 +425,7 @@ namespace Internal.IL RawLLVMValue = llvmValue; } - public override StackEntry Duplicate() + public override StackEntry Duplicate(LLVMBuilderRef builder) { return new ExpressionEntry(Kind, Name, RawLLVMValue, Type); } @@ -433,7 +433,7 @@ namespace Internal.IL protected override LLVMValueRef ValueAsTypeInternal(LLVMTypeRef type, LLVMBuilderRef builder, bool signExtend) { //TODO: deal with sign extension here - return ILImporter.CastIfNecessary(builder, RawLLVMValue, type); + return ILImporter.CastIfNecessary(builder, RawLLVMValue, type, Name); } } @@ -449,14 +449,14 @@ namespace Internal.IL { } - public override StackEntry Duplicate() + public override StackEntry Duplicate(LLVMBuilderRef builder) { - return new LoadExpressionEntry(Kind, Name, RawLLVMValue, Type); + return new ExpressionEntry(Kind, "duplicate_" + Name, ILImporter.LoadValue(builder, RawLLVMValue, Type, ILImporter.GetLLVMTypeForTypeDesc(Type), false, "load_duplicate_" + Name), Type); } protected override LLVMValueRef ValueAsTypeInternal(LLVMTypeRef type, LLVMBuilderRef builder, bool signExtend) { - return ILImporter.LoadValue(builder, RawLLVMValue, Type, type, signExtend); + return ILImporter.LoadValue(builder, RawLLVMValue, Type, type, signExtend, $"Load{Name}"); } } @@ -472,14 +472,14 @@ namespace Internal.IL { } - public override StackEntry Duplicate() + public override StackEntry Duplicate(LLVMBuilderRef builder) { - return new LoadExpressionEntry(Kind, Name, RawLLVMValue, Type); + return new AddressExpressionEntry(Kind, Name, RawLLVMValue, Type); } protected override LLVMValueRef ValueAsTypeInternal(LLVMTypeRef type, LLVMBuilderRef builder, bool signExtend) { - return ILImporter.CastIfNecessary(builder, RawLLVMValue, type); + return ILImporter.CastIfNecessary(builder, RawLLVMValue, type, Name); } } @@ -501,7 +501,7 @@ namespace Internal.IL IsVirtual = isVirtual; } - public override StackEntry Duplicate() + public override StackEntry Duplicate(LLVMBuilderRef builder) { return new FunctionPointerEntry(Name, Method, RawLLVMValue, Type, IsVirtual); } @@ -519,7 +519,7 @@ namespace Internal.IL LdToken = token; } - public override StackEntry Duplicate() + public override StackEntry Duplicate(LLVMBuilderRef builder) { return new LdTokenEntry(Kind, Name, LdToken, RawLLVMValue, Type); } @@ -529,7 +529,7 @@ namespace Internal.IL if (RawLLVMValue.Pointer == IntPtr.Zero) throw new NullReferenceException(); - return ILImporter.CastIfNecessary(builder, RawLLVMValue, type); + return ILImporter.CastIfNecessary(builder, RawLLVMValue, type, Name); } } @@ -544,7 +544,7 @@ namespace Internal.IL { } - public override StackEntry Duplicate() + public override StackEntry Duplicate(LLVMBuilderRef builder) { return this; } @@ -576,9 +576,17 @@ namespace Internal.IL return ILImporter.CastIfNecessary(builder, value, type); } - public override StackEntry Duplicate() + public override StackEntry Duplicate(LLVMBuilderRef builder) { return new SpilledExpressionEntry(Kind, Name, Type, LocalIndex, _importer); } } + + internal static class StackEntryExtensions + { + public static string Name(this StackEntry entry) + { + return (entry as ExpressionEntry)?.Name; + } + } } diff --git a/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/ILToWebAssemblyImporter.cs.REMOVED.git-id b/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/ILToWebAssemblyImporter.cs.REMOVED.git-id index 9b3bc33d22..ce903781ff 100644 --- a/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/ILToWebAssemblyImporter.cs.REMOVED.git-id +++ b/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/ILToWebAssemblyImporter.cs.REMOVED.git-id @@ -1 +1 @@ -8b0936d1e35484835afc47737fadb2882caef023 \ No newline at end of file +e828d6d979ca42f30dcf55b35b9372d08777c61c \ No newline at end of file diff --git a/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/ILToWebAssemblyImporter_Statics.cs b/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/ILToWebAssemblyImporter_Statics.cs index ad6bc1c78d..5bbfc2906b 100644 --- a/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/ILToWebAssemblyImporter_Statics.cs +++ b/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/ILToWebAssemblyImporter_Statics.cs @@ -51,8 +51,9 @@ namespace Internal.IL try { string mangledName; - // TODO: We should use the startup node to generate StartupCodeMain and avoid special casing here - if (methodCodeNodeNeedingCode.Method.Signature.IsStatic && methodCodeNodeNeedingCode.Method.Name == "Main") + + // TODO: Better detection of the StartupCodeMain method + if (methodCodeNodeNeedingCode.Method.Signature.IsStatic && methodCodeNodeNeedingCode.Method.Name == "StartupCodeMain") { mangledName = "StartupCodeMain"; } @@ -96,6 +97,17 @@ namespace Internal.IL //methodCodeNodeNeedingCode.SetCode(sb.ToString(), Array.Empty()); } + // Uncomment the block below to get specific method failures when LLVM fails for cryptic reasons +#if false + LLVMBool result = LLVM.VerifyFunction(ilImporter._llvmFunction, LLVMVerifierFailureAction.LLVMPrintMessageAction); + if (result.Value != 0) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"Error compliling {method.OwningType}.{method}"); + Console.ResetColor(); + } +#endif // false + // Ensure dependencies show up regardless of exceptions to avoid breaking LLVM methodCodeNodeNeedingCode.SetDependencies(ilImporter.GetDependencies()); } diff --git a/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/LLVMPInvokes.cs b/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/LLVMPInvokes.cs new file mode 100644 index 0000000000..708ef5b51b --- /dev/null +++ b/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/LLVMPInvokes.cs @@ -0,0 +1,78 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.InteropServices; +using LLVMSharp; + +namespace ILCompiler.WebAssembly +{ + // LLVM P/Invokes copied from LLVMSharp that match the current LLVM surface area. + // If we get a new version of LLVMSharp containing these, this file should be removed. + internal class LLVMPInvokes + { + const string libraryPath = "libLLVM"; + [DllImport(libraryPath, CallingConvention = CallingConvention.Cdecl)] + public static extern LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M); + + [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateCompileUnit", CallingConvention = CallingConvention.Cdecl)] + public static extern LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(LLVMDIBuilderRef @Builder, LLVMDWARFSourceLanguage @Lang, LLVMMetadataRef @FileRef, [MarshalAs(UnmanagedType.LPStr)] string @Producer, size_t @ProducerLen, LLVMBool @isOptimized, [MarshalAs(UnmanagedType.LPStr)] string @Flags, size_t @FlagsLen, uint @RuntimeVer, [MarshalAs(UnmanagedType.LPStr)] string @SplitName, size_t @SplitNameLen, LLVMDWARFEmissionKind @Kind, uint @DWOId, LLVMBool @SplitDebugInlining, LLVMBool @DebugInfoForProfiling); + + [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateFile", CallingConvention = CallingConvention.Cdecl)] + public static extern LLVMMetadataRef LLVMDIBuilderCreateFile(LLVMDIBuilderRef @Builder, [MarshalAs(UnmanagedType.LPStr)] string @Filename, size_t @FilenameLen, [MarshalAs(UnmanagedType.LPStr)] string @Directory, size_t @DirectoryLen); + + [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateDebugLocation", CallingConvention = CallingConvention.Cdecl)] + public static extern LLVMMetadataRef LLVMDIBuilderCreateDebugLocation(LLVMContextRef @Ctx, uint @Line, uint @Column, LLVMMetadataRef @Scope, LLVMMetadataRef @InlinedAt); + } + + internal enum LLVMDWARFSourceLanguage : int + { + @LLVMDWARFSourceLanguageC89 = 0, + @LLVMDWARFSourceLanguageC = 1, + @LLVMDWARFSourceLanguageAda83 = 2, + @LLVMDWARFSourceLanguageC_plus_plus = 3, + @LLVMDWARFSourceLanguageCobol74 = 4, + @LLVMDWARFSourceLanguageCobol85 = 5, + @LLVMDWARFSourceLanguageFortran77 = 6, + @LLVMDWARFSourceLanguageFortran90 = 7, + @LLVMDWARFSourceLanguagePascal83 = 8, + @LLVMDWARFSourceLanguageModula2 = 9, + @LLVMDWARFSourceLanguageJava = 10, + @LLVMDWARFSourceLanguageC99 = 11, + @LLVMDWARFSourceLanguageAda95 = 12, + @LLVMDWARFSourceLanguageFortran95 = 13, + @LLVMDWARFSourceLanguagePLI = 14, + @LLVMDWARFSourceLanguageObjC = 15, + @LLVMDWARFSourceLanguageObjC_plus_plus = 16, + @LLVMDWARFSourceLanguageUPC = 17, + @LLVMDWARFSourceLanguageD = 18, + @LLVMDWARFSourceLanguagePython = 19, + @LLVMDWARFSourceLanguageOpenCL = 20, + @LLVMDWARFSourceLanguageGo = 21, + @LLVMDWARFSourceLanguageModula3 = 22, + @LLVMDWARFSourceLanguageHaskell = 23, + @LLVMDWARFSourceLanguageC_plus_plus_03 = 24, + @LLVMDWARFSourceLanguageC_plus_plus_11 = 25, + @LLVMDWARFSourceLanguageOCaml = 26, + @LLVMDWARFSourceLanguageRust = 27, + @LLVMDWARFSourceLanguageC11 = 28, + @LLVMDWARFSourceLanguageSwift = 29, + @LLVMDWARFSourceLanguageJulia = 30, + @LLVMDWARFSourceLanguageDylan = 31, + @LLVMDWARFSourceLanguageC_plus_plus_14 = 32, + @LLVMDWARFSourceLanguageFortran03 = 33, + @LLVMDWARFSourceLanguageFortran08 = 34, + @LLVMDWARFSourceLanguageRenderScript = 35, + @LLVMDWARFSourceLanguageBLISS = 36, + @LLVMDWARFSourceLanguageMips_Assembler = 37, + @LLVMDWARFSourceLanguageGOOGLE_RenderScript = 38, + @LLVMDWARFSourceLanguageBORLAND_Delphi = 39, + } + + internal enum LLVMDWARFEmissionKind : int + { + @LLVMDWARFEmissionNone = 0, + @LLVMDWARFEmissionFull = 1, + @LLVMDWARFEmissionLineTablesOnly = 2, + } +} diff --git a/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/WebAssemblyObjectWriter.cs b/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/WebAssemblyObjectWriter.cs index 8808a2e028..f89f1ce973 100644 --- a/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/WebAssemblyObjectWriter.cs +++ b/external/corert/src/ILCompiler.WebAssembly/src/CodeGen/WebAssemblyObjectWriter.cs @@ -144,6 +144,8 @@ namespace ILCompiler.DependencyAnalysis // this is the llvm instance. public LLVMModuleRef Module { get; } + public LLVMDIBuilderRef DIBuilder { get; } + // This is used to build mangled names private Utf8StringBuilder _sb = new Utf8StringBuilder(); @@ -181,6 +183,9 @@ namespace ILCompiler.DependencyAnalysis } EmitNativeMain(); + + EmitDebugMetadata(); + LLVM.WriteBitcodeToFile(Module, _objectFilePath); #if DEBUG LLVM.PrintModuleToFile(Module, Path.ChangeExtension(_objectFilePath, ".txt"), out string unused2); @@ -190,6 +195,25 @@ namespace ILCompiler.DependencyAnalysis //throw new NotImplementedException(); // This function isn't complete } + private void EmitDebugMetadata() + { + var dwarfVersion = LLVM.MDNode(new[] + { + LLVM.ConstInt(LLVM.Int32Type(), 2, false), + LLVM.MDString("Dwarf Version", 13), + LLVM.ConstInt(LLVM.Int32Type(), 4, false) + }); + var dwarfSchemaVersion = LLVM.MDNode(new[] + { + LLVM.ConstInt(LLVM.Int32Type(), 2, false), + LLVM.MDString("Debug Info Version", 18), + LLVM.ConstInt(LLVM.Int32Type(), 3, false) + }); + LLVM.AddNamedMetadataOperand(Module, "llvm.module.flags", dwarfVersion); + LLVM.AddNamedMetadataOperand(Module, "llvm.module.flags", dwarfSchemaVersion); + LLVM.DIBuilderFinalize(DIBuilder); + } + public static LLVMValueRef GetConstZeroArray(int length) { var int8Type = LLVM.Int8Type(); @@ -225,6 +249,19 @@ namespace ILCompiler.DependencyAnalysis throw new NotImplementedException(); } + private void EmitReadyToRunHeaderCallback() + { + LLVMTypeRef intPtr = LLVM.PointerType(LLVM.Int32Type(), 0); + LLVMTypeRef intPtrPtr = LLVM.PointerType(intPtr, 0); + var callback = LLVM.AddFunction(Module, "RtRHeaderWrapper", LLVM.FunctionType(intPtrPtr, new LLVMTypeRef[0], false)); + var builder = LLVM.CreateBuilder(); + var block = LLVM.AppendBasicBlock(callback, "Block"); + LLVM.PositionBuilderAtEnd(builder, block); + + LLVMValueRef rtrHeaderPtr = GetSymbolValuePointer(Module, _nodeFactory.ReadyToRunHeader, _nodeFactory.NameMangler, false); + LLVMValueRef castRtrHeaderPtr = LLVM.BuildPointerCast(builder, rtrHeaderPtr, intPtrPtr, "castRtrHeaderPtr"); + LLVM.BuildRet(builder, castRtrHeaderPtr); + } private void EmitNativeMain() { @@ -243,20 +280,32 @@ namespace ILCompiler.DependencyAnalysis LLVMTypeRef reversePInvokeFrameType = LLVM.StructType(new LLVMTypeRef[] { LLVM.PointerType(LLVM.Int8Type(), 0), LLVM.PointerType(LLVM.Int8Type(), 0) }, false); LLVMValueRef reversePinvokeFrame = LLVM.BuildAlloca(builder, reversePInvokeFrameType, "ReversePInvokeFrame"); - LLVMValueRef RhpReversePInvoke2 = LLVM.AddFunction(Module, "RhpReversePInvoke2", LLVM.FunctionType(LLVM.VoidType(), new LLVMTypeRef[] { LLVM.PointerType(reversePInvokeFrameType, 0) }, false)); + LLVMValueRef RhpReversePInvoke2 = LLVM.GetNamedFunction(Module, "RhpReversePInvoke2"); + + if (RhpReversePInvoke2.Pointer == IntPtr.Zero) + { + RhpReversePInvoke2 = LLVM.AddFunction(Module, "RhpReversePInvoke2", LLVM.FunctionType(LLVM.VoidType(), new LLVMTypeRef[] { LLVM.PointerType(reversePInvokeFrameType, 0) }, false)); + } + LLVM.BuildCall(builder, RhpReversePInvoke2, new LLVMValueRef[] { reversePinvokeFrame }, ""); var shadowStack = LLVM.BuildMalloc(builder, LLVM.ArrayType(LLVM.Int8Type(), 1000000), String.Empty); var castShadowStack = LLVM.BuildPointerCast(builder, shadowStack, LLVM.PointerType(LLVM.Int8Type(), 0), String.Empty); LLVM.BuildStore(builder, castShadowStack, shadowStackTop); - LLVM.BuildCall(builder, managedMain, new LLVMValueRef[] + + // Pass on main arguments + LLVMValueRef argc = LLVM.GetParam(mainFunc, 0); + LLVMValueRef argv = LLVM.GetParam(mainFunc, 1); + + LLVMValueRef mainReturn = LLVM.BuildCall(builder, managedMain, new LLVMValueRef[] { castShadowStack, - LLVM.ConstPointerNull(LLVM.PointerType(LLVM.Int8Type(), 0)) + argc, + argv, }, - String.Empty); + "returnValue"); - LLVM.BuildRet(builder, LLVM.ConstInt(LLVM.Int32Type(), 42, LLVMMisc.False)); + LLVM.BuildRet(builder, mainReturn); LLVM.SetLinkage(mainFunc, LLVMLinkage.LLVMExternalLinkage); } @@ -474,13 +523,15 @@ namespace ILCompiler.DependencyAnalysis delta = checked(delta + sizeof(int)); } + int totalOffset = checked(delta + offsetFromSymbolName); + EmitBlob(new byte[this._nodeFactory.Target.PointerSize]); if (relocType == RelocType.IMAGE_REL_BASED_REL32) { return this._nodeFactory.Target.PointerSize; } - _currentObjectSymbolRefs.Add(symbolStartOffset, new SymbolRefData(isFunction, realSymbolName, delta)); + _currentObjectSymbolRefs.Add(symbolStartOffset, new SymbolRefData(isFunction, realSymbolName, totalOffset)); return _nodeFactory.Target.PointerSize; } @@ -618,6 +669,7 @@ namespace ILCompiler.DependencyAnalysis _nodeFactory = factory; _objectFilePath = objectFilePath; Module = compilation.Module; + DIBuilder = compilation.DIBuilder; } public void Dispose() @@ -699,6 +751,7 @@ namespace ILCompiler.DependencyAnalysis try { + objectWriter.EmitReadyToRunHeaderCallback(); //ObjectNodeSection managedCodeSection = null; var listOfOffsets = new List(); diff --git a/external/corert/src/ILCompiler.WebAssembly/src/Compiler/DependencyAnalysis/WebAssemblyCodegenNodeFactory.cs b/external/corert/src/ILCompiler.WebAssembly/src/Compiler/DependencyAnalysis/WebAssemblyCodegenNodeFactory.cs index a43a1e5729..2c09fc8fdb 100644 --- a/external/corert/src/ILCompiler.WebAssembly/src/Compiler/DependencyAnalysis/WebAssemblyCodegenNodeFactory.cs +++ b/external/corert/src/ILCompiler.WebAssembly/src/Compiler/DependencyAnalysis/WebAssemblyCodegenNodeFactory.cs @@ -51,7 +51,7 @@ namespace ILCompiler.DependencyAnalysis protected override IMethodNode CreateUnboxingStubNode(MethodDesc method) { - return new WebAssemblyMethodCodeNode(TypeSystemContext.GetUnboxingThunk(method, CompilationModuleGroup.GeneratedAssembly)); + return new WebAssemblyMethodCodeNode(TypeSystemContext.GetUnboxingThunk(method, TypeSystemContext.GeneratedAssembly)); } protected override ISymbolNode CreateReadyToRunHelperNode(ReadyToRunHelperKey helperCall) diff --git a/external/corert/src/ILCompiler.WebAssembly/src/Compiler/DependencyAnalysis/WebAssemblyMethodCodeNode.cs b/external/corert/src/ILCompiler.WebAssembly/src/Compiler/DependencyAnalysis/WebAssemblyMethodCodeNode.cs index 0cfd4382c2..0405b88d2d 100644 --- a/external/corert/src/ILCompiler.WebAssembly/src/Compiler/DependencyAnalysis/WebAssemblyMethodCodeNode.cs +++ b/external/corert/src/ILCompiler.WebAssembly/src/Compiler/DependencyAnalysis/WebAssemblyMethodCodeNode.cs @@ -68,9 +68,9 @@ namespace ILCompiler.DependencyAnalysis public override IEnumerable GetConditionalStaticDependencies(NodeFactory factory) => null; public override IEnumerable SearchDynamicDependencies(List> markedNodes, int firstNode, NodeFactory factory) => null; - int ISortableSymbolNode.ClassCode => -1502960727; + int ISortableNode.ClassCode => -1502960727; - int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) + int ISortableNode.CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_method, ((WebAssemblyMethodCodeNode)other)._method); } diff --git a/external/corert/src/ILCompiler.WebAssembly/src/Compiler/DependencyAnalysis/WebAssemblyVTableSlotNode.cs b/external/corert/src/ILCompiler.WebAssembly/src/Compiler/DependencyAnalysis/WebAssemblyVTableSlotNode.cs index 6f7897a8f0..5122f8dc05 100644 --- a/external/corert/src/ILCompiler.WebAssembly/src/Compiler/DependencyAnalysis/WebAssemblyVTableSlotNode.cs +++ b/external/corert/src/ILCompiler.WebAssembly/src/Compiler/DependencyAnalysis/WebAssemblyVTableSlotNode.cs @@ -61,15 +61,24 @@ namespace ILCompiler.DependencyAnalysis if (!relocsOnly) { - var tableOffset = EETypeNode.GetVTableOffset(factory.Target.PointerSize) / factory.Target.PointerSize; - objData.EmitInt(tableOffset + VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, _targetMethod)); + int tableOffset; + if (_targetMethod.OwningType.IsInterface) + { + tableOffset = 0; + } + else + { + tableOffset = EETypeNode.GetVTableOffset(factory.Target.PointerSize) / factory.Target.PointerSize; + } + + objData.EmitInt(tableOffset + VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, _targetMethod, _targetMethod.OwningType)); } return objData.ToObjectData(); } - protected override int ClassCode => 0; + public override int ClassCode => 0; - protected override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_targetMethod, ((WebAssemblyVTableSlotNode)other)._targetMethod); } diff --git a/external/corert/src/ILCompiler.WebAssembly/src/Compiler/WebAssemblyCodegenCompilation.cs b/external/corert/src/ILCompiler.WebAssembly/src/Compiler/WebAssemblyCodegenCompilation.cs index 5a32248a7d..e49cbba16c 100644 --- a/external/corert/src/ILCompiler.WebAssembly/src/Compiler/WebAssemblyCodegenCompilation.cs +++ b/external/corert/src/ILCompiler.WebAssembly/src/Compiler/WebAssemblyCodegenCompilation.cs @@ -9,6 +9,7 @@ using Internal.TypeSystem; using ILCompiler.DependencyAnalysis; using ILCompiler.DependencyAnalysisFramework; using LLVMSharp; +using ILCompiler.WebAssembly; namespace ILCompiler { @@ -17,18 +18,23 @@ namespace ILCompiler internal WebAssemblyCodegenConfigProvider Options { get; } internal LLVMModuleRef Module { get; } public new WebAssemblyCodegenNodeFactory NodeFactory { get; } + internal LLVMDIBuilderRef DIBuilder { get; } + internal Dictionary DebugMetadataMap { get; } internal WebAssemblyCodegenCompilation( DependencyAnalyzerBase dependencyGraph, WebAssemblyCodegenNodeFactory nodeFactory, IEnumerable roots, + DebugInformationProvider debugInformationProvider, Logger logger, WebAssemblyCodegenConfigProvider options) - : base(dependencyGraph, nodeFactory, GetCompilationRoots(roots, nodeFactory), null, null, logger) + : base(dependencyGraph, nodeFactory, GetCompilationRoots(roots, nodeFactory), debugInformationProvider, null, logger) { NodeFactory = nodeFactory; Module = LLVM.ModuleCreateWithName("netscripten"); LLVM.SetTarget(Module, "asmjs-unknown-emscripten"); Options = options; + DIBuilder = LLVMPInvokes.LLVMCreateDIBuilder(Module); + DebugMetadataMap = new Dictionary(); } private static IEnumerable GetCompilationRoots(IEnumerable existingRoots, NodeFactory factory) diff --git a/external/corert/src/ILCompiler.WebAssembly/src/Compiler/WebAssemblyCodegenCompilationBuilder.cs b/external/corert/src/ILCompiler.WebAssembly/src/Compiler/WebAssemblyCodegenCompilationBuilder.cs index 48bfaa15ba..3b40a60f72 100644 --- a/external/corert/src/ILCompiler.WebAssembly/src/Compiler/WebAssemblyCodegenCompilationBuilder.cs +++ b/external/corert/src/ILCompiler.WebAssembly/src/Compiler/WebAssemblyCodegenCompilationBuilder.cs @@ -31,11 +31,10 @@ namespace ILCompiler public override ICompilation ToCompilation() { - var interopStubManager = new CompilerGeneratedInteropStubManager(_compilationGroup, _context, new InteropStateManager(_compilationGroup.GeneratedAssembly)); + var interopStubManager = new CompilerGeneratedInteropStubManager(_compilationGroup, _context, new InteropStateManager(_context.GeneratedAssembly)); WebAssemblyCodegenNodeFactory factory = new WebAssemblyCodegenNodeFactory(_context, _compilationGroup, _metadataManager, interopStubManager, _nameMangler, _vtableSliceProvider, _dictionaryLayoutProvider); - DependencyAnalyzerBase graph = CreateDependencyGraph(factory); - - return new WebAssemblyCodegenCompilation(graph, factory, _compilationRoots, _logger, _config); + DependencyAnalyzerBase graph = CreateDependencyGraph(factory, new ObjectNode.ObjectNodeComparer(new CompilerComparer())); + return new WebAssemblyCodegenCompilation(graph, factory, _compilationRoots, _debugInformationProvider, _logger, _config); } } diff --git a/external/corert/src/ILCompiler.WebAssembly/src/ILCompiler.WebAssembly.csproj b/external/corert/src/ILCompiler.WebAssembly/src/ILCompiler.WebAssembly.csproj index 58b4c14ebf..26e9f32530 100644 --- a/external/corert/src/ILCompiler.WebAssembly/src/ILCompiler.WebAssembly.csproj +++ b/external/corert/src/ILCompiler.WebAssembly/src/ILCompiler.WebAssembly.csproj @@ -37,8 +37,10 @@ IL\HelperExtensions.cs + + @@ -56,13 +58,13 @@ PreserveNewest - + PreserveNewest - + PreserveNewest - + PreserveNewest diff --git a/external/corert/src/ILCompiler.WebAssembly/src/libLLVMdep.depproj b/external/corert/src/ILCompiler.WebAssembly/src/libLLVMdep.depproj index 5c1bac3da7..97b7dd4b9a 100644 --- a/external/corert/src/ILCompiler.WebAssembly/src/libLLVMdep.depproj +++ b/external/corert/src/ILCompiler.WebAssembly/src/libLLVMdep.depproj @@ -13,7 +13,7 @@ - 4.0.0 + 6.0.0-beta1 diff --git a/external/corert/src/ILCompiler/ObjectWriter/ObjectWriter.depproj b/external/corert/src/ILCompiler/ObjectWriter/ObjectWriter.depproj index d1f46b4ae0..6046fd628f 100644 --- a/external/corert/src/ILCompiler/ObjectWriter/ObjectWriter.depproj +++ b/external/corert/src/ILCompiler/ObjectWriter/ObjectWriter.depproj @@ -5,12 +5,9 @@ - .NETCoreApp,Version=v2.0 - netcoreapp2.0 + .NETCoreApp,Version=v2.1 + netcoreapp2.1 $(NuPkgRid) - win7-x64 - osx.10.10-x64 - ubuntu.14.04-x64 true diff --git a/external/corert/src/ILCompiler/RyuJIT/RyuJIT.depproj b/external/corert/src/ILCompiler/RyuJIT/RyuJIT.depproj index 1eb94f741f..c8aa48a876 100644 --- a/external/corert/src/ILCompiler/RyuJIT/RyuJIT.depproj +++ b/external/corert/src/ILCompiler/RyuJIT/RyuJIT.depproj @@ -5,8 +5,8 @@ - .NETCoreApp,Version=v2.0 - netcoreapp2.0 + .NETCoreApp,Version=v2.1 + netcoreapp2.1 $(NuPkgRid) true diff --git a/external/corert/src/ILCompiler/netcoreapp/ilc.csproj b/external/corert/src/ILCompiler/netcoreapp/ilc.csproj index 1feb02316e..06240cfef8 100644 --- a/external/corert/src/ILCompiler/netcoreapp/ilc.csproj +++ b/external/corert/src/ILCompiler/netcoreapp/ilc.csproj @@ -2,7 +2,7 @@ Exe - netcoreapp2.0 + netcoreapp2.1 diff --git a/external/corert/src/ILCompiler/repro/repro.csproj b/external/corert/src/ILCompiler/repro/repro.csproj index 5e3e753125..e8ec9a0423 100644 --- a/external/corert/src/ILCompiler/repro/repro.csproj +++ b/external/corert/src/ILCompiler/repro/repro.csproj @@ -3,16 +3,22 @@ Exe repro - netcoreapp2.0 + netcoreapp2.1 true true false false + + + 169;414 $(MicrosoftNETCoreAppPackageVersion) + + 4.5.1 + diff --git a/external/corert/src/ILCompiler/repro/repro.ilproj b/external/corert/src/ILCompiler/repro/repro.ilproj index 2c49426955..8fdd23d406 100644 --- a/external/corert/src/ILCompiler/repro/repro.ilproj +++ b/external/corert/src/ILCompiler/repro/repro.ilproj @@ -3,7 +3,7 @@ Exe repro - netcoreapp2.0 + netcoreapp2.1 true diff --git a/external/corert/src/ILCompiler/reproNative/reproNative.vcxproj b/external/corert/src/ILCompiler/reproNative/reproNative.vcxproj index 9d9f6eed2a..3b88d1751f 100644 --- a/external/corert/src/ILCompiler/reproNative/reproNative.vcxproj +++ b/external/corert/src/ILCompiler/reproNative/reproNative.vcxproj @@ -62,7 +62,7 @@ Console true - ..\..\..\bin\obj\Windows_NT.x64.Debug\repro\native\repro.obj;kernel32.lib;user32.lib;gdi32.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;bcrypt.lib;%(AdditionalDependencies);..\..\..\bin\Windows_NT.x64.Debug\sdk\Runtime.lib + ..\..\..\bin\obj\Windows_NT.x64.Debug\repro\native\repro.obj;kernel32.lib;user32.lib;gdi32.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;bcrypt.lib;%(AdditionalDependencies);..\..\..\bin\Windows_NT.x64.Debug\sdk\Runtime.lib;..\..\..\bin\Windows_NT.x64.Debug\sdk\System.Private.TypeLoader.Native.lib @@ -84,7 +84,7 @@ true true true - ..\..\..\bin\obj\Windows_NT.x64.Release\repro\native\repro.obj;kernel32.lib;user32.lib;gdi32.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;bcrypt.lib;%(AdditionalDependencies);..\..\..\bin\Windows_NT.x64.Release\sdk\Runtime.lib + ..\..\..\bin\obj\Windows_NT.x64.Release\repro\native\repro.obj;kernel32.lib;user32.lib;gdi32.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;bcrypt.lib;%(AdditionalDependencies);..\..\..\bin\Windows_NT.x64.Release\sdk\Runtime.lib;..\..\..\bin\Windows_NT.x64.Release\sdk\System.Private.TypeLoader.Native.lib diff --git a/external/corert/src/ILCompiler/src/ILCompiler.csproj b/external/corert/src/ILCompiler/src/ILCompiler.csproj index 75d6ba4e2c..4e437223ed 100644 --- a/external/corert/src/ILCompiler/src/ILCompiler.csproj +++ b/external/corert/src/ILCompiler/src/ILCompiler.csproj @@ -8,7 +8,7 @@ ILCompiler ilc true - netcoreapp2.0 + netcoreapp2.1 false .dll diff --git a/external/corert/src/ILCompiler/src/Program.cs b/external/corert/src/ILCompiler/src/Program.cs index e869f7540d..cd75a913eb 100644 --- a/external/corert/src/ILCompiler/src/Program.cs +++ b/external/corert/src/ILCompiler/src/Program.cs @@ -17,6 +17,8 @@ namespace ILCompiler { internal class Program { + private const string DefaultSystemModule = "System.Private.CoreLib"; + private Dictionary _inputFilePaths = new Dictionary(StringComparer.OrdinalIgnoreCase); private Dictionary _referenceFilePaths = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -37,7 +39,7 @@ namespace ILCompiler private OptimizationMode _optimizationMode; private bool _enableDebugInfo; private string _ilDump; - private string _systemModuleName = "System.Private.CoreLib"; + private string _systemModuleName = DefaultSystemModule; private bool _multiFile; private bool _nativeLib; private string _exportsFile; @@ -47,6 +49,8 @@ namespace ILCompiler private bool _emitStackTraceData; private string _mapFileName; private string _metadataLogFileName; + private bool _noMetadataBlocking; + private bool _completeTypesMetadata; private string _singleMethodTypeName; private string _singleMethodName; @@ -56,6 +60,12 @@ namespace ILCompiler private IReadOnlyList _rdXmlFilePaths = Array.Empty(); + private IReadOnlyList _initAssemblies = Array.Empty(); + + private IReadOnlyList _appContextSwitches = Array.Empty(); + + private IReadOnlyList _runtimeOptions = Array.Empty(); + private bool _help; private Program() @@ -88,20 +98,20 @@ namespace ILCompiler switch (RuntimeInformation.ProcessArchitecture) { - case Architecture.X86: - _targetArchitecture = TargetArchitecture.X86; - break; - case Architecture.X64: - _targetArchitecture = TargetArchitecture.X64; - break; - case Architecture.Arm: - _targetArchitecture = TargetArchitecture.ARM; - break; - case Architecture.Arm64: - _targetArchitecture = TargetArchitecture.ARM64; - break; - default: - throw new NotImplementedException(); + case Architecture.X86: + _targetArchitecture = TargetArchitecture.X86; + break; + case Architecture.X64: + _targetArchitecture = TargetArchitecture.X64; + break; + case Architecture.Arm: + _targetArchitecture = TargetArchitecture.ARM; + break; + case Architecture.Arm64: + _targetArchitecture = TargetArchitecture.ARM64; + break; + default: + throw new NotImplementedException(); } // Workaround for https://github.com/dotnet/corefx/issues/25267 @@ -149,10 +159,15 @@ namespace ILCompiler syntax.DefineOptionList("rdxml", ref _rdXmlFilePaths, "RD.XML file(s) for compilation"); syntax.DefineOption("map", ref _mapFileName, "Generate a map file"); syntax.DefineOption("metadatalog", ref _metadataLogFileName, "Generate a metadata log file"); + syntax.DefineOption("nometadatablocking", ref _noMetadataBlocking, "Ignore metadata blocking for internal implementation details"); + syntax.DefineOption("completetypemetadata", ref _completeTypesMetadata, "Generate complete metadata for types"); syntax.DefineOption("scan", ref _useScanner, "Use IL scanner to generate optimized code (implied by -O)"); syntax.DefineOption("noscan", ref _noScanner, "Do not use IL scanner to generate optimized code"); syntax.DefineOption("ildump", ref _ilDump, "Dump IL assembly listing for compiler-generated IL"); syntax.DefineOption("stacktracedata", ref _emitStackTraceData, "Emit data to support generating stack trace strings at runtime"); + syntax.DefineOptionList("initassembly", ref _initAssemblies, "Assembly(ies) with a library initializer"); + syntax.DefineOptionList("appcontextswitch", ref _appContextSwitches, "System.AppContext switches to set"); + syntax.DefineOptionList("runtimeopt", ref _runtimeOptions, "Runtime options to set"); syntax.DefineOption("targetarch", ref _targetArchitectureStr, "Target architecture for cross compilation"); syntax.DefineOption("targetos", ref _targetOSStr, "Target OS for cross compilation"); @@ -180,6 +195,33 @@ namespace ILCompiler return argSyntax; } + private IReadOnlyCollection CreateInitializerList(TypeSystemContext context) + { + List assembliesWithInitalizers = new List(); + + // Build a list of assemblies that have an initializer that needs to run before + // any user code runs. + foreach (string initAssemblyName in _initAssemblies) + { + ModuleDesc assembly = context.ResolveAssembly(new AssemblyName(initAssemblyName)); + assembliesWithInitalizers.Add(assembly); + } + + var libraryInitializers = new LibraryInitializers(context, assembliesWithInitalizers); + + List initializerList = new List(libraryInitializers.LibraryInitializerMethods); + + // If there are any AppContext switches the user wishes to enable, generate code that sets them. + if (_appContextSwitches.Count > 0) + { + MethodDesc appContextInitMethod = new Internal.IL.Stubs.StartupCode.AppContextInitializerMethod( + context.GeneratedAssembly.GetGlobalModuleType(), _appContextSwitches); + initializerList.Add(appContextInitMethod); + } + + return initializerList; + } + private int Run(string[] args) { InitializeDefaultOptions(); @@ -190,7 +232,7 @@ namespace ILCompiler Help(syntax.GetHelpText()); return 1; } - + if (_outputFilePath == null) throw new CommandLineException("Output filename must be specified (/out )"); @@ -231,6 +273,7 @@ namespace ILCompiler if (_isWasmCodegen) _targetArchitecture = TargetArchitecture.Wasm32; + // // Initialize type system context // @@ -239,8 +282,9 @@ namespace ILCompiler SharedGenericsMode.CanonicalReferenceTypes : SharedGenericsMode.Disabled; // TODO: compiler switch for SIMD support? - var simdVectorLength = (_isCppCodegen || _isWasmCodegen) ? SimdVectorLength.None : SimdVectorLength.Vector128Bit; - var targetDetails = new TargetDetails(_targetArchitecture, _targetOS, TargetAbi.CoreRT, simdVectorLength); + var simdVectorLength = (_isCppCodegen || _isWasmCodegen) ? SimdVectorLength.None : SimdVectorLength.Vector128Bit; + var targetAbi = _isCppCodegen ? TargetAbi.CppCodegen : TargetAbi.CoreRT; + var targetDetails = new TargetDetails(_targetArchitecture, _targetOS, targetAbi, simdVectorLength); var typeSystemContext = new CompilerTypeSystemContext(targetDetails, genericsMode); // @@ -309,15 +353,8 @@ namespace ILCompiler if (entrypointModule != null) { - LibraryInitializers libraryInitializers = - new LibraryInitializers(typeSystemContext, _isCppCodegen); - compilationRoots.Add(new MainMethodRootProvider(entrypointModule, libraryInitializers.LibraryInitializerMethods)); - } - else if (_nativeLib) - { - EcmaModule module = (EcmaModule)typeSystemContext.SystemModule; - LibraryInitializers libraryInitializers = new LibraryInitializers(typeSystemContext, _isCppCodegen); - compilationRoots.Add(new NativeLibraryInitializerRootProvider(module, libraryInitializers.LibraryInitializerMethods)); + compilationRoots.Add(new MainMethodRootProvider(entrypointModule, CreateInitializerList(typeSystemContext))); + compilationRoots.Add(new RuntimeConfigurationRootProvider(_runtimeOptions)); } if (_multiFile) @@ -344,8 +381,15 @@ namespace ILCompiler throw new Exception("No entrypoint module"); compilationRoots.Add(new ExportedMethodsRootProvider((EcmaModule)typeSystemContext.SystemModule)); + compilationGroup = new SingleFileCompilationModuleGroup(); + } - compilationGroup = new SingleFileCompilationModuleGroup(typeSystemContext); + if (_nativeLib) + { + // Set owning module of generated native library startup method to compiler generated module, + // to ensure the startup method is included in the object file during multimodule mode build + compilationRoots.Add(new NativeLibraryInitializerRootProvider(typeSystemContext.GeneratedAssembly, CreateInitializerList(typeSystemContext))); + compilationRoots.Add(new RuntimeConfigurationRootProvider(_runtimeOptions)); } if (_rdXmlFilePaths.Count > 0) @@ -371,12 +415,27 @@ namespace ILCompiler var stackTracePolicy = _emitStackTraceData ? (StackTraceEmissionPolicy)new EcmaMethodStackTraceEmissionPolicy() : new NoStackTraceEmissionPolicy(); + MetadataBlockingPolicy mdBlockingPolicy = _noMetadataBlocking ? + (MetadataBlockingPolicy)new NoMetadataBlockingPolicy() : new BlockedInternalsBlockingPolicy(); + + ManifestResourceBlockingPolicy resBlockingPolicy = new NoManifestResourceBlockingPolicy(); + + UsageBasedMetadataGenerationOptions metadataGenerationOptions = UsageBasedMetadataGenerationOptions.None; + if (_completeTypesMetadata) + metadataGenerationOptions |= UsageBasedMetadataGenerationOptions.CompleteTypesOnly; + + DynamicInvokeThunkGenerationPolicy invokeThunkGenerationPolicy = new DefaultDynamicInvokeThunkGenerationPolicy(); + UsageBasedMetadataManager metadataManager = new UsageBasedMetadataManager( compilationGroup, typeSystemContext, - new BlockedInternalsBlockingPolicy(), + mdBlockingPolicy, + resBlockingPolicy, _metadataLogFileName, - stackTracePolicy); + stackTracePolicy, + invokeThunkGenerationPolicy, + metadataGenerationOptions + ); // Unless explicitly opted in at the command line, we enable scanner for retail builds by default. // We don't do this for CppCodegen and Wasm, because those codegens are behind. @@ -388,7 +447,9 @@ namespace ILCompiler useScanner &= !_noScanner; - MetadataManager compilationMetadataManager = _isWasmCodegen ? (MetadataManager)new EmptyMetadataManager(typeSystemContext) : metadataManager; + bool supportsReflection = !_isWasmCodegen && !_isCppCodegen && _systemModuleName == DefaultSystemModule; + + MetadataManager compilationMetadataManager = supportsReflection ? metadataManager : (MetadataManager)new EmptyMetadataManager(typeSystemContext); ILScanResults scanResults = null; if (useScanner) { @@ -494,7 +555,7 @@ namespace ILCompiler // We additionally skip methods in SIMD module because there's just too many intrisics to handle and IL scanner // doesn't expand them. They would show up as noisy diffs. DiffCompilationResults(ref dummy, scanResults.CompiledMethodBodies, compilationResults.CompiledMethodBodies, - "Methods", "scanned", "compiled", method => !(method.GetTypicalMethodDefinition() is EcmaMethod) || simdHelper.IsInSimdModule(method.OwningType)); + "Methods", "scanned", "compiled", method => !(method.GetTypicalMethodDefinition() is EcmaMethod) || simdHelper.IsSimdType(method.OwningType)); DiffCompilationResults(ref dummy, scanResults.ConstructedEETypes, compilationResults.ConstructedEETypes, "EETypes", "scanned", "compiled", type => !(type.GetTypeDefinition() is EcmaType)); } diff --git a/external/corert/src/ILVerification/src/ILVerification.csproj b/external/corert/src/ILVerification/src/ILVerification.csproj index efa6e53495..8d058dbf61 100644 --- a/external/corert/src/ILVerification/src/ILVerification.csproj +++ b/external/corert/src/ILVerification/src/ILVerification.csproj @@ -7,8 +7,12 @@ true false netstandard1.3 - ..\StrongNameKeys\ILVerify.snk + true + + true + + true @@ -77,6 +81,9 @@ TypeSystem\Common\ExceptionStringID.cs + + Utilities\DebugNameFormatter.cs + TypeSystem\Common\FieldForInstantiatedType.cs @@ -86,6 +93,9 @@ TypeSystem\Common\FieldDesc.FieldLayout.cs + + TypeSystem\Common\FieldDesc.ToString.cs + TypeSystem\Common\FieldLayoutAlgorithm.cs @@ -167,6 +177,9 @@ TypeSystem\Common\MethodDesc.cs + + TypeSystem\Common\MethodDesc.ToString.cs + TypeSystem\Common\StandardVirtualMethodAlgorithm.cs @@ -176,6 +189,9 @@ TypeSystem\Common\TypeDesc.Interfaces.cs + + TypeSystem\Common\TypeDesc.ToString.cs + TypeSystem\Common\DefType.cs diff --git a/external/corert/src/ILVerification/src/ILVerifyTypeSystemContext.cs b/external/corert/src/ILVerification/src/ILVerifyTypeSystemContext.cs index 528dc6a90c..96aaa3fd90 100644 --- a/external/corert/src/ILVerification/src/ILVerifyTypeSystemContext.cs +++ b/external/corert/src/ILVerification/src/ILVerifyTypeSystemContext.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using System.IO; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; @@ -29,18 +30,39 @@ namespace ILVerify public override ModuleDesc ResolveAssembly(AssemblyName name, bool throwIfNotFound = true) { - PEReader peReader = _resolver.Resolve(name); - if (peReader == null && throwIfNotFound) - { - throw new VerifierException("Assembly or module not found: " + name.Name); - } + // Note: we use simple names instead of full names to resolve, because we can't get a full name from an assembly without reading it + string simpleName = name.Name; + return ResolveAssemblyOrNetmodule(simpleName, simpleName, throwIfNotFound); + } - var module = GetModule(peReader); - VerifyModuleName(name, module); + internal override ModuleDesc ResolveModule(ModuleDesc referencingModule, string fileName, bool throwIfNotFound = true) + { + // Referenced modules are stored without their extension (see CommandLineHelpers.cs), so we have to drop + // the extension here as well to find a match. + string simpleName = Path.GetFileNameWithoutExtension(fileName); + // The referencing module is not getting verified currently. + // However, netmodules are resolved in the context of assembly, not in the global context. + EcmaModule module = ResolveAssemblyOrNetmodule(simpleName, fileName, throwIfNotFound); + if (module.MetadataReader.IsAssembly) + { + throw new VerifierException($"The module '{fileName}' is not expected to be an assembly"); + } return module; } - private static void VerifyModuleName(AssemblyName name, EcmaModule module) + private EcmaModule ResolveAssemblyOrNetmodule(string simpleName, string verificationName, bool throwIfNotFound) + { + PEReader peReader = _resolver.Resolve(simpleName); + if (peReader == null && throwIfNotFound) + { + throw new VerifierException("Assembly or module not found: " + simpleName); + } + var module = GetModule(peReader); + VerifyModuleName(verificationName, module); + return module; + } + + private static void VerifyModuleName(string simpleName, EcmaModule module) { MetadataReader metadataReader = module.MetadataReader; StringHandle nameHandle = metadataReader.IsAssembly @@ -48,9 +70,9 @@ namespace ILVerify : metadataReader.GetModuleDefinition().Name; string actualSimpleName = metadataReader.GetString(nameHandle); - if (!actualSimpleName.Equals(name.Name, StringComparison.OrdinalIgnoreCase)) + if (!actualSimpleName.Equals(simpleName, StringComparison.OrdinalIgnoreCase)) { - throw new VerifierException($"Actual PE name '{actualSimpleName}' does not match provided name '{name}'"); + throw new VerifierException($"Actual PE name '{actualSimpleName}' does not match provided name '{simpleName}'"); } } diff --git a/external/corert/src/ILVerification/src/IResolver.cs b/external/corert/src/ILVerification/src/IResolver.cs index f3706cf3b9..aec09c82a7 100644 --- a/external/corert/src/ILVerification/src/IResolver.cs +++ b/external/corert/src/ILVerification/src/IResolver.cs @@ -13,7 +13,7 @@ namespace ILVerify /// /// This method should return the same instance when queried multiple times. /// - PEReader Resolve(AssemblyName name); + PEReader Resolve(string simpleName); } /// @@ -23,16 +23,14 @@ namespace ILVerify { private readonly Dictionary _resolverCache = new Dictionary(); - public PEReader Resolve(AssemblyName name) + public PEReader Resolve(string simpleName) { - // Note: we use simple names instead of full names to resolve, because we can't get a full name from an assembly without reading it - string simpleName = name.Name; if (_resolverCache.TryGetValue(simpleName, out PEReader peReader)) { return peReader; } - PEReader result = ResolveCore(name); + PEReader result = ResolveCore(simpleName); if (result != null) { _resolverCache.Add(simpleName, result); @@ -42,6 +40,6 @@ namespace ILVerify return null; } - protected abstract PEReader ResolveCore(AssemblyName name); + protected abstract PEReader ResolveCore(string simpleName); } } diff --git a/external/corert/src/ILVerification/src/Verifier.cs b/external/corert/src/ILVerification/src/Verifier.cs index 9341ef3958..ef9374f14a 100644 --- a/external/corert/src/ILVerification/src/Verifier.cs +++ b/external/corert/src/ILVerification/src/Verifier.cs @@ -34,7 +34,12 @@ namespace ILVerify public void SetSystemModuleName(AssemblyName name) { - _typeSystemContext.SetSystemModule(_typeSystemContext.GetModule(_typeSystemContext._resolver.Resolve(name))); + PEReader peReader = _typeSystemContext._resolver.Resolve(name.Name); + if (peReader is null) + { + throw new VerifierException("Assembly or module not found: " + name.FullName); + } + _typeSystemContext.SetSystemModule(_typeSystemContext.GetModule(peReader)); } internal EcmaModule GetModule(PEReader peReader) @@ -161,7 +166,7 @@ namespace ILVerify private IEnumerable VerifyMethod(EcmaModule module, MethodIL methodIL, MethodDefinitionHandle methodHandle) { var builder = new ArrayBuilder(); - MethodDesc method = methodIL.OwningMethod; + MethodDesc method = methodIL.OwningMethod; try { diff --git a/external/corert/src/ILVerification/tests/ILMethodTester.cs b/external/corert/src/ILVerification/tests/ILMethodTester.cs index eb92c3dcb2..871045ed0b 100644 --- a/external/corert/src/ILVerification/tests/ILMethodTester.cs +++ b/external/corert/src/ILVerification/tests/ILMethodTester.cs @@ -20,7 +20,7 @@ namespace ILVerification.Tests void TestMethodsWithValidIL(ValidILTestCase validIL) { var results = Verify(validIL); - Assert.Equal(0, results.Count()); + Assert.Empty(results); } [Theory(DisplayName = "")] diff --git a/external/corert/src/ILVerification/tests/ILTests/AccessTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/AccessTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/AccessTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/AccessTestsExtern.ilproj b/external/corert/src/ILVerification/tests/ILTests/AccessTestsExtern.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/AccessTestsExtern.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/AccessTestsFriend.ilproj b/external/corert/src/ILVerification/tests/ILTests/AccessTestsFriend.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/AccessTestsFriend.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/ArrayTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/ArrayTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/ArrayTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/BasicArithmeticTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/BasicArithmeticTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/BasicArithmeticTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/BranchingTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/BranchingTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/BranchingTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/CallTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/CallTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/CallTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/CastingTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/CastingTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/CastingTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/ComparisonTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/ComparisonTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/ComparisonTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/DelegateTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/DelegateTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/DelegateTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/ExceptionRegionTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/ExceptionRegionTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/ExceptionRegionTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/FieldTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/FieldTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/FieldTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/FtnTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/FtnTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/FtnTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/ILTests.targets b/external/corert/src/ILVerification/tests/ILTests/ILTests.targets new file mode 100644 index 0000000000..22983bd3a1 --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/ILTests.targets @@ -0,0 +1,17 @@ + + + + + Library + $(MSBuildProjectName) + $(BaseOutputPath)$(OSPlatformConfig)/ILVerification.Tests/Tests + true + true + + + + + + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/LoadStoreIndirectTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/LoadStoreIndirectTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/LoadStoreIndirectTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/NewobjTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/NewobjTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/NewobjTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/PrefixTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/PrefixTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/PrefixTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/ReturnTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/ReturnTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/ReturnTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/ShiftTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/ShiftTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/ShiftTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/ThisStateTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/ThisStateTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/ThisStateTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILTests/ValueTypeTests.ilproj b/external/corert/src/ILVerification/tests/ILTests/ValueTypeTests.ilproj new file mode 100644 index 0000000000..8e8765d14a --- /dev/null +++ b/external/corert/src/ILVerification/tests/ILTests/ValueTypeTests.ilproj @@ -0,0 +1,3 @@ + + + diff --git a/external/corert/src/ILVerification/tests/ILVerification.Tests.csproj b/external/corert/src/ILVerification/tests/ILVerification.Tests.csproj index 4d5f17abf5..237655cccf 100644 --- a/external/corert/src/ILVerification/tests/ILVerification.Tests.csproj +++ b/external/corert/src/ILVerification/tests/ILVerification.Tests.csproj @@ -3,7 +3,7 @@ Library - netstandard1.5 + netstandard2.0 false @@ -14,16 +14,21 @@ - - - - + + + + + false + Content + + + @@ -32,8 +37,5 @@ - - - diff --git a/external/corert/src/ILVerification/tests/TestDataLoader.cs b/external/corert/src/ILVerification/tests/TestDataLoader.cs index 91a1195f80..4184a5f6fd 100644 --- a/external/corert/src/ILVerification/tests/TestDataLoader.cs +++ b/external/corert/src/ILVerification/tests/TestDataLoader.cs @@ -20,19 +20,17 @@ namespace ILVerification.Tests { /// /// Parses the methods in the test assemblies. - /// It loads all assemblies from the test folder defined in TestDataLoader.TESTASSEMBLYPATH + /// It loads all assemblies from the test folder defined in TestDataLoader.TestAssemblyPath /// This class feeds the xunit Theories /// class TestDataLoader { /// - /// The folder with the binaries which are compiled from the test driver IL Code - /// Currently the test .il code is built manually, but the plan is to have a ProjectReference and automatically build the .il files. - /// See: https://github.com/dotnet/corert/pull/3725#discussion_r118820770 + /// The folder with the test binaries /// - public static string TESTASSEMBLYPATH = @"..\..\..\ILTests\"; + private const string TestAssemblyPath = @"Tests\"; - private const string SPECIALTEST_PREFIX = "special."; + private const string SpecialTestPrefix = "special."; /// /// Returns all methods that contain valid IL code based on the following naming convention: @@ -129,11 +127,11 @@ namespace ILVerification.Tests private static MethodDefinitionHandle HandleSpecialTests(string[] methodParams, EcmaMethod method) { - if (!methodParams[0].StartsWith(SPECIALTEST_PREFIX)) + if (!methodParams[0].StartsWith(SpecialTestPrefix)) return method.Handle; // Cut off special prefix - var specialParams = methodParams[0].Substring(SPECIALTEST_PREFIX.Length); + var specialParams = methodParams[0].Substring(SpecialTestPrefix.Length); // Get friendly name / special name int delimiter = specialParams.IndexOf('.'); @@ -152,7 +150,7 @@ namespace ILVerification.Tests private static IEnumerable GetAllTestDlls() { - foreach (var item in Directory.GetFiles(TESTASSEMBLYPATH)) + foreach (var item in Directory.GetFiles(TestAssemblyPath)) { if (item.ToLower().EndsWith(".dll")) { @@ -167,7 +165,7 @@ namespace ILVerification.Tests foreach (var fileName in GetAllTestDlls()) { - simpleNameToPathMap.Add(Path.GetFileNameWithoutExtension(fileName), TESTASSEMBLYPATH + fileName); + simpleNameToPathMap.Add(Path.GetFileNameWithoutExtension(fileName), TestAssemblyPath + fileName); } Assembly coreAssembly = typeof(object).GetTypeInfo().Assembly; @@ -178,9 +176,9 @@ namespace ILVerification.Tests var resolver = new TestResolver(simpleNameToPathMap); var typeSystemContext = new ILVerifyTypeSystemContext(resolver); - typeSystemContext.SetSystemModule(typeSystemContext.GetModule(resolver.Resolve(coreAssembly.GetName()))); + typeSystemContext.SetSystemModule(typeSystemContext.GetModule(resolver.Resolve(coreAssembly.GetName().Name))); - return typeSystemContext.GetModule(resolver.Resolve(new AssemblyName(Path.GetFileNameWithoutExtension(assemblyName)))); + return typeSystemContext.GetModule(resolver.Resolve(new AssemblyName(Path.GetFileNameWithoutExtension(assemblyName)).Name)); } private sealed class TestResolver : ResolverBase @@ -191,9 +189,9 @@ namespace ILVerification.Tests _simpleNameToPathMap = simpleNameToPathMap; } - protected override PEReader ResolveCore(AssemblyName name) + protected override PEReader ResolveCore(string simpleName) { - if (_simpleNameToPathMap.TryGetValue(name.Name, out string path)) + if (_simpleNameToPathMap.TryGetValue(simpleName, out string path)) { return new PEReader(File.OpenRead(path)); } diff --git a/external/corert/src/ILVerify/README.md b/external/corert/src/ILVerify/README.md index ef4d0d81f6..286c70d506 100644 --- a/external/corert/src/ILVerify/README.md +++ b/external/corert/src/ILVerify/README.md @@ -17,7 +17,7 @@ Historically on Full Framework IL generators used PEVerify to make sure that the - Fast spin up/tear down. ## The codebase -The project targets netcoreapp2.0 and uses the new .csproj based project format. If you want to open and compile it with Visual Studio then you need a version, which supports .NET Core 2.0 tooling. This is supported in Visual Studio 2017 Update 3 (Version 15.3) or later. The other option is to use command (with .NET Core 2.0 tooling). +The project targets netcoreapp2.1 and uses the new .csproj based project format. If you want to open and compile it with Visual Studio then you need a version, which supports .NET Core 2.1 tooling. This is supported in Visual Studio 2017 Version 15.8 or later. The other option is to use command (with .NET Core 2.1 tooling). The code is split into three projects: - ILVerification is the library with the core verification logic, - ILVerification.Tests contains the tests for ILVerification, @@ -27,18 +27,6 @@ The code is split into three projects: To test the ILVerification library we have small methods checked in as .il files testing specific verification scenarios. These tests live under [src/ILVerification/tests/ILTests](../ILVerification/tests/ILTests). Tests are grouped into .il files based on functionalities they test. There is no strict policy here, the goal is to have a few dozen .il files instead of thousands containing each only a single method. -Currently the IL files are NOT compiled automatically. You have to compile manually (We want to automate this step later): - -``` -ilasm [filename.il] /dll /ERROR -``` - -Note: if you run the tests and get an error similar to this then it means that the .il files were not compiled, or none of them contained methods that follow the naming convention described below: - -``` -Result Message: System.InvalidOperationException : No data found for ILVerify.Tests.ILMethodTester.TestMethodsWithInvalidIL -``` - The test project itself is under [src/ILVerification/tests](../ILVerification/tests) Method names in the .il files must follow the following naming convention: diff --git a/external/corert/src/ILVerify/netcoreapp/ILVerify.csproj b/external/corert/src/ILVerify/netcoreapp/ILVerify.csproj index 47b7d31450..302e01f7de 100644 --- a/external/corert/src/ILVerify/netcoreapp/ILVerify.csproj +++ b/external/corert/src/ILVerify/netcoreapp/ILVerify.csproj @@ -2,7 +2,7 @@ Exe - netcoreapp2.0 + netcoreapp2.1 diff --git a/external/corert/src/ILVerify/src/ILVerify.csproj b/external/corert/src/ILVerify/src/ILVerify.csproj index 0f5d1e9903..9042c8a850 100644 --- a/external/corert/src/ILVerify/src/ILVerify.csproj +++ b/external/corert/src/ILVerify/src/ILVerify.csproj @@ -4,9 +4,13 @@ Exe ILVerify ILVerify - ..\..\ILVerification\StrongNameKeys\ILVerify.snk - netcoreapp2.0 + true + + true + + true + netcoreapp2.1 false .dll diff --git a/external/corert/src/ILVerify/src/Program.cs b/external/corert/src/ILVerify/src/Program.cs index d748084b81..36e978512f 100644 --- a/external/corert/src/ILVerify/src/Program.cs +++ b/external/corert/src/ILVerify/src/Program.cs @@ -10,6 +10,7 @@ using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; +using System.Text; using System.Text.RegularExpressions; using Internal.CommandLine; using Internal.TypeSystem.Ecma; @@ -20,6 +21,8 @@ namespace ILVerify class Program : ResolverBase { private bool _help; + private bool _verbose; + private bool _printStatistics; private AssemblyName _systemModule = new AssemblyName("mscorlib"); private Dictionary _inputFilePaths = new Dictionary(StringComparer.OrdinalIgnoreCase); // map of simple name to file path @@ -73,6 +76,8 @@ namespace ILVerify syntax.DefineOption("include-file", ref includeFile, "Same as --include, but the regular expression(s) are declared line by line in the specified file."); syntax.DefineOptionList("e|exclude", ref excludePatterns, "Skip methods/types/namespaces, which match the given regular expression(s)"); syntax.DefineOption("exclude-file", ref excludeFile, "Same as --exclude, but the regular expression(s) are declared line by line in the specified file."); + syntax.DefineOption("statistics", ref _printStatistics, "Print verification statistics"); + syntax.DefineOption("v|verbose", ref _verbose, "Verbose output"); syntax.DefineParameterList("in", ref inputFiles, "Input file(s)"); }); @@ -99,6 +104,25 @@ namespace ILVerify } _excludePatterns = StringPatternsToRegexList(excludePatterns); + if (_verbose) + { + WriteLine(); + foreach (var path in _inputFilePaths) + WriteLine($"Using input file '{path.Value}'"); + + WriteLine(); + foreach (var path in _referenceFilePaths) + WriteLine($"Using reference file '{path.Value}'"); + + WriteLine(); + foreach (var pattern in _includePatterns) + WriteLine($"Using include pattern '{pattern}'"); + + WriteLine(); + foreach (var pattern in _excludePatterns) + WriteLine($"Using exclude pattern '{pattern}'"); + } + return argSyntax; } @@ -119,19 +143,7 @@ namespace ILVerify foreach (var kvp in _inputFilePaths) { - var results = VerifyAssembly(new AssemblyName(kvp.Key), out EcmaModule module); - int numErrors = 0; - - foreach (var result in results) - { - numErrors++; - PrintResult(result, module, kvp.Value); - } - - if (numErrors > 0) - WriteLine(numErrors + " Error(s) Verifying " + kvp.Value); - else - WriteLine("All Classes and Methods in " + kvp.Value + " Verified."); + VerifyAssembly(new AssemblyName(kvp.Key), kvp.Value); } return 0; @@ -216,29 +228,82 @@ namespace ILVerify Write(")"); } - private IEnumerable VerifyAssembly(AssemblyName name, out EcmaModule module) + private void VerifyAssembly(AssemblyName name, string path) { - PEReader peReader = Resolve(name); - module = _verifier.GetModule(peReader); + PEReader peReader = Resolve(name.Name); + EcmaModule module = _verifier.GetModule(peReader); - return VerifyAssembly(peReader); + VerifyAssembly(peReader, module, path); } - private IEnumerable VerifyAssembly(PEReader peReader) + private void VerifyAssembly(PEReader peReader, EcmaModule module, string path) { + int numErrors = 0; + int verifiedMethodCounter = 0; + int methodCounter = 0; + MetadataReader metadataReader = peReader.GetMetadataReader(); foreach (var methodHandle in metadataReader.MethodDefinitions) { - var methodName = metadataReader.GetString(metadataReader.GetMethodDefinition(methodHandle).Name); - if (ShouldVerifyMethod(methodName)) + // get fully qualified method name + var methodName = GetQualifiedMethodName(metadataReader, methodHandle); + + bool verifying = ShouldVerifyMethod(methodName); + if (_verbose) + { + Write(verifying ? "Verifying " : "Skipping "); + WriteLine(methodName); + } + + if (verifying) { var results = _verifier.Verify(peReader, methodHandle); foreach (var result in results) { - yield return result; + PrintResult(result, module, path); + numErrors++; } + + verifiedMethodCounter++; } + + methodCounter++; } + + if (numErrors > 0) + WriteLine(numErrors + " Error(s) Verifying " + path); + else + WriteLine("All Classes and Methods in " + path + " Verified."); + + if (_printStatistics) + { + WriteLine($"Methods found: {methodCounter}"); + WriteLine($"Methods verified: {verifiedMethodCounter}"); + } + } + + /// + /// This method returns the fully qualified method name by concatenating assembly, type and method name. + /// This method exists to avoid additional assembly resolving, which might be triggered by calling + /// MethodDesc.ToString(). + /// + private string GetQualifiedMethodName(MetadataReader metadataReader, MethodDefinitionHandle methodHandle) + { + var methodDef = metadataReader.GetMethodDefinition(methodHandle); + var typeDef = metadataReader.GetTypeDefinition(methodDef.GetDeclaringType()); + + var methodName = metadataReader.GetString(metadataReader.GetMethodDefinition(methodHandle).Name); + var typeName = metadataReader.GetString(typeDef.Name); + var namespaceName = metadataReader.GetString(typeDef.Namespace); + var assemblyName = metadataReader.GetString(metadataReader.IsAssembly ? metadataReader.GetAssemblyDefinition().Name : metadataReader.GetModuleDefinition().Name); + + StringBuilder builder = new StringBuilder(); + builder.Append($"[{assemblyName}]"); + if (!string.IsNullOrEmpty(namespaceName)) + builder.Append($"{namespaceName}."); + builder.Append($"{typeName}.{methodName}"); + + return builder.ToString(); } private bool ShouldVerifyMethod(string methodName) @@ -256,11 +321,8 @@ namespace ILVerify return true; } - protected override PEReader ResolveCore(AssemblyName name) + protected override PEReader ResolveCore(string simpleName) { - // Note: we use simple names instead of full names to resolve, because we can't get a full name from an assembly without reading it - string simpleName = name.Name; - string path = null; if (_inputFilePaths.TryGetValue(simpleName, out path) || _referenceFilePaths.TryGetValue(simpleName, out path)) { diff --git a/external/corert/src/JitInterface/src/CorInfoBase.cs.REMOVED.git-id b/external/corert/src/JitInterface/src/CorInfoBase.cs.REMOVED.git-id index b680729bde..c9b7cc32a1 100644 --- a/external/corert/src/JitInterface/src/CorInfoBase.cs.REMOVED.git-id +++ b/external/corert/src/JitInterface/src/CorInfoBase.cs.REMOVED.git-id @@ -1 +1 @@ -8ce1de30094ddd19b5efe44cc1711ecb871ce82e \ No newline at end of file +f9f78d97aa1d25d11ca445ab865437670dbf1a2f \ No newline at end of file diff --git a/external/corert/src/JitInterface/src/CorInfoImpl.Intrinsics.cs b/external/corert/src/JitInterface/src/CorInfoImpl.Intrinsics.cs index 888957b322..903ba093c9 100644 --- a/external/corert/src/JitInterface/src/CorInfoImpl.Intrinsics.cs +++ b/external/corert/src/JitInterface/src/CorInfoImpl.Intrinsics.cs @@ -131,9 +131,9 @@ namespace Internal.JitInterface table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InitializeArray, "InitializeArray", "System.Runtime.CompilerServices", "RuntimeHelpers"); //table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetTypeFromHandle, "GetTypeFromHandle", "System", "Type"); // RuntimeTypeHandle has to be RuntimeType table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_RTH_GetValueInternal, "GetValueInternal", "System", "RuntimeTypeHandle"); - table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_TypeEQ, "op_Equality", "System", "Type"); - table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_TypeNEQ, "op_Inequality", "System", "Type"); - table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Object_GetType, "GetType", "System", "Object"); + //table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_TypeEQ, "op_Equality", "System", "Type"); // https://github.com/dotnet/corert/issues/5180 + //table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_TypeNEQ, "op_Inequality", "System", "Type"); // https://github.com/dotnet/corert/issues/5180 + //table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Object_GetType, "GetType", "System", "Object"); // https://github.com/dotnet/corert/issues/5180 // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetStubContext, "GetStubContext", "System.StubHelpers", "StubHelpers"); // interop-specific // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetStubContextAddr, "GetStubContextAddr", "System.StubHelpers", "StubHelpers"); // interop-specific // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetNDirectTarget, "GetNDirectTarget", "System.StubHelpers", "StubHelpers"); // interop-specific diff --git a/external/corert/src/JitInterface/src/CorInfoImpl.cs.REMOVED.git-id b/external/corert/src/JitInterface/src/CorInfoImpl.cs.REMOVED.git-id index 4350779b07..fc783738fb 100644 --- a/external/corert/src/JitInterface/src/CorInfoImpl.cs.REMOVED.git-id +++ b/external/corert/src/JitInterface/src/CorInfoImpl.cs.REMOVED.git-id @@ -1 +1 @@ -a9eaceaabddd739f9ab20745add8ddcffb771683 \ No newline at end of file +b02092b30e22f2b768d9b1784f3fee40930f074b \ No newline at end of file diff --git a/external/corert/src/JitInterface/src/CorInfoTypes.cs b/external/corert/src/JitInterface/src/CorInfoTypes.cs index b0ceda6134..6d0662be50 100644 --- a/external/corert/src/JitInterface/src/CorInfoTypes.cs +++ b/external/corert/src/JitInterface/src/CorInfoTypes.cs @@ -193,6 +193,7 @@ namespace Internal.JitInterface // Constant Lookups are either: // IAT_VALUE: immediate (relocatable) values, // IAT_PVALUE: immediate values access via an indirection through an immediate (relocatable) address + // IAT_RELPVALUE: immediate values access via a relative indirection through an immediate offset // IAT_PPVALUE: immediate values access via a double indirection through an immediate (relocatable) address // // Runtime Lookups @@ -220,6 +221,7 @@ namespace Internal.JitInterface // If accessType is // IAT_VALUE --> "handle" stores the real handle or "addr " stores the computed address // IAT_PVALUE --> "addr" stores a pointer to a location which will hold the real handle + // IAT_RELPVALUE --> "addr" stores a relative pointer to a location which will hold the real handle // IAT_PPVALUE --> "addr" stores a double indirection to a location which will hold the real handle public InfoAccessType accessType; @@ -301,6 +303,7 @@ namespace Internal.JitInterface // Otherwise, it's a representative... If accessType is // IAT_VALUE --> "handle" stores the real handle or "addr " stores the computed address // IAT_PVALUE --> "addr" stores a pointer to a location which will hold the real handle + // IAT_RELPVALUE --> "addr" stores a relative pointer to a location which will hold the real handle // IAT_PPVALUE --> "addr" stores a double indirection to a location which will hold the real handle public ref CORINFO_CONST_LOOKUP constLookup { @@ -495,7 +498,8 @@ namespace Internal.JitInterface { IAT_VALUE, // The info value is directly available IAT_PVALUE, // The value needs to be accessed via an indirection - IAT_PPVALUE // The value needs to be accessed via a double indirection + IAT_PPVALUE, // The value needs to be accessed via a double indirection + IAT_RELPVALUE // The value needs to be accessed via a relative indirection } public enum CorInfoGCType @@ -1508,7 +1512,7 @@ namespace Internal.JitInterface CORJIT_FLAG_HAS_ARM64_LRCPC = 52, // ID_AA64ISAR1_EL1.LRCPC is 1 or better CORJIT_FLAG_HAS_ARM64_PMULL = 53, // ID_AA64ISAR0_EL1.AES is 2 or better CORJIT_FLAG_HAS_ARM64_SHA1 = 54, // ID_AA64ISAR0_EL1.SHA1 is 1 or better - CORJIT_FLAG_HAS_ARM64_SHA2 = 55, // ID_AA64ISAR0_EL1.SHA2 is 1 or better + CORJIT_FLAG_HAS_ARM64_SHA256 = 55, // ID_AA64ISAR0_EL1.SHA2 is 1 or better CORJIT_FLAG_HAS_ARM64_SHA512 = 56, // ID_AA64ISAR0_EL1.SHA2 is 2 or better CORJIT_FLAG_HAS_ARM64_SHA3 = 57, // ID_AA64ISAR0_EL1.SHA3 is 1 or better CORJIT_FLAG_HAS_ARM64_SIMD = 58, // ID_AA64PFR0_EL1.AdvSIMD is 0 or better diff --git a/external/corert/src/JitInterface/src/ThunkGenerator/ThunkInput.txt b/external/corert/src/JitInterface/src/ThunkGenerator/ThunkInput.txt index 4792e13d1f..056daa6db7 100644 --- a/external/corert/src/JitInterface/src/ThunkGenerator/ThunkInput.txt +++ b/external/corert/src/JitInterface/src/ThunkGenerator/ThunkInput.txt @@ -314,6 +314,7 @@ FUNCTIONS CORINFO_METHOD_HANDLE GetDelegateCtor(CORINFO_METHOD_HANDLE methHnd, CORINFO_CLASS_HANDLE clsHnd, CORINFO_METHOD_HANDLE targetMethodHnd, DelegateCtorArgs * pCtorData); void MethodCompileComplete(CORINFO_METHOD_HANDLE methHnd); void* getTailCallCopyArgsThunk (CORINFO_SIG_INFO *pSig, CorInfoHelperTailCallSpecialHandling flags); + bool convertPInvokeCalliToCall(CORINFO_RESOLVED_TOKEN * pResolvedToken, bool mustConvert); [ManualNativeWrapper] IEEMemoryManager* getMemoryManager(); void allocMem( ULONG hotCodeSize, ULONG coldCodeSize, ULONG roDataSize, ULONG xcptnsCount, CorJitAllocMemFlag flag, void** hotCodeBlock, void** coldCodeBlock, void** roDataBlock ); void reserveUnwindInfo(BOOL isFunclet, BOOL isColdCode, ULONG unwindSize) diff --git a/external/corert/src/JitInterface/src/ThunkGenerator/cordebuginfo.h b/external/corert/src/JitInterface/src/ThunkGenerator/cordebuginfo.h index b065c5fc06..8c076e8b68 100644 --- a/external/corert/src/JitInterface/src/ThunkGenerator/cordebuginfo.h +++ b/external/corert/src/JitInterface/src/ThunkGenerator/cordebuginfo.h @@ -2,6 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +// +// Keep in sync with https://github.com/dotnet/corert/blob/master/src/Native/ObjWriter/cordebuginfo.h +// + /**********************************************************************************/ // DebugInfo types shared by JIT-EE interface and EE-Debugger interface @@ -191,104 +195,114 @@ public: VLT_INVALID, }; + // VLT_REG/VLT_REG_FP -- Any pointer-sized enregistered value (TYP_INT, TYP_REF, etc) + // eg. EAX + // VLT_REG_BYREF -- the specified register contains the address of the variable + // eg. [EAX] + + struct vlReg + { + RegNum vlrReg; + }; + + // VLT_STK -- Any 32 bit value which is on the stack + // eg. [ESP+0x20], or [EBP-0x28] + // VLT_STK_BYREF -- the specified stack location contains the address of the variable + // eg. mov EAX, [ESP+0x20]; [EAX] + + struct vlStk + { + RegNum vlsBaseReg; + signed vlsOffset; + }; + + // VLT_REG_REG -- TYP_LONG with both DWords enregistred + // eg. RBM_EAXEDX + + struct vlRegReg + { + RegNum vlrrReg1; + RegNum vlrrReg2; + }; + + // VLT_REG_STK -- Partly enregistered TYP_LONG + // eg { LowerDWord=EAX UpperDWord=[ESP+0x8] } + + struct vlRegStk + { + RegNum vlrsReg; + struct + { + RegNum vlrssBaseReg; + signed vlrssOffset; + } vlrsStk; + }; + + // VLT_STK_REG -- Partly enregistered TYP_LONG + // eg { LowerDWord=[ESP+0x8] UpperDWord=EAX } + + struct vlStkReg + { + struct + { + RegNum vlsrsBaseReg; + signed vlsrsOffset; + } vlsrStk; + RegNum vlsrReg; + }; + + // VLT_STK2 -- Any 64 bit value which is on the stack, + // in 2 successsive DWords. + // eg 2 DWords at [ESP+0x10] + + struct vlStk2 + { + RegNum vls2BaseReg; + signed vls2Offset; + }; + + // VLT_FPSTK -- enregisterd TYP_DOUBLE (on the FP stack) + // eg. ST(3). Actually it is ST("FPstkHeigth - vpFpStk") + + struct vlFPstk + { + unsigned vlfReg; + }; + + // VLT_FIXED_VA -- fixed argument of a varargs function. + // The argument location depends on the size of the variable + // arguments (...). Inspecting the VARARGS_HANDLE indicates the + // location of the first arg. This argument can then be accessed + // relative to the position of the first arg + + struct vlFixedVarArg + { + unsigned vlfvOffset; + }; + + // VLT_MEMORY + + struct vlMemory + { + void *rpValue; // pointer to the in-process + // location of the value. + }; + struct VarLoc { VarLocType vlType; union { - // VLT_REG/VLT_REG_FP -- Any pointer-sized enregistered value (TYP_INT, TYP_REF, etc) - // eg. EAX - // VLT_REG_BYREF -- the specified register contains the address of the variable - // eg. [EAX] - - struct - { - RegNum vlrReg; - } vlReg; - - // VLT_STK -- Any 32 bit value which is on the stack - // eg. [ESP+0x20], or [EBP-0x28] - // VLT_STK_BYREF -- the specified stack location contains the address of the variable - // eg. mov EAX, [ESP+0x20]; [EAX] - - struct - { - RegNum vlsBaseReg; - signed vlsOffset; - } vlStk; - - // VLT_REG_REG -- TYP_LONG with both DWords enregistred - // eg. RBM_EAXEDX - - struct - { - RegNum vlrrReg1; - RegNum vlrrReg2; - } vlRegReg; - - // VLT_REG_STK -- Partly enregistered TYP_LONG - // eg { LowerDWord=EAX UpperDWord=[ESP+0x8] } - - struct - { - RegNum vlrsReg; - struct - { - RegNum vlrssBaseReg; - signed vlrssOffset; - } vlrsStk; - } vlRegStk; - - // VLT_STK_REG -- Partly enregistered TYP_LONG - // eg { LowerDWord=[ESP+0x8] UpperDWord=EAX } - - struct - { - struct - { - RegNum vlsrsBaseReg; - signed vlsrsOffset; - } vlsrStk; - RegNum vlsrReg; - } vlStkReg; - - // VLT_STK2 -- Any 64 bit value which is on the stack, - // in 2 successsive DWords. - // eg 2 DWords at [ESP+0x10] - - struct - { - RegNum vls2BaseReg; - signed vls2Offset; - } vlStk2; - - // VLT_FPSTK -- enregisterd TYP_DOUBLE (on the FP stack) - // eg. ST(3). Actually it is ST("FPstkHeigth - vpFpStk") - - struct - { - unsigned vlfReg; - } vlFPstk; - - // VLT_FIXED_VA -- fixed argument of a varargs function. - // The argument location depends on the size of the variable - // arguments (...). Inspecting the VARARGS_HANDLE indicates the - // location of the first arg. This argument can then be accessed - // relative to the position of the first arg - - struct - { - unsigned vlfvOffset; - } vlFixedVarArg; - - // VLT_MEMORY - - struct - { - void *rpValue; // pointer to the in-process - // location of the value. - } vlMemory; + vlReg vlReg; + vlStk vlStk; + vlRegReg vlRegReg; + vlRegStk vlRegStk; + vlStkReg vlStkReg; + vlStk2 vlStk2; + vlFPstk vlFPstk; + vlFixedVarArg vlFixedVarArg; + vlMemory vlMemory; }; }; diff --git a/external/corert/src/JitInterface/src/ThunkGenerator/corinfo.h.REMOVED.git-id b/external/corert/src/JitInterface/src/ThunkGenerator/corinfo.h.REMOVED.git-id index 90413a9157..910a9620aa 100644 --- a/external/corert/src/JitInterface/src/ThunkGenerator/corinfo.h.REMOVED.git-id +++ b/external/corert/src/JitInterface/src/ThunkGenerator/corinfo.h.REMOVED.git-id @@ -1 +1 @@ -f3b509c5ad764568b7ac3c43714b64b8d6ee0f54 \ No newline at end of file +89cd95f758b06e9106e22b4c25e66c492b95185d \ No newline at end of file diff --git a/external/corert/src/JitInterface/src/ThunkGenerator/corjitflags.h b/external/corert/src/JitInterface/src/ThunkGenerator/corjitflags.h index da303b6a03..84fb42f083 100644 --- a/external/corert/src/JitInterface/src/ThunkGenerator/corjitflags.h +++ b/external/corert/src/JitInterface/src/ThunkGenerator/corjitflags.h @@ -120,7 +120,7 @@ public: CORJIT_FLAG_HAS_ARM64_LRCPC = 52, // ID_AA64ISAR1_EL1.LRCPC is 1 or better CORJIT_FLAG_HAS_ARM64_PMULL = 53, // ID_AA64ISAR0_EL1.AES is 2 or better CORJIT_FLAG_HAS_ARM64_SHA1 = 54, // ID_AA64ISAR0_EL1.SHA1 is 1 or better - CORJIT_FLAG_HAS_ARM64_SHA2 = 55, // ID_AA64ISAR0_EL1.SHA2 is 1 or better + CORJIT_FLAG_HAS_ARM64_SHA256 = 55, // ID_AA64ISAR0_EL1.SHA2 is 1 or better CORJIT_FLAG_HAS_ARM64_SHA512 = 56, // ID_AA64ISAR0_EL1.SHA2 is 2 or better CORJIT_FLAG_HAS_ARM64_SHA3 = 57, // ID_AA64ISAR0_EL1.SHA3 is 1 or better CORJIT_FLAG_HAS_ARM64_SIMD = 58, // ID_AA64PFR0_EL1.AdvSIMD is 0 or better diff --git a/external/corert/src/JitInterface/src/ThunkGenerator/corjithost.h b/external/corert/src/JitInterface/src/ThunkGenerator/corjithost.h index 8242fab2b8..b2ab80646b 100644 --- a/external/corert/src/JitInterface/src/ThunkGenerator/corjithost.h +++ b/external/corert/src/JitInterface/src/ThunkGenerator/corjithost.h @@ -15,15 +15,11 @@ class ICorJitHost { public: - // Allocate memory of the given size in bytes. All bytes of the returned block - // must be initialized to zero. If `usePageAllocator` is true, the implementation - // should use an allocator that deals in OS pages if one exists. - virtual void* allocateMemory(size_t size, bool usePageAllocator = false) = 0; + // Allocate memory of the given size in bytes. + virtual void* allocateMemory(size_t size) = 0; - // Frees memory previous obtained by a call to `ICorJitHost::allocateMemory`. The - // value of the `usePageAllocator` parameter must match the value that was - // provided to the call to used to allocate the memory. - virtual void freeMemory(void* block, bool usePageAllocator = false) = 0; + // Frees memory previous obtained by a call to `ICorJitHost::allocateMemory`. + virtual void freeMemory(void* block) = 0; // Return an integer config value for the given key, if any exists. virtual int getIntConfigValue( @@ -43,6 +39,20 @@ public: virtual void freeStringConfigValue( const wchar_t* value ) = 0; + + // Allocate memory slab of the given size in bytes. The host is expected to pool + // these for a good performance. + virtual void* allocateSlab(size_t size, size_t* pActualSize) + { + *pActualSize = size; + return allocateMemory(size); + } + + // Free memory slab of the given size in bytes. + virtual void freeSlab(void* slab, size_t actualSize) + { + freeMemory(slab); + } }; #endif diff --git a/external/corert/src/Native/Bootstrap/main.cpp b/external/corert/src/Native/Bootstrap/main.cpp index 43860640d4..f327d28c65 100644 --- a/external/corert/src/Native/Bootstrap/main.cpp +++ b/external/corert/src/Native/Bootstrap/main.cpp @@ -245,9 +245,12 @@ extern "C" void RhpUniversalTransition_DebugStepTailCall() { throw "RhpUniversalTransition_DebugStepTailCall"; } +extern "C" void ConstrainedCallSupport_GetStubs() +{ + throw "ConstrainedCallSupport_GetStubs"; +} -void* RtRHeaderWrapper(); - +extern "C" void* RtRHeaderWrapper(); #endif // CPPCODEGEN // This works around System.Private.Interop's references to Interop.Native. @@ -279,6 +282,8 @@ extern "C" bool RhRegisterOSModule(void * pModule, extern "C" void* PalGetModuleHandleFromPointer(void* pointer); +#endif // !CPPCODEGEN + extern "C" void GetRuntimeException(); extern "C" void FailFast(); extern "C" void AppendExceptionStackFrame(); @@ -299,8 +304,6 @@ static const pfn c_classlibFunctions[] = { nullptr, // &DebugFuncEvalAbortHelper, }; -#endif // !CPPCODEGEN - extern "C" void InitializeModules(void* osModule, void ** modules, int count, void ** pClasslibFunctions, int nClasslibFunctions); #ifndef CORERT_DLL @@ -341,10 +344,9 @@ static int InitializeRuntime() #ifndef CPPCODEGEN InitializeModules(osModule, __modules_a, (int)((__modules_z - __modules_a)), (void **)&c_classlibFunctions, _countof(c_classlibFunctions)); #elif defined _WASM_ - // WASMTODO: Figure out what to do here. This is a NativeCallable method in the runtime - // and we also would have to figure out what to pass for pModuleHeaders + InitializeModules(nullptr, (void**)RtRHeaderWrapper(), 1, nullptr, 0); #else // !CPPCODEGEN - InitializeModules(nullptr, (void**)RtRHeaderWrapper(), 2, nullptr, 0); + InitializeModules(nullptr, (void**)RtRHeaderWrapper(), 2, (void **)&c_classlibFunctions, _countof(c_classlibFunctions)); #endif // !CPPCODEGEN #ifdef CORERT_DLL diff --git a/external/corert/src/Native/CMakeLists.txt b/external/corert/src/Native/CMakeLists.txt index 219d689364..1a3622a0de 100644 --- a/external/corert/src/Native/CMakeLists.txt +++ b/external/corert/src/Native/CMakeLists.txt @@ -95,33 +95,26 @@ if (CLR_CMAKE_PLATFORM_UNIX) add_compile_options(-Wno-null-arithmetic) add_compile_options(-Wno-null-conversion) - if (CLR_CMAKE_PLATFORM_ARCH_AMD64 OR CLR_CMAKE_PLATFORM_ARCH_I386) + # Since 6 version, clang generates pragma-pack warnings, so disable it because we use pshpack[1..8].h/poppack.h + add_compile_options(-Wno-pragmas) + + if(CLR_CMAKE_PLATFORM_ARCH_AMD64 OR CLR_CMAKE_PLATFORM_ARCH_I386) # Allow 16 byte compare-exchange add_compile_options(-mcx16) endif() - if (CLR_CMAKE_PLATFORM_ARCH_ARM) - # Because we don't use CMAKE_C_COMPILER/CMAKE_CXX_COMPILER to use clang - # we have to set the triple by adding a compiler argument + if(CLR_CMAKE_PLATFORM_ARCH_ARM) + add_compile_options(-march=armv7-a) if(TOOLCHAIN STREQUAL arm-linux-gnueabi) - add_compile_options(-target armv7-linux-gnueabi) add_compile_options(-mfloat-abi=softfp) - else () - add_compile_options(-target armv7-linux-gnueabihf) - endif () + endif() add_compile_options(-mthumb) add_compile_options(-mfpu=vfpv3) endif() - if (CLR_CMAKE_PLATFORM_ARCH_ARM64) - # Because we don't use CMAKE_C_COMPILER/CMAKE_CXX_COMPILER to use clang - # we have to set the triple by adding a compiler argument - add_compile_options(-target aarch64-linux-gnu) - endif () - - if (CLR_CMAKE_PLATFORM_ARCH_AMD64) + if(CLR_CMAKE_PLATFORM_ARCH_AMD64) add_definitions(-DUNIX_AMD64_ABI) - elseif (CLR_CMAKE_PLATFORM_ARCH_I386) + elseif(CLR_CMAKE_PLATFORM_ARCH_I386) add_definitions(-DUNIX_X86_ABI) endif() @@ -228,7 +221,10 @@ if(NOT WIN32) add_subdirectory(System.Private.CoreLib.Native) endif(NOT WIN32) -# Build ObjWriter on Linux only -if(CMAKE_SYSTEM_NAME STREQUAL Linux AND OBJWRITER_BUILD) +if(NOT CLR_CMAKE_PLATFORM_WASM) + add_subdirectory(System.Private.TypeLoader.Native) +endif(NOT CLR_CMAKE_PLATFORM_WASM) + +if(OBJWRITER_BUILD) add_subdirectory(ObjWriter/llvmCap) endif() diff --git a/external/corert/src/Native/ObjWriter/.nuget/Microsoft.DotNet.ObjectWriter.nuspec b/external/corert/src/Native/ObjWriter/.nuget/Microsoft.DotNet.ObjectWriter.nuspec deleted file mode 100644 index f3421bb32a..0000000000 --- a/external/corert/src/Native/ObjWriter/.nuget/Microsoft.DotNet.ObjectWriter.nuspec +++ /dev/null @@ -1,20 +0,0 @@ - - - - Microsoft.DotNet.ObjectWriter - 1.0.19-prerelease-00001 - Microsoft .NET Object File Generator - Microsoft - Microsoft - http://go.microsoft.com/fwlink/?LinkId=329770 - https://github.com/dotnet/corert - http://go.microsoft.com/fwlink/?LinkID=288859 - true - Provides object writer to the managed to native code-generator. - Initial release - Copyright © Microsoft Corporation - - - - - diff --git a/external/corert/src/Native/ObjWriter/.nuget/runtime.json b/external/corert/src/Native/ObjWriter/.nuget/runtime.json deleted file mode 100644 index c9c5b8e6b1..0000000000 --- a/external/corert/src/Native/ObjWriter/.nuget/runtime.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "runtimes": { - "win7-x64": { - "Microsoft.DotNet.ObjectWriter": { - "toolchain.win7-x64.Microsoft.DotNet.ObjectWriter": "1.0.19-prerelease-00001" - } - }, - "ubuntu.14.04-x64": { - "Microsoft.DotNet.ObjectWriter": { - "toolchain.ubuntu.14.04-x64.Microsoft.DotNet.ObjectWriter": "1.0.19-prerelease-00001" - } - }, - "osx.10.10-x64": { - "Microsoft.DotNet.ObjectWriter": { - "toolchain.osx.10.10-x64.Microsoft.DotNet.ObjectWriter": "1.0.19-prerelease-00001" - } - } - } -} diff --git a/external/corert/src/Native/ObjWriter/.nuget/toolchain.osx.10.10-x64.Microsoft.DotNet.ObjectWriter.nuspec b/external/corert/src/Native/ObjWriter/.nuget/toolchain.osx.10.10-x64.Microsoft.DotNet.ObjectWriter.nuspec deleted file mode 100644 index 7a571beaf4..0000000000 --- a/external/corert/src/Native/ObjWriter/.nuget/toolchain.osx.10.10-x64.Microsoft.DotNet.ObjectWriter.nuspec +++ /dev/null @@ -1,20 +0,0 @@ - - - - toolchain.osx.10.10-x64.Microsoft.DotNet.ObjectWriter - 1.0.19-prerelease-00001 - Microsoft .NET Object File Generator - Microsoft - Microsoft - http://go.microsoft.com/fwlink/?LinkId=329770 - https://github.com/dotnet/corert - http://go.microsoft.com/fwlink/?LinkID=288859 - true - Provides object writer to the managed to native code-generator. - Initial release - Copyright © Microsoft Corporation - - - - - diff --git a/external/corert/src/Native/ObjWriter/.nuget/toolchain.ubuntu.14.04-x64.Microsoft.DotNet.ObjectWriter.nuspec b/external/corert/src/Native/ObjWriter/.nuget/toolchain.ubuntu.14.04-x64.Microsoft.DotNet.ObjectWriter.nuspec deleted file mode 100644 index fd9c514c65..0000000000 --- a/external/corert/src/Native/ObjWriter/.nuget/toolchain.ubuntu.14.04-x64.Microsoft.DotNet.ObjectWriter.nuspec +++ /dev/null @@ -1,20 +0,0 @@ - - - - toolchain.ubuntu.14.04-x64.Microsoft.DotNet.ObjectWriter - 1.0.19-prerelease-00001 - Microsoft .NET Object File Generator - Microsoft - Microsoft - http://go.microsoft.com/fwlink/?LinkId=329770 - https://github.com/dotnet/corert - http://go.microsoft.com/fwlink/?LinkID=288859 - true - Provides object writer to the managed to native code-generator. - Initial release - Copyright © Microsoft Corporation - - - - - diff --git a/external/corert/src/Native/ObjWriter/.nuget/toolchain.win7-x64.Microsoft.DotNet.ObjectWriter.nuspec b/external/corert/src/Native/ObjWriter/.nuget/toolchain.win7-x64.Microsoft.DotNet.ObjectWriter.nuspec deleted file mode 100644 index a54cdc2303..0000000000 --- a/external/corert/src/Native/ObjWriter/.nuget/toolchain.win7-x64.Microsoft.DotNet.ObjectWriter.nuspec +++ /dev/null @@ -1,20 +0,0 @@ - - - - toolchain.win7-x64.Microsoft.DotNet.ObjectWriter - 1.0.19-prerelease-00001 - Microsoft .NET Object File Generator - Microsoft - Microsoft - http://go.microsoft.com/fwlink/?LinkId=329770 - https://github.com/dotnet/corert - http://go.microsoft.com/fwlink/?LinkID=288859 - true - Provides object writer to the managed to native code-generator. - Initial release - Copyright © Microsoft Corporation - - - - - diff --git a/external/corert/src/Native/ObjWriter/CMakeLists.txt b/external/corert/src/Native/ObjWriter/CMakeLists.txt index fae4ddb12b..490a36701b 100644 --- a/external/corert/src/Native/ObjWriter/CMakeLists.txt +++ b/external/corert/src/Native/ObjWriter/CMakeLists.txt @@ -2,7 +2,15 @@ project(objwriter) set(CMAKE_BUILD_TYPE "${OBJWRITER_BUILD_TYPE}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OBJWRITER_C_FLAGS}") -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OBJWRITER_CXX_FLAGS} -std=c++11 -fno-rtti") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OBJWRITER_CXX_FLAGS}") + +if(WIN32) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHsc") +endif() + +if(NOT WIN32) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fno-rtti") +endif() message(STATUS "ObjWriter configuring with (${CMAKE_BUILD_TYPE}) build type and (${LLVM_DEFAULT_TARGET_TRIPLE}) default target triple") @@ -29,9 +37,16 @@ endif() add_library(objwriter SHARED objwriter.cpp - typeBuilder.cpp + debugInfo/codeView/codeViewTypeBuilder.cpp + debugInfo/codeView/codeViewTypeBuilder.h + debugInfo/dwarf/dwarfTypeBuilder.cpp + debugInfo/dwarf/dwarfTypeBuilder.h + debugInfo/dwarf/dwarfGen.cpp + debugInfo/dwarf/dwarfGen.h + debugInfo/dwarf/dwarfAbbrev.cpp + debugInfo/dwarf/dwarfAbbrev.h + debugInfo/typeBuilder.h objwriter.h # Visual Studio generator doesn't include necessary header files into the project automatically - typeBuilder.h ${OBJWRITER_EXPORTS_DEF} ) diff --git a/external/corert/src/Native/ObjWriter/cordebuginfo.h b/external/corert/src/Native/ObjWriter/cordebuginfo.h index 1ed430a11d..46d74c2e1c 100644 --- a/external/corert/src/Native/ObjWriter/cordebuginfo.h +++ b/external/corert/src/Native/ObjWriter/cordebuginfo.h @@ -195,104 +195,114 @@ public: VLT_INVALID, }; + // VLT_REG/VLT_REG_FP -- Any pointer-sized enregistered value (TYP_INT, TYP_REF, etc) + // eg. EAX + // VLT_REG_BYREF -- the specified register contains the address of the variable + // eg. [EAX] + + struct vlReg + { + RegNum vlrReg; + }; + + // VLT_STK -- Any 32 bit value which is on the stack + // eg. [ESP+0x20], or [EBP-0x28] + // VLT_STK_BYREF -- the specified stack location contains the address of the variable + // eg. mov EAX, [ESP+0x20]; [EAX] + + struct vlStk + { + RegNum vlsBaseReg; + signed vlsOffset; + }; + + // VLT_REG_REG -- TYP_LONG with both DWords enregistred + // eg. RBM_EAXEDX + + struct vlRegReg + { + RegNum vlrrReg1; + RegNum vlrrReg2; + }; + + // VLT_REG_STK -- Partly enregistered TYP_LONG + // eg { LowerDWord=EAX UpperDWord=[ESP+0x8] } + + struct vlRegStk + { + RegNum vlrsReg; + struct + { + RegNum vlrssBaseReg; + signed vlrssOffset; + } vlrsStk; + }; + + // VLT_STK_REG -- Partly enregistered TYP_LONG + // eg { LowerDWord=[ESP+0x8] UpperDWord=EAX } + + struct vlStkReg + { + struct + { + RegNum vlsrsBaseReg; + signed vlsrsOffset; + } vlsrStk; + RegNum vlsrReg; + }; + + // VLT_STK2 -- Any 64 bit value which is on the stack, + // in 2 successsive DWords. + // eg 2 DWords at [ESP+0x10] + + struct vlStk2 + { + RegNum vls2BaseReg; + signed vls2Offset; + }; + + // VLT_FPSTK -- enregisterd TYP_DOUBLE (on the FP stack) + // eg. ST(3). Actually it is ST("FPstkHeigth - vpFpStk") + + struct vlFPstk + { + unsigned vlfReg; + }; + + // VLT_FIXED_VA -- fixed argument of a varargs function. + // The argument location depends on the size of the variable + // arguments (...). Inspecting the VARARGS_HANDLE indicates the + // location of the first arg. This argument can then be accessed + // relative to the position of the first arg + + struct vlFixedVarArg + { + unsigned vlfvOffset; + }; + + // VLT_MEMORY + + struct vlMemory + { + void *rpValue; // pointer to the in-process + // location of the value. + }; + struct VarLoc { VarLocType vlType; union { - // VLT_REG/VLT_REG_FP -- Any pointer-sized enregistered value (TYP_INT, TYP_REF, etc) - // eg. EAX - // VLT_REG_BYREF -- the specified register contains the address of the variable - // eg. [EAX] - - struct - { - RegNum vlrReg; - } vlReg; - - // VLT_STK -- Any 32 bit value which is on the stack - // eg. [ESP+0x20], or [EBP-0x28] - // VLT_STK_BYREF -- the specified stack location contains the address of the variable - // eg. mov EAX, [ESP+0x20]; [EAX] - - struct - { - RegNum vlsBaseReg; - signed vlsOffset; - } vlStk; - - // VLT_REG_REG -- TYP_LONG with both DWords enregistred - // eg. RBM_EAXEDX - - struct - { - RegNum vlrrReg1; - RegNum vlrrReg2; - } vlRegReg; - - // VLT_REG_STK -- Partly enregistered TYP_LONG - // eg { LowerDWord=EAX UpperDWord=[ESP+0x8] } - - struct - { - RegNum vlrsReg; - struct - { - RegNum vlrssBaseReg; - signed vlrssOffset; - } vlrsStk; - } vlRegStk; - - // VLT_STK_REG -- Partly enregistered TYP_LONG - // eg { LowerDWord=[ESP+0x8] UpperDWord=EAX } - - struct - { - struct - { - RegNum vlsrsBaseReg; - signed vlsrsOffset; - } vlsrStk; - RegNum vlsrReg; - } vlStkReg; - - // VLT_STK2 -- Any 64 bit value which is on the stack, - // in 2 successsive DWords. - // eg 2 DWords at [ESP+0x10] - - struct - { - RegNum vls2BaseReg; - signed vls2Offset; - } vlStk2; - - // VLT_FPSTK -- enregisterd TYP_DOUBLE (on the FP stack) - // eg. ST(3). Actually it is ST("FPstkHeigth - vpFpStk") - - struct - { - unsigned vlfReg; - } vlFPstk; - - // VLT_FIXED_VA -- fixed argument of a varargs function. - // The argument location depends on the size of the variable - // arguments (...). Inspecting the VARARGS_HANDLE indicates the - // location of the first arg. This argument can then be accessed - // relative to the position of the first arg - - struct - { - unsigned vlfvOffset; - } vlFixedVarArg; - - // VLT_MEMORY - - struct - { - void *rpValue; // pointer to the in-process - // location of the value. - } vlMemory; + ICorDebugInfo::vlReg vlReg; + ICorDebugInfo::vlStk vlStk; + ICorDebugInfo::vlRegReg vlRegReg; + ICorDebugInfo::vlRegStk vlRegStk; + ICorDebugInfo::vlStkReg vlStkReg; + ICorDebugInfo::vlStk2 vlStk2; + ICorDebugInfo::vlFPstk vlFPstk; + ICorDebugInfo::vlFixedVarArg vlFixedVarArg; + ICorDebugInfo::vlMemory vlMemory; }; }; diff --git a/external/corert/src/Native/ObjWriter/cvconst.h b/external/corert/src/Native/ObjWriter/cvconst.h index 5c4f2569e2..92c5bb4e78 100644 --- a/external/corert/src/Native/ObjWriter/cvconst.h +++ b/external/corert/src/Native/ObjWriter/cvconst.h @@ -1,18 +1,6 @@ -/////////////////////////////////////////////////////////////////////////////// -// -// Copyright (c) 2015 Microsoft Corporation. All rights reserved. -// -// This code is licensed under the MIT License (MIT). -// -// 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. -// -/////////////////////////////////////////////////////////////////////////////// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. // cvconst.h - codeview constant definitions //----------------------------------------------------------------- diff --git a/external/corert/src/Native/ObjWriter/typeBuilder.cpp b/external/corert/src/Native/ObjWriter/debugInfo/codeView/codeViewTypeBuilder.cpp similarity index 74% rename from external/corert/src/Native/ObjWriter/typeBuilder.cpp rename to external/corert/src/Native/ObjWriter/debugInfo/codeView/codeViewTypeBuilder.cpp index 2b6edacc5a..d3af316ca3 100644 --- a/external/corert/src/Native/ObjWriter/typeBuilder.cpp +++ b/external/corert/src/Native/ObjWriter/debugInfo/codeView/codeViewTypeBuilder.cpp @@ -1,55 +1,43 @@ -//===---- typeBuilder.cpp --------------------------------*- C++ -*-===// +//===---- codeViewTypeBuilder.cpp -------------------------------*- C++ -*-===// // // type builder implementation using codeview::TypeTableBuilder // -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. -// See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. // //===----------------------------------------------------------------------===// -#include "typeBuilder.h" +#include "codeViewTypeBuilder.h" #include "llvm/BinaryFormat/COFF.h" #include #include -UserDefinedTypesBuilder::UserDefinedTypesBuilder() - : Allocator(), TypeTable(Allocator), Streamer(nullptr), - TargetPointerSize(0) +UserDefinedCodeViewTypesBuilder::UserDefinedCodeViewTypesBuilder() + : Allocator(), TypeTable(Allocator) { VFTableShapeRecord vfTableShape(TypeRecordKind::VFTableShape); ClassVTableTypeIndex = TypeTable.writeKnownType(vfTableShape); } -void UserDefinedTypesBuilder::SetStreamer(MCObjectStreamer *Streamer) { - assert(this->Streamer == nullptr); - assert(Streamer != nullptr); - this->Streamer = Streamer; -} - -void UserDefinedTypesBuilder::SetTargetPointerSize(unsigned TargetPointerSize) { - assert(this->TargetPointerSize == 0); - assert(TargetPointerSize != 0); - this->TargetPointerSize = TargetPointerSize; -} - -void UserDefinedTypesBuilder::EmitCodeViewMagicVersion() { +void UserDefinedCodeViewTypesBuilder::EmitCodeViewMagicVersion() { Streamer->EmitValueToAlignment(4); Streamer->AddComment("Debug section magic"); Streamer->EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4); } -ClassOptions UserDefinedTypesBuilder::GetCommonClassOptions() { +ClassOptions UserDefinedCodeViewTypesBuilder::GetCommonClassOptions() { return ClassOptions(); } -void UserDefinedTypesBuilder::EmitTypeInformation( - MCSection *COFFDebugTypesSection) { +void UserDefinedCodeViewTypesBuilder::EmitTypeInformation( + MCSection *TypeSection, + MCSection *StrSection) { if (TypeTable.empty()) return; - Streamer->SwitchSection(COFFDebugTypesSection); + Streamer->SwitchSection(TypeSection); EmitCodeViewMagicVersion(); TypeTable.ForEachRecord([&](TypeIndex FieldTypeIndex, @@ -59,7 +47,7 @@ void UserDefinedTypesBuilder::EmitTypeInformation( }); } -unsigned UserDefinedTypesBuilder::GetEnumFieldListType( +unsigned UserDefinedCodeViewTypesBuilder::GetEnumFieldListType( uint64 Count, const EnumRecordTypeDescriptor *TypeRecords) { FieldListRecordBuilder FLRB(TypeTable); FLRB.begin(); @@ -77,7 +65,7 @@ unsigned UserDefinedTypesBuilder::GetEnumFieldListType( return Type.getIndex(); } -unsigned UserDefinedTypesBuilder::GetEnumTypeIndex( +unsigned UserDefinedCodeViewTypesBuilder::GetEnumTypeIndex( const EnumTypeDescriptor &TypeDescriptor, const EnumRecordTypeDescriptor *TypeRecords) { @@ -92,11 +80,11 @@ unsigned UserDefinedTypesBuilder::GetEnumTypeIndex( ElementTypeIndex); TypeIndex Type = TypeTable.writeKnownType(EnumRecord); - UserDefinedTypes.push_back(std::make_pair(TypeDescriptor.Name, Type)); + UserDefinedTypes.push_back(std::make_pair(TypeDescriptor.Name, Type.getIndex())); return Type.getIndex(); } -unsigned UserDefinedTypesBuilder::GetClassTypeIndex( +unsigned UserDefinedCodeViewTypesBuilder::GetClassTypeIndex( const ClassTypeDescriptor &ClassDescriptor) { TypeRecordKind Kind = ClassDescriptor.IsStruct ? TypeRecordKind::Struct : TypeRecordKind::Class; @@ -119,10 +107,11 @@ unsigned UserDefinedTypesBuilder::GetClassTypeIndex( return FwdDeclTI.getIndex(); } -unsigned UserDefinedTypesBuilder::GetCompleteClassTypeIndex( +unsigned UserDefinedCodeViewTypesBuilder::GetCompleteClassTypeIndex( const ClassTypeDescriptor &ClassDescriptor, const ClassFieldsTypeDescriptior &ClassFieldsDescriptor, - const DataFieldDescriptor *FieldsDescriptors) { + const DataFieldDescriptor *FieldsDescriptors, + const StaticDataFieldDescriptor *StaticsDescriptors) { FieldListRecordBuilder FLBR(TypeTable); FLBR.begin(); @@ -165,12 +154,12 @@ unsigned UserDefinedTypesBuilder::GetCompleteClassTypeIndex( ClassDescriptor.Name, StringRef()); TypeIndex ClassIndex = TypeTable.writeKnownType(CR); - UserDefinedTypes.push_back(std::make_pair(ClassDescriptor.Name, ClassIndex)); + UserDefinedTypes.push_back(std::make_pair(ClassDescriptor.Name, ClassIndex.getIndex())); return ClassIndex.getIndex(); } -unsigned UserDefinedTypesBuilder::GetArrayTypeIndex( +unsigned UserDefinedCodeViewTypesBuilder::GetArrayTypeIndex( const ClassTypeDescriptor &ClassDescriptor, const ArrayTypeDescriptor &ArrayDescriptor) { FieldListRecordBuilder FLBR(TypeTable); @@ -229,12 +218,12 @@ unsigned UserDefinedTypesBuilder::GetArrayTypeIndex( StringRef()); TypeIndex ClassIndex = TypeTable.writeKnownType(CR); - UserDefinedTypes.push_back(std::make_pair(ClassDescriptor.Name, ClassIndex)); + UserDefinedTypes.push_back(std::make_pair(ClassDescriptor.Name, ClassIndex.getIndex())); return ClassIndex.getIndex(); } -unsigned UserDefinedTypesBuilder::GetPointerTypeIndex(const PointerTypeDescriptor& PointerDescriptor) +unsigned UserDefinedCodeViewTypesBuilder::GetPointerTypeIndex(const PointerTypeDescriptor& PointerDescriptor) { uint32_t elementType = PointerDescriptor.ElementType; PointerKind pointerKind = PointerDescriptor.Is64Bit ? PointerKind::Near64 : PointerKind::Near32; @@ -246,7 +235,7 @@ unsigned UserDefinedTypesBuilder::GetPointerTypeIndex(const PointerTypeDescripto return PointerIndex.getIndex(); } -unsigned UserDefinedTypesBuilder::GetMemberFunctionTypeIndex(const MemberFunctionTypeDescriptor& MemberDescriptor, +unsigned UserDefinedCodeViewTypesBuilder::GetMemberFunctionTypeIndex(const MemberFunctionTypeDescriptor& MemberDescriptor, uint32_t const *const ArgumentTypes) { std::vector argumentTypes; @@ -271,14 +260,52 @@ unsigned UserDefinedTypesBuilder::GetMemberFunctionTypeIndex(const MemberFunctio return MemberFunctionIndex.getIndex(); } -unsigned UserDefinedTypesBuilder::GetMemberFunctionId(const MemberFunctionIdTypeDescriptor& MemberIdDescriptor) +unsigned UserDefinedCodeViewTypesBuilder::GetMemberFunctionId(const MemberFunctionIdTypeDescriptor& MemberIdDescriptor) { MemberFuncIdRecord MemberFuncId(TypeIndex(MemberIdDescriptor.MemberFunction), TypeIndex(MemberIdDescriptor.ParentClass), MemberIdDescriptor.Name); TypeIndex MemberFuncIdIndex = TypeTable.writeKnownType(MemberFuncId); return MemberFuncIdIndex.getIndex(); } -void UserDefinedTypesBuilder::AddBaseClass(FieldListRecordBuilder &FLBR, +unsigned UserDefinedCodeViewTypesBuilder::GetPrimitiveTypeIndex(PrimitiveTypeFlags Type) { + switch (Type) { + case PrimitiveTypeFlags::Void: + return TypeIndex::Void().getIndex(); + case PrimitiveTypeFlags::Boolean: + return TypeIndex(SimpleTypeKind::Boolean8).getIndex(); + case PrimitiveTypeFlags::Char: + return TypeIndex::WideCharacter().getIndex(); + case PrimitiveTypeFlags::SByte: + return TypeIndex(SimpleTypeKind::SByte).getIndex(); + case PrimitiveTypeFlags::Byte: + return TypeIndex(SimpleTypeKind::Byte).getIndex(); + case PrimitiveTypeFlags::Int16: + return TypeIndex(SimpleTypeKind::Int16).getIndex(); + case PrimitiveTypeFlags::UInt16: + return TypeIndex(SimpleTypeKind::UInt16).getIndex(); + case PrimitiveTypeFlags::Int32: + return TypeIndex::Int32().getIndex(); + case PrimitiveTypeFlags::UInt32: + return TypeIndex::UInt32().getIndex(); + case PrimitiveTypeFlags::Int64: + return TypeIndex::Int64().getIndex(); + case PrimitiveTypeFlags::UInt64: + return TypeIndex::UInt64().getIndex(); + case PrimitiveTypeFlags::Single: + return TypeIndex::Float32().getIndex(); + case PrimitiveTypeFlags::Double: + return TypeIndex::Float64().getIndex(); + case PrimitiveTypeFlags::IntPtr: + case PrimitiveTypeFlags::UIntPtr: + return TargetPointerSize == 4 ? TypeIndex::VoidPointer32().getIndex() : + TypeIndex::VoidPointer64().getIndex(); + default: + assert(false && "Unexpected type"); + return 0; + } +} + +void UserDefinedCodeViewTypesBuilder::AddBaseClass(FieldListRecordBuilder &FLBR, unsigned BaseClassId) { MemberAttributes def; TypeIndex BaseTypeIndex(BaseClassId); @@ -286,7 +313,7 @@ void UserDefinedTypesBuilder::AddBaseClass(FieldListRecordBuilder &FLBR, FLBR.writeMemberType(BCR); } -void UserDefinedTypesBuilder::AddClassVTShape(FieldListRecordBuilder &FLBR) { +void UserDefinedCodeViewTypesBuilder::AddClassVTShape(FieldListRecordBuilder &FLBR) { VFPtrRecord VfPtr(ClassVTableTypeIndex); FLBR.writeMemberType(VfPtr); } diff --git a/external/corert/src/Native/ObjWriter/debugInfo/codeView/codeViewTypeBuilder.h b/external/corert/src/Native/ObjWriter/debugInfo/codeView/codeViewTypeBuilder.h new file mode 100644 index 0000000000..5534cc7d37 --- /dev/null +++ b/external/corert/src/Native/ObjWriter/debugInfo/codeView/codeViewTypeBuilder.h @@ -0,0 +1,73 @@ +//===---- codeViewTypeBuilder.h ---------------------------------*- C++ -*-===// +// +// type builder is used to convert .Net types into CodeView descriptors. +// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "debugInfo/typeBuilder.h" +#include "llvm/DebugInfo/CodeView/TypeTableBuilder.h" + +#include + +using namespace llvm::codeview; + +class ArrayDimensionsDescriptor { +public: + const char *GetLengthName(unsigned index); + const char *GetBoundsName(unsigned index); + +private: + void Resize(unsigned NewSize); + + std::vector Lengths; + std::vector Bounds; +}; + +class UserDefinedCodeViewTypesBuilder : public UserDefinedTypesBuilder { +public: + UserDefinedCodeViewTypesBuilder(); + void EmitTypeInformation(MCSection *TypeSection, MCSection *StrSection = nullptr) override; + + unsigned GetEnumTypeIndex(const EnumTypeDescriptor &TypeDescriptor, + const EnumRecordTypeDescriptor *TypeRecords) override; + unsigned GetClassTypeIndex(const ClassTypeDescriptor &ClassDescriptor) override; + unsigned GetCompleteClassTypeIndex( + const ClassTypeDescriptor &ClassDescriptor, + const ClassFieldsTypeDescriptior &ClassFieldsDescriptor, + const DataFieldDescriptor *FieldsDescriptors, + const StaticDataFieldDescriptor *StaticsDescriptors) override; + + unsigned GetArrayTypeIndex(const ClassTypeDescriptor &ClassDescriptor, + const ArrayTypeDescriptor &ArrayDescriptor) override; + + unsigned GetPointerTypeIndex(const PointerTypeDescriptor& PointerDescriptor) override; + + unsigned GetMemberFunctionTypeIndex(const MemberFunctionTypeDescriptor& MemberDescriptor, + uint32_t const *const ArgumentTypes) override; + + unsigned GetMemberFunctionId(const MemberFunctionIdTypeDescriptor& MemberIdDescriptor) override; + + unsigned GetPrimitiveTypeIndex(PrimitiveTypeFlags Type) override; + +private: + void EmitCodeViewMagicVersion(); + ClassOptions GetCommonClassOptions(); + + unsigned GetEnumFieldListType(uint64 Count, + const EnumRecordTypeDescriptor *TypeRecords); + + void AddBaseClass(FieldListRecordBuilder &FLBR, unsigned BaseClassId); + void AddClassVTShape(FieldListRecordBuilder &FLBR); + + BumpPtrAllocator Allocator; + TypeTableBuilder TypeTable; + + ArrayDimensionsDescriptor ArrayDimentions; + TypeIndex ClassVTableTypeIndex; +}; \ No newline at end of file diff --git a/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfAbbrev.cpp b/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfAbbrev.cpp new file mode 100644 index 0000000000..23ee3fa308 --- /dev/null +++ b/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfAbbrev.cpp @@ -0,0 +1,284 @@ +//===---- dwarfAbbrev.cpp ---------------------------------------*- C++ -*-===// +// +// dwarf abbreviations implementation +// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +// +//===----------------------------------------------------------------------===// + +#include "dwarfAbbrev.h" +#include "llvm/MC/MCContext.h" +#include "llvm/MC/MCObjectFileInfo.h" + +namespace DwarfAbbrev { + +void Dump(MCObjectStreamer *Streamer, uint16_t DwarfVersion, unsigned TargetPointerSize) { + uint16_t DW_FORM_size; + switch (TargetPointerSize) { + case 1: + DW_FORM_size = dwarf::DW_FORM_data1; + break; + case 2: + DW_FORM_size = dwarf::DW_FORM_data2; + break; + case 4: + DW_FORM_size = dwarf::DW_FORM_data4; + break; + case 8: + DW_FORM_size = dwarf::DW_FORM_data8; + break; + default: + assert(false && "Unexpected TargerPointerSize"); + return; + } + + const uint16_t AbbrevTable[] = { + CompileUnit, + dwarf::DW_TAG_compile_unit, dwarf::DW_CHILDREN_yes, + dwarf::DW_AT_producer, dwarf::DW_FORM_string, + dwarf::DW_AT_language, dwarf::DW_FORM_data2, + dwarf::DW_AT_stmt_list, (DwarfVersion >= 4 ? dwarf::DW_FORM_sec_offset : dwarf::DW_FORM_data4), + 0, 0, + + BaseType, + dwarf::DW_TAG_base_type, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, + dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, + 0, 0, + + EnumerationType, + dwarf::DW_TAG_enumeration_type, dwarf::DW_CHILDREN_yes, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, + 0, 0, + + Enumerator1, + dwarf::DW_TAG_enumerator, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_const_value, dwarf::DW_FORM_data1, + 0, 0, + + Enumerator2, + dwarf::DW_TAG_enumerator, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_const_value, dwarf::DW_FORM_data2, + 0, 0, + + Enumerator4, + dwarf::DW_TAG_enumerator, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_const_value, dwarf::DW_FORM_data4, + 0, 0, + + Enumerator8, + dwarf::DW_TAG_enumerator, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_const_value, dwarf::DW_FORM_data8, + 0, 0, + + TypeDef, + dwarf::DW_TAG_typedef, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + 0, 0, + + Subprogram, + dwarf::DW_TAG_subprogram, dwarf::DW_CHILDREN_yes, + dwarf::DW_AT_specification, dwarf::DW_FORM_ref4, + dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, + dwarf::DW_AT_high_pc, DW_FORM_size, + dwarf::DW_AT_frame_base, dwarf::DW_FORM_exprloc, + dwarf::DW_AT_object_pointer, dwarf::DW_FORM_ref4, + 0, 0, + + SubprogramStatic, + dwarf::DW_TAG_subprogram, dwarf::DW_CHILDREN_yes, + dwarf::DW_AT_specification, dwarf::DW_FORM_ref4, + dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, + dwarf::DW_AT_high_pc, DW_FORM_size, + dwarf::DW_AT_frame_base, dwarf::DW_FORM_exprloc, + 0, 0, + + SubprogramSpec, + dwarf::DW_TAG_subprogram, dwarf::DW_CHILDREN_yes, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_linkage_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, + dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_external, dwarf::DW_FORM_flag_present, + dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, + dwarf::DW_AT_object_pointer, dwarf::DW_FORM_ref4, + 0, 0, + + SubprogramStaticSpec, + dwarf::DW_TAG_subprogram, dwarf::DW_CHILDREN_yes, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_linkage_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, + dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_external, dwarf::DW_FORM_flag_present, + dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, + 0, 0, + + Variable, + dwarf::DW_TAG_variable, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, + dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_location, dwarf::DW_FORM_exprloc, + 0, 0, + + VariableLoc, + dwarf::DW_TAG_variable, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, + dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_location, dwarf::DW_FORM_sec_offset, + 0, 0, + + VariableStatic, + dwarf::DW_TAG_variable, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_specification, dwarf::DW_FORM_ref4, + dwarf::DW_AT_location, dwarf::DW_FORM_exprloc, + 0, 0, + + FormalParameter, + dwarf::DW_TAG_formal_parameter, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, + dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_location, dwarf::DW_FORM_exprloc, + 0, 0, + + FormalParameterThis, + dwarf::DW_TAG_formal_parameter, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, + dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_location, dwarf::DW_FORM_exprloc, + dwarf::DW_AT_artificial, dwarf::DW_FORM_flag_present, + 0, 0, + + FormalParameterLoc, + dwarf::DW_TAG_formal_parameter, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, + dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_location, dwarf::DW_FORM_sec_offset, + 0, 0, + + FormalParameterThisLoc, + dwarf::DW_TAG_formal_parameter, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, + dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_location, dwarf::DW_FORM_sec_offset, + dwarf::DW_AT_artificial, dwarf::DW_FORM_flag_present, + 0, 0, + + FormalParameterSpec, + dwarf::DW_TAG_formal_parameter, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + 0, 0, + + FormalParameterThisSpec, + dwarf::DW_TAG_formal_parameter, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_artificial, dwarf::DW_FORM_flag_present, + 0, 0, + + ClassType, + dwarf::DW_TAG_class_type, dwarf::DW_CHILDREN_yes, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_byte_size, dwarf::DW_FORM_data4, + 0, 0, + + ClassTypeDecl, + dwarf::DW_TAG_class_type, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, + 0, 0, + + ClassMember, + dwarf::DW_TAG_member, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data4, + 0, 0, + + ClassMemberStatic, + dwarf::DW_TAG_member, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_name, dwarf::DW_FORM_strp, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_external, dwarf::DW_FORM_flag_present, + dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, + 0, 0, + + PointerType, + dwarf::DW_TAG_pointer_type, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, + 0, 0, + + ReferenceType, + dwarf::DW_TAG_reference_type, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, + 0, 0, + + ArrayType, + dwarf::DW_TAG_array_type, dwarf::DW_CHILDREN_yes, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + 0, 0, + + SubrangeType, + dwarf::DW_TAG_subrange_type, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_upper_bound, dwarf::DW_FORM_udata, + 0, 0, + + ClassInheritance, + dwarf::DW_TAG_inheritance, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_type, dwarf::DW_FORM_ref4, + dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, + 0, 0, + + LexicalBlock, + dwarf::DW_TAG_lexical_block, dwarf::DW_CHILDREN_yes, + dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, + dwarf::DW_AT_high_pc, DW_FORM_size, + 0, 0, + + TryBlock, + dwarf::DW_TAG_try_block, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, + dwarf::DW_AT_high_pc, DW_FORM_size, + 0, 0, + + CatchBlock, + dwarf::DW_TAG_catch_block, dwarf::DW_CHILDREN_no, + dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, + dwarf::DW_AT_high_pc, DW_FORM_size, + 0, 0 + }; + + MCContext &context = Streamer->getContext(); + Streamer->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); + + for (uint16_t e : AbbrevTable) { + Streamer->EmitULEB128IntValue(e); + } +} + +} \ No newline at end of file diff --git a/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfAbbrev.h b/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfAbbrev.h new file mode 100644 index 0000000000..82589c0273 --- /dev/null +++ b/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfAbbrev.h @@ -0,0 +1,59 @@ +//===---- dwarfAbbrev.h -----------------------------------------*- C++ -*-===// +// +// dwarf abbreviations +// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "llvm/BinaryFormat/Dwarf.h" +#include "llvm/MC/MCObjectStreamer.h" + +using namespace llvm; + +namespace DwarfAbbrev { + +enum DwarfAbbrev : uint16_t +{ + CompileUnit = 0x1, + BaseType, + EnumerationType, + Enumerator1, + Enumerator2, + Enumerator4, + Enumerator8, + TypeDef, + Subprogram, + SubprogramStatic, + SubprogramSpec, + SubprogramStaticSpec, + Variable, + VariableLoc, + VariableStatic, + FormalParameter, + FormalParameterThis, + FormalParameterLoc, + FormalParameterThisLoc, + FormalParameterSpec, + FormalParameterThisSpec, + ClassType, + ClassTypeDecl, + ClassMember, + ClassMemberStatic, + PointerType, + ReferenceType, + ArrayType, + SubrangeType, + ClassInheritance, + LexicalBlock, + TryBlock, + CatchBlock +}; + +void Dump(MCObjectStreamer *Streamer, uint16_t DwarfVersion, unsigned TargetPointerSize); + +} diff --git a/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfGen.cpp b/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfGen.cpp new file mode 100644 index 0000000000..5186086736 --- /dev/null +++ b/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfGen.cpp @@ -0,0 +1,1066 @@ +//===---- dwarfGen.cpp ------------------------------------------*- C++ -*-===// +// +// dwarf generator implementation +// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +// +//===----------------------------------------------------------------------===// + +#include "dwarfGen.h" +#include "dwarfAbbrev.h" + +#include "llvm/MC/MCContext.h" +#include "llvm/MC/MCAsmInfo.h" +#include "llvm/MC/MCObjectFileInfo.h" +#include "llvm/Support/LEB128.h" + +#ifdef FEATURE_LANGID_CS +#define DW_LANG_MICROSOFT_CSHARP 0x9e57 +#endif + +// Keep sync with ICorDebugInfo::RegNum (cordebuginfo.h) + +enum class RegNumX86 +{ + REGNUM_EAX, + REGNUM_ECX, + REGNUM_EDX, + REGNUM_EBX, + REGNUM_ESP, + REGNUM_EBP, + REGNUM_ESI, + REGNUM_EDI, + REGNUM_COUNT, + REGNUM_FP = REGNUM_EBP, + REGNUM_SP = REGNUM_ESP +}; + +enum class RegNumArm +{ + REGNUM_R0, + REGNUM_R1, + REGNUM_R2, + REGNUM_R3, + REGNUM_R4, + REGNUM_R5, + REGNUM_R6, + REGNUM_R7, + REGNUM_R8, + REGNUM_R9, + REGNUM_R10, + REGNUM_R11, + REGNUM_R12, + REGNUM_SP, + REGNUM_LR, + REGNUM_PC, + REGNUM_COUNT, + REGNUM_FP = REGNUM_R7 +}; + +enum class RegNumArm64 +{ + REGNUM_X0, + REGNUM_X1, + REGNUM_X2, + REGNUM_X3, + REGNUM_X4, + REGNUM_X5, + REGNUM_X6, + REGNUM_X7, + REGNUM_X8, + REGNUM_X9, + REGNUM_X10, + REGNUM_X11, + REGNUM_X12, + REGNUM_X13, + REGNUM_X14, + REGNUM_X15, + REGNUM_X16, + REGNUM_X17, + REGNUM_X18, + REGNUM_X19, + REGNUM_X20, + REGNUM_X21, + REGNUM_X22, + REGNUM_X23, + REGNUM_X24, + REGNUM_X25, + REGNUM_X26, + REGNUM_X27, + REGNUM_X28, + REGNUM_FP, + REGNUM_LR, + REGNUM_SP, + REGNUM_PC, + REGNUM_COUNT +}; + +enum class RegNumAmd64 +{ + REGNUM_RAX, + REGNUM_RCX, + REGNUM_RDX, + REGNUM_RBX, + REGNUM_RSP, + REGNUM_RBP, + REGNUM_RSI, + REGNUM_RDI, + REGNUM_R8, + REGNUM_R9, + REGNUM_R10, + REGNUM_R11, + REGNUM_R12, + REGNUM_R13, + REGNUM_R14, + REGNUM_R15, + REGNUM_COUNT, + REGNUM_SP = REGNUM_RSP, + REGNUM_FP = REGNUM_RBP +}; + +// Helper routines from lib/MC/MCDwarf.cpp +static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) { + MCContext &Context = OS.getContext(); + assert(!isa(Expr)); + if (Context.getAsmInfo()->hasAggressiveSymbolFolding()) + return Expr; + + MCSymbol *ABS = Context.createTempSymbol(); + OS.EmitAssignment(ABS, Expr); + return MCSymbolRefExpr::create(ABS, Context); +} + +static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) { + const MCExpr *ABS = forceExpAbs(OS, Value); + OS.EmitValue(ABS, Size); +} + +static const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS, + const MCSymbol &Start, + const MCSymbol &End, + int IntVal) { + MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; + const MCExpr *Res = + MCSymbolRefExpr::create(&End, Variant, MCOS.getContext()); + const MCExpr *RHS = + MCSymbolRefExpr::create(&Start, Variant, MCOS.getContext()); + const MCExpr *Res1 = + MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext()); + const MCExpr *Res2 = + MCConstantExpr::create(IntVal, MCOS.getContext()); + const MCExpr *Res3 = + MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext()); + return Res3; +} + +static int GetDwarfRegNum(Triple::ArchType ArchType, int RegNum) { + switch (ArchType) { + case Triple::x86: + switch (static_cast(RegNum)) { + case RegNumX86::REGNUM_EAX: return 0; + case RegNumX86::REGNUM_ECX: return 1; + case RegNumX86::REGNUM_EDX: return 2; + case RegNumX86::REGNUM_EBX: return 3; + case RegNumX86::REGNUM_ESP: return 4; + case RegNumX86::REGNUM_EBP: return 5; + case RegNumX86::REGNUM_ESI: return 6; + case RegNumX86::REGNUM_EDI: return 7; + // fp registers + default: + return RegNum - static_cast(RegNumX86::REGNUM_COUNT) + 32; + } + case Triple::arm: // fall through + case Triple::armeb: // fall through + case Triple::thumb: // fall through + case Triple::thumbeb: + switch (static_cast(RegNum)) { + case RegNumArm::REGNUM_R0: return 0; + case RegNumArm::REGNUM_R1: return 1; + case RegNumArm::REGNUM_R2: return 2; + case RegNumArm::REGNUM_R3: return 3; + case RegNumArm::REGNUM_R4: return 4; + case RegNumArm::REGNUM_R5: return 5; + case RegNumArm::REGNUM_R6: return 6; + case RegNumArm::REGNUM_R7: return 7; + case RegNumArm::REGNUM_R8: return 8; + case RegNumArm::REGNUM_R9: return 9; + case RegNumArm::REGNUM_R10: return 10; + case RegNumArm::REGNUM_R11: return 11; + case RegNumArm::REGNUM_R12: return 12; + case RegNumArm::REGNUM_SP: return 13; + case RegNumArm::REGNUM_LR: return 14; + case RegNumArm::REGNUM_PC: return 15; + // fp registers + default: + return RegNum - static_cast(RegNumArm::REGNUM_COUNT) + 64; + } + case Triple::aarch64: // fall through + case Triple::aarch64_be: + switch (static_cast(RegNum)) { + case RegNumArm64::REGNUM_X0: return 0; + case RegNumArm64::REGNUM_X1: return 1; + case RegNumArm64::REGNUM_X2: return 2; + case RegNumArm64::REGNUM_X3: return 3; + case RegNumArm64::REGNUM_X4: return 4; + case RegNumArm64::REGNUM_X5: return 5; + case RegNumArm64::REGNUM_X6: return 6; + case RegNumArm64::REGNUM_X7: return 7; + case RegNumArm64::REGNUM_X8: return 8; + case RegNumArm64::REGNUM_X9: return 9; + case RegNumArm64::REGNUM_X10: return 10; + case RegNumArm64::REGNUM_X11: return 11; + case RegNumArm64::REGNUM_X12: return 12; + case RegNumArm64::REGNUM_X13: return 13; + case RegNumArm64::REGNUM_X14: return 14; + case RegNumArm64::REGNUM_X15: return 15; + case RegNumArm64::REGNUM_X16: return 16; + case RegNumArm64::REGNUM_X17: return 17; + case RegNumArm64::REGNUM_X18: return 18; + case RegNumArm64::REGNUM_X19: return 19; + case RegNumArm64::REGNUM_X20: return 20; + case RegNumArm64::REGNUM_X21: return 21; + case RegNumArm64::REGNUM_X22: return 22; + case RegNumArm64::REGNUM_X23: return 23; + case RegNumArm64::REGNUM_X24: return 24; + case RegNumArm64::REGNUM_X25: return 25; + case RegNumArm64::REGNUM_X26: return 26; + case RegNumArm64::REGNUM_X27: return 27; + case RegNumArm64::REGNUM_X28: return 28; + case RegNumArm64::REGNUM_FP: return 29; + case RegNumArm64::REGNUM_LR: return 30; + case RegNumArm64::REGNUM_SP: return 31; + case RegNumArm64::REGNUM_PC: return 32; + // fp registers + default: + return RegNum - static_cast(RegNumArm64::REGNUM_COUNT) + 64; + } + case Triple::x86_64: + switch (static_cast(RegNum)) { + case RegNumAmd64::REGNUM_RAX: return 0; + case RegNumAmd64::REGNUM_RDX: return 1; + case RegNumAmd64::REGNUM_RCX: return 2; + case RegNumAmd64::REGNUM_RBX: return 3; + case RegNumAmd64::REGNUM_RSI: return 4; + case RegNumAmd64::REGNUM_RDI: return 5; + case RegNumAmd64::REGNUM_RBP: return 6; + case RegNumAmd64::REGNUM_RSP: return 7; + case RegNumAmd64::REGNUM_R8: return 8; + case RegNumAmd64::REGNUM_R9: return 9; + case RegNumAmd64::REGNUM_R10: return 10; + case RegNumAmd64::REGNUM_R11: return 11; + case RegNumAmd64::REGNUM_R12: return 12; + case RegNumAmd64::REGNUM_R13: return 13; + case RegNumAmd64::REGNUM_R14: return 14; + case RegNumAmd64::REGNUM_R15: return 15; + // fp registers + default: + return RegNum - static_cast(RegNumAmd64::REGNUM_COUNT) + 17; + } + default: + assert(false && "Unexpected architecture"); + return 0; + } +} + +static int GetDwarfFpRegNum(Triple::ArchType ArchType) +{ + switch (ArchType) { + case Triple::x86: + return GetDwarfRegNum(ArchType, static_cast(RegNumX86::REGNUM_FP)); + case Triple::arm: // fall through + case Triple::armeb: // fall through + case Triple::thumb: // fall through + case Triple::thumbeb: + return GetDwarfRegNum(ArchType, static_cast(RegNumArm::REGNUM_FP)); + case Triple::aarch64: // fall through + case Triple::aarch64_be: + return GetDwarfRegNum(ArchType, static_cast(RegNumArm64::REGNUM_FP)); + case Triple::x86_64: + return GetDwarfRegNum(ArchType, static_cast(RegNumAmd64::REGNUM_FP)); + default: + assert(false && "Unexpected architecture"); + return 0; + } +} + +static void EmitVarLocation(MCObjectStreamer *Streamer, + const ICorDebugInfo::NativeVarInfo &VarInfo, + bool IsLocList = false) { + MCContext &context = Streamer->getContext(); + unsigned TargetPointerSize = context.getAsmInfo()->getCodePointerSize(); + Triple::ArchType ArchType = context.getObjectFileInfo()->getTargetTriple().getArch(); + + int DwarfRegNum; + int DwarfRegNum2; + int DwarfBaseRegNum; + unsigned Len; + + bool IsByRef = false; + bool IsStk2 = false; + bool IsRegStk = false; + + switch (VarInfo.loc.vlType) { + case ICorDebugInfo::VLT_REG_BYREF: // fall through + IsByRef = true; + case ICorDebugInfo::VLT_REG_FP: // fall through + case ICorDebugInfo::VLT_REG: { + DwarfRegNum = GetDwarfRegNum(ArchType, VarInfo.loc.vlReg.vlrReg); + if (IsByRef) { + Len = 2; + if (IsLocList) { + Streamer->EmitIntValue(Len, 2); + } else { + Streamer->EmitULEB128IntValue(Len); + } + Streamer->EmitIntValue(DwarfRegNum + dwarf::DW_OP_breg0, 1); + Streamer->EmitSLEB128IntValue(0); + } else { + Len = 1; + if (IsLocList) { + Streamer->EmitIntValue(Len, 2); + } else { + Streamer->EmitULEB128IntValue(Len); + } + Streamer->EmitIntValue(DwarfRegNum + dwarf::DW_OP_reg0, 1); + } + + break; + } + case ICorDebugInfo::VLT_STK_BYREF: // fall through + IsByRef = true; + case ICorDebugInfo::VLT_STK2: + IsStk2 = true; + case ICorDebugInfo::VLT_STK: { + DwarfBaseRegNum = GetDwarfRegNum(ArchType, IsStk2 ? VarInfo.loc.vlStk2.vls2BaseReg : + VarInfo.loc.vlStk.vlsBaseReg); + + SmallString<128> Tmp; + raw_svector_ostream OSE(Tmp); + encodeSLEB128(IsStk2 ? VarInfo.loc.vlStk2.vls2Offset : + VarInfo.loc.vlStk.vlsOffset, OSE); + StringRef OffsetRepr = OSE.str(); + + if (IsByRef) { + Len = OffsetRepr.size() + 2; + if (IsLocList) { + Streamer->EmitIntValue(Len, 2); + } else { + Streamer->EmitULEB128IntValue(Len); + } + Streamer->EmitIntValue(DwarfBaseRegNum + dwarf::DW_OP_breg0, 1); + Streamer->EmitBytes(OffsetRepr); + Streamer->EmitIntValue(dwarf::DW_OP_deref, 1); + } else { + Len = OffsetRepr.size() + 1; + if (IsLocList) { + Streamer->EmitIntValue(Len, 2); + } else { + Streamer->EmitULEB128IntValue(Len); + } + Streamer->EmitIntValue(DwarfBaseRegNum + dwarf::DW_OP_breg0, 1); + Streamer->EmitBytes(OffsetRepr); + } + + break; + } + case ICorDebugInfo::VLT_REG_REG: { + DwarfRegNum = GetDwarfRegNum(ArchType, VarInfo.loc.vlRegReg.vlrrReg1); + DwarfRegNum2 = GetDwarfRegNum(ArchType, VarInfo.loc.vlRegReg.vlrrReg2); + + Len = (1 /* DW_OP_reg */ + 1 /* DW_OP_piece */ + 1 /* Reg size */) * 2 + 1; + if (IsLocList) { + Streamer->EmitIntValue(Len, 2); + } else { + Streamer->EmitULEB128IntValue(Len + 1); + } + + Streamer->EmitIntValue(DwarfRegNum2 + dwarf::DW_OP_reg0, 1); + Streamer->EmitIntValue(dwarf::DW_OP_piece, 1); + Streamer->EmitULEB128IntValue(TargetPointerSize); + + Streamer->EmitIntValue(DwarfRegNum + dwarf::DW_OP_reg0, 1); + Streamer->EmitIntValue(dwarf::DW_OP_piece, 1); + Streamer->EmitULEB128IntValue(TargetPointerSize); + + break; + } + case ICorDebugInfo::VLT_REG_STK: // fall through + IsRegStk = true; + case ICorDebugInfo::VLT_STK_REG: { + DwarfRegNum = GetDwarfRegNum(ArchType, IsRegStk ? VarInfo.loc.vlRegStk.vlrsReg : + VarInfo.loc.vlStkReg.vlsrReg); + DwarfBaseRegNum = GetDwarfRegNum(ArchType, IsRegStk ? VarInfo.loc.vlRegStk.vlrsStk.vlrssBaseReg : + VarInfo.loc.vlStkReg.vlsrStk.vlsrsBaseReg); + + SmallString<128> Tmp; + raw_svector_ostream OSE(Tmp); + encodeSLEB128(IsRegStk ? VarInfo.loc.vlRegStk.vlrsStk.vlrssOffset : + VarInfo.loc.vlStkReg.vlsrStk.vlsrsOffset, OSE); + StringRef OffsetRepr = OSE.str(); + + Len = (1 /* DW_OP_reg */ + 1 /* DW_OP_piece */ + 1 /* Reg size */) + + (1 /*DW_OP_breg */ + OffsetRepr.size() + 1 /* DW_OP_piece */ + 1 /* Reg size */) + 1; + + if (IsLocList) { + Streamer->EmitIntValue(Len, 2); + } else { + Streamer->EmitULEB128IntValue(Len + 1); + } + + if (IsRegStk) { + Streamer->EmitIntValue(DwarfRegNum + dwarf::DW_OP_reg0, 1); + Streamer->EmitIntValue(dwarf::DW_OP_piece, 1); + Streamer->EmitULEB128IntValue(TargetPointerSize); + + Streamer->EmitIntValue(DwarfBaseRegNum + dwarf::DW_OP_breg0, 1); + Streamer->EmitBytes(OffsetRepr); + Streamer->EmitIntValue(dwarf::DW_OP_piece, 1); + Streamer->EmitULEB128IntValue(TargetPointerSize); + } else { + Streamer->EmitIntValue(DwarfBaseRegNum + dwarf::DW_OP_breg0, 1); + Streamer->EmitBytes(OffsetRepr); + Streamer->EmitIntValue(dwarf::DW_OP_piece, 1); + Streamer->EmitULEB128IntValue(TargetPointerSize); + + Streamer->EmitIntValue(DwarfRegNum + dwarf::DW_OP_reg0, 1); + Streamer->EmitIntValue(dwarf::DW_OP_piece, 1); + Streamer->EmitULEB128IntValue(TargetPointerSize); + } + + break; + } + case ICorDebugInfo::VLT_FPSTK: + case ICorDebugInfo::VLT_FIXED_VA: + assert(false && "Unsupported varloc type!"); + default: + assert(false && "Unknown varloc type!"); + if (IsLocList) { + Streamer->EmitIntValue(0, 2); + } else { + Streamer->EmitULEB128IntValue(0); + } + } +} + +// Lexical scope + +class LexicalScope +{ +public: + LexicalScope(uint64_t Start, uint64_t End, bool IsFuncScope = false) : + Start(Start), + End(End), + IsFuncScope(IsFuncScope) {} + + LexicalScope(VarInfo *Info) : + Start(Info->GetStartOffset()), + End(Info->GetEndOffset()), + IsFuncScope(false) { Vars.push_back(Info); } + + bool IsContains(const VarInfo *Info) const { + return Start <= Info->GetStartOffset() && End >= Info->GetEndOffset(); + } + + void AddVar(VarInfo *Info); + + void Dump(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection, const MCExpr *SymExpr); + +private: + uint64_t Start; + uint64_t End; + bool IsFuncScope; + std::vector Vars; + std::vector InnerScopes; +}; + +void LexicalScope::AddVar(VarInfo *Info) { + if (Info->IsParam() && IsFuncScope) { + Vars.push_back(Info); + return; + } + + if (!IsContains(Info)) + return; + + uint64_t VarStart = Info->GetStartOffset(); + uint64_t VarEnd = Info->GetEndOffset(); + + // Var belongs to inner scope + if (VarStart != Start || VarEnd != End) { + // Try to add variable to one the inner scopes + for (auto &Scope : InnerScopes) { + if (Scope.IsContains(Info)) { + Scope.AddVar(Info); + return; + } + } + // We need to create new inner scope for this var + InnerScopes.emplace_back(Info); + } else { + Vars.push_back(Info); + } +} + +void LexicalScope::Dump(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection, const MCExpr *SymExpr) { + Streamer->SwitchSection(TypeSection); + + if (!IsFuncScope) + { + // Dump lexical block DIE + MCContext &context = Streamer->getContext(); + unsigned TargetPointerSize = context.getAsmInfo()->getCodePointerSize(); + + // Abbrev Number + Streamer->EmitULEB128IntValue(DwarfAbbrev::LexicalBlock); + + // DW_AT_low_pc + const MCExpr *StartExpr = MCConstantExpr::create(Start, context); + const MCExpr *LowPcExpr = MCBinaryExpr::create(MCBinaryExpr::Add, SymExpr, + StartExpr, context); + Streamer->EmitValue(LowPcExpr, TargetPointerSize); + + // DW_AT_high_pc + Streamer->EmitIntValue(End - Start, TargetPointerSize); + } + + for (auto *Var : Vars) { + Var->Dump(TypeBuilder, Streamer, TypeSection, StrSection); + } + + for (auto &Scope : InnerScopes) { + Scope.Dump(TypeBuilder, Streamer, TypeSection, StrSection, SymExpr); + } + + if (!IsFuncScope) { + // Terminate block + Streamer->EmitIntValue(0, 1); + } +} + +// StaticVarInfo + +class StaticVarInfo : public DwarfInfo +{ +public: + StaticVarInfo(const DwarfStaticDataField *StaticField) : StaticField(StaticField) {} + + void Dump(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) override; + +protected: + void DumpStrings(MCObjectStreamer *Streamer) override {}; + void DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) override; + +private: + const DwarfStaticDataField *StaticField; + + void EmitLocation(MCObjectStreamer *Streamer); +}; + +void StaticVarInfo::Dump(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) { + MCContext &context = Streamer->getContext(); + MCSymbol *Sym = context.getOrCreateSymbol(Twine(StaticField->GetStaticDataName())); + if (Sym->isUndefined()) + return; + + DwarfInfo::Dump(TypeBuilder, Streamer, TypeSection, StrSection); +} + +void StaticVarInfo::DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) { + // Abbrev Number + Streamer->EmitULEB128IntValue(DwarfAbbrev::VariableStatic); + + // DW_AT_specification + EmitInfoOffset(Streamer, StaticField, 4); + + // DW_AT_location + EmitLocation(Streamer); +} + +void StaticVarInfo::EmitLocation(MCObjectStreamer *Streamer) { + MCContext &context = Streamer->getContext(); + unsigned TargetPointerSize = context.getAsmInfo()->getCodePointerSize(); + + MCSymbol *Sym = context.getOrCreateSymbol(Twine(StaticField->GetStaticDataName())); + + SmallString<128> Tmp; + raw_svector_ostream OSE(Tmp); + encodeULEB128(StaticField->GetStaticOffset(), OSE); + StringRef OffsetRepr = OSE.str(); + + unsigned Len = 1 /* DW_OP_addr */ + TargetPointerSize; + + // Need double deref + if (StaticField->IsStaticDataInObject()) { + Len += (1 /* DW_OP_deref */) * 2; + } + + if (StaticField->GetStaticOffset() != 0) { + Len += 1 /* DW_OP_plus_uconst */ + OffsetRepr.size(); + } + + Streamer->EmitULEB128IntValue(Len); + Streamer->EmitIntValue(dwarf::DW_OP_addr, 1); + Streamer->EmitSymbolValue(Sym, TargetPointerSize); + + if (StaticField->IsStaticDataInObject()) { + Streamer->EmitIntValue(dwarf::DW_OP_deref, 1); + Streamer->EmitIntValue(dwarf::DW_OP_deref, 1); + } + + if (StaticField->GetStaticOffset() != 0) { + Streamer->EmitIntValue(dwarf::DW_OP_plus_uconst, 1); + Streamer->EmitBytes(OffsetRepr); + } +} + +// VarInfo + +VarInfo::VarInfo(const DebugVarInfo &Info, bool IsThis) : + DebugInfo(Info), + LocSymbol(nullptr), + IsThis(IsThis) { + if (!Info.IsParam) { + assert(!Info.Ranges.empty()); + StartOffset = Info.Ranges.front().startOffset; + EndOffset = Info.Ranges.back().endOffset; + } else { + // Params belong to func scope + StartOffset = 0xFFFFFFFF; + EndOffset = 0xFFFFFFFF; + } +} + +void VarInfo::DumpLocsIfNeeded(MCObjectStreamer *Streamer, + MCSection *LocSection, + const MCExpr *SymExpr) { + if (!IsDebugLocNeeded()) + return; + + Streamer->SwitchSection(LocSection); + + MCContext &context = Streamer->getContext(); + unsigned TargetPointerSize = context.getAsmInfo()->getCodePointerSize(); + + LocSymbol = context.createTempSymbol(); + Streamer->EmitLabel(LocSymbol); + + for (const auto &NativeInfo : DebugInfo.Ranges) { + const MCExpr *StartOffsetExpr = MCConstantExpr::create(NativeInfo.startOffset, context); + const MCExpr *EndOffsetExpr = MCConstantExpr::create(NativeInfo.endOffset, context); + + // Begin address + const MCExpr *BeginAddrExpr = MCBinaryExpr::create(MCBinaryExpr::Add, SymExpr, + StartOffsetExpr, context); + Streamer->EmitValue(BeginAddrExpr, TargetPointerSize); + + // End address + const MCExpr *EndAddrExpr = MCBinaryExpr::create(MCBinaryExpr::Add, SymExpr, + EndOffsetExpr, context); + Streamer->EmitValue(EndAddrExpr, TargetPointerSize); + + // Expression + EmitVarLocation(Streamer, NativeInfo, true); + } + + // Terminate list entry + Streamer->EmitIntValue(0, TargetPointerSize); + Streamer->EmitIntValue(0, TargetPointerSize); +} + +void VarInfo::DumpStrings(MCObjectStreamer *Streamer) { + if (IsThis) { + Streamer->EmitBytes(StringRef("this")); + } else { + Streamer->EmitBytes(StringRef(DebugInfo.Name)); + } + Streamer->EmitIntValue(0, 1); +} + +void VarInfo::DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) { + bool IsDebugLocUsed = IsDebugLocNeeded(); + + // Abbrev Number + if (DebugInfo.IsParam) { + if (IsThis) { + Streamer->EmitULEB128IntValue(IsDebugLocUsed ? DwarfAbbrev::FormalParameterThisLoc : + DwarfAbbrev::FormalParameterThis); + } else { + Streamer->EmitULEB128IntValue(IsDebugLocUsed ? DwarfAbbrev::FormalParameterLoc : + DwarfAbbrev::FormalParameter); + } + } else { + Streamer->EmitULEB128IntValue(IsDebugLocUsed ? DwarfAbbrev::VariableLoc : + DwarfAbbrev::Variable); + } + + // DW_AT_name + EmitSectionOffset(Streamer, StrSymbol, 4); + + // DW_AT_decl_file + Streamer->EmitIntValue(1, 1); + + // DW_AT_decl_line + Streamer->EmitIntValue(1, 1); + + // DW_AT_type + DwarfInfo *Info = TypeBuilder->GetTypeInfoByIndex(DebugInfo.TypeIndex); + assert(Info != nullptr); + + EmitInfoOffset(Streamer, Info, 4); + + // DW_AT_location + if (IsDebugLocUsed) { + EmitSectionOffset(Streamer, LocSymbol, 4); + } else { + assert(DebugInfo.Ranges.size() == 1); + EmitVarLocation(Streamer, DebugInfo.Ranges[0]); + } +} + +// SubprogramInfo + +SubprogramInfo::SubprogramInfo(const char *Name, + int Size, + DwarfMemberFunctionIdTypeInfo *MethodTypeInfo, + const std::vector &DebugVarInfos, + const std::vector &DebugEHClauseInfos) : + Name(Name), + Size(Size), + MethodTypeInfo(MethodTypeInfo), + DebugEHClauseInfos(DebugEHClauseInfos) { + bool IsStatic = MethodTypeInfo->IsStatic(); + for (unsigned i = 0; i < DebugVarInfos.size(); i++) { + VarInfos.emplace_back(DebugVarInfos[i], i == 0 && !IsStatic); + } +} + +void SubprogramInfo::Dump(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection, MCSection *LocSection) { + DumpDebugLoc(Streamer, LocSection); + + DwarfInfo::Dump(TypeBuilder, Streamer, TypeSection, StrSection); + + // Dump vars + DumpVars(TypeBuilder, Streamer, TypeSection, StrSection); + + // Dump try-catch blocks + Streamer->SwitchSection(TypeSection); + DumpEHClauses(Streamer, TypeSection); + + // Terminate subprogram DIE + Streamer->EmitIntValue(0, 1); +} + +void SubprogramInfo::DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) { + MCContext &context = Streamer->getContext(); + bool IsStatic = MethodTypeInfo->IsStatic(); + unsigned TargetPointerSize = context.getAsmInfo()->getCodePointerSize(); + Triple::ArchType ArchType = context.getObjectFileInfo()->getTargetTriple().getArch(); + + // Subprogram DIE + + // Abbrev Number + Streamer->EmitULEB128IntValue(IsStatic ? DwarfAbbrev::SubprogramStatic : + DwarfAbbrev::Subprogram); + + // DW_AT_specification + EmitInfoOffset(Streamer, MethodTypeInfo, 4); + + // DW_AT_low_pc + MCSymbol *Sym = context.getOrCreateSymbol(Twine(Name)); + const MCExpr *SymExpr = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, context); + Streamer->EmitValue(SymExpr, TargetPointerSize); + + // DW_AT_high_pc + Streamer->EmitIntValue(Size, TargetPointerSize); + + // DW_AT_frame_base + Streamer->EmitULEB128IntValue(1); + Streamer->EmitIntValue(GetDwarfFpRegNum(ArchType) + dwarf::DW_OP_reg0, 1); + + if (!IsStatic) { + // DW_AT_object_pointer + uint32_t Offset = Streamer->getOrCreateDataFragment()->getContents().size(); + + Streamer->EmitIntValue(Offset + 4, 4); + } +} + +void SubprogramInfo::DumpDebugLoc(MCObjectStreamer *Streamer, MCSection *LocSection) { + MCContext &context = Streamer->getContext(); + MCSymbol *Sym = context.getOrCreateSymbol(Twine(Name)); + const MCExpr *SymExpr = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, context); + + for (auto &VarInfo : VarInfos) { + VarInfo.DumpLocsIfNeeded(Streamer, LocSection, SymExpr); + } +} + +void SubprogramInfo::DumpVars(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) { + MCContext &context = Streamer->getContext(); + MCSymbol *Sym = context.getOrCreateSymbol(Twine(Name)); + const MCExpr *SymExpr = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, context); + + LexicalScope FuncScope(0, Size, true); + + for (unsigned i = 0; i < VarInfos.size(); i++) { + FuncScope.AddVar(&VarInfos[i]); + } + + FuncScope.Dump(TypeBuilder, Streamer, TypeSection, StrSection, SymExpr); +} + +static void DumpEHClause(MCObjectStreamer *Streamer, MCSection *TypeSection, int Abbrev, + const MCExpr *SymExpr, unsigned Offset, unsigned Length) { + MCContext &context = Streamer->getContext(); + unsigned TargetPointerSize = context.getAsmInfo()->getCodePointerSize(); + + // Abbrev Number + Streamer->EmitULEB128IntValue(Abbrev); + + // DW_AT_low_pc + const MCExpr *OffsetExpr = MCConstantExpr::create(Offset, context); + const MCExpr *AddrExpr = MCBinaryExpr::create(MCBinaryExpr::Add, SymExpr, + OffsetExpr, context); + + Streamer->EmitValue(AddrExpr, TargetPointerSize); + + // DW_AT_high_pc + Streamer->EmitIntValue(Length, TargetPointerSize); +} + +void SubprogramInfo::DumpEHClauses(MCObjectStreamer *Streamer, MCSection *TypeSection) { + MCContext &context = Streamer->getContext(); + + MCSymbol *Sym = context.getOrCreateSymbol(Twine(Name)); + const MCExpr *SymExpr = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, context); + + for (const auto &EHClause: DebugEHClauseInfos) { + // Try block DIE + DumpEHClause(Streamer, TypeSection, DwarfAbbrev::TryBlock, + SymExpr, EHClause.TryOffset, EHClause.TryLength); + + // Catch block DIE + DumpEHClause(Streamer, TypeSection, DwarfAbbrev::CatchBlock, + SymExpr, EHClause.HandlerOffset, EHClause.HandlerLength); + } +} + +// DwarfGen + +void DwarfGen::SetTypeBuilder(UserDefinedDwarfTypesBuilder *TypeBuilder) { + assert(this->TypeBuilder == nullptr); + assert(TypeBuilder != nullptr); + this->TypeBuilder = TypeBuilder; + this->Streamer = TypeBuilder->GetStreamer(); +} + +void DwarfGen::EmitCompileUnit() { + MCContext &context = Streamer->getContext(); + + MCSymbol *LineSectionSymbol = nullptr; + MCSymbol *AbbrevSectionSymbol = nullptr; + if (context.getAsmInfo()->doesDwarfUseRelocationsAcrossSections()) { + LineSectionSymbol = Streamer->getDwarfLineTableSymbol(0); + + Streamer->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); + AbbrevSectionSymbol = context.createTempSymbol(); + Streamer->EmitLabel(AbbrevSectionSymbol); + } + + MCSection *debugSection = context.getObjectFileInfo()->getDwarfInfoSection(); + Streamer->SwitchSection(debugSection); + + InfoStart = debugSection->getBeginSymbol(); + InfoEnd = context.createTempSymbol(); + + // Length + const MCExpr *Length = MakeStartMinusEndExpr(*Streamer, *InfoStart, *InfoEnd, 4); + emitAbsValue(*Streamer, Length, 4); + + // Version + Streamer->EmitIntValue(context.getDwarfVersion(), 2); + + // Unit type, Addr Size and Abbrev offset - DWARF >= 5 + // Abbrev offset, Addr Size - DWARF <= 4 + unsigned addrSize = context.getAsmInfo()->getCodePointerSize(); + if (context.getDwarfVersion() >= 5) { + Streamer->EmitIntValue(dwarf::DW_UT_compile, 1); + Streamer->EmitIntValue(addrSize, 1); + } + + // Abbrev Offset + if (AbbrevSectionSymbol == nullptr) { + Streamer->EmitIntValue(0, 4); + } else { + Streamer->EmitSymbolValue(AbbrevSectionSymbol, 4, + context.getAsmInfo()->needsDwarfSectionOffsetDirective()); + } + + if (context.getDwarfVersion() <= 4) + Streamer->EmitIntValue(addrSize, 1); + + // CompileUnit DIE + + // Abbrev Number + Streamer->EmitULEB128IntValue(DwarfAbbrev::CompileUnit); + + // DW_AT_producer: CoreRT + Streamer->EmitBytes(StringRef("CoreRT")); + Streamer->EmitIntValue(0, 1); + + // DW_AT_language +#ifdef FEATURE_LANGID_CS + Streamer->EmitIntValue(DW_LANG_MICROSOFT_CSHARP, 2); +#else + Streamer->EmitIntValue(dwarf::DW_LANG_C_plus_plus, 2); +#endif + + // DW_AT_stmt_list + if (LineSectionSymbol == nullptr) { + Streamer->EmitIntValue(0, 4); + } else { + Streamer->EmitSymbolValue(LineSectionSymbol, 4, + context.getAsmInfo()->needsDwarfSectionOffsetDirective()); + } +} + +void DwarfGen::EmitSubprogramInfo(const char *FunctionName, + int FunctionSize, + unsigned MethodTypeIndex, + const std::vector &VarInfos, + const std::vector &DebugEHClauseInfos) { + // return if CU isn't emitted + if (InfoStart == nullptr) + return; + + if (MethodTypeIndex == 0) + return; + + DwarfMemberFunctionIdTypeInfo *MethodTypeInfo = static_cast( + TypeBuilder->GetTypeInfoByIndex(MethodTypeIndex)); + assert(MethodTypeInfo != nullptr); + + MethodTypeInfo->SetLinkageName(FunctionName); + + Subprograms.emplace_back(FunctionName, FunctionSize, MethodTypeInfo, VarInfos, DebugEHClauseInfos); +} + +void DwarfGen::EmitAbbrev() { + // return if CU isn't emitted + if (InfoStart == nullptr) + return; + + MCContext &context = Streamer->getContext(); + + DwarfAbbrev::Dump(Streamer, context.getDwarfVersion(), + context.getAsmInfo()->getCodePointerSize()); +} + +void DwarfGen::EmitAranges() { + // return if CU isn't emitted + if (InfoStart == nullptr) + return; + + MCContext &context = Streamer->getContext(); + Streamer->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection()); + + auto &Sections = context.getGenDwarfSectionSyms(); + + int Length = 4 + 2 + 4 + 1 + 1; + int AddrSize = context.getAsmInfo()->getCodePointerSize(); + int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1)); + if (Pad == 2 * AddrSize) + Pad = 0; + Length += Pad; + + Length += 2 * AddrSize * Sections.size(); + Length += 2 * AddrSize; + + // Emit the header for this section. + // The 4 byte length not including the 4 byte value for the length. + Streamer->EmitIntValue(Length - 4, 4); + + // The 2 byte version, which is 2. + Streamer->EmitIntValue(2, 2); + + // The 4 byte offset to the compile unit in the .debug_info from the start + // of the .debug_info. + Streamer->EmitSymbolValue(InfoStart, 4, + context.getAsmInfo()->needsDwarfSectionOffsetDirective()); + + Streamer->EmitIntValue(AddrSize, 1); + + Streamer->EmitIntValue(0, 1); + + for(int i = 0; i < Pad; i++) + Streamer->EmitIntValue(0, 1); + + for (MCSection *Sec : Sections) { + const MCSymbol *StartSymbol = Sec->getBeginSymbol(); + MCSymbol *EndSymbol = Sec->getEndSymbol(context); + assert(StartSymbol && "StartSymbol must not be NULL"); + assert(EndSymbol && "EndSymbol must not be NULL"); + + const MCExpr *Addr = MCSymbolRefExpr::create( + StartSymbol, MCSymbolRefExpr::VK_None, context); + const MCExpr *Size = MakeStartMinusEndExpr(*Streamer, + *StartSymbol, *EndSymbol, 0); + Streamer->EmitValue(Addr, AddrSize); + emitAbsValue(*Streamer, Size, AddrSize); + } + + // Terminating zeros. + Streamer->EmitIntValue(0, AddrSize); + Streamer->EmitIntValue(0, AddrSize); +} + +void DwarfGen::Finish() { + // return if CU isn't emitted + if (InfoStart == nullptr) + return; + + MCContext &context = Streamer->getContext(); + + // Dump type info + + MCSection *InfoSection = context.getObjectFileInfo()->getDwarfInfoSection(); + MCSection *StrSection = context.getObjectFileInfo()->getDwarfStrSection(); + MCSection *LocSection = context.getObjectFileInfo()->getDwarfLocSection(); + + TypeBuilder->EmitTypeInformation(InfoSection, StrSection); + + // Dump subprograms + + for (auto &Subprogram : Subprograms) { + Subprogram.Dump(TypeBuilder, Streamer, InfoSection, StrSection, LocSection); + } + + // Dump static vars + + for (const auto *ClassTypeInfo : TypeBuilder->GetClassesWithStaticFields()) { + for (const auto &StaticField : ClassTypeInfo->GetStaticFields()) { + StaticVarInfo Info(&StaticField); + Info.Dump(TypeBuilder, Streamer, InfoSection, StrSection); + } + } + + // Add the NULL terminating the Compile Unit DIE's. + Streamer->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection()); + + Streamer->EmitIntValue(0, 1); + + Streamer->EmitLabel(InfoEnd); + + Streamer->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); + + // Terminate the abbreviations for this compilation unit + Streamer->EmitIntValue(0, 1); +} \ No newline at end of file diff --git a/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfGen.h b/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfGen.h new file mode 100644 index 0000000000..2fd78a5c68 --- /dev/null +++ b/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfGen.h @@ -0,0 +1,106 @@ +//===---- dwarfGen.h --------------------------------------------*- C++ -*-===// +// +// dwarf generator is used to generate dwarf debuginfo. +// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "llvm/MC/MCObjectStreamer.h" + +#include "dwarfTypeBuilder.h" +#include "jitDebugInfo.h" + +#include + +class VarInfo : public DwarfInfo +{ +public: + VarInfo(const DebugVarInfo &Info, bool IsThis); + + bool IsDebugLocNeeded() const { return DebugInfo.Ranges.size() > 1; } + + void DumpLocsIfNeeded(MCObjectStreamer *Streamer, MCSection *LocSection, const MCExpr *SymExpr); + + uint64_t GetStartOffset() const { return StartOffset; } + + uint64_t GetEndOffset() const { return EndOffset; } + + bool IsParam() const { return DebugInfo.IsParam; } + +protected: + void DumpStrings(MCObjectStreamer *Streamer) override; + void DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) override; + +private: + DebugVarInfo DebugInfo; + MCSymbol *LocSymbol; + bool IsThis; + uint64_t StartOffset; + uint64_t EndOffset; +}; + +class SubprogramInfo : public DwarfInfo +{ +public: + using DwarfInfo::Dump; + + SubprogramInfo(const char *Name, + int Size, + DwarfMemberFunctionIdTypeInfo *MethodTypeInfo, + const std::vector &DebugVarInfos, + const std::vector &DebugEHClauseInfos); + + void Dump(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection, MCSection *LocSection); + +protected: + void DumpStrings(MCObjectStreamer *Streamer) override {} + void DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) override; + +private: + void DumpDebugLoc(MCObjectStreamer *Streamer, MCSection *LocSection); + void DumpVars(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection); + void DumpEHClauses(MCObjectStreamer *Streamer, MCSection *TypeSection); + + std::string Name; + int Size; + DwarfMemberFunctionIdTypeInfo *MethodTypeInfo; + std::vector DebugEHClauseInfos; + std::vector VarInfos; +}; + +class DwarfGen +{ +public: + DwarfGen() : Streamer(nullptr), + TypeBuilder(nullptr), + InfoStart(nullptr), + InfoEnd(nullptr) {} + + void SetTypeBuilder(UserDefinedDwarfTypesBuilder *TypeBuilder); + void EmitCompileUnit(); + void EmitSubprogramInfo(const char *FunctionName, + int FunctionSize, + unsigned MethodTypeIndex, + const std::vector &VarsInfo, + const std::vector &DebugEHClauseInfos); + + void EmitAbbrev(); + void EmitAranges(); + void Finish(); + +private: + MCObjectStreamer *Streamer; + UserDefinedDwarfTypesBuilder *TypeBuilder; + + MCSymbol *InfoStart; + MCSymbol *InfoEnd; + + std::vector Subprograms; +}; \ No newline at end of file diff --git a/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfTypeBuilder.cpp b/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfTypeBuilder.cpp new file mode 100644 index 0000000000..da5448bf1c --- /dev/null +++ b/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfTypeBuilder.cpp @@ -0,0 +1,780 @@ +//===---- dwarfTypeBuilder.cpp ----------------------------------*- C++ -*-===// +// +// dwarf type builder implementation +// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +// +//===----------------------------------------------------------------------===// + +#include "dwarfTypeBuilder.h" +#include "dwarfAbbrev.h" +#include "llvm/MC/MCContext.h" +#include "llvm/MC/MCAsmInfo.h" +#include "llvm/MC/MCObjectFileInfo.h" + +#include +#include + +// DwarfInfo + +void DwarfInfo::Dump(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) { + if (IsDumped) + return; + + IsDumped = true; + + MCContext &context = Streamer->getContext(); + + InfoSymbol = context.createTempSymbol(); + InfoExpr = CreateOffsetExpr(context, TypeSection->getBeginSymbol(), InfoSymbol); + + DumpTypes(TypeBuilder, Streamer, TypeSection, StrSection); + + Streamer->SwitchSection(StrSection); + StrSymbol = context.createTempSymbol(); + Streamer->EmitLabel(StrSymbol); + DumpStrings(Streamer); + + Streamer->SwitchSection(TypeSection); + Streamer->EmitLabel(InfoSymbol); + DumpTypeInfo(Streamer, TypeBuilder); +} + +void DwarfInfo::DumpTypes(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) { + if (IsDumpedTypes) + return; + + IsDumpedTypes = true; +} + +void DwarfInfo::EmitSectionOffset(MCObjectStreamer *Streamer, + MCSymbol *Symbol, + unsigned Size, + uint32_t Offset) { + MCContext &context = Streamer->getContext(); + + if (context.getAsmInfo()->doesDwarfUseRelocationsAcrossSections()) { + if (Offset == 0) { + Streamer->EmitSymbolValue(Symbol, Size); + } else { + const MCSymbolRefExpr *SymbolExpr = MCSymbolRefExpr::create(Symbol, + MCSymbolRefExpr::VK_None, context); + const MCExpr *OffsetExpr = MCConstantExpr::create(Offset, context); + const MCExpr *Expr = MCBinaryExpr::createAdd(SymbolExpr, OffsetExpr, context); + Streamer->EmitValue(Expr, Size); + } + } else { + Streamer->EmitIntValue(Symbol->getOffset() + Offset, Size); + } +} + +const MCExpr *DwarfInfo::CreateOffsetExpr(MCContext &Context, + MCSymbol *BeginSymbol, + MCSymbol *Symbol) { + MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; + const MCExpr *StartExpr = + MCSymbolRefExpr::create(BeginSymbol, Variant, Context); + const MCExpr *EndExpr = + MCSymbolRefExpr::create(Symbol, Variant, Context); + return MCBinaryExpr::createSub(EndExpr, StartExpr, Context); +} + +void DwarfInfo::EmitOffset(MCObjectStreamer *Streamer, + const MCExpr *OffsetExpr, + unsigned Size) { + MCContext &context = Streamer->getContext(); + + if (!context.getAsmInfo()->hasAggressiveSymbolFolding()) { + MCSymbol *Temp = context.createTempSymbol(); + Streamer->EmitAssignment(Temp, OffsetExpr); + OffsetExpr = MCSymbolRefExpr::create(Temp, context); + } + + Streamer->EmitValue(OffsetExpr, Size); +} + +void DwarfInfo::EmitInfoOffset(MCObjectStreamer *Streamer, const DwarfInfo *Info, unsigned Size) { + uint64_t Offset = Info->InfoSymbol->getOffset(); + if (Offset != 0) { + Streamer->EmitIntValue(Offset, Size); + } else { + EmitOffset(Streamer, Info->InfoExpr, Size); + } +} + +// DwarfPrimitiveTypeInfo + +struct PrimitiveTypeDesc { + const char *Name; + int Encoding; + unsigned ByteSize; +}; + +static PrimitiveTypeDesc GetPrimitiveTypeDesc(PrimitiveTypeFlags Type, unsigned TargetPointerSize) { + switch (Type) { + case PrimitiveTypeFlags::Void: return {"void", dwarf::DW_ATE_address, 0}; + case PrimitiveTypeFlags::Boolean: return {"bool", dwarf::DW_ATE_boolean, 1}; + case PrimitiveTypeFlags::Char: return {"char16_t", dwarf::DW_ATE_UTF, 2}; + case PrimitiveTypeFlags::SByte: return {"sbyte", dwarf::DW_ATE_signed, 1}; + case PrimitiveTypeFlags::Byte: return {"byte", dwarf::DW_ATE_unsigned, 1}; + case PrimitiveTypeFlags::Int16: return {"short", dwarf::DW_ATE_signed, 2}; + case PrimitiveTypeFlags::UInt16: return {"ushort", dwarf::DW_ATE_unsigned, 2}; + case PrimitiveTypeFlags::Int32: return {"int", dwarf::DW_ATE_signed, 4}; + case PrimitiveTypeFlags::UInt32: return {"uint", dwarf::DW_ATE_unsigned, 4}; + case PrimitiveTypeFlags::Int64: return {"long", dwarf::DW_ATE_signed, 8}; + case PrimitiveTypeFlags::UInt64: return {"ulong", dwarf::DW_ATE_unsigned, 8}; + case PrimitiveTypeFlags::IntPtr: return {"System.IntPtr", dwarf::DW_ATE_signed, TargetPointerSize}; + case PrimitiveTypeFlags::UIntPtr: return {"System.UIntPtr", dwarf::DW_ATE_unsigned, TargetPointerSize}; + case PrimitiveTypeFlags::Single: return {"float", dwarf::DW_ATE_float, 4}; + case PrimitiveTypeFlags::Double: return {"double", dwarf::DW_ATE_float, 8}; + default: + assert(false && "Unexpected type"); + return {nullptr, 0, 0}; + } +} + +void DwarfPrimitiveTypeInfo::DumpStrings(MCObjectStreamer *Streamer) { + MCContext &context = Streamer->getContext(); + unsigned TargetPointerSize = context.getAsmInfo()->getCodePointerSize(); + + PrimitiveTypeDesc TD = GetPrimitiveTypeDesc(Type, TargetPointerSize); + if (TD.Name == nullptr) + return; + + Streamer->EmitBytes(StringRef(TD.Name)); + Streamer->EmitIntValue(0, 1); +} + +void DwarfPrimitiveTypeInfo::DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) { + MCContext &context = Streamer->getContext(); + unsigned TargetPointerSize = context.getAsmInfo()->getCodePointerSize(); + + PrimitiveTypeDesc TD = GetPrimitiveTypeDesc(Type, TargetPointerSize); + if (TD.Name == nullptr) + return; + + // Abbrev Number + Streamer->EmitULEB128IntValue(DwarfAbbrev::BaseType); + + // DW_AT_name + EmitSectionOffset(Streamer, StrSymbol, 4); + + // DW_AT_encoding + Streamer->EmitIntValue(TD.Encoding, 1); + + // DW_AT_byte_size + Streamer->EmitIntValue(TD.ByteSize, 1); +} + +// DwarfEnumerator + +void DwarfEnumerator::DumpStrings(MCObjectStreamer *Streamer) { + Streamer->EmitBytes(Name); + Streamer->EmitIntValue(0, 1); +} + +void DwarfEnumerator::DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) { + uint8_t Size = EnumTypeInfo->GetByteSize(); + + // Abbrev Number + switch (Size) { + case 1: + Streamer->EmitULEB128IntValue(DwarfAbbrev::Enumerator1); + break; + case 2: + Streamer->EmitULEB128IntValue(DwarfAbbrev::Enumerator2); + break; + case 4: + Streamer->EmitULEB128IntValue(DwarfAbbrev::Enumerator4); + break; + case 8: + Streamer->EmitULEB128IntValue(DwarfAbbrev::Enumerator8); + break; + default: + assert(false && "Unexpected byte size value"); + } + + // DW_AT_name + EmitSectionOffset(Streamer, StrSymbol, 4); + + // DW_AT_const_value + Streamer->EmitIntValue(Value, Size); +} + +// DwarfEnumTypeInfo + +DwarfEnumTypeInfo::DwarfEnumTypeInfo(const EnumTypeDescriptor &TypeDescriptor, + const EnumRecordTypeDescriptor *TypeRecords) : + Name(TypeDescriptor.Name), + ElementType(TypeDescriptor.ElementType) { + for (uint64 i = 0; i < TypeDescriptor.ElementCount; i++) { + Records.emplace_back(TypeRecords[i], this); + } +} + +void DwarfEnumTypeInfo::DumpTypes(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) { + if (IsDumpedTypes) + return; + + DwarfInfo::DumpTypes(TypeBuilder, Streamer, TypeSection, StrSection); + + DwarfInfo *Info = TypeBuilder->GetTypeInfoByIndex(ElementType); + assert(Info != nullptr); + + Info->Dump(TypeBuilder, Streamer, TypeSection, StrSection); +} + +void DwarfEnumTypeInfo::Dump(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) { + if (IsDumped) + return; + + MCContext &context = Streamer->getContext(); + unsigned TargetPointerSize = context.getAsmInfo()->getCodePointerSize(); + + DwarfPrimitiveTypeInfo *ElementTypeInfo = static_cast( + TypeBuilder->GetTypeInfoByIndex(ElementType)); + assert(ElementTypeInfo != nullptr); + + PrimitiveTypeDesc TD = GetPrimitiveTypeDesc(ElementTypeInfo->GetType(), TargetPointerSize); + ByteSize = TD.ByteSize; + + DwarfInfo::Dump(TypeBuilder, Streamer, TypeSection, StrSection); + + for (auto &Enumerator : Records) { + Enumerator.Dump(TypeBuilder, Streamer, TypeSection, StrSection); + } + + // Terminate DIE + Streamer->SwitchSection(TypeSection); + Streamer->EmitIntValue(0, 1); +} + +void DwarfEnumTypeInfo::DumpStrings(MCObjectStreamer *Streamer) { + Streamer->EmitBytes(Name); + Streamer->EmitIntValue(0, 1); +} + +void DwarfEnumTypeInfo::DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) { + // Abbrev Number + Streamer->EmitULEB128IntValue(DwarfAbbrev::EnumerationType); + + // DW_AT_name + EmitSectionOffset(Streamer, StrSymbol, 4); + + // DW_AT_type + DwarfInfo *Info = TypeBuilder->GetTypeInfoByIndex(ElementType); + assert(Info != nullptr); + + EmitInfoOffset(Streamer, Info, 4); + + // DW_AT_byte_size + Streamer->EmitIntValue(ByteSize, 1); +} + +// DwarfDataField + +void DwarfDataField::DumpStrings(MCObjectStreamer *Streamer) { + Streamer->EmitBytes(StringRef(Name)); + Streamer->EmitIntValue(0, 1); +} + +void DwarfDataField::DumpTypes(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) { + if (IsDumpedTypes) + return; + + DwarfInfo::DumpTypes(TypeBuilder, Streamer, TypeSection, StrSection); + + DwarfInfo *MemberTypeInfo = TypeBuilder->GetTypeInfoByIndex(TypeIndex); + assert(MemberTypeInfo != nullptr); + + MemberTypeInfo->Dump(TypeBuilder, Streamer, TypeSection, StrSection); +} + +void DwarfDataField::DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) { + // Abbrev Number + Streamer->EmitULEB128IntValue(DwarfAbbrev::ClassMember); + + // DW_AT_name + EmitSectionOffset(Streamer, StrSymbol, 4); + + // DW_AT_type + DwarfInfo *MemberTypeInfo = TypeBuilder->GetTypeInfoByIndex(TypeIndex); + assert(MemberTypeInfo != nullptr); + EmitInfoOffset(Streamer, MemberTypeInfo, 4); + + // DW_AT_data_member_location + Streamer->EmitIntValue(Offset, 4); +} + +// DwarfStaticDataField + +void DwarfStaticDataField::DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) { + // Abbrev Number + Streamer->EmitULEB128IntValue(DwarfAbbrev::ClassMemberStatic); + + // DW_AT_name + EmitSectionOffset(Streamer, StrSymbol, 4); + + // DW_AT_type + DwarfInfo *MemberTypeInfo = TypeBuilder->GetTypeInfoByIndex(TypeIndex); + assert(MemberTypeInfo != nullptr); + EmitInfoOffset(Streamer, MemberTypeInfo, 4); +} + +// DwarfClassTypeInfo + +DwarfClassTypeInfo::DwarfClassTypeInfo(const ClassTypeDescriptor &ClassDescriptor, + const ClassFieldsTypeDescriptior &ClassFieldsDescriptor, + const DataFieldDescriptor *FieldsDescriptors, + const StaticDataFieldDescriptor *StaticsDescriptors) : + Name(ClassDescriptor.Name), + IsStruct(ClassDescriptor.IsStruct), + BaseClassId(ClassDescriptor.BaseClassId), + Size(ClassDescriptor.InstanceSize), + IsForwardDecl(false) { + int32_t staticIdx = 0; + for (int32_t i = 0; i < ClassFieldsDescriptor.FieldsCount; i++) { + if (FieldsDescriptors[i].Offset == 0xFFFFFFFF) { + StaticFields.emplace_back(FieldsDescriptors[i], StaticsDescriptors[staticIdx++]); + } else { + Fields.emplace_back(FieldsDescriptors[i]); + } + } +} + +void DwarfClassTypeInfo::DumpTypes(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) { + if (IsDumpedTypes) + return; + + DwarfInfo::DumpTypes(TypeBuilder, Streamer, TypeSection, StrSection); + + if (BaseClassId != 0) { + DwarfInfo *BaseClassInfo = TypeBuilder->GetTypeInfoByIndex(BaseClassId); + assert(BaseClassInfo != nullptr); + + BaseClassInfo->Dump(TypeBuilder, Streamer, TypeSection, StrSection); + } + + for (auto &Field : Fields) { + Field.DumpTypes(TypeBuilder, Streamer, TypeSection, StrSection); + } + + for (auto &StaticField : StaticFields) { + StaticField.DumpTypes(TypeBuilder, Streamer, TypeSection, StrSection); + } + + for (auto *Function : MemberFunctions) { + Function->DumpTypes(TypeBuilder, Streamer, TypeSection, StrSection); + } +} + +void DwarfClassTypeInfo::Dump(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) { + if (IsDumped) + return; + + DwarfInfo::Dump(TypeBuilder, Streamer, TypeSection, StrSection); + + if (IsForwardDecl) + return; + + for (auto &Field : Fields) { + Field.Dump(TypeBuilder, Streamer, TypeSection, StrSection); + } + + for (auto &StaticField : StaticFields) { + StaticField.Dump(TypeBuilder, Streamer, TypeSection, StrSection); + } + + for (auto *Function : MemberFunctions) { + Function->Dump(TypeBuilder, Streamer, TypeSection, StrSection); + } + + // Terminate DIE + Streamer->SwitchSection(TypeSection); + Streamer->EmitIntValue(0, 1); +} + +void DwarfClassTypeInfo::DumpStrings(MCObjectStreamer *Streamer) { + Streamer->EmitBytes(StringRef(Name)); + Streamer->EmitIntValue(0, 1); +} + +void DwarfClassTypeInfo::DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) { + // Abbrev Number + Streamer->EmitULEB128IntValue(IsForwardDecl ? DwarfAbbrev::ClassTypeDecl : DwarfAbbrev::ClassType); + + // DW_AT_name + EmitSectionOffset(Streamer, StrSymbol, 4); + + if (!IsForwardDecl) { + // DW_AT_byte_size + Streamer->EmitIntValue(Size, 4); + } + + if (BaseClassId != 0) { + DwarfInfo *BaseClassInfo = TypeBuilder->GetTypeInfoByIndex(BaseClassId); + assert(BaseClassInfo != nullptr); + + // DW_TAG_inheritance DIE + + // Abbrev Number + Streamer->EmitULEB128IntValue(DwarfAbbrev::ClassInheritance); + + // DW_AT_type + EmitInfoOffset(Streamer, BaseClassInfo, 4); + + // DW_AT_data_member_location = 0 + Streamer->EmitIntValue(0, 1); + } +} + +// DwarfSimpleArrayTypeInfo + +void DwarfSimpleArrayTypeInfo::DumpTypes(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) { + if (IsDumpedTypes) + return; + + DwarfInfo::DumpTypes(TypeBuilder, Streamer, TypeSection, StrSection); + + DwarfInfo *ElementInfo = TypeBuilder->GetTypeInfoByIndex(ElementType); + assert(ElementInfo != nullptr); + + ElementInfo->Dump(TypeBuilder, Streamer, TypeSection, StrSection); +} + +void DwarfSimpleArrayTypeInfo::DumpStrings(MCObjectStreamer *Streamer) { + // nothing to dump +} + +void DwarfSimpleArrayTypeInfo::DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) { + // Abbrev Number + Streamer->EmitULEB128IntValue(DwarfAbbrev::ArrayType); + + DwarfInfo *Info = TypeBuilder->GetTypeInfoByIndex(ElementType); + assert(Info != nullptr); + + // DW_AT_type + EmitInfoOffset(Streamer, Info, 4); + + // DW_TAG_subrange_type DIE + + // Abbrev Number + Streamer->EmitULEB128IntValue(DwarfAbbrev::SubrangeType); + + // DW_AT_upper_bound + Streamer->EmitULEB128IntValue(Size - 1); + + // Terminate DIE + Streamer->EmitIntValue(0, 1); +} + +// DwarfPointerTypeInfo + +void DwarfPointerTypeInfo::DumpTypes(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) { + if (IsDumpedTypes) + return; + + DwarfInfo::DumpTypes(TypeBuilder, Streamer, TypeSection, StrSection); + + DwarfInfo *Info = TypeBuilder->GetTypeInfoByIndex(TypeDesc.ElementType); + assert(Info != nullptr); + + Info->Dump(TypeBuilder, Streamer, TypeSection, StrSection); +} + +void DwarfPointerTypeInfo::DumpStrings(MCObjectStreamer *Streamer) { + // nothing to dump +} + +void DwarfPointerTypeInfo::DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) { + // Abbrev Number + Streamer->EmitULEB128IntValue(TypeDesc.IsReference ? DwarfAbbrev::ReferenceType : DwarfAbbrev::PointerType); + + DwarfInfo *Info = TypeBuilder->GetTypeInfoByIndex(TypeDesc.ElementType); + assert(Info != nullptr); + + // DW_AT_type + EmitInfoOffset(Streamer, Info, 4); + + // DW_AT_byte_size + Streamer->EmitIntValue(TypeDesc.Is64Bit ? 8 : 4, 1); +} + +// DwarfMemberFunctionTypeInfo + +DwarfMemberFunctionTypeInfo::DwarfMemberFunctionTypeInfo( + const MemberFunctionTypeDescriptor& MemberDescriptor, + uint32_t const *const ArgumentTypes, + bool IsStaticMethod) : + TypeDesc(MemberDescriptor), + IsStaticMethod(IsStaticMethod) { + for (uint16_t i = 0; i < MemberDescriptor.NumberOfArguments; i++) { + this->ArgumentTypes.push_back(ArgumentTypes[i]); + } +} + +void DwarfMemberFunctionTypeInfo::DumpStrings(MCObjectStreamer *Streamer) { + // nothing to dump +} + +void DwarfMemberFunctionTypeInfo::DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) { + // nothing to dump +} + +// DwarfMemberFunctionIdTypeInfo + +void DwarfMemberFunctionIdTypeInfo::DumpTypes(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) { + if (IsDumpedTypes) + return; + + DwarfInfo::DumpTypes(TypeBuilder, Streamer, TypeSection, StrSection); + + // Dump return type + DwarfInfo *ReturnTypeInfo = TypeBuilder->GetTypeInfoByIndex(MemberFunctionTypeInfo->GetReturnTypeIndex()); + assert(ReturnTypeInfo != nullptr); + + ReturnTypeInfo->Dump(TypeBuilder, Streamer, TypeSection, StrSection); + + // Dump this pointer type + if (!MemberFunctionTypeInfo->IsStatic()) { + DwarfInfo *ThisPtrTypeInfo = TypeBuilder->GetTypeInfoByIndex(MemberFunctionTypeInfo->GetThisPtrTypeIndex()); + assert(ThisPtrTypeInfo != nullptr); + + ThisPtrTypeInfo->Dump(TypeBuilder, Streamer, TypeSection, StrSection); + } + + // Dump argument types + for (uint32_t ArgTypeIndex : MemberFunctionTypeInfo->GetArgTypes()) { + DwarfInfo *ArgTypeInfo = TypeBuilder->GetTypeInfoByIndex(ArgTypeIndex); + assert(ArgTypeInfo != nullptr); + ArgTypeInfo->Dump(TypeBuilder, Streamer, TypeSection, StrSection); + } +} + +void DwarfMemberFunctionIdTypeInfo::DumpStrings(MCObjectStreamer *Streamer) { + Streamer->EmitBytes(StringRef(Name)); + Streamer->EmitIntValue(0, 1); + + MCContext &context = Streamer->getContext(); + LinkageNameSymbol = context.createTempSymbol(); + Streamer->EmitLabel(LinkageNameSymbol); + Streamer->EmitBytes(StringRef(LinkageName)); + Streamer->EmitIntValue(0, 1); +} + +void DwarfMemberFunctionIdTypeInfo::DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) { + // Abbrev Number + bool IsStatic = MemberFunctionTypeInfo->IsStatic(); + + Streamer->EmitULEB128IntValue(IsStatic ? DwarfAbbrev::SubprogramStaticSpec : DwarfAbbrev::SubprogramSpec); + + // DW_AT_name + EmitSectionOffset(Streamer, StrSymbol, 4); + + // DW_AT_linkage_name + EmitSectionOffset(Streamer, LinkageNameSymbol, 4); + + // DW_AT_decl_file + Streamer->EmitIntValue(1, 1); + + // DW_AT_decl_line + Streamer->EmitIntValue(1, 1); + + // DW_AT_type + DwarfInfo *ReturnTypeInfo = TypeBuilder->GetTypeInfoByIndex(MemberFunctionTypeInfo->GetReturnTypeIndex()); + assert(ReturnTypeInfo != nullptr); + + EmitInfoOffset(Streamer, ReturnTypeInfo, 4); + + if (!IsStatic) { + // DW_AT_object_pointer + uint32_t Offset = Streamer->getOrCreateDataFragment()->getContents().size(); + + Streamer->EmitIntValue(Offset + 4, 4); + + // This formal parameter DIE + DwarfInfo *ThisTypeInfo = TypeBuilder->GetTypeInfoByIndex(MemberFunctionTypeInfo->GetThisPtrTypeIndex()); + assert(ThisTypeInfo != nullptr); + + // Abbrev Number + Streamer->EmitULEB128IntValue(DwarfAbbrev::FormalParameterThisSpec); + + // DW_AT_type + EmitInfoOffset(Streamer, ThisTypeInfo, 4); + } + + for (uint32_t ArgTypeIndex : MemberFunctionTypeInfo->GetArgTypes()) { + DwarfInfo *ArgTypeInfo = TypeBuilder->GetTypeInfoByIndex(ArgTypeIndex); + assert(ArgTypeInfo != nullptr); + + // Formal parameter DIE + + // Abbrev Number + Streamer->EmitULEB128IntValue(DwarfAbbrev::FormalParameterSpec); + + // DW_AT_type + EmitInfoOffset(Streamer, ArgTypeInfo, 4); + } + + // Ternimate DIE + Streamer->EmitIntValue(0, 1); +} + +// DwarfTypesBuilder + +void UserDefinedDwarfTypesBuilder::EmitTypeInformation( + MCSection *TypeSection, + MCSection *StrSection) { + for (auto &Info : DwarfTypes) { + Info->Dump(this, Streamer, TypeSection, StrSection); + } +} + +unsigned UserDefinedDwarfTypesBuilder::GetEnumTypeIndex( + const EnumTypeDescriptor &TypeDescriptor, + const EnumRecordTypeDescriptor *TypeRecords) { + unsigned TypeIndex = ArrayIndexToTypeIndex(DwarfTypes.size()); + UserDefinedTypes.push_back(std::make_pair(TypeDescriptor.Name, TypeIndex)); + DwarfTypes.push_back(make_unique(TypeDescriptor, TypeRecords)); + return TypeIndex; +} + +unsigned UserDefinedDwarfTypesBuilder::GetClassTypeIndex( + const ClassTypeDescriptor &ClassDescriptor) { + unsigned TypeIndex = ArrayIndexToTypeIndex(DwarfTypes.size()); + DwarfTypes.push_back(make_unique(ClassDescriptor)); + return TypeIndex; +} + +unsigned UserDefinedDwarfTypesBuilder::GetCompleteClassTypeIndex( + const ClassTypeDescriptor &ClassDescriptor, + const ClassFieldsTypeDescriptior &ClassFieldsDescriptor, + const DataFieldDescriptor *FieldsDescriptors, + const StaticDataFieldDescriptor *StaticsDescriptors) { + unsigned TypeIndex = ArrayIndexToTypeIndex(DwarfTypes.size()); + UserDefinedTypes.push_back(std::make_pair(ClassDescriptor.Name, TypeIndex)); + + DwarfClassTypeInfo *ClassTypeInfo = new DwarfClassTypeInfo(ClassDescriptor, ClassFieldsDescriptor, + FieldsDescriptors, StaticsDescriptors); + + DwarfTypes.push_back(std::unique_ptr(ClassTypeInfo)); + + if (ClassTypeInfo->GetStaticFields().size() > 0) { + ClassesWithStaticFields.push_back(ClassTypeInfo); + } + + return TypeIndex; +} + +unsigned UserDefinedDwarfTypesBuilder::GetArrayTypeIndex( + const ClassTypeDescriptor &ClassDescriptor, + const ArrayTypeDescriptor &ArrayDescriptor) { + // Create corresponding class info + ClassTypeDescriptor ArrayClassDescriptor = ClassDescriptor; + + std::vector FieldDescs; + unsigned FieldOffset = TargetPointerSize; + + FieldDescs.push_back({GetPrimitiveTypeIndex(PrimitiveTypeFlags::Int32), FieldOffset, "m_NumComponents"}); + FieldOffset += TargetPointerSize; + + if (ArrayDescriptor.IsMultiDimensional == 1) { + unsigned BoundsTypeIndex = GetSimpleArrayTypeIndex(GetPrimitiveTypeIndex(PrimitiveTypeFlags::Int32), ArrayDescriptor.Rank); + FieldDescs.push_back({BoundsTypeIndex, FieldOffset, "m_Bounds"}); + FieldOffset += 2 * 4 * ArrayDescriptor.Rank; + } + + unsigned DataTypeIndex = GetSimpleArrayTypeIndex(ArrayDescriptor.ElementType, 0); + FieldDescs.push_back({DataTypeIndex, FieldOffset, "m_Data"}); + + ClassFieldsTypeDescriptior FieldsTypeDesc = + {TargetPointerSize, ArrayDescriptor.IsMultiDimensional ? 3 : 2}; + + ArrayClassDescriptor.InstanceSize = FieldOffset; + + unsigned TypeIndex = ArrayIndexToTypeIndex(DwarfTypes.size()); + UserDefinedTypes.push_back(std::make_pair(ArrayClassDescriptor.Name, TypeIndex)); + DwarfTypes.push_back(make_unique(ArrayClassDescriptor, FieldsTypeDesc, FieldDescs.data(), nullptr)); + + return TypeIndex; +} + +unsigned UserDefinedDwarfTypesBuilder::GetPointerTypeIndex(const PointerTypeDescriptor& PointerDescriptor) +{ + unsigned TypeIndex = ArrayIndexToTypeIndex(DwarfTypes.size()); + DwarfTypes.push_back(make_unique(PointerDescriptor)); + return TypeIndex; +} + +unsigned UserDefinedDwarfTypesBuilder::GetMemberFunctionTypeIndex(const MemberFunctionTypeDescriptor& MemberDescriptor, + uint32_t const *const ArgumentTypes) +{ + unsigned TypeIndex = ArrayIndexToTypeIndex(DwarfTypes.size()); + bool IsStatic = MemberDescriptor.TypeIndexOfThisPointer == GetPrimitiveTypeIndex(PrimitiveTypeFlags::Void); + DwarfTypes.push_back(make_unique(MemberDescriptor, ArgumentTypes, IsStatic)); + return TypeIndex; +} + +unsigned UserDefinedDwarfTypesBuilder::GetMemberFunctionId(const MemberFunctionIdTypeDescriptor& MemberIdDescriptor) +{ + unsigned TypeIndex = ArrayIndexToTypeIndex(DwarfTypes.size()); + + DwarfMemberFunctionTypeInfo *MemberFunctionTypeInfo = static_cast( + GetTypeInfoByIndex(MemberIdDescriptor.MemberFunction)); + assert(MemberFunctionTypeInfo != nullptr); + + DwarfMemberFunctionIdTypeInfo *MemberFunctionIdTypeInfo = + new DwarfMemberFunctionIdTypeInfo(MemberIdDescriptor, MemberFunctionTypeInfo); + + DwarfTypes.push_back(std::unique_ptr(MemberFunctionIdTypeInfo)); + + DwarfClassTypeInfo *ParentClassInfo = static_cast( + GetTypeInfoByIndex(MemberIdDescriptor.ParentClass)); + assert(ParentClassInfo != nullptr); + + ParentClassInfo->AddMemberFunction(MemberFunctionIdTypeInfo); + + return TypeIndex; +} + +unsigned UserDefinedDwarfTypesBuilder::GetPrimitiveTypeIndex(PrimitiveTypeFlags Type) { + auto Iter = PrimitiveDwarfTypes.find(Type); + if (Iter != PrimitiveDwarfTypes.end()) + return Iter->second; + + unsigned TypeIndex = ArrayIndexToTypeIndex(DwarfTypes.size()); + DwarfTypes.push_back(make_unique(Type)); + + PrimitiveDwarfTypes.insert(std::make_pair(Type, TypeIndex)); + + return TypeIndex; +} + +unsigned UserDefinedDwarfTypesBuilder::GetSimpleArrayTypeIndex(unsigned ElemIndex, unsigned Size) { + auto Iter = SimpleArrayDwarfTypes.find(ElemIndex); + if (Iter != SimpleArrayDwarfTypes.end()) { + auto CountMap = Iter->second; + auto CountIter = CountMap.find(Size); + if (CountIter != CountMap.end()) + return CountIter->second; + } + + unsigned TypeIndex = ArrayIndexToTypeIndex(DwarfTypes.size()); + DwarfTypes.push_back(make_unique(ElemIndex, Size)); + + SimpleArrayDwarfTypes[ElemIndex][Size] = TypeIndex; + + return TypeIndex; +} \ No newline at end of file diff --git a/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfTypeBuilder.h b/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfTypeBuilder.h new file mode 100644 index 0000000000..0ea43a4511 --- /dev/null +++ b/external/corert/src/Native/ObjWriter/debugInfo/dwarf/dwarfTypeBuilder.h @@ -0,0 +1,366 @@ +//===---- dwarfTypeBuilder.h ------------------------------------*- C++ -*-===// +// +// type builder is used to convert .Net types into Dwarf debuginfo. +// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "debugInfo/typeBuilder.h" + +#include +#include + +class UserDefinedDwarfTypesBuilder; + +class DwarfInfo +{ +public: + DwarfInfo() : + StrSymbol(nullptr), + InfoSymbol(nullptr), + IsDumped(false), + IsDumpedTypes(false) {} + + virtual ~DwarfInfo() {} + + virtual void Dump(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection); + + virtual void DumpTypes(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection); + + MCSymbol *GetInfoSymbol() { return InfoSymbol; } + + const MCExpr *GetInfoExpr() { return InfoExpr; } + +protected: + virtual void DumpStrings(MCObjectStreamer *Streamer) = 0; + virtual void DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) = 0; + + static void EmitSectionOffset(MCObjectStreamer *Streamer, + MCSymbol *Symbol, + unsigned Size, + uint32_t Offset = 0); + + static const MCExpr *CreateOffsetExpr(MCContext &Context, + MCSymbol *BeginSymbol, + MCSymbol *Symbol); + + static void EmitOffset(MCObjectStreamer *Streamer, + const MCExpr *OffsetExpr, + unsigned Size); + + static void EmitInfoOffset(MCObjectStreamer *Streamer, const DwarfInfo *Info, unsigned Size); + + MCSymbol *StrSymbol; + MCSymbol *InfoSymbol; + const MCExpr *InfoExpr; + + bool IsDumped; + bool IsDumpedTypes; +}; + +class DwarfPrimitiveTypeInfo : public DwarfInfo +{ +public: + DwarfPrimitiveTypeInfo(PrimitiveTypeFlags PrimitiveType) : Type(PrimitiveType) {} + + PrimitiveTypeFlags GetType() { return Type; } + +protected: + void DumpStrings(MCObjectStreamer *Streamer) override; + void DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) override; + +private: + PrimitiveTypeFlags Type; +}; + +class DwarfEnumTypeInfo; + +class DwarfEnumerator : public DwarfInfo +{ +public: + DwarfEnumerator(const EnumRecordTypeDescriptor &Descriptor, DwarfEnumTypeInfo *TypeInfo) : + Name(Descriptor.Name), Value(Descriptor.Value), EnumTypeInfo(TypeInfo) {} + +protected: + void DumpStrings(MCObjectStreamer *Streamer) override; + void DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) override; + +private: + std::string Name; + uint64 Value; + DwarfEnumTypeInfo *EnumTypeInfo; +}; + +class DwarfEnumTypeInfo : public DwarfInfo +{ +public: + DwarfEnumTypeInfo(const EnumTypeDescriptor &TypeDescriptor, + const EnumRecordTypeDescriptor *TypeRecords); + + void Dump(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) override; + + void DumpTypes(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) override; + + uint8_t GetByteSize() const { return ByteSize; } + +protected: + void DumpStrings(MCObjectStreamer *Streamer) override; + void DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) override; + +private: + std::string Name; + uint32_t ElementType; + std::vector Records; + uint8_t ByteSize; +}; + +class DwarfDataField : public DwarfInfo +{ +public: + DwarfDataField(const DataFieldDescriptor &Descriptor) : + Name(Descriptor.Name), + TypeIndex(Descriptor.FieldTypeIndex), + Offset(Descriptor.Offset) {} + + void DumpTypes(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) override; + + uint32_t GetTypeIndex() const { return TypeIndex; } + + const std::string &GetName() const { return Name; } + +protected: + void DumpStrings(MCObjectStreamer *Streamer) override; + void DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) override; + + std::string Name; + uint32_t TypeIndex; + uint64 Offset; +}; + +class DwarfStaticDataField : public DwarfDataField +{ +public: + DwarfStaticDataField(const DataFieldDescriptor &Descriptor, + const StaticDataFieldDescriptor &StaticDescriptor) : + DwarfDataField(Descriptor), + StaticDataName(StaticDescriptor.StaticDataName), + StaticOffset(StaticDescriptor.StaticOffset), + StaticDataInObject(StaticDescriptor.IsStaticDataInObject) {} + + const std::string &GetStaticDataName() const { return StaticDataName; } + uint64 GetStaticOffset() const { return StaticOffset; } + bool IsStaticDataInObject() const { return StaticDataInObject; } + +protected: + void DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) override; + +private: + std::string StaticDataName; + uint64 StaticOffset; + bool StaticDataInObject; +}; + +class DwarfMemberFunctionIdTypeInfo; + +class DwarfClassTypeInfo : public DwarfInfo +{ +public: + DwarfClassTypeInfo(const ClassTypeDescriptor &ClassDescriptor) : + Name(ClassDescriptor.Name), + IsStruct(ClassDescriptor.IsStruct), + BaseClassId(ClassDescriptor.BaseClassId), + Size(ClassDescriptor.InstanceSize), + IsForwardDecl(true) {} + + DwarfClassTypeInfo(const ClassTypeDescriptor &ClassDescriptor, + const ClassFieldsTypeDescriptior &ClassFieldsDescriptor, + const DataFieldDescriptor *FieldsDescriptors, + const StaticDataFieldDescriptor *StaticsDescriptors); + + void Dump(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) override; + + void DumpTypes(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) override; + + void AddMemberFunction(DwarfMemberFunctionIdTypeInfo* TypeInfo) { + MemberFunctions.push_back(TypeInfo); + } + + const std::vector &GetStaticFields() const { return StaticFields; } + + const std::string &GetName() const { return Name; } + +protected: + void DumpStrings(MCObjectStreamer *Streamer) override; + void DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) override; + +private: + std::string Name; + bool IsStruct; + uint32_t BaseClassId; + uint64 Size; + bool IsForwardDecl; + std::vector Fields; + std::vector StaticFields; + std::vector MemberFunctions; +}; + +class DwarfSimpleArrayTypeInfo : public DwarfInfo +{ +public: + DwarfSimpleArrayTypeInfo(uint32_t ArrayElementType, uint64_t Size) : + ElementType(ArrayElementType), + Size(Size) {} + + void DumpTypes(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) override; + +protected: + void DumpStrings(MCObjectStreamer *Streamer) override; + void DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) override; + +private: + uint32_t ElementType; + uint64_t Size; +}; + +class DwarfPointerTypeInfo : public DwarfInfo +{ +public: + DwarfPointerTypeInfo(const PointerTypeDescriptor& PointerDescriptor) : + TypeDesc(PointerDescriptor) {} + + void DumpTypes(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) override; + +protected: + void DumpStrings(MCObjectStreamer *Streamer) override; + void DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) override; + +private: + PointerTypeDescriptor TypeDesc; +}; + +class DwarfMemberFunctionTypeInfo : public DwarfInfo +{ +public: + DwarfMemberFunctionTypeInfo(const MemberFunctionTypeDescriptor& MemberDescriptor, + uint32_t const *const ArgumentTypes, + bool IsStaticMethod); + + const std::vector &GetArgTypes() const { return ArgumentTypes; } + + bool IsStatic() const { return IsStaticMethod; } + + uint32_t GetReturnTypeIndex() const { return TypeDesc.ReturnType; } + + uint32_t GetThisPtrTypeIndex() const { return TypeDesc.TypeIndexOfThisPointer; } + +protected: + void DumpStrings(MCObjectStreamer *Streamer) override; + void DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) override; + +private: + MemberFunctionTypeDescriptor TypeDesc; + std::vector ArgumentTypes; + bool IsStaticMethod; +}; + +class DwarfMemberFunctionIdTypeInfo : public DwarfInfo +{ +public: + DwarfMemberFunctionIdTypeInfo(const MemberFunctionIdTypeDescriptor& MemberIdDescriptor, + DwarfMemberFunctionTypeInfo *TypeInfo) : + LinkageName(MemberIdDescriptor.Name), + Name(MemberIdDescriptor.Name), + ParentClass(MemberIdDescriptor.ParentClass), + MemberFunctionTypeInfo(TypeInfo), + LinkageNameSymbol(nullptr) {} + + const std::vector &GetArgTypes() const { return MemberFunctionTypeInfo->GetArgTypes(); } + + void SetLinkageName(const char *Name) { LinkageName = Name; } + + void DumpTypes(UserDefinedDwarfTypesBuilder *TypeBuilder, MCObjectStreamer *Streamer, + MCSection *TypeSection, MCSection *StrSection) override; + + bool IsStatic() const { return MemberFunctionTypeInfo->IsStatic(); } + +protected: + void DumpStrings(MCObjectStreamer *Streamer) override; + void DumpTypeInfo(MCObjectStreamer *Streamer, UserDefinedDwarfTypesBuilder *TypeBuilder) override; + +private: + std::string LinkageName; + std::string Name; + uint32_t ParentClass; + DwarfMemberFunctionTypeInfo *MemberFunctionTypeInfo; + MCSymbol *LinkageNameSymbol; +}; + +template +class EnumHash +{ + typedef typename std::underlying_type::type enumType; +public: + size_t operator()(const T& elem) const { + return std::hash()(static_cast(elem)); + } +}; + +class UserDefinedDwarfTypesBuilder : public UserDefinedTypesBuilder +{ +public: + UserDefinedDwarfTypesBuilder() {} + void EmitTypeInformation(MCSection *TypeSection, MCSection *StrSection = nullptr) override; + + unsigned GetEnumTypeIndex(const EnumTypeDescriptor &TypeDescriptor, + const EnumRecordTypeDescriptor *TypeRecords) override; + unsigned GetClassTypeIndex(const ClassTypeDescriptor &ClassDescriptor) override; + unsigned GetCompleteClassTypeIndex( + const ClassTypeDescriptor &ClassDescriptor, + const ClassFieldsTypeDescriptior &ClassFieldsDescriptor, + const DataFieldDescriptor *FieldsDescriptors, + const StaticDataFieldDescriptor *StaticsDescriptors) override; + + unsigned GetArrayTypeIndex(const ClassTypeDescriptor &ClassDescriptor, + const ArrayTypeDescriptor &ArrayDescriptor) override; + + unsigned GetPointerTypeIndex(const PointerTypeDescriptor& PointerDescriptor) override; + + unsigned GetMemberFunctionTypeIndex(const MemberFunctionTypeDescriptor& MemberDescriptor, + uint32_t const *const ArgumentTypes) override; + + unsigned GetMemberFunctionId(const MemberFunctionIdTypeDescriptor& MemberIdDescriptor) override; + + unsigned GetPrimitiveTypeIndex(PrimitiveTypeFlags Type) override; + + DwarfInfo *GetTypeInfoByIndex(unsigned Index) const { return DwarfTypes[TypeIndexToArrayIndex(Index)].get(); } + + unsigned GetSimpleArrayTypeIndex(unsigned ElemIndex, unsigned Size); + + const std::vector &GetClassesWithStaticFields() const { return ClassesWithStaticFields; } + +private: + static const unsigned StartTypeIndex = 1; // Make TypeIndex 0 - Invalid + static unsigned TypeIndexToArrayIndex(unsigned TypeIndex) { return TypeIndex - StartTypeIndex; } + static unsigned ArrayIndexToTypeIndex(unsigned ArrayIndex) { return ArrayIndex + StartTypeIndex; } + + std::vector> DwarfTypes; + std::unordered_map> PrimitiveDwarfTypes; + // map[ElemTypeIndex][Size] -> ArrTypeIndex + std::unordered_map> SimpleArrayDwarfTypes; + + std::vector ClassesWithStaticFields; +}; \ No newline at end of file diff --git a/external/corert/src/Native/ObjWriter/debugInfo/typeBuilder.h b/external/corert/src/Native/ObjWriter/debugInfo/typeBuilder.h new file mode 100644 index 0000000000..f3e3046e50 --- /dev/null +++ b/external/corert/src/Native/ObjWriter/debugInfo/typeBuilder.h @@ -0,0 +1,158 @@ +//===---- typeBuilder.h -----------------------------------------*- C++ -*-===// +// +// type builder is used to convert .Net types into debuginfo. +// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "llvm/MC/MCObjectStreamer.h" + +#include +#include + +using namespace llvm; + +// Keep in sync with Internal.TypeSystem.TypeFlags (Common/src/TypeSystem/Common/TypeFlags.cs) +enum class PrimitiveTypeFlags { + Unknown = 0x00, + Void = 0x01, + Boolean = 0x02, + Char = 0x03, + SByte = 0x04, + Byte = 0x05, + Int16 = 0x06, + UInt16 = 0x07, + Int32 = 0x08, + UInt32 = 0x09, + Int64 = 0x0A, + UInt64 = 0x0B, + IntPtr = 0x0C, + UIntPtr = 0x0D, + Single = 0x0E, + Double = 0x0F +}; + +typedef unsigned long long uint64; + +#pragma pack(push, 8) + +extern "C" struct EnumRecordTypeDescriptor { + uint64 Value; + const char *Name; +}; + +extern "C" struct EnumTypeDescriptor { + uint32_t ElementType; + uint64 ElementCount; + const char *Name; +}; + +extern "C" struct ClassTypeDescriptor { + int32_t IsStruct; + const char *Name; + uint32_t BaseClassId; + uint64 InstanceSize; +}; + +extern "C" struct DataFieldDescriptor { + uint32_t FieldTypeIndex; + uint64 Offset; + const char *Name; +}; + +extern "C" struct StaticDataFieldDescriptor { + const char *StaticDataName; + uint64 StaticOffset; + int IsStaticDataInObject; +}; + +extern "C" struct ClassFieldsTypeDescriptior { + uint64 Size; + int32_t FieldsCount; +}; + +extern "C" struct ArrayTypeDescriptor { + uint32_t Rank; + uint32_t ElementType; + uint32_t Size; // ElementSize + int32_t IsMultiDimensional; +}; + +extern "C" struct PointerTypeDescriptor { + uint32_t ElementType; + int32_t IsReference; + int32_t IsConst; + int32_t Is64Bit; +}; + +extern "C" struct MemberFunctionTypeDescriptor { + uint32_t ReturnType; + uint32_t ContainingClass; + uint32_t TypeIndexOfThisPointer; + int32_t ThisAdjust; + uint32_t CallingConvention; + uint16_t NumberOfArguments; +}; + +extern "C" struct MemberFunctionIdTypeDescriptor { + uint32_t MemberFunction; + uint32_t ParentClass; + const char *Name; +}; + +#pragma pack(pop) +class UserDefinedTypesBuilder { +public: + UserDefinedTypesBuilder() : Streamer(nullptr), TargetPointerSize(0) {} + virtual ~UserDefinedTypesBuilder() {} + void SetStreamer(MCObjectStreamer *Streamer) { + assert(this->Streamer == nullptr); + assert(Streamer != nullptr); + this->Streamer = Streamer; + } + MCObjectStreamer *GetStreamer() const { + return Streamer; + } + void SetTargetPointerSize(unsigned TargetPointerSize) { + assert(this->TargetPointerSize == 0); + assert(TargetPointerSize != 0); + this->TargetPointerSize = TargetPointerSize; + } + virtual void EmitTypeInformation(MCSection *TypeSection, MCSection *StrSection = nullptr) = 0; + + virtual unsigned GetEnumTypeIndex(const EnumTypeDescriptor &TypeDescriptor, + const EnumRecordTypeDescriptor *TypeRecords) = 0; + virtual unsigned GetClassTypeIndex(const ClassTypeDescriptor &ClassDescriptor) = 0; + virtual unsigned GetCompleteClassTypeIndex( + const ClassTypeDescriptor &ClassDescriptor, + const ClassFieldsTypeDescriptior &ClassFieldsDescriptor, + const DataFieldDescriptor *FieldsDescriptors, + const StaticDataFieldDescriptor *StaticsDescriptors) = 0; + + virtual unsigned GetArrayTypeIndex(const ClassTypeDescriptor &ClassDescriptor, + const ArrayTypeDescriptor &ArrayDescriptor) = 0; + + virtual unsigned GetPointerTypeIndex(const PointerTypeDescriptor& PointerDescriptor) = 0; + + virtual unsigned GetMemberFunctionTypeIndex(const MemberFunctionTypeDescriptor& MemberDescriptor, + uint32_t const *const ArgumentTypes) = 0; + + virtual unsigned GetMemberFunctionId(const MemberFunctionIdTypeDescriptor& MemberIdDescriptor) = 0; + + virtual unsigned GetPrimitiveTypeIndex(PrimitiveTypeFlags Type) = 0; + + virtual const std::vector> &GetUDTs() { + return UserDefinedTypes; + } + +protected: + MCObjectStreamer *Streamer; + unsigned TargetPointerSize; + + std::vector> UserDefinedTypes; +}; \ No newline at end of file diff --git a/external/corert/src/Native/ObjWriter/jitDebugInfo.h b/external/corert/src/Native/ObjWriter/jitDebugInfo.h index 103dff8ad1..ec63c3dfb4 100644 --- a/external/corert/src/Native/ObjWriter/jitDebugInfo.h +++ b/external/corert/src/Native/ObjWriter/jitDebugInfo.h @@ -26,6 +26,18 @@ struct DebugVarInfo { : Name(ArgName), TypeIndex(ArgTypeIndex), IsParam(ArgIsParam) {} }; +struct DebugEHClauseInfo { + unsigned TryOffset; + unsigned TryLength; + unsigned HandlerOffset; + unsigned HandlerLength; + + DebugEHClauseInfo(unsigned TryOffset, unsigned TryLength, + unsigned HandlerOffset, unsigned HandlerLength) : + TryOffset(TryOffset), TryLength(TryLength), + HandlerOffset(HandlerOffset), HandlerLength(HandlerLength) {} +}; + typedef unsigned short CVRegMapping; #define CVREGDAT(p2, cv) cv diff --git a/external/corert/src/Native/ObjWriter/llvm.patch b/external/corert/src/Native/ObjWriter/llvm.patch index fd8420125e..67ae23ec95 100644 --- a/external/corert/src/Native/ObjWriter/llvm.patch +++ b/external/corert/src/Native/ObjWriter/llvm.patch @@ -15,7 +15,7 @@ index 7c1189e..d1d77c9 100644 /// can change its size during relaxation. virtual void EmitInstToFragment(const MCInst &Inst, const MCSubtargetInfo &); diff --git a/include/llvm/MC/MCStreamer.h b/include/llvm/MC/MCStreamer.h -index 5390e79..e28a3cc 100644 +index 5390e79..5b258e7 100644 --- a/include/llvm/MC/MCStreamer.h +++ b/include/llvm/MC/MCStreamer.h @@ -115,6 +115,7 @@ public: @@ -26,6 +26,16 @@ index 5390e79..e28a3cc 100644 virtual void emitUnwindRaw(int64_t StackOffset, const SmallVectorImpl &Opcodes); +@@ -548,6 +549,9 @@ public: + /// etc. + virtual void EmitBytes(StringRef Data); + ++ /// \brief Emit the given \p Instruction data into the current section. ++ virtual void EmitInstructionBytes(StringRef Data); ++ + /// Functionally identical to EmitBytes. When emitting textual assembly, this + /// method uses .byte directives instead of .ascii or .asciz for readability. + virtual void EmitBinaryData(StringRef Data); diff --git a/lib/MC/MCObjectStreamer.cpp b/lib/MC/MCObjectStreamer.cpp index 174397e..ef7161f 100644 --- a/lib/MC/MCObjectStreamer.cpp @@ -57,6 +67,18 @@ index 174397e..ef7161f 100644 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) { // We need to create a local symbol to avoid relocations. Frame.Begin = getContext().createTempSymbol(); +diff --git a/lib/MC/MCStreamer.cpp b/lib/MC/MCStreamer.cpp +index 2bfb9a6..a710098 100644 +--- a/lib/MC/MCStreamer.cpp ++++ b/lib/MC/MCStreamer.cpp +@@ -830,6 +830,7 @@ void MCStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, + void MCStreamer::ChangeSection(MCSection *, const MCExpr *) {} + void MCStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {} + void MCStreamer::EmitBytes(StringRef Data) {} ++void MCStreamer::EmitInstructionBytes(StringRef Data) { EmitBytes(Data); } + void MCStreamer::EmitBinaryData(StringRef Data) { EmitBytes(Data); } + void MCStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc) { + visitUsedExpr(*Value); diff --git a/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp b/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp index a77df7a..e1aa752 100644 --- a/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp @@ -122,7 +144,7 @@ index 59f31be..9b95598 100644 case ARM::fixup_arm_uncondbl: switch (Modifier) { diff --git a/lib/Target/ARM/MCTargetDesc/ARMELFStreamer.cpp b/lib/Target/ARM/MCTargetDesc/ARMELFStreamer.cpp -index 93f4006..67ae439 100644 +index 93f4006..81e4caa 100644 --- a/lib/Target/ARM/MCTargetDesc/ARMELFStreamer.cpp +++ b/lib/Target/ARM/MCTargetDesc/ARMELFStreamer.cpp @@ -396,6 +396,7 @@ private: @@ -141,7 +163,26 @@ index 93f4006..67ae439 100644 void emitUnwindRaw(int64_t Offset, const SmallVectorImpl &Opcodes); void ChangeSection(MCSection *Section, const MCExpr *Subsection) override { -@@ -698,6 +700,7 @@ private: +@@ -533,6 +535,18 @@ public: + MCELFStreamer::EmitBytes(Data); + } + ++ /// This function is the one used to emit instruction data into the ELF ++ /// streamer. We override it to add the appropriate mapping symbol if ++ /// necessary. ++ void EmitInstructionBytes(StringRef Data) override { ++ if (IsThumb) ++ EmitThumbMappingSymbol(); ++ else ++ EmitARMMappingSymbol(); ++ ++ MCELFStreamer::EmitBytes(Data); ++ } ++ + void FlushPendingMappingSymbol() { + if (!LastEMSInfo->hasInfo()) + return; +@@ -698,6 +712,7 @@ private: bool CantUnwind; SmallVector Opcodes; UnwindOpcodeAssembler UnwindOpAsm; @@ -149,7 +190,7 @@ index 93f4006..67ae439 100644 }; } // end anonymous namespace -@@ -740,6 +743,10 @@ void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl &RegList, +@@ -740,6 +755,10 @@ void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl &RegList, getStreamer().emitRegSave(RegList, isVector); } @@ -160,7 +201,7 @@ index 93f4006..67ae439 100644 void ARMTargetELFStreamer::emitUnwindRaw(int64_t Offset, const SmallVectorImpl &Opcodes) { getStreamer().emitUnwindRaw(Offset, Opcodes); -@@ -1233,6 +1240,7 @@ void ARMELFStreamer::EHReset() { +@@ -1233,6 +1252,7 @@ void ARMELFStreamer::EHReset() { PendingOffset = 0; UsedFP = false; CantUnwind = false; @@ -168,7 +209,7 @@ index 93f4006..67ae439 100644 Opcodes.clear(); UnwindOpAsm.Reset(); -@@ -1330,6 +1338,8 @@ void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) { +@@ -1330,6 +1350,8 @@ void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) { } // Finalize the unwind opcode sequence @@ -177,7 +218,7 @@ index 93f4006..67ae439 100644 UnwindOpAsm.Finalize(PersonalityIndex, Opcodes); // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx -@@ -1374,7 +1384,13 @@ void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) { +@@ -1374,7 +1396,13 @@ void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) { // // In case that the .handlerdata directive is not specified by the // programmer, we should emit zero to terminate the handler data. @@ -192,7 +233,7 @@ index 93f4006..67ae439 100644 EmitIntValue(0, 4); } -@@ -1457,6 +1473,10 @@ void ARMELFStreamer::emitRegSave(const SmallVectorImpl &RegList, +@@ -1457,6 +1485,10 @@ void ARMELFStreamer::emitRegSave(const SmallVectorImpl &RegList, UnwindOpAsm.EmitRegSave(Mask); } diff --git a/external/corert/src/Native/ObjWriter/llvmCap/CMakeLists.txt b/external/corert/src/Native/ObjWriter/llvmCap/CMakeLists.txt index a749ea8782..07dca10e93 100644 --- a/external/corert/src/Native/ObjWriter/llvmCap/CMakeLists.txt +++ b/external/corert/src/Native/ObjWriter/llvmCap/CMakeLists.txt @@ -116,14 +116,32 @@ ExternalProject_Add(LLVM ExternalProject_Get_Property(LLVM source_dir) set(LLVM_SOURCE_DIR ${source_dir}) ExternalProject_Add_Step(LLVM PatchingLLVM - COMMAND git apply --3way ${OBJWRITER_ROOT}/llvm.patch COMMENT "Applying LLVM patch with ObjWriter fixes" + COMMAND git checkout -- . + COMMAND git apply ${OBJWRITER_ROOT}/llvm.patch COMMENT "Applying LLVM patch with ObjWriter fixes" WORKING_DIRECTORY ${LLVM_SOURCE_DIR} DEPENDEES patch USES_TERMINAL 1 ) + +if(CMAKE_HOST_WIN32) +ExternalProject_Add_Step(LLVM ObjWriterInjection + COMMAND ${CMAKE_COMMAND} -E copy_directory ${OBJWRITER_ROOT} ${OBJWRITER_LLVM_POINT} COMMENT "copy ${OBJWRITER_ROOT} -> ${OBJWRITER_LLVM_POINT}" + WORKING_DIRECTORY ${LLVM_SOURCE_DIR} + DEPENDEES patch + USES_TERMINAL 1 + ) +else() ExternalProject_Add_Step(LLVM ObjWriterInjection COMMAND ${CMAKE_COMMAND} -E create_symlink ${OBJWRITER_ROOT} ${OBJWRITER_LLVM_POINT} COMMENT "mklink ${OBJWRITER_ROOT} -> ${OBJWRITER_LLVM_POINT}" WORKING_DIRECTORY ${LLVM_SOURCE_DIR} DEPENDEES patch USES_TERMINAL 1 ) +endif() + +ExternalProject_Add_Step(LLVM forceconfigure + COMMAND ${CMAKE_COMMAND} -E echo "Force configure of LLVM" + DEPENDEES update + DEPENDERS configure + ALWAYS 1 + ) diff --git a/external/corert/src/Native/ObjWriter/objwriter.cpp b/external/corert/src/Native/ObjWriter/objwriter.cpp index 55f79aa479..bdf1016dc6 100644 --- a/external/corert/src/Native/ObjWriter/objwriter.cpp +++ b/external/corert/src/Native/ObjWriter/objwriter.cpp @@ -1,10 +1,10 @@ -//===---- objwriter.cpp --------------------------------*- C++ -*-===// +//===---- objwriter.cpp -----------------------------------------*- C++ -*-===// // // object writer // -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. -// See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. // //===----------------------------------------------------------------------===// /// @@ -14,6 +14,8 @@ //===----------------------------------------------------------------------===// #include "objwriter.h" +#include "debugInfo/dwarf/dwarfTypeBuilder.h" +#include "debugInfo/codeView/codeViewTypeBuilder.h" #include "llvm/DebugInfo/CodeView/CodeView.h" #include "llvm/DebugInfo/CodeView/Line.h" #include "llvm/DebugInfo/CodeView/SymbolRecord.h" @@ -162,9 +164,18 @@ bool ObjectWriter::Init(llvm::StringRef ObjectFilePath) { SetCodeSectionAttribute("text", CustomSectionAttributes_Executable, nullptr); if (ObjFileInfo->getObjectFileType() == ObjFileInfo->IsCOFF) { - TypeBuilder.SetStreamer(Streamer); - unsigned TargetPointerSize = AssemblerPrinter->getPointerSize(); - TypeBuilder.SetTargetPointerSize(TargetPointerSize); + TypeBuilder.reset(new UserDefinedCodeViewTypesBuilder()); + } else { + TypeBuilder.reset(new UserDefinedDwarfTypesBuilder()); + } + + TypeBuilder->SetStreamer(Streamer); + unsigned TargetPointerSize = AssemblerPrinter->getPointerSize(); + TypeBuilder->SetTargetPointerSize(TargetPointerSize); + + if (ObjFileInfo->getObjectFileType() == ObjFileInfo->IsELF) { + DwarfGenerator.reset(new DwarfGen()); + DwarfGenerator->SetTypeBuilder(static_cast(TypeBuilder.get())); } return true; @@ -294,7 +305,11 @@ void ObjectWriter::EmitAlignment(int ByteAlignment) { } void ObjectWriter::EmitBlob(int BlobSize, const char *Blob) { - Streamer->EmitBytes(StringRef(Blob, BlobSize)); + if (Streamer->getCurrentSectionOnly()->getKind().isText()) { + Streamer->EmitInstructionBytes(StringRef(Blob, BlobSize)); + } else { + Streamer->EmitBytes(StringRef(Blob, BlobSize)); + } } void ObjectWriter::EmitIntValue(uint64_t Value, unsigned Size) { @@ -690,6 +705,22 @@ void ObjectWriter::EmitCVDebugFunctionInfo(const char *FunctionName, Streamer->EmitCVLinetableDirective(FuncId++, Fn, FnEnd); } +void ObjectWriter::EmitDwarfFunctionInfo(const char *FunctionName, + int FunctionSize, + unsigned MethodTypeIndex) { + if (FuncId == 1) { + DwarfGenerator->EmitCompileUnit(); + } + + DwarfGenerator->EmitSubprogramInfo(FunctionName, FunctionSize, + MethodTypeIndex, DebugVarInfos, DebugEHClauseInfos); + + DebugVarInfos.clear(); + DebugEHClauseInfos.clear(); + + FuncId++; +} + void ObjectWriter::EmitDebugFileInfo(int FileId, const char *FileName) { assert(FileId > 0 && "FileId should be greater than 0."); if (ObjFileInfo->getObjectFileType() == ObjFileInfo->IsCOFF) { @@ -700,7 +731,8 @@ void ObjectWriter::EmitDebugFileInfo(int FileId, const char *FileName) { } void ObjectWriter::EmitDebugFunctionInfo(const char *FunctionName, - int FunctionSize) { + int FunctionSize, + unsigned MethodTypeIndex) { if (ObjFileInfo->getObjectFileType() == ObjFileInfo->IsCOFF) { Streamer->EmitCVFuncIdDirective(FuncId); EmitCVDebugFunctionInfo(FunctionName, FunctionSize); @@ -710,6 +742,7 @@ void ObjectWriter::EmitDebugFunctionInfo(const char *FunctionName, Streamer->EmitSymbolAttribute(Sym, MCSA_ELF_TypeFunction); Streamer->emitELFSize(Sym, MCConstantExpr::create(FunctionSize, *OutContext)); + EmitDwarfFunctionInfo(FunctionName, FunctionSize, MethodTypeIndex); } // TODO: Should test it for Macho. } @@ -729,6 +762,13 @@ void ObjectWriter::EmitDebugVar(char *Name, int TypeIndex, bool IsParm, DebugVarInfos.push_back(NewVar); } +void ObjectWriter::EmitDebugEHClause(unsigned TryOffset, unsigned TryLength, + unsigned HandlerOffset, unsigned HandlerLength) { + if (ObjFileInfo->getObjectFileType() == ObjFileInfo->IsELF) { + DebugEHClauseInfos.emplace_back(TryOffset, TryLength, HandlerOffset, HandlerLength); + } +} + void ObjectWriter::EmitDebugLoc(int NativeOffset, int FileId, int LineNumber, int ColNumber) { assert(FileId > 0 && "FileId should be greater than 0."); @@ -742,7 +782,7 @@ void ObjectWriter::EmitDebugLoc(int NativeOffset, int FileId, int LineNumber, } void ObjectWriter::EmitCVUserDefinedTypesSymbols() { - const auto &UDTs = TypeBuilder.GetUDTs(); + const auto &UDTs = TypeBuilder->GetUDTs(); if (UDTs.empty()) { return; } @@ -755,12 +795,12 @@ void ObjectWriter::EmitCVUserDefinedTypesSymbols() { EmitLabelDiff(SymbolsBegin, SymbolsEnd); Streamer->EmitLabel(SymbolsBegin); - for (const std::pair &UDT : UDTs) { + for (const std::pair &UDT : UDTs) { unsigned NameLength = UDT.first.length() + 1; unsigned RecordLength = 2 + 4 + NameLength; Streamer->EmitIntValue(RecordLength, 2); Streamer->EmitIntValue(unsigned(SymbolKind::S_UDT), 2); - Streamer->EmitIntValue(UDT.second.getIndex(), 4); + Streamer->EmitIntValue(UDT.second, 4); Streamer->EmitBytes(StringRef(UDT.first.c_str(), NameLength)); } Streamer->EmitLabel(SymbolsEnd); @@ -769,7 +809,7 @@ void ObjectWriter::EmitCVUserDefinedTypesSymbols() { void ObjectWriter::EmitDebugModuleInfo() { if (ObjFileInfo->getObjectFileType() == ObjFileInfo->IsCOFF) { - TypeBuilder.EmitTypeInformation(ObjFileInfo->getCOFFDebugTypesSection()); + TypeBuilder->EmitTypeInformation(ObjFileInfo->getCOFFDebugTypesSection()); EmitCVUserDefinedTypesSymbols(); } @@ -783,6 +823,10 @@ void ObjectWriter::EmitDebugModuleInfo() { Streamer->SwitchSection(Section); Streamer->EmitCVFileChecksumsDirective(); Streamer->EmitCVStringTableDirective(); + } else if (ObjFileInfo->getObjectFileType() == ObjFileInfo->IsELF) { + DwarfGenerator->EmitAbbrev(); + DwarfGenerator->EmitAranges(); + DwarfGenerator->Finish(); } else { OutContext->setGenDwarfForAssembly(true); } @@ -791,56 +835,50 @@ void ObjectWriter::EmitDebugModuleInfo() { unsigned ObjectWriter::GetEnumTypeIndex(const EnumTypeDescriptor &TypeDescriptor, const EnumRecordTypeDescriptor *TypeRecords) { - assert(ObjFileInfo->getObjectFileType() == ObjFileInfo->IsCOFF && - "only COFF is supported now"); - return TypeBuilder.GetEnumTypeIndex(TypeDescriptor, TypeRecords); + return TypeBuilder->GetEnumTypeIndex(TypeDescriptor, TypeRecords); } unsigned ObjectWriter::GetClassTypeIndex(const ClassTypeDescriptor &ClassDescriptor) { - assert(ObjFileInfo->getObjectFileType() == ObjFileInfo->IsCOFF && - "only COFF is supported now"); - return TypeBuilder.GetClassTypeIndex(ClassDescriptor); + unsigned res = TypeBuilder->GetClassTypeIndex(ClassDescriptor); + return res; } unsigned ObjectWriter::GetCompleteClassTypeIndex( const ClassTypeDescriptor &ClassDescriptor, const ClassFieldsTypeDescriptior &ClassFieldsDescriptor, - const DataFieldDescriptor *FieldsDescriptors) { - assert(ObjFileInfo->getObjectFileType() == ObjFileInfo->IsCOFF && - "only COFF is supported now"); - return TypeBuilder.GetCompleteClassTypeIndex( - ClassDescriptor, ClassFieldsDescriptor, FieldsDescriptors); + const DataFieldDescriptor *FieldsDescriptors, + const StaticDataFieldDescriptor *StaticsDescriptors) { + unsigned res = TypeBuilder->GetCompleteClassTypeIndex(ClassDescriptor, + ClassFieldsDescriptor, FieldsDescriptors, StaticsDescriptors); + return res; } unsigned ObjectWriter::GetArrayTypeIndex(const ClassTypeDescriptor &ClassDescriptor, const ArrayTypeDescriptor &ArrayDescriptor) { - assert(ObjFileInfo->getObjectFileType() == ObjFileInfo->IsCOFF && - "only COFF is supported now"); - return TypeBuilder.GetArrayTypeIndex(ClassDescriptor, ArrayDescriptor); + return TypeBuilder->GetArrayTypeIndex(ClassDescriptor, ArrayDescriptor); } unsigned ObjectWriter::GetPointerTypeIndex(const PointerTypeDescriptor& PointerDescriptor) { - assert(ObjFileInfo->getObjectFileType() == ObjFileInfo->IsCOFF && - "only COFF is supported now"); - return TypeBuilder.GetPointerTypeIndex(PointerDescriptor); + return TypeBuilder->GetPointerTypeIndex(PointerDescriptor); } unsigned ObjectWriter::GetMemberFunctionTypeIndex(const MemberFunctionTypeDescriptor& MemberDescriptor, uint32_t const *const ArgumentTypes) { - assert(ObjFileInfo->getObjectFileType() == ObjFileInfo->IsCOFF && - "only COFF is supported now"); - return TypeBuilder.GetMemberFunctionTypeIndex(MemberDescriptor, ArgumentTypes); + return TypeBuilder->GetMemberFunctionTypeIndex(MemberDescriptor, ArgumentTypes); } unsigned ObjectWriter::GetMemberFunctionId(const MemberFunctionIdTypeDescriptor& MemberIdDescriptor) { - assert(ObjFileInfo->getObjectFileType() == ObjFileInfo->IsCOFF && - "only COFF is supported now"); - return TypeBuilder.GetMemberFunctionId(MemberIdDescriptor); + return TypeBuilder->GetMemberFunctionId(MemberIdDescriptor); +} + +unsigned +ObjectWriter::GetPrimitiveTypeIndex(int Type) { + return TypeBuilder->GetPrimitiveTypeIndex(static_cast(Type)); } void @@ -883,13 +921,13 @@ void ObjectWriter::EmitARMExIdxCode(int Offset, const char *Blob) ATS.emitPad(CfiCode->Offset); break; case CFI_REL_OFFSET: - RegList.push_back(CfiCode->DwarfReg); + RegList.push_back(CfiCode->DwarfReg + 14); // See ARMRegEncodingTable in ARMGenRegisterInfo.inc by getEncodingValue ATS.emitRegSave(RegList, false); break; case CFI_DEF_CFA_REGISTER: assert(CfiCode->Offset == 0 && "Unexpected Offset Value for OpDefCfaRegister"); - ATS.emitMovSP(CfiCode->DwarfReg, 0); + ATS.emitMovSP(CfiCode->DwarfReg + 14, 0); // See ARMRegEncodingTable in ARMGenRegisterInfo.inc by getEncodingValue break; default: assert(false && "Unrecognized CFI"); diff --git a/external/corert/src/Native/ObjWriter/objwriter.h b/external/corert/src/Native/ObjWriter/objwriter.h index 21327b3be9..6c1ba86451 100644 --- a/external/corert/src/Native/ObjWriter/objwriter.h +++ b/external/corert/src/Native/ObjWriter/objwriter.h @@ -1,10 +1,10 @@ -//===---- objwriter.h --------------------------------*- C++ -*-===// +//===---- objwriter.h ------------------------------------------*- C++ -*-===// // // object writer // -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. -// See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. // //===----------------------------------------------------------------------===// @@ -19,7 +19,8 @@ #include "jitDebugInfo.h" #include #include -#include "typeBuilder.h" +#include "debugInfo/typeBuilder.h" +#include "debugInfo/dwarf/dwarfGen.h" using namespace llvm; using namespace llvm::codeview; @@ -68,11 +69,13 @@ public: int EmitSymbolRef(const char *SymbolName, RelocType RelocType, int Delta); void EmitDebugFileInfo(int FileId, const char *FileName); - void EmitDebugFunctionInfo(const char *FunctionName, int FunctionSize); + void EmitDebugFunctionInfo(const char *FunctionName, int FunctionSize, unsigned MethodTypeIndex); void EmitDebugVar(char *Name, int TypeIndex, bool IsParm, int RangeCount, const ICorDebugInfo::NativeVarInfo *Ranges); void EmitDebugLoc(int NativeOffset, int FileId, int LineNumber, int ColNumber); + void EmitDebugEHClause(unsigned TryOffset, unsigned TryLength, + unsigned HandlerOffset, unsigned HandlerLength); void EmitDebugModuleInfo(); void EmitCFIStart(int Offset); @@ -86,7 +89,8 @@ public: unsigned GetCompleteClassTypeIndex( const ClassTypeDescriptor &ClassDescriptor, const ClassFieldsTypeDescriptior &ClassFieldsDescriptor, - const DataFieldDescriptor *FieldsDescriptors); + const DataFieldDescriptor *FieldsDescriptors, + const StaticDataFieldDescriptor *StaticsDescriptors); unsigned GetArrayTypeIndex(const ClassTypeDescriptor &ClassDescriptor, const ArrayTypeDescriptor &ArrayDescriptor); @@ -98,6 +102,8 @@ public: unsigned GetMemberFunctionId(const MemberFunctionIdTypeDescriptor& MemberIdDescriptor); + unsigned GetPrimitiveTypeIndex(int Type); + void EmitARMFnStart(); void EmitARMFnEnd(); void EmitARMExIdxCode(int Offset, const char *Blob); @@ -114,6 +120,8 @@ private: int NumVarInfos); void EmitCVDebugFunctionInfo(const char *FunctionName, int FunctionSize); + void EmitDwarfFunctionInfo(const char *FunctionName, int FunctionSize, unsigned MethodTypeIndex); + const MCSymbolRefExpr *GetSymbolRefExpr( const char *SymbolName, MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None); @@ -149,16 +157,18 @@ private: std::unique_ptr TMachine; std::unique_ptr AssemblerPrinter; MCAssembler *Assembler; // Owned by MCStreamer + std::unique_ptr DwarfGenerator; std::unique_ptr OS; MCTargetOptions TargetMOptions; bool FrameOpened; std::vector DebugVarInfos; + std::vector DebugEHClauseInfos; std::set Sections; int FuncId; - UserDefinedTypesBuilder TypeBuilder; + std::unique_ptr TypeBuilder; std::string TripleName; @@ -258,9 +268,10 @@ DLL_EXPORT void EmitDebugFileInfo(ObjectWriter *OW, int FileId, DLL_EXPORT void EmitDebugFunctionInfo(ObjectWriter *OW, const char *FunctionName, - int FunctionSize) { + int FunctionSize, + unsigned MethodTypeIndex) { assert(OW && "ObjWriter is null"); - OW->EmitDebugFunctionInfo(FunctionName, FunctionSize); + OW->EmitDebugFunctionInfo(FunctionName, FunctionSize, MethodTypeIndex); } DLL_EXPORT void EmitDebugVar(ObjectWriter *OW, char *Name, int TypeIndex, @@ -270,6 +281,13 @@ DLL_EXPORT void EmitDebugVar(ObjectWriter *OW, char *Name, int TypeIndex, OW->EmitDebugVar(Name, TypeIndex, IsParam, RangeCount, Ranges); } +DLL_EXPORT void EmitDebugEHClause(ObjectWriter *OW, unsigned TryOffset, + unsigned TryLength, unsigned HandlerOffset, + unsigned HandlerLength) { + assert(OW && "ObjWriter is null"); + OW->EmitDebugEHClause(TryOffset, TryLength, HandlerOffset, HandlerLength); +} + DLL_EXPORT void EmitDebugLoc(ObjectWriter *OW, int NativeOffset, int FileId, int LineNumber, int ColNumber) { assert(OW && "ObjWriter is null"); @@ -299,10 +317,11 @@ DLL_EXPORT unsigned GetClassTypeIndex(ObjectWriter *OW, DLL_EXPORT unsigned GetCompleteClassTypeIndex(ObjectWriter *OW, ClassTypeDescriptor ClassDescriptor, ClassFieldsTypeDescriptior ClassFieldsDescriptor, - DataFieldDescriptor *FieldsDescriptors) { + DataFieldDescriptor *FieldsDescriptors, + StaticDataFieldDescriptor *StaticsDescriptors) { assert(OW && "ObjWriter is null"); return OW->GetCompleteClassTypeIndex(ClassDescriptor, ClassFieldsDescriptor, - FieldsDescriptors); + FieldsDescriptors, StaticsDescriptors); } DLL_EXPORT unsigned GetArrayTypeIndex(ObjectWriter *OW, @@ -331,6 +350,11 @@ DLL_EXPORT unsigned GetMemberFunctionIdTypeIndex(ObjectWriter *OW, return OW->GetMemberFunctionId(MemberIdDescriptor); } +DLL_EXPORT unsigned GetPrimitiveTypeIndex(ObjectWriter *OW, int Type) { + assert(OW && "ObjWriter is null"); + return OW->GetPrimitiveTypeIndex(Type); +} + DLL_EXPORT void EmitARMFnStart(ObjectWriter *OW) { assert(OW && "ObjWriter is null"); return OW->EmitARMFnStart(); diff --git a/external/corert/src/Native/ObjWriter/typeBuilder.h b/external/corert/src/Native/ObjWriter/typeBuilder.h deleted file mode 100644 index a5037b7690..0000000000 --- a/external/corert/src/Native/ObjWriter/typeBuilder.h +++ /dev/null @@ -1,145 +0,0 @@ -//===---- typeBuilder.h --------------------------------*- C++ -*-===// -// -// type builder is used to convert .Net types into CodeView descriptors. -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. -// See LICENSE file in the project root for full license information. -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "llvm/DebugInfo/CodeView/TypeTableBuilder.h" -#include "llvm/MC/MCObjectStreamer.h" - -#include -#include - -using namespace llvm; -using namespace llvm::codeview; - -typedef unsigned long long uint64; - -#pragma pack(push, 8) - -extern "C" struct EnumRecordTypeDescriptor { - uint64 Value; - char *Name; -}; - -extern "C" struct EnumTypeDescriptor { - uint32_t ElementType; - uint64 ElementCount; - char *Name; -}; - -extern "C" struct ClassTypeDescriptor { - int32_t IsStruct; - char *Name; - uint32_t BaseClassId; -}; - -extern "C" struct DataFieldDescriptor { - uint32_t FieldTypeIndex; - uint64 Offset; - char *Name; -}; - -extern "C" struct ClassFieldsTypeDescriptior { - uint64 Size; - int32_t FieldsCount; -}; - -extern "C" struct ArrayTypeDescriptor { - uint32_t Rank; - uint32_t ElementType; - uint32_t Size; - int32_t IsMultiDimensional; -}; - -extern "C" struct PointerTypeDescriptor { - uint32_t ElementType; - int32_t IsReference; - int32_t IsConst; - int32_t Is64Bit; -}; - -extern "C" struct MemberFunctionTypeDescriptor { - uint32_t ReturnType; - uint32_t ContainingClass; - uint32_t TypeIndexOfThisPointer; - int32_t ThisAdjust; - uint32_t CallingConvention; - uint16_t NumberOfArguments; -}; - -extern "C" struct MemberFunctionIdTypeDescriptor { - uint32_t MemberFunction; - uint32_t ParentClass; - char *Name; -}; - -class ArrayDimensionsDescriptor { -public: - const char *GetLengthName(unsigned index); - const char *GetBoundsName(unsigned index); - -private: - void Resize(unsigned NewSize); - - std::vector Lengths; - std::vector Bounds; -}; - -#pragma pack(pop) -class UserDefinedTypesBuilder { -public: - UserDefinedTypesBuilder(); - void SetStreamer(MCObjectStreamer *Streamer); - void SetTargetPointerSize(unsigned TargetPointerSize); - void EmitTypeInformation(MCSection *COFFDebugTypesSection); - - unsigned GetEnumTypeIndex(const EnumTypeDescriptor &TypeDescriptor, - const EnumRecordTypeDescriptor *TypeRecords); - unsigned GetClassTypeIndex(const ClassTypeDescriptor &ClassDescriptor); - unsigned GetCompleteClassTypeIndex( - const ClassTypeDescriptor &ClassDescriptor, - const ClassFieldsTypeDescriptior &ClassFieldsDescriptor, - const DataFieldDescriptor *FieldsDescriptors); - - unsigned GetArrayTypeIndex(const ClassTypeDescriptor &ClassDescriptor, - const ArrayTypeDescriptor &ArrayDescriptor); - - unsigned GetPointerTypeIndex(const PointerTypeDescriptor& PointerDescriptor); - - unsigned GetMemberFunctionTypeIndex(const MemberFunctionTypeDescriptor& MemberDescriptor, - uint32_t const *const ArgumentTypes); - - unsigned GetMemberFunctionId(const MemberFunctionIdTypeDescriptor& MemberIdDescriptor); - - const std::vector> &GetUDTs() { - return UserDefinedTypes; - } - -private: - void EmitCodeViewMagicVersion(); - ClassOptions GetCommonClassOptions(); - - unsigned GetEnumFieldListType(uint64 Count, - const EnumRecordTypeDescriptor *TypeRecords); - - void AddBaseClass(FieldListRecordBuilder &FLBR, unsigned BaseClassId); - void AddClassVTShape(FieldListRecordBuilder &FLBR); - - BumpPtrAllocator Allocator; - TypeTableBuilder TypeTable; - - MCObjectStreamer *Streamer; - unsigned TargetPointerSize; - - ArrayDimensionsDescriptor ArrayDimentions; - TypeIndex ClassVTableTypeIndex; - - std::vector> UserDefinedTypes; -}; diff --git a/external/corert/src/Native/Runtime/CMakeLists.txt b/external/corert/src/Native/Runtime/CMakeLists.txt index 1cd4cd9497..b650114328 100644 --- a/external/corert/src/Native/Runtime/CMakeLists.txt +++ b/external/corert/src/Native/Runtime/CMakeLists.txt @@ -48,8 +48,6 @@ set(COMMON_RUNTIME_SOURCES ../gc/gccommon.cpp ../gc/gceewks.cpp ../gc/gcwks.cpp - ../gc/gceesvr.cpp - ../gc/gcsvr.cpp ../gc/gcscan.cpp ../gc/handletable.cpp ../gc/handletablecache.cpp @@ -58,6 +56,11 @@ set(COMMON_RUNTIME_SOURCES ../gc/objecthandle.cpp ) +set(SERVER_GC_SOURCES + ../gc/gceesvr.cpp + ../gc/gcsvr.cpp +) + set(FULL_RUNTIME_SOURCES AsmOffsetsVerify.cpp ThunksMapping.cpp @@ -171,7 +174,6 @@ convert_to_absolute_path(ARCH_SOURCES_DIR ${ARCH_SOURCES_DIR}) include_directories(${ARCH_SOURCES_DIR}) add_definitions(-DFEATURE_BACKGROUND_GC) -add_definitions(-DFEATURE_SVR_GC) add_definitions(-DFEATURE_BASICFREEZE) add_definitions(-DFEATURE_CONSERVATIVE_GC) add_definitions(-DFEATURE_CUSTOM_IMPORTS) @@ -183,6 +185,7 @@ add_definitions(-DCORERT) add_definitions(-DFEATURE_CACHED_INTERFACE_DISPATCH) add_definitions(-D_LIB) add_definitions(-DEETYPE_TYPE_MANAGER) +add_definitions(-DFEATURE_EMBEDDED_CONFIG) if(WIN32) # There is a problem with undefined symbol g_pConfig, windows don't care since it is in template method, but clang does @@ -221,6 +224,7 @@ convert_to_absolute_path(COMMON_RUNTIME_SOURCES ${COMMON_RUNTIME_SOURCES}) convert_to_absolute_path(FULL_RUNTIME_SOURCES ${FULL_RUNTIME_SOURCES}) convert_to_absolute_path(PORTABLE_RUNTIME_SOURCES ${PORTABLE_RUNTIME_SOURCES}) +convert_to_absolute_path(SERVER_GC_SOURCES ${SERVER_GC_SOURCES}) convert_to_absolute_path(RUNTIME_SOURCES_ARCH_ASM ${RUNTIME_SOURCES_ARCH_ASM}) diff --git a/external/corert/src/Native/Runtime/Full/CMakeLists.txt b/external/corert/src/Native/Runtime/Full/CMakeLists.txt index af7de3a21c..fff2da4b35 100644 --- a/external/corert/src/Native/Runtime/Full/CMakeLists.txt +++ b/external/corert/src/Native/Runtime/Full/CMakeLists.txt @@ -11,6 +11,11 @@ add_definitions(-DFEATURE_RX_THUNKS) add_library(Runtime STATIC ${COMMON_RUNTIME_SOURCES} ${FULL_RUNTIME_SOURCES} ${RUNTIME_SOURCES_ARCH_ASM}) +add_library(Runtime.ServerGC STATIC ${COMMON_RUNTIME_SOURCES} ${FULL_RUNTIME_SOURCES} ${RUNTIME_SOURCES_ARCH_ASM} ${SERVER_GC_SOURCES}) + +target_compile_definitions(Runtime.ServerGC PRIVATE -DFEATURE_SVR_GC) + + # Get the current list of definitions get_compile_definitions(DEFINITIONS) @@ -72,7 +77,8 @@ foreach(CONFIG IN LISTS CMAKE_CONFIGURATION_TYPES) endforeach() # Install the static Runtime library -install (TARGETS Runtime DESTINATION sdk) +install (TARGETS Runtime Runtime.ServerGC DESTINATION sdk) if(WIN32) install (FILES ${CMAKE_CURRENT_BINARY_DIR}/Runtime.dir/$/Runtime.pdb DESTINATION sdk) + install (FILES ${CMAKE_CURRENT_BINARY_DIR}/Runtime.ServerGC.dir/$/Runtime.ServerGC.pdb DESTINATION sdk) endif() diff --git a/external/corert/src/Native/Runtime/Portable/CMakeLists.txt b/external/corert/src/Native/Runtime/Portable/CMakeLists.txt index 21dbb7d7c9..7de7ce9d0f 100644 --- a/external/corert/src/Native/Runtime/Portable/CMakeLists.txt +++ b/external/corert/src/Native/Runtime/Portable/CMakeLists.txt @@ -1,6 +1,6 @@ project(PortableRuntime) -# Portable version of the runtime is designed to be used with CppCodeGen only. +# Portable version of the runtime is designed to be used with CppCodeGen or WASM. # It should be written in pure C/C++, with no assembly code. include_directories(..) @@ -34,6 +34,7 @@ add_custom_command( # Install the static Runtime library install (TARGETS PortableRuntime DESTINATION sdk) + if(WIN32) install (FILES ${CMAKE_CURRENT_BINARY_DIR}/PortableRuntime.dir/$/PortableRuntime.pdb DESTINATION sdk) endif() diff --git a/external/corert/src/Native/Runtime/RHCodeMan.cpp b/external/corert/src/Native/Runtime/RHCodeMan.cpp index b6a173bb27..054287fc47 100644 --- a/external/corert/src/Native/Runtime/RHCodeMan.cpp +++ b/external/corert/src/Native/Runtime/RHCodeMan.cpp @@ -891,7 +891,7 @@ bool EECodeManager::UnwindStackFrame(GCInfoHeader * pInfoHeader, { CalleeSavedRegMask regMask = pInfoHeader->GetSavedRegs(); ASSERT_MSG(ebpFrame || !(regMask & CSR_MASK_RBP), "We should never use EBP as a preserved register"); - ASSERT_MSG(!(regMask & CSR_MASK_RBX) || !pInfoHeader->HasDynamicAlignment(), "Can't have EBX as preserved regster and dynamic alignment frame pointer") + ASSERT_MSG(!(regMask & CSR_MASK_RBX) || !pInfoHeader->HasDynamicAlignment(), "Can't have EBX as preserved register and dynamic alignment frame pointer") if (regMask & CSR_MASK_RBX) { pContext->pRbx = (PTR_UIntNative)((PTR_UInt8)RSP - registerSaveDisplacement); ++RSP; } // registers saved at bottom of frame if (regMask & CSR_MASK_RSI) { pContext->pRsi = (PTR_UIntNative)((PTR_UInt8)RSP - registerSaveDisplacement); ++RSP; } // registers saved at bottom of frame if (regMask & CSR_MASK_RDI) { pContext->pRdi = (PTR_UIntNative)((PTR_UInt8)RSP - registerSaveDisplacement); ++RSP; } // registers saved at bottom of frame @@ -1064,10 +1064,9 @@ bool EECodeManager::UnwindStackFrame(GCInfoHeader * pInfoHeader, // The compiler enforces that by placing an 8-byte padding between those areas if needed. // Account for that padding and ensure that the unwound SP is 16-byte aligned. RSP = dac_cast((dac_cast(RSP) + 0xf) & ~0xf); + #else - -#error NYI - For this arch - +#error Unexpected target architecture #endif pContext->SetSP((UIntNative) dac_cast(RSP)); @@ -1135,7 +1134,7 @@ UIntNative EECodeManager::GetConservativeUpperBoundForOutgoingArgs(GCInfoHeader upperBound = pContext->GetFP() - pInfoHeader->GetFramePointerOffset(); #else -#error NYI - For this arch +#error Unexpected target architecture #endif } else @@ -1145,21 +1144,15 @@ UIntNative EECodeManager::GetConservativeUpperBoundForOutgoingArgs(GCInfoHeader // Adding the frame size to the SP is guaranteed to yield an address above all outgoing // arguments. // - // If this frame contains one or more callee-saved register (guaranteed on ARM since at + // If this frame contains one or more callee-saved register (guaranteed on ARM/ARM64 since at // least LR is saved in all functions that contain callsites), then the computed address // will point at the lowest callee-saved register (or possibly above it in the x86 case // where registers are saved at the bottom of the frame). // - // If the frame contains no callee-saved registers (impossible on ARM), then the computed + // If the frame contains no callee-saved registers (impossible on ARM/ARM64), then the computed // address will point to the pushed return address. upperBound = pContext->GetSP() + pInfoHeader->GetFrameSize(); - -#if defined(_TARGET_ARM_) - ASSERT(pInfoHeader->GetSavedRegs() != 0); -#elif defined(_TARGET_ARM64_) - PORTABILITY_ASSERT("@TODO: FIXME:ARM64"); -#endif } } @@ -1200,37 +1193,24 @@ PTR_PTR_VOID EECodeManager::GetReturnAddressLocationForHijack( } #ifdef _ARM_ - // We cannot get the return address unless LR has - // be saved in the prolog. + // We cannot get the return address unless LR has been saved in the prolog. if (!pHeader->IsRegSaved(CSR_MASK_LR)) return NULL; #elif defined(_ARM64_) - // We can get return address if LR was saved either with FP or on its own: - bool ebpFrame = pHeader->HasFramePointer(); - if (!ebpFrame && !pHeader->IsRegSaved(CSR_MASK_LR)) { + // We can get return address if LR was saved either with FP or on its own. + if (!pHeader->HasFramePointer() && !pHeader->IsRegSaved(CSR_MASK_LR)) return NULL; - } #endif // _ARM_ - void ** ppvResult; - UInt32 epilogOffset = 0; UInt32 epilogSize = 0; if (GetEpilogOffset(pGCInfoHeader, cbMethodCodeSize, pbEpilogTable, codeOffset, &epilogOffset, &epilogSize)) { -#ifdef _ARM_ - // Disable hijacking from epilogs on ARM until we implement GetReturnAddressLocationFromEpilog. - return NULL; -#elif defined(_ARM64_) - // Disable hijacking from epilogs on ARM64: +#if defined(_ARM_) || defined(_ARM64_) + // Disable hijacking from epilogs until we implement GetReturnAddressLocationFromEpilog. return NULL; #else - ppvResult = GetReturnAddressLocationFromEpilog(pHeader, pContext, epilogOffset, epilogSize); - // Early out if GetReturnAddressLocationFromEpilog indicates a non-hijackable epilog (e.g. exception - // throw epilog or tail call). - if (ppvResult == NULL) - return NULL; - goto Finished; + return GetReturnAddressLocationFromEpilog(pHeader, pContext, epilogOffset, epilogSize); #endif } @@ -1238,11 +1218,7 @@ PTR_PTR_VOID EECodeManager::GetReturnAddressLocationForHijack( // ARM always sets up R11 as an OS frame chain pointer to enable fast ETW stack walking (except in the // case where LR is not pushed, but that was handled above). The protocol specifies that the return // address is pushed at [r11, #4]. - ppvResult = (void **)((*pContext->pR11) + sizeof(void *)); - goto Finished; -#elif _ARM64_ - ppvResult = (void **)(pContext->pLR); - goto Finished; + return (void **)((*pContext->pR11) + sizeof(void *)); #else // We are in the body of the method, so just find the return address using the unwind info. @@ -1254,8 +1230,7 @@ PTR_PTR_VOID EECodeManager::GetReturnAddressLocationForHijack( // In this case, we have the normal EBP frame pointer, but also an EBX frame pointer. Use the EBX // one, because the return address associated with that frame pointer is the one we're actually // going to return to. The other one (next to EBP) is only for EBP-chain-walking. - ppvResult = (void **)((*pContext->pRbx) + sizeof(void *)); - goto Finished; + return (void **)((*pContext->pRbx) + sizeof(void *)); } #endif @@ -1263,25 +1238,24 @@ PTR_PTR_VOID EECodeManager::GetReturnAddressLocationForHijack( #ifdef _AMD64_ framePointerOffset = pHeader->GetFramePointerOffset(); #endif - ppvResult = (void **)((*pContext->pRbp) + sizeof(void *) - framePointerOffset); - goto Finished; + return (void **)(pContext->GetFP() + sizeof(void *) - framePointerOffset); } { // We do not have a frame pointer, but we are also not in the prolog or epilog - UInt8 * RSP = (UInt8 *)pContext->GetSP(); - RSP += pHeader->GetFrameSize(); + UIntNative RSP = pContext->GetSP() + pHeader->GetFrameSize(); +#if _ARM64_ + // LR is saved at the bottom of the preserved registers area + ASSERT(pHeader->IsRegSaved(CSR_MASK_LR)); +#else RSP += pHeader->GetPreservedRegsSaveSize(); - - // RSP should point to the return address now. - ppvResult = (void**)RSP; - } - goto Finished; #endif - Finished: - return ppvResult; + // RSP should point to the return address now. + return (void**)RSP; + } +#endif } #endif @@ -1350,6 +1324,9 @@ bool EECodeManager::GetEpilogOffset( #ifndef DACCESS_COMPILE +// ARM64 epilogs have a window between loading the hijackable return address into LR and the RET instruction. +// We cannot hijack or unhijack a thread while it is suspended in that window unless we implement hijacking +// via LR register modification. void ** EECodeManager::GetReturnAddressLocationFromEpilog(GCInfoHeader * pInfoHeader, REGDISPLAY * pContext, UInt32 epilogOffset, UInt32 epilogSize) { diff --git a/external/corert/src/Native/Runtime/RhConfig.cpp b/external/corert/src/Native/Runtime/RhConfig.cpp index f1879ab104..fb85754070 100644 --- a/external/corert/src/Native/Runtime/RhConfig.cpp +++ b/external/corert/src/Native/Runtime/RhConfig.cpp @@ -34,14 +34,20 @@ UInt32 RhConfig::ReadConfigValue(_In_z_ const TCHAR *wszName, UInt32 uiDefaultVa UInt32 cchResult = 0; -#ifdef RH_ENVIRONMENT_VARIABLE_CONFIG_ENABLED +#ifdef FEATURE_ENVIRONMENT_VARIABLE_CONFIG cchResult = PalGetEnvironmentVariable(wszName, wszBuffer, cchBuffer); -#endif // RH_ENVIRONMENT_VARIABLE_CONFIG_ENABLED +#endif // FEATURE_ENVIRONMENT_VARIABLE_CONFIG //if the config key wasn't found in the environment if ((cchResult == 0) || (cchResult >= cchBuffer)) cchResult = GetIniVariable(wszName, wszBuffer, cchBuffer); +#ifdef FEATURE_EMBEDDED_CONFIG + // if the config key wasn't found in the ini file + if ((cchResult == 0) || (cchResult >= cchBuffer)) + cchResult = GetEmbeddedVariable(wszName, wszBuffer, cchBuffer); +#endif // FEATURE_EMBEDDED_CONFIG + if ((cchResult == 0) || (cchResult >= cchBuffer)) return uiDefaultValue; // not found, return default @@ -90,10 +96,40 @@ UInt32 RhConfig::GetIniVariable(_In_z_ const TCHAR* configName, _Out_writes_all_ return 0; } + return GetConfigVariable(configName, (ConfigPair*)g_iniSettings, outputBuffer, cchOutputBuffer); +} + +#ifdef FEATURE_EMBEDDED_CONFIG +UInt32 RhConfig::GetEmbeddedVariable(_In_z_ const TCHAR* configName, _Out_writes_all_(cchOutputBuffer) TCHAR* outputBuffer, _In_ UInt32 cchOutputBuffer) +{ + //the buffer needs to be big enough to read the value buffer + null terminator + if (cchOutputBuffer < CONFIG_VAL_MAXLEN + 1) + { + return 0; + } + + //if we haven't read the config yet try to read + if (g_embeddedSettings == NULL) + { + ReadEmbeddedSettings(); + } + + //if the config wasn't read or reading failed return 0 immediately + if (g_embeddedSettings == CONFIG_INI_NOT_AVAIL) + { + return 0; + } + + return GetConfigVariable(configName, (ConfigPair*)g_embeddedSettings, outputBuffer, cchOutputBuffer); +} +#endif // FEATURE_EMBEDDED_CONFIG + +UInt32 RhConfig::GetConfigVariable(_In_z_ const TCHAR* configName, const ConfigPair* configPairs, _Out_writes_all_(cchOutputBuffer) TCHAR* outputBuffer, _In_ UInt32 cchOutputBuffer) +{ //find the first name which matches (case insensitive to be compat with environment variable counterpart) for (int iSettings = 0; iSettings < RCV_Count; iSettings++) { - if (_tcsicmp(configName, ((ConfigPair*)g_iniSettings)[iSettings].Key) == 0) + if (_tcsicmp(configName, configPairs[iSettings].Key) == 0) { bool nullTerm = FALSE; @@ -101,7 +137,7 @@ UInt32 RhConfig::GetIniVariable(_In_z_ const TCHAR* configName, _Out_writes_all_ for (iValue = 0; (iValue < CONFIG_VAL_MAXLEN + 1) && (iValue < (Int32)cchOutputBuffer); iValue++) { - outputBuffer[iValue] = ((ConfigPair*)g_iniSettings)[iSettings].Value[iValue]; + outputBuffer[iValue] = configPairs[iSettings].Value[iValue]; if (outputBuffer[iValue] == '\0') { @@ -218,6 +254,81 @@ void RhConfig::ReadConfigIni() return; } +#ifdef FEATURE_EMBEDDED_CONFIG +struct CompilerEmbeddedSettingsBlob +{ + UInt32 Size; + char Data[1]; +}; + +extern "C" CompilerEmbeddedSettingsBlob g_compilerEmbeddedSettingsBlob; + +void RhConfig::ReadEmbeddedSettings() +{ + if (g_embeddedSettings == NULL) + { + //if reading the file contents failed set g_embeddedSettings to CONFIG_INI_NOT_AVAIL + if (g_compilerEmbeddedSettingsBlob.Size == 0) + { + //only set if another thread hasn't initialized the buffer yet, otherwise ignore and let the first setter win + PalInterlockedCompareExchangePointer(&g_embeddedSettings, CONFIG_INI_NOT_AVAIL, NULL); + + return; + } + + ConfigPair* iniBuff = new (nothrow) ConfigPair[RCV_Count]; + if (iniBuff == NULL) + { + //only set if another thread hasn't initialized the buffer yet, otherwise ignore and let the first setter win + PalInterlockedCompareExchangePointer(&g_embeddedSettings, CONFIG_INI_NOT_AVAIL, NULL); + + return; + } + + UInt32 iBuff = 0; + UInt32 iIniBuff = 0; + char* currLine; + + //while we haven't reached the max number of config pairs, or the end of the file, read the next line + while (iIniBuff < RCV_Count && iBuff < g_compilerEmbeddedSettingsBlob.Size) + { + currLine = &g_compilerEmbeddedSettingsBlob.Data[iBuff]; + + //find the end of the line + while ((g_compilerEmbeddedSettingsBlob.Data[iBuff] != '\0') && (iBuff < g_compilerEmbeddedSettingsBlob.Size)) + iBuff++; + + //parse the line + //only increment iIniBuff if the parsing succeeded otherwise reuse the config struct + if (ParseConfigLine(&iniBuff[iIniBuff], currLine)) + { + iIniBuff++; + } + + //advance to the next line; + iBuff++; + } + + //initialize the remaining config pairs to "\0" + while (iIniBuff < RCV_Count) + { + iniBuff[iIniBuff].Key[0] = '\0'; + iniBuff[iIniBuff].Value[0] = '\0'; + iIniBuff++; + } + + //if another thread initialized first let the first setter win + //delete the iniBuff to avoid leaking memory + if (PalInterlockedCompareExchangePointer(&g_embeddedSettings, iniBuff, NULL) != NULL) + { + delete[] iniBuff; + } + } + + return; +} +#endif // FEATURE_EMBEDDED_CONFIG + //returns the path to the runtime configuration ini _Ret_maybenull_z_ TCHAR* RhConfig::GetConfigPath() { diff --git a/external/corert/src/Native/Runtime/RhConfig.h b/external/corert/src/Native/Runtime/RhConfig.h index 677d97516d..b5879c3862 100644 --- a/external/corert/src/Native/Runtime/RhConfig.h +++ b/external/corert/src/Native/Runtime/RhConfig.h @@ -21,7 +21,7 @@ #ifndef DACCESS_COMPILE #if defined(_DEBUG) || !defined(APP_LOCAL_RUNTIME) -#define RH_ENVIRONMENT_VARIABLE_CONFIG_ENABLED +#define FEATURE_ENVIRONMENT_VARIABLE_CONFIG #endif class RhConfig @@ -53,6 +53,12 @@ private: private: void* volatile g_iniSettings = NULL; +#ifdef FEATURE_EMBEDDED_CONFIG + // g_embeddedSettings works similarly to g_iniSettings, except the source of the data + // is a data blob generated by the compiler and embedded into the executable. + void* volatile g_embeddedSettings = NULL; +#endif // FEATURE_EMBEDDED_CONFIG + public: #define DEFINE_VALUE_ACCESSOR(_name, defaultVal) \ @@ -123,6 +129,14 @@ private: //cchOutputBuffer is the maximum number of characters to write to outputBuffer UInt32 GetIniVariable(_In_z_ const TCHAR* configName, _Out_writes_all_(cchOutputBuffer) TCHAR* outputBuffer, _In_ UInt32 cchOutputBuffer); +#ifdef FEATURE_EMBEDDED_CONFIG + void ReadEmbeddedSettings(); + + UInt32 GetEmbeddedVariable(_In_z_ const TCHAR* configName, _Out_writes_all_(cchOutputBuffer) TCHAR* outputBuffer, _In_ UInt32 cchOutputBuffer); +#endif // FEATURE_EMBEDDED_CONFIG + + UInt32 GetConfigVariable(_In_z_ const TCHAR* configName, const ConfigPair* configPairs, _Out_writes_all_(cchOutputBuffer) TCHAR* outputBuffer, _In_ UInt32 cchOutputBuffer); + static bool priv_isspace(char c) { return (c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'); diff --git a/external/corert/src/Native/Runtime/RuntimeInstance.cpp b/external/corert/src/Native/Runtime/RuntimeInstance.cpp index d2efcf3bd2..0f1db5c648 100644 --- a/external/corert/src/Native/Runtime/RuntimeInstance.cpp +++ b/external/corert/src/Native/Runtime/RuntimeInstance.cpp @@ -349,8 +349,6 @@ Module * RuntimeInstance::FindModuleByOsHandle(HANDLE hOsHandle) RuntimeInstance::RuntimeInstance() : m_pThreadStore(NULL), - m_fStandaloneExeMode(false), - m_pStandaloneExeModule(NULL), m_pStaticGCRefsDescChunkList(NULL), m_pThreadStaticGCRefsDescChunkList(NULL), m_pGenericUnificationHashtable(NULL), @@ -382,13 +380,6 @@ EXTERN_C void REDHAWK_CALLCONV RhpSetHaveNewClasslibs(); bool RuntimeInstance::RegisterModule(ModuleHeader *pModuleHeader) { - // Determine whether we're in standalone exe mode. If we are we'll see the runtime module load followed by - // exactly one additional module (the exe itself). The exe module will have a standalone flag set in its - // header. - ASSERT(m_fStandaloneExeMode == false); - if (pModuleHeader->Flags & ModuleHeader::StandaloneExe) - m_fStandaloneExeMode = true; - CreateHolder pModule = Module::Create(pModuleHeader); if (NULL == pModule) @@ -401,9 +392,6 @@ bool RuntimeInstance::RegisterModule(ModuleHeader *pModuleHeader) m_ModuleList.PushHead(pModule); } - if (m_fStandaloneExeMode) - m_pStandaloneExeModule = pModule; - if (pModule->IsClasslibModule()) RhpSetHaveNewClasslibs(); diff --git a/external/corert/src/Native/Runtime/RuntimeInstance.h b/external/corert/src/Native/Runtime/RuntimeInstance.h index 5bbc096510..2b49bfd909 100644 --- a/external/corert/src/Native/Runtime/RuntimeInstance.h +++ b/external/corert/src/Native/Runtime/RuntimeInstance.h @@ -66,14 +66,6 @@ public: private: TypeManagerList m_TypeManagerList; - // Indicates whether the runtime is in standalone exe mode where the only Redhawk module that will be - // loaded into the process (besides the runtime's own module) is the exe itself. This flag will be - // correctly initialized once the exe module has loaded. - bool m_fStandaloneExeMode; - - // If m_fStandaloneExeMode is set this contains a pointer to the exe module. Otherwise it's null. - Module * m_pStandaloneExeModule; - #ifdef FEATURE_PROFILING // The thread writing the profile data is created lazily, whenever // a module with a profile section is registered. @@ -236,16 +228,6 @@ public: void WriteProfileInfo(); #endif // FEATURE_PROFILING - bool IsInStandaloneExeMode() - { - return m_fStandaloneExeMode; - } - - Module * GetStandaloneExeModule() - { - ASSERT(IsInStandaloneExeMode()); - return m_pStandaloneExeModule; - } }; typedef DPTR(RuntimeInstance) PTR_RuntimeInstance; diff --git a/external/corert/src/Native/Runtime/amd64/ExceptionHandling.S b/external/corert/src/Native/Runtime/amd64/ExceptionHandling.S index fcf4dfbda0..fa80c26ad2 100644 --- a/external/corert/src/Native/Runtime/amd64/ExceptionHandling.S +++ b/external/corert/src/Native/Runtime/amd64/ExceptionHandling.S @@ -207,6 +207,7 @@ NESTED_ENTRY RhpRethrow, _TEXT, NoHandler mov [rsi + OFFSETOF__ExInfo__m_exception], rdx // init the exception object to null mov byte ptr [rsi + OFFSETOF__ExInfo__m_passNumber], 1 // init to the first pass mov dword ptr [rsi + OFFSETOF__ExInfo__m_idxCurClause], 0xFFFFFFFF + mov byte ptr [rsi + OFFSETOF__ExInfo__m_kind], 0 // init to a deterministic value (ExKind.None) // link the ExInfo into the thread's ExInfo chain diff --git a/external/corert/src/Native/Runtime/amd64/ExceptionHandling.asm b/external/corert/src/Native/Runtime/amd64/ExceptionHandling.asm index 566dad71f1..b8727fc84b 100644 --- a/external/corert/src/Native/Runtime/amd64/ExceptionHandling.asm +++ b/external/corert/src/Native/Runtime/amd64/ExceptionHandling.asm @@ -254,6 +254,7 @@ NESTED_ENTRY RhpRethrow, _TEXT mov [rdx + OFFSETOF__ExInfo__m_exception], r8 ;; init the exception object to null mov byte ptr [rdx + OFFSETOF__ExInfo__m_passNumber], 1 ;; init to the first pass mov dword ptr [rdx + OFFSETOF__ExInfo__m_idxCurClause], 0FFFFFFFFh + mov byte ptr [rdx + OFFSETOF__ExInfo__m_kind], 0 ;; init to a deterministic value (ExKind.None) ;; link the ExInfo into the thread's ExInfo chain diff --git a/external/corert/src/Native/Runtime/arm/AllocFast.S b/external/corert/src/Native/Runtime/arm/AllocFast.S index e4dd26643a..ec9260855b 100644 --- a/external/corert/src/Native/Runtime/arm/AllocFast.S +++ b/external/corert/src/Native/Runtime/arm/AllocFast.S @@ -469,7 +469,7 @@ LOCAL_LABEL(BoxAlloc8Failed): // finalization. mov r0, r4 // restore EEType mov r1, #(GC_ALLOC_ALIGN8 | GC_ALLOC_ALIGN8_BIAS) - EPILOG_POP "{r4,pc}" + EPILOG_POP "{r4,lr}" b C_FUNC(RhpNewObject) LEAF_END RhpNewFastMisalign, _TEXT diff --git a/external/corert/src/Native/Runtime/arm/ExceptionHandling.S b/external/corert/src/Native/Runtime/arm/ExceptionHandling.S index 2732282e8e..3037905beb 100644 --- a/external/corert/src/Native/Runtime/arm/ExceptionHandling.S +++ b/external/corert/src/Native/Runtime/arm/ExceptionHandling.S @@ -109,7 +109,7 @@ NESTED_ENTRY RhpThrowEx, _TEXT, NoHandler // where the tail-calling thread had saved LR, which may not match where we have saved LR. ldr r1, [r0, #OFFSETOF__Thread__m_pvHijackedReturnAddress] - cbz r1, LOCAL_LABEL(NotHijacked) + cbz r1, LOCAL_LABEL(NotHiJacked) ldr r3, [r0, #OFFSETOF__Thread__m_ppvHijackedReturnAddressLocation] @@ -206,6 +206,7 @@ NESTED_ENTRY RhpRethrow, _TEXT, NoHandler mov r3, #0 str r3, [r1, #OFFSETOF__ExInfo__m_exception] // init the exception object to null + strb r3, [r1, #OFFSETOF__ExInfo__m_kind] // init to a deterministic value (ExKind.None) mov r3, #0xFFFFFFFF str r3, [r1, #OFFSETOF__ExInfo__m_idxCurClause] diff --git a/external/corert/src/Native/Runtime/arm/ExceptionHandling.asm b/external/corert/src/Native/Runtime/arm/ExceptionHandling.asm index bf21df089f..39c29992ae 100644 --- a/external/corert/src/Native/Runtime/arm/ExceptionHandling.asm +++ b/external/corert/src/Native/Runtime/arm/ExceptionHandling.asm @@ -211,6 +211,7 @@ NotHijacked add r1, sp, #rsp_offsetof_ExInfo ;; r1 <- ExInfo* mov r3, #0 str r3, [r1, #OFFSETOF__ExInfo__m_exception] ;; pExInfo->m_exception = null + strb r3, [r1, #OFFSETOF__ExInfo__m_kind] ;; init to a deterministic value (ExKind.None) mov r3, #1 strb r3, [r1, #OFFSETOF__ExInfo__m_passNumber] ;; pExInfo->m_passNumber = 1 mov r3, #0xFFFFFFFF diff --git a/external/corert/src/Native/Runtime/arm64/CallingConventionConverterHelpers.asm b/external/corert/src/Native/Runtime/arm64/CallingConventionConverterHelpers.asm index 2d43d5bba4..f60e115780 100644 --- a/external/corert/src/Native/Runtime/arm64/CallingConventionConverterHelpers.asm +++ b/external/corert/src/Native/Runtime/arm64/CallingConventionConverterHelpers.asm @@ -46,7 +46,7 @@ POINTER_SIZE equ 0x08 ldr xip0, [xip0, #POINTER_SIZE] ; get pointer to CallingConventionConverter_CommonCallingStub_PointerData into xip0 ldr x12, [xip0, #POINTER_SIZE] ; get address of UniversalTransitionThunk (which we'll tailcall to later) ldr xip0, [xip0] ; get address of ManagedCallConverterThunk (target for universal thunk to call) - ret x12 + br x12 LEAF_END __jmpstub__CallingConventionConverter_CommonCallingStub ;; diff --git a/external/corert/src/Native/Runtime/arm64/ExceptionHandling.asm b/external/corert/src/Native/Runtime/arm64/ExceptionHandling.asm index e08118516b..5a548279a0 100644 --- a/external/corert/src/Native/Runtime/arm64/ExceptionHandling.asm +++ b/external/corert/src/Native/Runtime/arm64/ExceptionHandling.asm @@ -15,15 +15,16 @@ ;; Macro used to create frame of exception throwing helpers (RhpThrowEx, RhpThrowHwEx) MACRO ALLOC_THROW_FRAME $exceptionType - - PROLOG_NOP mov x3, sp + PROLOG_NOP mov x3, sp + ;; Setup a PAL_LIMITED_CONTEXT on the stack { - PROLOG_STACK_ALLOC 0x50 IF $exceptionType == HARDWARE_EXCEPTION + PROLOG_NOP sub sp,sp,#0x50 PROLOG_NOP stp x3, x1, [sp] ; x3 is the SP and x1 is the IP of the fault site PROLOG_PUSH_MACHINE_FRAME ELSE + PROLOG_STACK_ALLOC 0x50 PROLOG_NOP stp x3, lr, [sp] ; x3 is the SP and lr is the IP of the fault site ENDIF PROLOG_NOP stp d8, d9, [sp, #0x10] @@ -49,12 +50,18 @@ MACRO ALLOC_CALL_FUNCLET_FRAME $extraStackSize - PROLOG_SAVE_REG_PAIR fp, lr, #-0x60! + ; Using below prolog instead of PROLOG_SAVE_REG_PAIR fp,lr, #-60! + ; is intentional. Above statement would also emit instruction to save + ; sp in fp. If sp is saved in fp in prolog then it is not expected that fp can change in the body + ; of method. However, this method needs to be able to change fp before calling funclet. + ; This is required to access locals in funclet. + PROLOG_SAVE_REG_PAIR_NO_FP fp,lr, #-0x60! PROLOG_SAVE_REG_PAIR x19, x20, #0x10 PROLOG_SAVE_REG_PAIR x21, x22, #0x20 PROLOG_SAVE_REG_PAIR x23, x24, #0x30 PROLOG_SAVE_REG_PAIR x25, x26, #0x40 PROLOG_SAVE_REG_PAIR x27, x28, #0x50 + PROLOG_NOP mov fp, sp IF $extraStackSize != 0 PROLOG_STACK_ALLOC $extraStackSize @@ -353,6 +360,7 @@ NotHijacked add x1, sp, #rsp_offsetof_ExInfo ;; x1 <- ExInfo* str xzr, [x1, #OFFSETOF__ExInfo__m_exception] ;; pExInfo->m_exception = null + strb wzr, [x1, #OFFSETOF__ExInfo__m_kind] ;; init to a deterministic value (ExKind.None) mov w3, #1 strb w3, [x1, #OFFSETOF__ExInfo__m_passNumber] ;; pExInfo->m_passNumber = 1 mov w3, #0xFFFFFFFF @@ -482,7 +490,7 @@ DonePopping NoAbort ;; reset SP and jump to continuation address mov sp, x2 - ret x0 + br x0 NESTED_END RhpCallCatchFunclet diff --git a/external/corert/src/Native/Runtime/arm64/GcProbe.asm b/external/corert/src/Native/Runtime/arm64/GcProbe.asm index 051b4158dc..73d674a5cb 100644 --- a/external/corert/src/Native/Runtime/arm64/GcProbe.asm +++ b/external/corert/src/Native/Runtime/arm64/GcProbe.asm @@ -48,7 +48,7 @@ PROBE_FRAME_SIZE field 0 ;; Perform the parts of setting up a probe frame that can occur during the prolog (and indeed this macro ;; can only be called from within the prolog). MACRO - ALLOC_PROBE_FRAME $extraStackSpace + ALLOC_PROBE_FRAME $extraStackSpace, $saveFPRegisters ;; First create PInvokeTransitionFrame PROLOG_SAVE_REG_PAIR fp, lr, #-(PROBE_FRAME_SIZE + $extraStackSpace)! ;; Push down stack pointer and store FP and LR @@ -80,16 +80,18 @@ PROBE_FRAME_SIZE field 0 ;; Slot at [sp, #0x118] is reserved for NZCV - ; Save the floating return registers - PROLOG_NOP stp d0, d1, [sp, #0x120] - PROLOG_NOP stp d2, d3, [sp, #0x130] + ;; Save the floating return registers + IF $saveFPRegisters + PROLOG_NOP stp d0, d1, [sp, #0x120] + PROLOG_NOP stp d2, d3, [sp, #0x130] + ENDIF MEND ;; Undo the effects of an ALLOC_PROBE_FRAME. This may only be called within an epilog. Note that all ;; registers are restored (apart for sp and pc), even volatiles. MACRO - FREE_PROBE_FRAME $extraStackSpace + FREE_PROBE_FRAME $extraStackSpace, $restoreFPRegisters ;; Restore the scratch registers PROLOG_NOP ldr x0, [sp, #0x78] @@ -105,8 +107,10 @@ PROBE_FRAME_SIZE field 0 PROLOG_NOP ldr lr, [sp, #0x110] ; Restore the floating return registers - EPILOG_NOP ldp d0, d1, [sp, #0x120] - EPILOG_NOP ldp d2, d3, [sp, #0x130] + IF $restoreFPRegisters + EPILOG_NOP ldp d0, d1, [sp, #0x120] + EPILOG_NOP ldp d2, d3, [sp, #0x130] + ENDIF ;; Restore callee saved registers EPILOG_RESTORE_REG_PAIR x19, x20, #0x20 @@ -167,7 +171,7 @@ __PPF_ThreadReg SETS "$threadReg" ; Define the method prolog, allocating enough stack space for the PInvokeTransitionFrame and saving ; incoming register values into it. - ALLOC_PROBE_FRAME 0 + ALLOC_PROBE_FRAME 0, {true} ; If the caller didn't provide a value for $threadReg then generate code to fetch the Thread* into x2. ; Record that x2 holds the Thread* in our local variable. @@ -188,58 +192,64 @@ __PPF_ThreadReg SETS "x2" MACRO EPILOG_PROBE_FRAME - FREE_PROBE_FRAME 0 + FREE_PROBE_FRAME 0, {true} EPILOG_RETURN MEND -;; ALLOC_PROBE_FRAME will save the first 4 vfp registers, in order to avoid trashing VFP registers across the loop -;; hijack, we must save the rest -- d4-d31 (28). -EXTRA_SAVE_SIZE equ (28*8) +;; In order to avoid trashing VFP registers across the loop hijack we must save all user registers, so that +;; registers used by the loop being hijacked will not be affected. Unlike ARM32 where neon registers (NQ0, ..., NQ15) +;; are fully covered by the floating point registers D0 ... D31, we have 32 neon registers Q0, ... Q31 on ARM64 +;; which are not fully covered by the register D0 ... D31. Therefore we must explicitly save all Q registers. +EXTRA_SAVE_SIZE equ (32*16) MACRO ALLOC_LOOP_HIJACK_FRAME PROLOG_STACK_ALLOC EXTRA_SAVE_SIZE -;; save VFP registers that were not saved by the ALLOC_PROBE_FRAME - PROLOG_NOP stp d4, d5, [sp] - PROLOG_NOP stp d6, d7, [sp, #0x10] - PROLOG_NOP stp d8, d9, [sp, #0x20] - PROLOG_NOP stp d10, d11, [sp, #0x30] - PROLOG_NOP stp d12, d13, [sp, #0x40] - PROLOG_NOP stp d14, d15, [sp, #0x50] - PROLOG_NOP stp d16, d17, [sp, #0x60] - PROLOG_NOP stp d18, d19, [sp, #0x70] - PROLOG_NOP stp d20, d21, [sp, #0x80] - PROLOG_NOP stp d22, d23, [sp, #0x90] - PROLOG_NOP stp d24, d25, [sp, #0xA0] - PROLOG_NOP stp d26, d27, [sp, #0xB0] - PROLOG_NOP stp d28, d29, [sp, #0xC0] - PROLOG_NOP stp d30, d31, [sp, #0xD0] - - ALLOC_PROBE_FRAME 0 + ;; Save all neon registers + PROLOG_NOP stp q0, q1, [sp] + PROLOG_NOP stp q2, q3, [sp, #0x20] + PROLOG_NOP stp q4, q5, [sp, #0x40] + PROLOG_NOP stp q6, q7, [sp, #0x60] + PROLOG_NOP stp q8, q9, [sp, #0x80] + PROLOG_NOP stp q10, q11, [sp, #0xA0] + PROLOG_NOP stp q12, q13, [sp, #0xC0] + PROLOG_NOP stp q14, q15, [sp, #0xE0] + PROLOG_NOP stp q16, q17, [sp, #0x100] + PROLOG_NOP stp q18, q19, [sp, #0x120] + PROLOG_NOP stp q20, q21, [sp, #0x140] + PROLOG_NOP stp q22, q23, [sp, #0x160] + PROLOG_NOP stp q24, q25, [sp, #0x180] + PROLOG_NOP stp q26, q27, [sp, #0x1A0] + PROLOG_NOP stp q28, q29, [sp, #0x1C0] + PROLOG_NOP stp q30, q31, [sp, #0x1E0] + + ALLOC_PROBE_FRAME 0, {false} MEND MACRO FREE_LOOP_HIJACK_FRAME - FREE_PROBE_FRAME 0 + FREE_PROBE_FRAME 0, {false} -;; restore VFP registers that will not be restored by the FREE_PROBE_FRAME - PROLOG_NOP ldp d4, d5, [sp] - PROLOG_NOP ldp d6, d7, [sp, #0x10] - PROLOG_NOP ldp d8, d9, [sp, #0x20] - PROLOG_NOP ldp d10, d11, [sp, #0x30] - PROLOG_NOP ldp d12, d13, [sp, #0x40] - PROLOG_NOP ldp d14, d15, [sp, #0x50] - PROLOG_NOP ldp d16, d17, [sp, #0x60] - PROLOG_NOP ldp d18, d19, [sp, #0x70] - PROLOG_NOP ldp d20, d21, [sp, #0x80] - PROLOG_NOP ldp d22, d23, [sp, #0x90] - PROLOG_NOP ldp d24, d25, [sp, #0xA0] - PROLOG_NOP ldp d26, d27, [sp, #0xB0] - PROLOG_NOP ldp d28, d29, [sp, #0xC0] - PROLOG_NOP ldp d30, d31, [sp, #0xD0] + ;; restore all neon registers + PROLOG_NOP ldp q0, q1, [sp] + PROLOG_NOP ldp q2, q3, [sp, #0x20] + PROLOG_NOP ldp q4, q5, [sp, #0x40] + PROLOG_NOP ldp q6, q7, [sp, #0x60] + PROLOG_NOP ldp q8, q9, [sp, #0x80] + PROLOG_NOP ldp q10, q11, [sp, #0xA0] + PROLOG_NOP ldp q12, q13, [sp, #0xC0] + PROLOG_NOP ldp q14, q15, [sp, #0xE0] + PROLOG_NOP ldp q16, q17, [sp, #0x100] + PROLOG_NOP ldp q18, q19, [sp, #0x120] + PROLOG_NOP ldp q20, q21, [sp, #0x140] + PROLOG_NOP ldp q22, q23, [sp, #0x160] + PROLOG_NOP ldp q24, q25, [sp, #0x180] + PROLOG_NOP ldp q26, q27, [sp, #0x1A0] + PROLOG_NOP ldp q28, q29, [sp, #0x1C0] + PROLOG_NOP ldp q30, q31, [sp, #0x1E0] EPILOG_STACK_FREE EXTRA_SAVE_SIZE MEND @@ -311,7 +321,7 @@ EXTRA_SAVE_SIZE equ (28*8) tst w2, #TSF_SuppressGcStress__OR__TSF_DoNotTriggerGC bne %ft0 - ldr x2, [x4, #OFFSETOF__Thread__m_pHackPInvokeTunnel] + ldr x9, [x4, #OFFSETOF__Thread__m_pHackPInvokeTunnel] bl RhpWaitForGCNoAbort 0 MEND @@ -383,7 +393,6 @@ EXTRA_SAVE_SIZE equ (28*8) #endif ;; FEATURE_GC_STRESS LEAF_ENTRY RhpGcProbe - brk 0xf000 ;; TODO: remove after debugging/testing stub ldr x3, =RhpTrapThreads ldr w3, [x3] tbnz x3, #TrapThreadsFlags_TrapThreads_Bit, RhpGcProbeRare @@ -393,7 +402,6 @@ EXTRA_SAVE_SIZE equ (28*8) EXTERN RhpThrowHwEx NESTED_ENTRY RhpGcProbeRare - brk 0xf000 ;; TODO: remove after debugging/testing stub PROLOG_PROBE_FRAME x2, x3, x12, mov x4, x2 @@ -405,7 +413,7 @@ EXTRA_SAVE_SIZE equ (28*8) EPILOG_PROBE_FRAME 1 - FREE_PROBE_FRAME 0 + FREE_PROBE_FRAME 0, {true} EPILOG_NOP mov w0, #STATUS_REDHAWK_THREAD_ABORT EPILOG_NOP mov x1, lr ;; return address as exception PC EPILOG_NOP b RhpThrowHwEx @@ -558,7 +566,7 @@ EXTRA_SAVE_SIZE equ (28*8) EPILOG_RESTORE_REG_PAIR x27, x28, #0x60 EPILOG_NOP ldr x9, [sp, #0x78] EPILOG_RESTORE_REG_PAIR fp, lr, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x20)! - EPILOG_NOP ret x9 + EPILOG_NOP br x9 NESTED_END RhpHijackForGcStressLeaf @@ -630,7 +638,7 @@ EXTRA_SAVE_SIZE equ (28*8) EHJumpProbeProlog PROLOG_NOP mov x0, x1 ; move the ex object reference into x0 so we can report it - ALLOC_PROBE_FRAME 0x10 + ALLOC_PROBE_FRAME 0x10, {true} str x2, [sp, #PROBE_FRAME_SIZE] ;; x2 <- GetThread(), TRASHES x1 @@ -665,9 +673,9 @@ EXTRA_SAVE_SIZE equ (28*8) EHJumpProbeEpilog ldr x2, [sp, #PROBE_FRAME_SIZE] - FREE_PROBE_FRAME 0x10 ; This restores exception object back into x0 + FREE_PROBE_FRAME 0x10, {true} ; This restores exception object back into x0 EPILOG_NOP mov x1, x0 ; Move the Exception object back into x1 where the catch handler expects it - EPILOG_NOP ret x2 + EPILOG_NOP br x2 MEND ;; @@ -825,7 +833,7 @@ Success NoGcStress #endif ;; FEATURE_GC_STRESS - add x2, sp, xzr ; sp is address of PInvokeTransitionFrame + mov x9, sp ; sp is address of PInvokeTransitionFrame bl RhpWaitForGCNoAbort DoneWaitingForGc @@ -839,7 +847,7 @@ DoneWaitingForGc EPILOG_NOP ldr x1, [sp, #8] ; hijack target address EPILOG_STACK_FREE 0x10 - EPILOG_NOP ret x1 ; jump to the hijack target + EPILOG_NOP br x1 ; jump to the hijack target Abort FREE_LOOP_HIJACK_FRAME @@ -852,4 +860,123 @@ Abort INLINE_GETTHREAD_CONSTANT_POOL +;; Trap to GC. +;; Set up the P/Invoke transition frame with the return address as the safe point. +;; All registers, both volatile and non-volatile, are preserved. +;; The function should be called not jumped because it's expecting the return address + NESTED_ENTRY RhpTrapToGC, _TEXT +;; + ;; What we want to get to: + ;; + ;; [sp + ] -> m_FramePointer -------| + ;; [sp + 8] -> m_RIP | + ;; [sp + 10] -> m_pThread | + ;; [sp + 18] -> m_Flags / m_dwAlignPad2 | + ;; [sp + 20] -> x19 save | + ;; [sp + 28] -> x20 save | + ;; [sp + 30] -> x21 save | + ;; [sp + 38] -> x22 save | + ;; [sp + 40] -> x23 save | + ;; [sp + 48] -> x24 save | PInvokeTransitionFrame + ;; [sp + 50] -> x25 save | + ;; [sp + 58] -> x26 save | + ;; [sp + 60] -> x27 save | + ;; [sp + 68] -> x28 save | + ;; [sp + 70] -> sp save ;caller sp | + ;; [sp + 78] -> x0 save | + ;; [sp + 80] -> x1 save | + ;; [sp + 88] -> x2 save | + ;; [sp + 90] -> x3 save | + ;; [sp + 98] -> x4 save | + ;; [sp + a0] -> x5 save | + ;; [sp + a8] -> x6 save | + ;; [sp + b0] -> x7 save | + ;; [sp + b8] -> x8 save | + ;; [sp + c0] -> x9 save | + ;; [sp + c8] -> x10 save | + ;; [sp + d0] -> x11 save | + ;; [sp + d8] -> x12 save | + ;; [sp + e0] -> x13 save | + ;; [sp + e8] -> x14 save | + ;; [sp + f0] -> x15 save | + ;; [sp + f8] -> x16 save | + ;; [sp + 100] -> x17 save | + ;; [sp + 108] -> x18 save | + ;; [sp + 110] -> lr save -------| + ;; + ;; [sp + 118] -> NZCV + ;; + ;; [sp + 120] -> not used + ;; [sp + 140] -> q0 ... q31 + ;; + + ALLOC_LOOP_HIJACK_FRAME + + ;; Slot at [sp, #0x118] is reserved for NZCV + mrs x1, NZCV + str x1, [sp, #m_SavedNZCV] + + ;; x4 <- GetThread(), TRASHES x1 + INLINE_GETTHREAD x4, x1 + INIT_PROBE_FRAME x4, x1, #PROBE_SAVE_FLAGS_EVERYTHING, 0, (PROBE_FRAME_SIZE + EXTRA_SAVE_SIZE) + + ; Early out if GC stress is currently suppressed. Do this after we have computed the real address to + ; return to but before we link the transition frame onto m_pHackPInvokeTunnel (because hitting this + ; condition implies we're running restricted callouts during a GC itself and we could end up + ; overwriting a co-op frame set by the code that caused the GC in the first place, e.g. a GC.Collect + ; call). + ldr w1, [x4, #OFFSETOF__Thread__m_ThreadStateFlags] + tst w1, #TSF_SuppressGcStress__OR__TSF_DoNotTriggerGC + bne DoNotTriggerGC + + ; link the frame into the Thread + add x1, sp, xzr + str x1, [x4, #OFFSETOF__Thread__m_pHackPInvokeTunnel] + + ;; + ;; Unhijack this thread, if necessary. + ;; + INLINE_THREAD_UNHIJACK x4, x1, x2 ;; trashes x1, x2 + +#ifdef FEATURE_GC_STRESS + + ldr x1, =g_fGcStressStarted + ldr w1, [x1] + cbnz w1, SkipGcStress + + mov x1, x0 + ldr x0, =$g_pTheRuntimeInstance + ldr x0, [x0] + bl $RuntimeInstance__ShouldHijackLoopForGcStress + cbnz x0, SkipGcStress + + bl $REDHAWKGCINTERFACE__STRESSGC +SkipGcStress +#endif ;; FEATURE_GC_STRESS + + mov x9, sp ; sp is address of PInvokeTransitionFrame + bl RhpWaitForGCNoAbort + +DoNotTriggerGC + ldr x1, [sp, #OFFSETOF__PInvokeTransitionFrame__m_Flags] + tbnz x1, #PTFF_THREAD_ABORT_BIT, ToAbort + + ; restore condition codes + ldr x1, [sp, #m_SavedNZCV] + msr NZCV, x1 + + FREE_LOOP_HIJACK_FRAME + EPILOG_RETURN + +ToAbort + FREE_LOOP_HIJACK_FRAME + EPILOG_NOP mov w0, #STATUS_REDHAWK_THREAD_ABORT + EPILOG_NOP mov x1, lr ; hijack target address as exception PC + EPILOG_NOP b RhpThrowHwEx + + NESTED_END RhpTrapToGC + + INLINE_GETTHREAD_CONSTANT_POOL + end + diff --git a/external/corert/src/Native/Runtime/arm64/InteropThunksHelpers.asm b/external/corert/src/Native/Runtime/arm64/InteropThunksHelpers.asm index 88bb7da5d5..cc8489ef13 100644 --- a/external/corert/src/Native/Runtime/arm64/InteropThunksHelpers.asm +++ b/external/corert/src/Native/Runtime/arm64/InteropThunksHelpers.asm @@ -58,7 +58,7 @@ __SECTIONREL_ThunkParamSlot ;; Now load the target address and jump to it. ldr xip0, [xip0, #POINTER_SIZE] - ret xip0 + br xip0 LEAF_END RhCommonStub diff --git a/external/corert/src/Native/Runtime/arm64/MiscStubs.asm b/external/corert/src/Native/Runtime/arm64/MiscStubs.asm index ba18a93c20..99c05e4a37 100644 --- a/external/corert/src/Native/Runtime/arm64/MiscStubs.asm +++ b/external/corert/src/Native/Runtime/arm64/MiscStubs.asm @@ -96,7 +96,7 @@ RhpCheckCctor__SlowPath EPILOG_RESTORE_REG_PAIR fp, lr, #0x20! ;; tail-call the class lib cctor check function. This function is required to return its first ;; argument, so that x0 can be preserved. - EPILOG_NOP ret x12 + EPILOG_NOP br x12 NESTED_END RhpCheckCctor__SlowPath2 diff --git a/external/corert/src/Native/Runtime/arm64/StubDispatch.asm b/external/corert/src/Native/Runtime/arm64/StubDispatch.asm index 82a4f861e3..8f3b7488c1 100644 --- a/external/corert/src/Native/Runtime/arm64/StubDispatch.asm +++ b/external/corert/src/Native/Runtime/arm64/StubDispatch.asm @@ -55,7 +55,7 @@ SECTIONREL_t_TLS_DispatchCell cmp x10, x11 bne %ft0 ;; Jump to label '0' ldr x9, [x9, #(OFFSETOF__InterfaceDispatchCache__m_rgEntries + ($entry * 16) + 8)] - ret x9 + br x9 0 ;; Label '0' MEND @@ -70,7 +70,7 @@ SECTIONREL_t_TLS_DispatchCell ;; Now load the target address and jump to it. ldr x9, [xip0, #8] - ret x9 + br x9 LEAF_END RhpCastableObjectDispatch_CommonStub LEAF_ENTRY RhpTailCallTLSDispatchCell @@ -79,7 +79,7 @@ SECTIONREL_t_TLS_DispatchCell ;; Tail call to the target of the dispatch cell, preserving the cell address in xip1 ldr x9, [xip1] - ret x9 + br x9 LEAF_END RhpTailCallTLSDispatchCell LEAF_ENTRY RhpCastableObjectDispatchHelper_TailCalled @@ -168,7 +168,7 @@ CurrentEntry SETA CurrentEntry + 1 ;; Load the target address of the vtable into x12 ldr x12, [x12] - ret x12 + br x12 LEAF_END RhpVTableOffsetDispatch ;; diff --git a/external/corert/src/Native/Runtime/arm64/ThunkPoolThunks.asm b/external/corert/src/Native/Runtime/arm64/ThunkPoolThunks.asm index ddd2636dbc..ddf39de36a 100644 --- a/external/corert/src/Native/Runtime/arm64/ThunkPoolThunks.asm +++ b/external/corert/src/Native/Runtime/arm64/ThunkPoolThunks.asm @@ -29,7 +29,6 @@ RO$name % 8 MACRO LOAD_DATA_ADDRESS $groupIndex, $index, $pageIndex - ALIGN 0x10 ;; make sure we align to 16-byte boundary for CFG table ;; Set xip0 to the address of the current thunk's data block. This is done using labels. adr xip0, label_$groupIndex_$index_P$pageIndex @@ -42,9 +41,9 @@ RO$name % 8 ;; fix offset to point to last QWROD in page : xip1 <- [xip0 + PAGE_SIZE - POINTER_SIZE] ;; tailcall to the location pointed at by the last qword in the data page ldr xip1, [xip0, #(PAGE_SIZE - POINTER_SIZE - ($groupIndex * THUNK_DATASIZE * 10 + THUNK_DATASIZE * $index))] - ret xip1 + br xip1 - brk 0xf000 ;; Stubs need to be 16-byte aligned (see comment above). Filling padding with a + brk 0xf000 ;; Stubs need to be 16-byte aligned for CFG table. Filling padding with a ;; deterministic brk instruction, instead of having it just filled with zeros. MEND diff --git a/external/corert/src/Native/Runtime/arm64/UniversalTransition.asm b/external/corert/src/Native/Runtime/arm64/UniversalTransition.asm index fe47637405..dc699ebed4 100644 --- a/external/corert/src/Native/Runtime/arm64/UniversalTransition.asm +++ b/external/corert/src/Native/Runtime/arm64/UniversalTransition.asm @@ -147,7 +147,7 @@ EPILOG_RESTORE_REG_PAIR fp, lr, #STACK_SIZE! ;; Tailcall to the target address. - EPILOG_NOP ret x12 + EPILOG_NOP br x12 NESTED_END Rhp$FunctionName diff --git a/external/corert/src/Native/Runtime/i386/ExceptionHandling.asm b/external/corert/src/Native/Runtime/i386/ExceptionHandling.asm index 270cb23303..1981279abc 100644 --- a/external/corert/src/Native/Runtime/i386/ExceptionHandling.asm +++ b/external/corert/src/Native/Runtime/i386/ExceptionHandling.asm @@ -207,6 +207,7 @@ FASTCALL_FUNC RhpRethrow, 0 mov [edx + OFFSETOF__ExInfo__m_exception], esi ;; init the exception object to null mov byte ptr [edx + OFFSETOF__ExInfo__m_passNumber], 1 ;; init to the first pass mov dword ptr [edx + OFFSETOF__ExInfo__m_idxCurClause], 0FFFFFFFFh + mov byte ptr [edx + OFFSETOF__ExInfo__m_kind], 0 ;; init to a deterministic value (ExKind.None) ;; link the ExInfo into the thread's ExInfo chain mov ecx, [eax + OFFSETOF__Thread__m_pExInfoStackHead] ;; ecx <- currently active ExInfo diff --git a/external/corert/src/Native/Runtime/i386/ThunkPoolThunks.asm b/external/corert/src/Native/Runtime/i386/ThunkPoolThunks.asm index 1eb5312a0c..848ab3dd17 100644 --- a/external/corert/src/Native/Runtime/i386/ThunkPoolThunks.asm +++ b/external/corert/src/Native/Runtime/i386/ThunkPoolThunks.asm @@ -1,8 +1,6 @@ -;; ==++== -;; -;; Copyright (c) Microsoft Corporation. All rights reserved. -;; -;; ==--== +;; Licensed to the .NET Foundation under one or more agreements. +;; The .NET Foundation licenses this file to you under the MIT license. +;; See the LICENSE file in the project root for more information. .586 .model flat diff --git a/external/corert/src/Native/Runtime/inc/eetype.h b/external/corert/src/Native/Runtime/inc/eetype.h index 39949b5ebf..48431726ae 100644 --- a/external/corert/src/Native/Runtime/inc/eetype.h +++ b/external/corert/src/Native/Runtime/inc/eetype.h @@ -568,23 +568,7 @@ public: bool HasDynamicallyAllocatedDispatchMap() { return (get_RareFlags() & HasDynamicallyAllocatedDispatchMapFlag) != 0; } - // Retrieve the generic type definition EEType for this generic instance - void set_GenericDefinition(EEType *pTypeDef); - - // Retrieve the generic type definition EEType for this generic instance - EETypeRef & get_GenericDefinition(); - inline void set_GenericComposition(GenericComposition *); - inline GenericComposition *get_GenericComposition(); - - // Retrieve the number of generic arguments for this generic type instance - UInt32 get_GenericArity(); - - // Retrieve the generic arguments to this type - EETypeRef * get_GenericArguments(); - - // Retrieve the generic variance associated with this type - GenericVarianceType* get_GenericVariance(); // Retrieve template used to create the dynamic type EEType * get_DynamicTemplateType(); diff --git a/external/corert/src/Native/Runtime/inc/eetype.inl b/external/corert/src/Native/Runtime/inc/eetype.inl index e52fed1482..38e4ad89a3 100644 --- a/external/corert/src/Native/Runtime/inc/eetype.inl +++ b/external/corert/src/Native/Runtime/inc/eetype.inl @@ -372,65 +372,15 @@ inline UInt8 EEType::GetNullableValueOffset() return pOptFields->GetNullableValueOffset(0) + 1; } -inline void EEType::set_GenericDefinition(EEType *pTypeDef) -{ - ASSERT(IsGeneric()); - - UInt32 cbOffset = GetFieldOffset(ETF_GenericDefinition); - - *(EEType**)((UInt8*)this + cbOffset) = pTypeDef; -} - -inline EETypeRef & EEType::get_GenericDefinition() -{ - ASSERT(IsGeneric()); - - UInt32 cbOffset = GetFieldOffset(ETF_GenericDefinition); - - return *(EETypeRef *)((UInt8*)this + cbOffset); -} - inline void EEType::set_GenericComposition(GenericComposition *pGenericComposition) { - ASSERT(IsGeneric()); + ASSERT(IsGeneric() && IsDynamicType()); UInt32 cbOffset = GetFieldOffset(ETF_GenericComposition); *(GenericComposition **)((UInt8*)this + cbOffset) = pGenericComposition; } -inline GenericComposition *EEType::get_GenericComposition() -{ - ASSERT(IsGeneric()); - - UInt32 cbOffset = GetFieldOffset(ETF_GenericComposition); - - GenericComposition *pGenericComposition = *(GenericComposition **)((UInt8*)this + cbOffset); - - return pGenericComposition; -} - -inline UInt32 EEType::get_GenericArity() -{ - GenericComposition *pGenericComposition = get_GenericComposition(); - - return pGenericComposition->GetArity(); -} - -inline EETypeRef* EEType::get_GenericArguments() -{ - GenericComposition *pGenericComposition = get_GenericComposition(); - - return pGenericComposition->GetArguments(); -} - -inline GenericVarianceType* EEType::get_GenericVariance() -{ - GenericComposition *pGenericComposition = get_GenericComposition(); - - return pGenericComposition->GetVariance(); -} - inline EEType * EEType::get_DynamicTemplateType() { ASSERT(IsDynamicType()); @@ -570,7 +520,7 @@ inline DynamicModule * EEType::get_DynamicModule() + (fRequiresOptionalFields ? sizeof(UIntTarget) : 0) + (fRequiresNullableType ? sizeof(UIntTarget) : 0) + (fHasSealedVirtuals ? sizeof(Int32) : 0) - + (fHasGenericInfo ? sizeof(UIntTarget)*2 : 0); + + (fHasGenericInfo ? sizeof(UInt32)*2 : 0); } #if !defined(BINDER) && !defined(DACCESS_COMPILE) @@ -578,21 +528,10 @@ inline DynamicModule * EEType::get_DynamicModule() // represented - instead the classlib has a common one for all arrays inline EEType * EEType::GetArrayBaseType() { - RuntimeInstance * pRuntimeInstance = GetRuntimeInstance(); - Module * pModule = NULL; - if (pRuntimeInstance->IsInStandaloneExeMode()) - { - // With dynamically created types, there is no home module to use to find System.Array. That's okay - // for now, but when we support multi-module, we'll have to do something more clever here. - pModule = pRuntimeInstance->GetStandaloneExeModule(); - } - else - { - EEType *pEEType = this; - if (pEEType->IsDynamicType()) - pEEType = pEEType->get_DynamicTemplateType(); - pModule = GetRuntimeInstance()->FindModuleByReadOnlyDataAddress(pEEType); - } + EEType *pEEType = this; + if (pEEType->IsDynamicType()) + pEEType = pEEType->get_DynamicTemplateType(); + Module * pModule = GetRuntimeInstance()->FindModuleByReadOnlyDataAddress(pEEType); EEType * pArrayBaseType = pModule->GetArrayBaseType(); return pArrayBaseType; } @@ -684,7 +623,7 @@ __forceinline UInt32 EEType::GetFieldOffset(EETypeField eField) return cbOffset; } if (IsGeneric()) - cbOffset += sizeof(UIntTarget); + cbOffset += (IsDynamicType() ? sizeof(UIntTarget) : sizeof(UInt32)); if (eField == ETF_GenericComposition) { @@ -692,7 +631,7 @@ __forceinline UInt32 EEType::GetFieldOffset(EETypeField eField) return cbOffset; } if (IsGeneric()) - cbOffset += sizeof(UIntTarget); + cbOffset += (IsDynamicType() ? sizeof(UIntTarget) : sizeof(UInt32)); if (eField == ETF_DynamicModule) { @@ -806,7 +745,7 @@ __forceinline UInt32 EEType::GetFieldOffset(EETypeField eField) { return cbOffset; } - cbOffset += sizeof(UIntTarget); + cbOffset += sizeof(UInt32); if (eField == ETF_GenericComposition) { diff --git a/external/corert/src/Native/Runtime/thread.cpp b/external/corert/src/Native/Runtime/thread.cpp index 994c21dad8..aaefff9717 100644 --- a/external/corert/src/Native/Runtime/thread.cpp +++ b/external/corert/src/Native/Runtime/thread.cpp @@ -31,7 +31,8 @@ #ifndef DACCESS_COMPILE EXTERN_C REDHAWK_API void* REDHAWK_CALLCONV RhpHandleAlloc(void* pObject, int type); -EXTERN_C REDHAWK_API void REDHAWK_CALLCONV RhHandleFree(void*); +EXTERN_C REDHAWK_API void REDHAWK_CALLCONV RhHandleSet(void* handle, void* pObject); +EXTERN_C REDHAWK_API void REDHAWK_CALLCONV RhHandleFree(void* handle); static int (*g_RuntimeInitializationCallback)(); static Thread* g_RuntimeInitializingThread; @@ -132,7 +133,7 @@ void Thread::ResetCachedTransitionFrame() // This function simulates a PInvoke transition using a frame pointer from somewhere further up the stack that // was passed in via the m_pHackPInvokeTunnel field. It is used to allow us to grandfather-in the set of GC // code that runs in cooperative mode without having to rewrite it in managed code. The result is that the -// code that calls into this special mode must spill preserved registeres as if it's going to PInvoke, but +// code that calls into this special mode must spill preserved registers as if it's going to PInvoke, but // record its transition frame pointer in m_pHackPInvokeTunnel and leave the thread in the cooperative // mode. Later on, when this function is called, we effect the state transition to 'unmanaged' using the // previously setup transition frame. @@ -727,8 +728,6 @@ bool Thread::InternalHijack(PAL_LIMITED_CONTEXT * pSuspendCtx, void * pvHijackTa if (frameIterator.IsValid()) { - CrossThreadUnhijack(); - frameIterator.CalculateCurrentMethodState(); frameIterator.GetCodeManager()->UnsynchronizedHijackMethodLoops(frameIterator.GetMethodInfo()); @@ -737,10 +736,16 @@ bool Thread::InternalHijack(PAL_LIMITED_CONTEXT * pSuspendCtx, void * pvHijackTa GCRefKind retValueKind; if (frameIterator.GetCodeManager()->GetReturnAddressHijackInfo(frameIterator.GetMethodInfo(), - frameIterator.GetRegisterSet(), - &ppvRetAddrLocation, - &retValueKind)) + frameIterator.GetRegisterSet(), + &ppvRetAddrLocation, + &retValueKind)) { + // ARM64 epilogs have a window between loading the hijackable return address into LR and the RET instruction. + // We cannot hijack or unhijack a thread while it is suspended in that window unless we implement hijacking + // via LR register modification. Therefore it is important to check our ability to hijack the thread before + // unhijacking it. + CrossThreadUnhijack(); + void* pvRetAddr = *ppvRetAddrLocation; ASSERT(ppvRetAddrLocation != NULL); ASSERT(pvRetAddr != NULL); @@ -1318,26 +1323,27 @@ Boolean Thread::SetThreadStaticStorageForModule(Object * pStorage, UInt32 module m_numThreadLocalModuleStatics = newSize; } - void* threadStaticsStorageHandle = RhpHandleAlloc(pStorage, 2 /* Normal */); - if (threadStaticsStorageHandle == NULL) - { - return FALSE; - } - - // Free the existing storage before assigning a new one if (m_pThreadLocalModuleStatics[moduleIndex] != NULL) { - RhHandleFree(m_pThreadLocalModuleStatics[moduleIndex]); + RhHandleSet(m_pThreadLocalModuleStatics[moduleIndex], pStorage); + } + else + { + void* threadStaticsStorageHandle = RhpHandleAlloc(pStorage, 2 /* Normal */); + if (threadStaticsStorageHandle == NULL) + { + return FALSE; + } + m_pThreadLocalModuleStatics[moduleIndex] = threadStaticsStorageHandle; } - m_pThreadLocalModuleStatics[moduleIndex] = threadStaticsStorageHandle; return TRUE; } -COOP_PINVOKE_HELPER(Array*, RhGetThreadStaticStorageForModule, (UInt32 moduleIndex)) +COOP_PINVOKE_HELPER(Object*, RhGetThreadStaticStorageForModule, (UInt32 moduleIndex)) { Thread * pCurrentThread = ThreadStore::RawGetCurrentThread(); - return (Array*)pCurrentThread->GetThreadStaticStorageForModule(moduleIndex); + return pCurrentThread->GetThreadStaticStorageForModule(moduleIndex); } COOP_PINVOKE_HELPER(Boolean, RhSetThreadStaticStorageForModule, (Array * pStorage, UInt32 moduleIndex)) @@ -1357,6 +1363,12 @@ COOP_PINVOKE_HELPER(UInt8*, RhCurrentNativeThreadId, ()) } #endif // !PROJECTN +// This function is used to get the OS thread identifier for the current thread. +COOP_PINVOKE_HELPER(UInt64, RhCurrentOSThreadId, ()) +{ + return PalGetCurrentThreadIdForLogging(); +} + // Standard calling convention variant and actual implementation for RhpReversePInvokeAttachOrTrapThread EXTERN_C NOINLINE void FASTCALL RhpReversePInvokeAttachOrTrapThread2(ReversePInvokeFrame * pFrame) { diff --git a/external/corert/src/Native/Runtime/thread.h b/external/corert/src/Native/Runtime/thread.h index c3934c823d..b2143c75d7 100644 --- a/external/corert/src/Native/Runtime/thread.h +++ b/external/corert/src/Native/Runtime/thread.h @@ -46,7 +46,9 @@ struct ExInfo; typedef DPTR(ExInfo) PTR_ExInfo; -// also defined in ExceptionHandling.cs, layouts must match +// Also defined in ExceptionHandling.cs, layouts must match. +// When adding new fields to this struct, ensure they get properly initialized in the exception handling +// assembly stubs struct ExInfo { diff --git a/external/corert/src/Native/Runtime/unix/PalRedhawkInline.h b/external/corert/src/Native/Runtime/unix/PalRedhawkInline.h index e46d9ce874..67e197e72a 100644 --- a/external/corert/src/Native/Runtime/unix/PalRedhawkInline.h +++ b/external/corert/src/Native/Runtime/unix/PalRedhawkInline.h @@ -43,7 +43,11 @@ FORCEINLINE Int32 PalInterlockedCompareExchange(_Inout_ _Interlocked_operand_ In FORCEINLINE Int64 PalInterlockedCompareExchange64(_Inout_ _Interlocked_operand_ Int64 volatile *pDst, Int64 iValue, Int64 iComparand) { +#if defined(_WASM_) + PORTABILITY_ASSERT("Emscripten does not support 64-bit atomics until version 1.37.33"); +#else // _WASM_ return __sync_val_compare_and_swap(pDst, iComparand, iValue); +#endif // _WASM_ } #if defined(_AMD64_) diff --git a/external/corert/src/Native/Runtime/unix/PalRedhawkUnix.cpp b/external/corert/src/Native/Runtime/unix/PalRedhawkUnix.cpp index 0807d80041..de3d296aee 100644 --- a/external/corert/src/Native/Runtime/unix/PalRedhawkUnix.cpp +++ b/external/corert/src/Native/Runtime/unix/PalRedhawkUnix.cpp @@ -94,6 +94,14 @@ using std::nullptr_t; #endif #endif // __APPLE__ +#if defined(_ARM_) || defined(_ARM64_) +#define SYSCONF_GET_NUMPROCS _SC_NPROCESSORS_CONF +#define SYSCONF_GET_NUMPROCS_NAME "_SC_NPROCESSORS_CONF" +#else +#define SYSCONF_GET_NUMPROCS _SC_NPROCESSORS_ONLN +#define SYSCONF_GET_NUMPROCS_NAME "_SC_NPROCESSORS_ONLN" +#endif + #define PalRaiseFailFastException RaiseFailFastException #define FATAL_ASSERT(e, msg) \ @@ -834,10 +842,10 @@ bool QueryCacheSize() bool QueryLogicalProcessorCount() { #if HAVE_SYSCONF - g_cLogicalCpus = sysconf(_SC_NPROCESSORS_ONLN); + g_cLogicalCpus = sysconf(SYSCONF_GET_NUMPROCS); if (g_cLogicalCpus < 1) { - ASSERT_UNCONDITIONALLY("sysconf failed for _SC_NPROCESSORS_ONLN\n"); + ASSERT_UNCONDITIONALLY("sysconf failed for " SYSCONF_GET_NUMPROCS_NAME "\n"); return false; } #elif HAVE_SYSCTL @@ -1268,10 +1276,10 @@ bool InitializeSystemInfo() int nrcpus = 0; #if HAVE_SYSCONF - nrcpus = sysconf(_SC_NPROCESSORS_ONLN); + nrcpus = sysconf(SYSCONF_GET_NUMPROCS); if (nrcpus < 1) { - ASSERT_UNCONDITIONALLY("sysconf failed for _SC_NPROCESSORS_ONLN\n"); + ASSERT_UNCONDITIONALLY("sysconf failed for " SYSCONF_GET_NUMPROCS_NAME "\n"); return false; } #elif HAVE_SYSCTL diff --git a/external/corert/src/Native/Runtime/unix/UnixContext.cpp b/external/corert/src/Native/Runtime/unix/UnixContext.cpp index 18fff0ccbd..ea538213c0 100644 --- a/external/corert/src/Native/Runtime/unix/UnixContext.cpp +++ b/external/corert/src/Native/Runtime/unix/UnixContext.cpp @@ -232,11 +232,11 @@ int unw_get_save_loc(unw_cursor_t*, int, unw_save_loc_t*) static void RegDisplayToUnwindCursor(REGDISPLAY* regDisplay, unw_cursor_t *cursor) { #define ASSIGN_REG(regName1, regName2) \ - unw_set_reg(cursor, regName1, regDisplay->regName2); + unw_set_reg(cursor, regName1, regDisplay->regName2, 0); #define ASSIGN_REG_PTR(regName1, regName2) \ if (regDisplay->p##regName2 != NULL) \ - unw_set_reg(cursor, regName1, *(regDisplay->p##regName2)); + unw_set_reg(cursor, regName1, *(regDisplay->p##regName2), 0); #if defined(_AMD64_) ASSIGN_REG(UNW_REG_SP, SP) diff --git a/external/corert/src/Native/Runtime/unix/UnixNativeCodeManager.cpp b/external/corert/src/Native/Runtime/unix/UnixNativeCodeManager.cpp index 480893f972..70b94e752a 100644 --- a/external/corert/src/Native/Runtime/unix/UnixNativeCodeManager.cpp +++ b/external/corert/src/Native/Runtime/unix/UnixNativeCodeManager.cpp @@ -41,8 +41,10 @@ struct UnixNativeMethodInfo static_assert(sizeof(UnixNativeMethodInfo) <= sizeof(MethodInfo), "UnixNativeMethodInfo too big"); UnixNativeCodeManager::UnixNativeCodeManager(TADDR moduleBase, + PTR_VOID pvManagedCodeStartRange, UInt32 cbManagedCodeRange, PTR_PTR_VOID pClasslibFunctions, UInt32 nClasslibFunctions) : m_moduleBase(moduleBase), + m_pvManagedCodeStartRange(pvManagedCodeStartRange), m_cbManagedCodeRange(cbManagedCodeRange), m_pClasslibFunctions(pClasslibFunctions), m_nClasslibFunctions(nClasslibFunctions) { } @@ -54,6 +56,13 @@ UnixNativeCodeManager::~UnixNativeCodeManager() bool UnixNativeCodeManager::FindMethodInfo(PTR_VOID ControlPC, MethodInfo * pMethodInfoOut) { + // Stackwalker may call this with ControlPC that does not belong to this code manager + if (dac_cast(ControlPC) < dac_cast(m_pvManagedCodeStartRange) || + dac_cast(m_pvManagedCodeStartRange) + m_cbManagedCodeRange <= dac_cast(ControlPC)) + { + return false; + } + UnixNativeMethodInfo * pMethodInfo = (UnixNativeMethodInfo *)pMethodInfoOut; UIntNative startAddress; UIntNative lsda; @@ -396,6 +405,7 @@ bool RhRegisterOSModule(void * pModule, void ** pClasslibFunctions, UInt32 nClasslibFunctions) { NewHolder pUnixNativeCodeManager = new (nothrow) UnixNativeCodeManager((TADDR)pModule, + pvManagedCodeStartRange, cbManagedCodeRange, pClasslibFunctions, nClasslibFunctions); if (pUnixNativeCodeManager == nullptr) diff --git a/external/corert/src/Native/Runtime/unix/UnixNativeCodeManager.h b/external/corert/src/Native/Runtime/unix/UnixNativeCodeManager.h index b8e38fbb0e..0b80291b8e 100644 --- a/external/corert/src/Native/Runtime/unix/UnixNativeCodeManager.h +++ b/external/corert/src/Native/Runtime/unix/UnixNativeCodeManager.h @@ -7,12 +7,17 @@ class UnixNativeCodeManager : public ICodeManager { TADDR m_moduleBase; + + PTR_VOID m_pvManagedCodeStartRange; + UInt32 m_cbManagedCodeRange; + PTR_PTR_VOID m_pClasslibFunctions; UInt32 m_nClasslibFunctions; public: UnixNativeCodeManager(TADDR moduleBase, - PTR_PTR_VOID pClasslibFunctions, UInt32 nClasslibFunctions); + PTR_VOID pvManagedCodeStartRange, UInt32 cbManagedCodeRange, + PTR_PTR_VOID pClasslibFunctions, UInt32 nClasslibFunctions); virtual ~UnixNativeCodeManager(); diff --git a/external/corert/src/Native/Runtime/unix/UnwindHelpers.cpp b/external/corert/src/Native/Runtime/unix/UnwindHelpers.cpp index c77de82009..7322e1ab1e 100644 --- a/external/corert/src/Native/Runtime/unix/UnwindHelpers.cpp +++ b/external/corert/src/Native/Runtime/unix/UnwindHelpers.cpp @@ -292,13 +292,152 @@ struct Registers_REGDISPLAY : REGDISPLAY }; #endif // _TARGET_AMD64_ +#if defined(_TARGET_ARM_) + +class Registers_arm_rt: public libunwind::Registers_arm { +public: + Registers_arm_rt() { abort(); }; + Registers_arm_rt(void *registers) { regs = (REGDISPLAY *)registers; }; + uint32_t getRegister(int num); + void setRegister(int num, uint32_t value, uint32_t location); + uint32_t getRegisterLocation(int regNum) const { abort();} + unw_fpreg_t getFloatRegister(int num) { abort();} + void setFloatRegister(int num, unw_fpreg_t value) {abort();} + bool validVectorRegister(int num) const { abort();} + uint32_t getVectorRegister(int num) const {abort();}; + void setVectorRegister(int num, uint32_t value) {abort();}; + void jumpto() { abort();}; + uint32_t getSP() const { return regs->SP;} + void setSP(uint32_t value, uint32_t location) { regs->SP = value;} + uint32_t getIP() const { return regs->IP;} + void setIP(uint32_t value, uint32_t location) + { regs->IP = value; regs->pIP = (PTR_UIntNative)location; } + void saveVFPAsX() {abort();}; +private: + REGDISPLAY *regs; +}; + +inline uint32_t Registers_arm_rt::getRegister(int regNum) { + if (regNum == UNW_REG_SP || regNum == UNW_ARM_SP) + return regs->SP; + + if (regNum == UNW_ARM_LR) + return *regs->pLR; + + if (regNum == UNW_REG_IP || regNum == UNW_ARM_IP) + return regs->IP; + + switch (regNum) + { + case (UNW_ARM_R0): + return *regs->pR0; + case (UNW_ARM_R1): + return *regs->pR1; + case (UNW_ARM_R2): + return *regs->pR2; + case (UNW_ARM_R3): + return *regs->pR3; + case (UNW_ARM_R4): + return *regs->pR4; + case (UNW_ARM_R5): + return *regs->pR5; + case (UNW_ARM_R6): + return *regs->pR6; + case (UNW_ARM_R7): + return *regs->pR7; + case (UNW_ARM_R8): + return *regs->pR8; + case (UNW_ARM_R9): + return *regs->pR9; + case (UNW_ARM_R10): + return *regs->pR10; + case (UNW_ARM_R11): + return *regs->pR11; + case (UNW_ARM_R12): + return *regs->pR12; + } + + PORTABILITY_ASSERT("unsupported arm register"); +} + +void Registers_arm_rt::setRegister(int num, uint32_t value, uint32_t location) +{ + + if (num == UNW_REG_SP || num == UNW_ARM_SP) { + regs->SP = (UIntNative )value; + return; + } + + if (num == UNW_ARM_LR) { + regs->pLR = (PTR_UIntNative)location; + return; + } + + if (num == UNW_REG_IP || num == UNW_ARM_IP) { + regs->IP = value; + /* the location could be NULL, we could try to recover + pointer to value in stack from pLR */ + if ((!location) && (regs->pLR) && (*regs->pLR == value)) + regs->pIP = regs->pLR; + else + regs->pIP = (PTR_UIntNative)location; + return; + } + + switch (num) + { + case (UNW_ARM_R0): + regs->pR0 = (PTR_UIntNative)location; + break; + case (UNW_ARM_R1): + regs->pR1 = (PTR_UIntNative)location; + break; + case (UNW_ARM_R2): + regs->pR2 = (PTR_UIntNative)location; + break; + case (UNW_ARM_R3): + regs->pR3 = (PTR_UIntNative)location; + break; + case (UNW_ARM_R4): + regs->pR4 = (PTR_UIntNative)location; + break; + case (UNW_ARM_R5): + regs->pR5 = (PTR_UIntNative)location; + break; + case (UNW_ARM_R6): + regs->pR6 = (PTR_UIntNative)location; + break; + case (UNW_ARM_R7): + regs->pR7 = (PTR_UIntNative)location; + break; + case (UNW_ARM_R8): + regs->pR8 = (PTR_UIntNative)location; + break; + case (UNW_ARM_R9): + regs->pR9 = (PTR_UIntNative)location; + break; + case (UNW_ARM_R10): + regs->pR10 = (PTR_UIntNative)location; + break; + case (UNW_ARM_R11): + regs->pR11 = (PTR_UIntNative)location; + break; + case (UNW_ARM_R12): + regs->pR12 = (PTR_UIntNative)location; + break; + default: + PORTABILITY_ASSERT("unsupported arm register"); + } +} + +#endif // _TARGET_ARM_ bool DoTheStep(uintptr_t pc, UnwindInfoSections uwInfoSections, REGDISPLAY *regs) { #if defined(_TARGET_AMD64_) libunwind::UnwindCursor uc(_addressSpace); #elif defined(_TARGET_ARM_) - libunwind::UnwindCursor uc(_addressSpace); + libunwind::UnwindCursor uc(_addressSpace, regs); #else #error "Unwinding is not implemented for this architecture yet." #endif @@ -322,8 +461,13 @@ bool DoTheStep(uintptr_t pc, UnwindInfoSections uwInfoSections, REGDISPLAY *regs } regs->pIP = PTR_PCODE(regs->SP - sizeof(TADDR)); -#else - PORTABILITY_ASSERT("DoTheStep"); +#elif defined(_LIBUNWIND_ARM_EHABI) + uc.setInfoBasedOnIPRegister(true); + int stepRet = uc.step(); + if ((stepRet != UNW_STEP_SUCCESS) && (stepRet != UNW_STEP_END)) + { + return false; + } #endif return true; @@ -365,18 +509,20 @@ UnwindInfoSections LocateUnwindSections(uintptr_t pc) bool UnwindHelpers::StepFrame(REGDISPLAY *regs) { - uintptr_t pc = regs->GetIP(); - - UnwindInfoSections uwInfoSections = LocateUnwindSections(pc); - #if _LIBUNWIND_SUPPORT_DWARF_UNWIND + uintptr_t pc = regs->GetIP(); + UnwindInfoSections uwInfoSections = LocateUnwindSections(pc); if (uwInfoSections.dwarf_section == NULL) { return false; } + return DoTheStep(pc, uwInfoSections, regs); +#elif defined(_LIBUNWIND_ARM_EHABI) + // unwind section is located later for ARM + // pc will be taked from regs parameter + UnwindInfoSections uwInfoSections; + return DoTheStep(0, uwInfoSections, regs); #else PORTABILITY_ASSERT("StepFrame"); #endif - - return DoTheStep(pc, uwInfoSections, regs); } diff --git a/external/corert/src/Native/Runtime/unix/unixasmmacrosamd64.inc b/external/corert/src/Native/Runtime/unix/unixasmmacrosamd64.inc index d94fe2d8cc..f7fdc26c49 100644 --- a/external/corert/src/Native/Runtime/unix/unixasmmacrosamd64.inc +++ b/external/corert/src/Native/Runtime/unix/unixasmmacrosamd64.inc @@ -224,12 +224,14 @@ C_FUNC(\Name): .macro EXPORT_POINTER_TO_ADDRESS Name -1: +// NOTE: The label is intentionally left as 2 - otherwise on OSX 0b or 1b will be incorrectly interpreted as binary integers + +2: .data .align 8 C_FUNC(\Name): - .quad 1b + .quad 2b .global C_FUNC(\Name) .text diff --git a/external/corert/src/Native/Runtime/windows/CoffNativeCodeManager.cpp b/external/corert/src/Native/Runtime/windows/CoffNativeCodeManager.cpp index 22a37bb928..ae8be443f9 100644 --- a/external/corert/src/Native/Runtime/windows/CoffNativeCodeManager.cpp +++ b/external/corert/src/Native/Runtime/windows/CoffNativeCodeManager.cpp @@ -172,9 +172,11 @@ static PTR_VOID GetUnwindDataBlob(TADDR moduleBase, PTR_RUNTIME_FUNCTION pRuntim CoffNativeCodeManager::CoffNativeCodeManager(TADDR moduleBase, + PTR_VOID pvManagedCodeStartRange, UInt32 cbManagedCodeRange, PTR_RUNTIME_FUNCTION pRuntimeFunctionTable, UInt32 nRuntimeFunctionTable, PTR_PTR_VOID pClasslibFunctions, UInt32 nClasslibFunctions) : m_moduleBase(moduleBase), + m_pvManagedCodeStartRange(pvManagedCodeStartRange), m_cbManagedCodeRange(cbManagedCodeRange), m_pRuntimeFunctionTable(pRuntimeFunctionTable), m_nRuntimeFunctionTable(nRuntimeFunctionTable), m_pClasslibFunctions(pClasslibFunctions), m_nClasslibFunctions(nClasslibFunctions) { @@ -193,8 +195,6 @@ static int LookupUnwindInfoForMethod(UInt32 relativePc, relativePc |= THUMB_CODE; #endif - // Entries are sorted and terminated by sentinel value (DWORD)-1 - // Binary search the RUNTIME_FUNCTION table // Use linear search once we get down to a small number of elements // to avoid Binary search overhead. @@ -213,22 +213,23 @@ static int LookupUnwindInfoForMethod(UInt32 relativePc, } } - for (int i = low; i <= high; ++i) + for (int i = low; i < high; i++) { - // This is safe because of entries are terminated by sentinel value (DWORD)-1 PTR_RUNTIME_FUNCTION pNextFunctionEntry = pRuntimeFunctionTable + (i + 1); - if (relativePc < pNextFunctionEntry->BeginAddress) { - PTR_RUNTIME_FUNCTION pFunctionEntry = pRuntimeFunctionTable + i; - if (relativePc >= pFunctionEntry->BeginAddress) - { - return i; - } + high = i; break; } } + PTR_RUNTIME_FUNCTION pFunctionEntry = pRuntimeFunctionTable + high; + if (relativePc >= pFunctionEntry->BeginAddress) + { + return high; + } + + ASSERT_UNCONDITIONALLY("Invalid code address"); return -1; } @@ -245,6 +246,13 @@ static_assert(sizeof(CoffNativeMethodInfo) <= sizeof(MethodInfo), "CoffNativeMet bool CoffNativeCodeManager::FindMethodInfo(PTR_VOID ControlPC, MethodInfo * pMethodInfoOut) { + // Stackwalker may call this with ControlPC that does not belong to this code manager + if (dac_cast(ControlPC) < dac_cast(m_pvManagedCodeStartRange) || + dac_cast(m_pvManagedCodeStartRange) + m_cbManagedCodeRange <= dac_cast(ControlPC)) + { + return false; + } + CoffNativeMethodInfo * pMethodInfo = (CoffNativeMethodInfo *)pMethodInfoOut; TADDR relativePC = dac_cast(ControlPC) - m_moduleBase; @@ -372,9 +380,81 @@ void CoffNativeCodeManager::EnumGcRefs(MethodInfo * pMethodInfo, UIntNative CoffNativeCodeManager::GetConservativeUpperBoundForOutgoingArgs(MethodInfo * pMethodInfo, REGDISPLAY * pRegisterSet) { - // @TODO: CORERT: GetConservativeUpperBoundForOutgoingArgs +#if defined(_TARGET_AMD64_) + + // Return value + UIntNative upperBound; + CoffNativeMethodInfo* pNativeMethodInfo = (CoffNativeMethodInfo *) pMethodInfo; + + size_t unwindDataBlobSize; + PTR_VOID pUnwindDataBlob = GetUnwindDataBlob(m_moduleBase, pNativeMethodInfo->runtimeFunction, &unwindDataBlobSize); + PTR_UInt8 p = dac_cast(pUnwindDataBlob) + unwindDataBlobSize; + uint8_t unwindBlockFlags = *p++; + + if ((unwindBlockFlags & UBF_FUNC_HAS_ASSOCIATED_DATA) != 0) + p += sizeof(int32_t); + + if ((unwindBlockFlags & UBF_FUNC_REVERSE_PINVOKE) != 0) + { + TADDR basePointer = dac_cast(pRegisterSet->GetFP()); + + // Get the method's GC info + GcInfoDecoder decoder(GCInfoToken(p), DECODE_REVERSE_PINVOKE_VAR); + UINT32 stackBasedRegister = decoder.GetStackBaseRegister(); + + if (stackBasedRegister == NO_STACK_BASE_REGISTER) + { + basePointer = dac_cast(pRegisterSet->GetSP()); + } + else + { + basePointer = dac_cast(pRegisterSet->GetFP()); + } + // Reverse PInvoke case. The embedded reverse PInvoke frame is guaranteed to reside above + // all outgoing arguments. + INT32 slot = decoder.GetReversePInvokeFrameStackSlot(); + upperBound = (UIntNative) dac_cast(basePointer + slot); + } + else + { + // Check for a pushed RBP value + if (GetFramePointer(pMethodInfo, pRegisterSet) == NULL) + { + // Unwind the current method context to get the caller's stack pointer + // and obtain the upper bound of the callee is the value just below the caller's return address on the stack + SIZE_T EstablisherFrame; + PVOID HandlerData; + CONTEXT context; + context.Rsp = pRegisterSet->GetSP(); + context.Rbp = pRegisterSet->GetFP(); + context.Rip = pRegisterSet->GetIP(); + + RtlVirtualUnwind(NULL, + dac_cast(m_moduleBase), + pRegisterSet->IP, + (PRUNTIME_FUNCTION)pNativeMethodInfo->runtimeFunction, + &context, + &HandlerData, + &EstablisherFrame, + NULL); + + upperBound = dac_cast(context.Rsp - sizeof (PVOID)); + } + else + { + // In amd64, it is guaranteed that if there is a pushed RBP + // value at the top of the frame it resides above all outgoing arguments. Unlike x86, + // the frame pointer generally points to a location that is separated from the pushed RBP + // value by an offset that is recorded in the info header. Recover the address of the + // pushed RBP value by subtracting this offset. + upperBound = (UIntNative) dac_cast(pRegisterSet->GetFP() - ((PTR_UNWIND_INFO) pUnwindDataBlob)->FrameOffset); + } + } + return upperBound; +#else assert(false); return false; +#endif } bool CoffNativeCodeManager::UnwindStackFrame(MethodInfo * pMethodInfo, @@ -705,6 +785,12 @@ void * CoffNativeCodeManager::GetClasslibFunction(ClasslibFunctionId functionId) PTR_VOID CoffNativeCodeManager::GetAssociatedData(PTR_VOID ControlPC) { + if (dac_cast(ControlPC) < dac_cast(m_pvManagedCodeStartRange) || + dac_cast(m_pvManagedCodeStartRange) + m_cbManagedCodeRange <= dac_cast(ControlPC)) + { + return NULL; + } + TADDR relativePC = dac_cast(ControlPC) - m_moduleBase; int MethodIndex = LookupUnwindInfoForMethod((UInt32)relativePC, m_pRuntimeFunctionTable, 0, m_nRuntimeFunctionTable - 1); @@ -742,6 +828,7 @@ bool RhRegisterOSModule(void * pModule, IMAGE_DATA_DIRECTORY * pRuntimeFunctions = &(pNTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION]); NewHolder pCoffNativeCodeManager = new (nothrow) CoffNativeCodeManager((TADDR)pModule, + pvManagedCodeStartRange, cbManagedCodeRange, dac_cast((TADDR)pModule + pRuntimeFunctions->VirtualAddress), pRuntimeFunctions->Size / sizeof(RUNTIME_FUNCTION), pClasslibFunctions, nClasslibFunctions); diff --git a/external/corert/src/Native/Runtime/windows/CoffNativeCodeManager.h b/external/corert/src/Native/Runtime/windows/CoffNativeCodeManager.h index 81b4ee6251..ab4a561b72 100644 --- a/external/corert/src/Native/Runtime/windows/CoffNativeCodeManager.h +++ b/external/corert/src/Native/Runtime/windows/CoffNativeCodeManager.h @@ -40,6 +40,10 @@ typedef DPTR(T_RUNTIME_FUNCTION) PTR_RUNTIME_FUNCTION; class CoffNativeCodeManager : public ICodeManager { TADDR m_moduleBase; + + PTR_VOID m_pvManagedCodeStartRange; + UInt32 m_cbManagedCodeRange; + PTR_RUNTIME_FUNCTION m_pRuntimeFunctionTable; UInt32 m_nRuntimeFunctionTable; @@ -48,6 +52,7 @@ class CoffNativeCodeManager : public ICodeManager public: CoffNativeCodeManager(TADDR moduleBase, + PTR_VOID pvManagedCodeStartRange, UInt32 cbManagedCodeRange, PTR_RUNTIME_FUNCTION pRuntimeFunctionTable, UInt32 nRuntimeFunctionTable, PTR_PTR_VOID pClasslibFunctions, UInt32 nClasslibFunctions); ~CoffNativeCodeManager(); diff --git a/external/corert/src/Native/Runtime/windows/PalRedhawkCommon.cpp b/external/corert/src/Native/Runtime/windows/PalRedhawkCommon.cpp index 7618b24c0d..f5783eb6c1 100644 --- a/external/corert/src/Native/Runtime/windows/PalRedhawkCommon.cpp +++ b/external/corert/src/Native/Runtime/windows/PalRedhawkCommon.cpp @@ -143,7 +143,7 @@ REDHAWK_PALEXPORT void REDHAWK_PALAPI PalGetPDBInfo(HANDLE hOsHandle, _Out_ GUID if (cbDebugData < size_t(&((CV_INFO_PDB70*)0)->magic) + sizeof(((CV_INFO_PDB70*)0)->magic)) { // raw data too small to contain magic number at expected spot, so its format - // is not recognizeable. Skip + // is not recognizable. Skip continue; } diff --git a/external/corert/src/Native/Runtime/windows/PalRedhawkMinWin.cpp b/external/corert/src/Native/Runtime/windows/PalRedhawkMinWin.cpp index 95095e1db8..16ec4d6fe8 100644 --- a/external/corert/src/Native/Runtime/windows/PalRedhawkMinWin.cpp +++ b/external/corert/src/Native/Runtime/windows/PalRedhawkMinWin.cpp @@ -218,21 +218,28 @@ REDHAWK_PALEXPORT UInt32_BOOL REDHAWK_PALAPI PalMarkThunksAsValidCallTargets( REDHAWK_PALEXPORT UInt32 REDHAWK_PALAPI PalCompatibleWaitAny(UInt32_BOOL alertable, UInt32 timeout, UInt32 handleCount, HANDLE* pHandles, UInt32_BOOL allowReentrantWait) { - DWORD index; - SetLastError(ERROR_SUCCESS); // recommended by MSDN. - HRESULT hr = CoWaitForMultipleHandles(alertable ? COWAIT_ALERTABLE : 0, timeout, handleCount, pHandles, &index); - - switch (hr) + if (!allowReentrantWait) { - case S_OK: - return index; + return WaitForMultipleObjectsEx(handleCount, pHandles, FALSE, timeout, alertable); + } + else + { + DWORD index; + SetLastError(ERROR_SUCCESS); // recommended by MSDN. + HRESULT hr = CoWaitForMultipleHandles(alertable ? COWAIT_ALERTABLE : 0, timeout, handleCount, pHandles, &index); - case RPC_S_CALLPENDING: - return WAIT_TIMEOUT; + switch (hr) + { + case S_OK: + return index; - default: - SetLastError(HRESULT_CODE(hr)); - return WAIT_FAILED; + case RPC_S_CALLPENDING: + return WAIT_TIMEOUT; + + default: + SetLastError(HRESULT_CODE(hr)); + return WAIT_FAILED; + } } } @@ -1065,7 +1072,7 @@ void DumpCacheTopology(_In_reads_(cRecords) SYSTEM_LOGICAL_PROCESSOR_INFORMATION switch (pProcInfos[i].Relationship) { case RelationProcessorCore: - printf(" [%2d] Core: %d threads 0x%04zx mask, flags = %d\n", + printf(" [%2d] Core: %d threads 0x%04Ix mask, flags = %d\n", i, CountBits(pProcInfos[i].ProcessorMask), pProcInfos[i].ProcessorMask, pProcInfos[i].ProcessorCore.Flags); break; @@ -1079,16 +1086,16 @@ void DumpCacheTopology(_In_reads_(cRecords) SYSTEM_LOGICAL_PROCESSOR_INFORMATION case CacheTrace: pszCacheType = "[Trace ]"; break; default: pszCacheType = "[Unk ]"; break; } - printf(" [%2d] Cache: %s 0x%08x bytes 0x%04zx mask\n", i, pszCacheType, + printf(" [%2d] Cache: %s 0x%08x bytes 0x%04Ix mask\n", i, pszCacheType, pProcInfos[i].Cache.Size, pProcInfos[i].ProcessorMask); break; case RelationNumaNode: - printf(" [%2d] NumaNode: #%02d 0x%04zx mask\n", + printf(" [%2d] NumaNode: #%02d 0x%04Ix mask\n", i, pProcInfos[i].NumaNode.NodeNumber, pProcInfos[i].ProcessorMask); break; case RelationProcessorPackage: - printf(" [%2d] Package: 0x%04zx mask\n", + printf(" [%2d] Package: 0x%04Ix mask\n", i, pProcInfos[i].ProcessorMask); break; case RelationAll: @@ -1106,8 +1113,8 @@ void DumpCacheTopologyResults(UInt32 maxCpuId, CpuVendor cpuVendor, _In_reads_(c DumpCacheTopology(pProcInfos, cRecords); printf("maxCpuId: %d, %s\n", maxCpuId, (cpuVendor == CpuIntel) ? "CpuIntel" : ((cpuVendor == CpuAMD) ? "CpuAMD" : "CpuUnknown")); printf(" g_cLogicalCpus: %d %d :CLR_GetLogicalCpuCount\n", g_cLogicalCpus, CLR_GetLogicalCpuCount(pProcInfos, cRecords)); - printf(" g_cbLargestOnDieCache: 0x%08zx 0x%08zx :CLR_LargestOnDieCache(TRUE)\n", g_cbLargestOnDieCache, CLR_GetLargestOnDieCacheSize(TRUE, pProcInfos, cRecords)); - printf("g_cbLargestOnDieCacheAdjusted: 0x%08zx 0x%08zx :CLR_LargestOnDieCache(FALSE)\n", g_cbLargestOnDieCacheAdjusted, CLR_GetLargestOnDieCacheSize(FALSE, pProcInfos, cRecords)); + printf(" g_cbLargestOnDieCache: 0x%08Ix 0x%08Ix :CLR_LargestOnDieCache(TRUE)\n", g_cbLargestOnDieCache, CLR_GetLargestOnDieCacheSize(TRUE, pProcInfos, cRecords)); + printf("g_cbLargestOnDieCacheAdjusted: 0x%08Ix 0x%08Ix :CLR_LargestOnDieCache(FALSE)\n", g_cbLargestOnDieCacheAdjusted, CLR_GetLargestOnDieCacheSize(FALSE, pProcInfos, cRecords)); } #endif // _DEBUG @@ -1286,12 +1293,18 @@ bool PalQueryProcessorTopology() #ifdef TRACE_CACHE_TOPOLOGY DumpCacheTopologyResults(maxCpuId, cpuVendor, pProcInfos, cRecords); #endif - if ((CLR_GetLargestOnDieCacheSize(TRUE, pProcInfos, cRecords) != g_cbLargestOnDieCache) || - (CLR_GetLargestOnDieCacheSize(FALSE, pProcInfos, cRecords) != g_cbLargestOnDieCacheAdjusted) || - (CLR_GetLogicalCpuCount(pProcInfos, cRecords) != g_cLogicalCpus)) + // CLR_GetLargestOnDieCacheSize is implemented for Intel and AMD processors only + if ((cpuVendor == CpuIntel) || (cpuVendor == CpuAMD)) { - DumpCacheTopologyResults(maxCpuId, cpuVendor, pProcInfos, cRecords); - assert(!"QueryProcessorTopology doesn't match CLR's results. See stdout for more info."); + if ((CLR_GetLargestOnDieCacheSize(TRUE, pProcInfos, cRecords) != g_cbLargestOnDieCache) || + (CLR_GetLargestOnDieCacheSize(FALSE, pProcInfos, cRecords) != g_cbLargestOnDieCacheAdjusted) || + (CLR_GetLogicalCpuCount(pProcInfos, cRecords) != g_cLogicalCpus)) + { +#ifndef TRACE_CACHE_TOPOLOGY + DumpCacheTopologyResults(maxCpuId, cpuVendor, pProcInfos, cRecords); +#endif + assert(!"QueryProcessorTopology doesn't match CLR's results. See stdout for more info."); + } } #endif // _DEBUG } diff --git a/external/corert/src/Native/System.Private.CoreLib.Native/CMakeLists.txt b/external/corert/src/Native/System.Private.CoreLib.Native/CMakeLists.txt index 760b75e24d..d50340e671 100644 --- a/external/corert/src/Native/System.Private.CoreLib.Native/CMakeLists.txt +++ b/external/corert/src/Native/System.Private.CoreLib.Native/CMakeLists.txt @@ -6,7 +6,6 @@ set(NATIVE_SOURCES pal_dynamicload.cpp pal_environment.cpp pal_errno.cpp - pal_guid.cpp pal_memory.cpp pal_exepath.cpp pal_threading.cpp diff --git a/external/corert/src/Native/System.Private.CoreLib.Native/config.h.in b/external/corert/src/Native/System.Private.CoreLib.Native/config.h.in index 3d13262a26..3c3f11298c 100644 --- a/external/corert/src/Native/System.Private.CoreLib.Native/config.h.in +++ b/external/corert/src/Native/System.Private.CoreLib.Native/config.h.in @@ -5,6 +5,5 @@ #cmakedefine01 HAVE_CLOCK_MONOTONIC_COARSE #cmakedefine01 HAVE_MACH_ABSOLUTE_TIME #cmakedefine01 HAVE_SCHED_GETCPU -#cmakedefine01 HAVE_LIBUUID_H -#cmakedefine01 HAVE_UUID_GENERATE_RANDOM -#cmakedefine01 HAVE_UUID_GENERATE +#cmakedefine01 HAVE_GNU_LIBNAMES_H +#cmakedefine01 HAVE__NSGETENVIRON \ No newline at end of file diff --git a/external/corert/src/Native/System.Private.CoreLib.Native/configure.cmake b/external/corert/src/Native/System.Private.CoreLib.Native/configure.cmake index c84bf89718..1fbbf9c5eb 100644 --- a/external/corert/src/Native/System.Private.CoreLib.Native/configure.cmake +++ b/external/corert/src/Native/System.Private.CoreLib.Native/configure.cmake @@ -1,18 +1,10 @@ include(CheckCXXSourceCompiles) include(CheckCXXSourceRuns) include(CheckLibraryExists) +include(CheckFunctionExists) check_library_exists(pthread pthread_condattr_setclock "" HAVE_PTHREAD_CONDATTR_SETCLOCK) -check_include_files(uuid/uuid.h HAVE_LIBUUID_H) - -if(NOT CMAKE_SYSTEM_NAME STREQUAL Darwin) - set(CMAKE_REQUIRED_LIBRARIES uuid) -endif() -check_function_exists(uuid_generate_random HAVE_UUID_GENERATE_RANDOM) -check_function_exists(uuid_generate HAVE_UUID_GENERATE) -set(CMAKE_REQUIRED_LIBRARIES) - check_cxx_source_runs(" #include #include @@ -69,10 +61,9 @@ int main(void) }" HAVE_SCHED_GETCPU) set(CMAKE_REQUIRED_LIBRARIES) -if(NOT HAVE_LIBUUID_H) - unset(HAVE_LIBUUID_H CACHE) - message(FATAL_ERROR "Cannot find libuuid. Try installing uuid-dev or the appropriate packages for your platform") -endif() +check_include_files(gnu/lib-names.h HAVE_GNU_LIBNAMES_H) + +check_function_exists(_NSGetEnviron HAVE__NSGETENVIRON) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/config.h.in diff --git a/external/corert/src/Native/System.Private.CoreLib.Native/pal_dynamicload.cpp b/external/corert/src/Native/System.Private.CoreLib.Native/pal_dynamicload.cpp index dfb2917f25..d46e3da959 100644 --- a/external/corert/src/Native/System.Private.CoreLib.Native/pal_dynamicload.cpp +++ b/external/corert/src/Native/System.Private.CoreLib.Native/pal_dynamicload.cpp @@ -2,10 +2,38 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#include "pal_common.h" #include +#include + +#if HAVE_GNU_LIBNAMES_H +#include +#endif extern "C" void* CoreLibNative_LoadLibrary(const char* filename) { + // Check whether we have been requested to load 'libc'. If that's the case, then: + // * For Linux, use the full name of the library that is defined in by the + // LIBC_SO constant. The problem is that calling dlopen("libc.so") will fail for libc even + // though it works for other libraries. The reason is that libc.so is just linker script + // (i.e. a test file). + // As a result, we have to use the full name (i.e. lib.so.6) that is defined by LIBC_SO. + // * For macOS, use constant value absolute path "/usr/lib/libc.dylib". + // * For FreeBSD, use constant value "libc.so.7". + // * For rest of Unices, use constant value "libc.so". + if (strcmp(filename, "libc") == 0) + { +#if defined(__APPLE__) + filename = "/usr/lib/libc.dylib"; +#elif defined(__FreeBSD__) + filename = "libc.so.7"; +#elif defined(LIBC_SO) + filename = LIBC_SO; +#else + filename = "libc.so"; +#endif + } + return dlopen(filename, RTLD_LAZY); } diff --git a/external/corert/src/Native/System.Private.CoreLib.Native/pal_environment.cpp b/external/corert/src/Native/System.Private.CoreLib.Native/pal_environment.cpp index 94660babad..15ef90c346 100644 --- a/external/corert/src/Native/System.Private.CoreLib.Native/pal_environment.cpp +++ b/external/corert/src/Native/System.Private.CoreLib.Native/pal_environment.cpp @@ -10,6 +10,9 @@ #if HAVE_SCHED_GETCPU #include #endif +#if HAVE__NSGETENVIRON +#include +#endif extern "C" char* CoreLibNative_GetEnv(const char* variable) @@ -30,3 +33,17 @@ extern "C" void CoreLibNative_Exit(int32_t exitCode) { exit(exitCode); } + +extern "C" char** CoreLibNative_GetEnviron() +{ + char** sysEnviron; + +#if HAVE__NSGETENVIRON + sysEnviron = *(_NSGetEnviron()); +#else // HAVE__NSGETENVIRON + extern char **environ; + sysEnviron = environ; +#endif // HAVE__NSGETENVIRON + + return sysEnviron; +} \ No newline at end of file diff --git a/external/corert/src/Native/System.Private.CoreLib.Native/pal_guid.cpp b/external/corert/src/Native/System.Private.CoreLib.Native/pal_guid.cpp deleted file mode 100644 index 8e35d089ee..0000000000 --- a/external/corert/src/Native/System.Private.CoreLib.Native/pal_guid.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#include "pal_common.h" - -#if HAVE_LIBUUID_H -#include -#endif - -#include "pal_endian.h" - -typedef struct _GUID { - uint32_t Data1; // NOTE: diff from Win32, for LP64 - uint16_t Data2; - uint16_t Data3; - uint8_t Data4[8]; -} GUID; - -extern "C" void CoreLibNative_CreateGuid(GUID* pGuid) -{ -#if HAVE_UUID_GENERATE_RANDOM - uuid_generate_random(*(uuid_t*)pGuid); -#elif HAVE_UUID_GENERATE - uuid_generate(*(uuid_t*)pGuid); -#else -#error Don't know how to generate UUID on this platform -#endif - - // Change the byte order of the Data1, 2 and 3, since uuid_generate_random and uuid_generate - // generates them with big endian while GUIDS need to have them in little endian. - pGuid->Data1 = SWAP32(pGuid->Data1); - pGuid->Data2 = SWAP16(pGuid->Data2); - pGuid->Data3 = SWAP16(pGuid->Data3); -} diff --git a/external/corert/src/Native/System.Private.CoreLib.Native/pal_time.cpp b/external/corert/src/Native/System.Private.CoreLib.Native/pal_time.cpp index b0cd1b1ed6..136cb03bc8 100644 --- a/external/corert/src/Native/System.Private.CoreLib.Native/pal_time.cpp +++ b/external/corert/src/Native/System.Private.CoreLib.Native/pal_time.cpp @@ -168,7 +168,7 @@ extern "C" int32_t CoreLibNative_GetCpuUtilization(ProcessCpuInformation* previo { if (numProcessors <= 0) { - numProcessors = sysconf(_SC_NPROCESSORS_ONLN); + numProcessors = sysconf(_SC_NPROCESSORS_CONF); if (numProcessors <= 0) { return 0; diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/CMakeLists.txt b/external/corert/src/Native/System.Private.TypeLoader.Native/CMakeLists.txt new file mode 100644 index 0000000000..d1827372f1 --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/CMakeLists.txt @@ -0,0 +1,45 @@ +if(WIN32) + set(ASM_SUFFIX asm) + + if(CLR_CMAKE_PLATFORM_ARCH_AMD64) + set(ARCH_SOURCES_DIR amd64) + elseif(CLR_CMAKE_PLATFORM_ARCH_I386) + set(ARCH_SOURCES_DIR i386) + endif() + +else() + + set(ASM_SUFFIX S) + + if(CLR_CMAKE_PLATFORM_ARCH_AMD64) + set(ARCH_SOURCES_DIR amd64) + elseif(CLR_CMAKE_PLATFORM_ARCH_ARM64) + set(ARCH_SOURCES_DIR arm64) + elseif(CLR_CMAKE_PLATFORM_ARCH_ARM) + set(ARCH_SOURCES_DIR arm) + elseif(CLR_CMAKE_PLATFORM_ARCH_I386) + set(ARCH_SOURCES_DIR i386) + elseif(CLR_CMAKE_PLATFORM_ARCH_WASM) + set(ARCH_SOURCES_DIR wasm) + endif() + +endif() + +set(RUNTIME_SOURCES_ARCH_ASM + ${ARCH_SOURCES_DIR}/ConstrainedCallSupportHelpers.${ASM_SUFFIX} + ${ARCH_SOURCES_DIR}/MethodEntrypointStubs.${ASM_SUFFIX} + ${ARCH_SOURCES_DIR}/VTableResolver.${ASM_SUFFIX} +) + +convert_to_absolute_path(RUNTIME_SOURCES_ARCH_ASM ${RUNTIME_SOURCES_ARCH_ASM}) + +add_library(System.Private.TypeLoader.Native + STATIC + ${RUNTIME_SOURCES_ARCH_ASM} +) + +if (CMAKE_SYSTEM_NAME STREQUAL Linux) + target_link_libraries(System.Private.TypeLoader.Native rt) +endif () + +install (TARGETS System.Private.TypeLoader.Native DESTINATION sdk) diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/ConstrainedCallSupportHelpers.S b/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/ConstrainedCallSupportHelpers.S new file mode 100644 index 0000000000..bca35df818 --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/ConstrainedCallSupportHelpers.S @@ -0,0 +1,12 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +.intel_syntax noprefix + +#include <../../Runtime/unix/unixasmmacros.inc> + +LEAF_ENTRY ConstrainedCallSupport_GetStubs, _TEXT + // TODO: implement + ret +LEAF_END ConstrainedCallSupport_GetStubs, _TEXT diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/ConstrainedCallSupportHelpers.asm b/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/ConstrainedCallSupportHelpers.asm new file mode 100644 index 0000000000..4d22d914c0 --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/ConstrainedCallSupportHelpers.asm @@ -0,0 +1,85 @@ +;; Licensed to the .NET Foundation under one or more agreements. +;; The .NET Foundation licenses this file to you under the MIT license. +;; See the LICENSE file in the project root for more information. + +;; ----------------------------------------------------------------------------------------------------------- +;; #include "asmmacros.inc" +;; ----------------------------------------------------------------------------------------------------------- + +LEAF_ENTRY macro Name, Section + Section segment para 'CODE' + align 16 + public Name + Name proc +endm + +LEAF_END macro Name, Section + Name endp + Section ends +endm + +; - TAILCALL_RAX: ("jmp rax") should be used for tailcalls, this emits an instruction +; sequence which is recognized by the unwinder as a valid epilogue terminator +TAILJMP_RAX TEXTEQU +POINTER_SIZE equ 08h + +;; +;; Note: The "__jmpstub__" prefix is used to indicate to debugger +;; that it must step-through this stub when it encounters it while +;; stepping. +;; + +;; +;; __jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub +;; +;; r10 - AddressOfAddressOfFunctionToCallAfterDereferencingThis +;; +LEAF_ENTRY __jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub, _TEXT + mov rax, [r10] ; Tail jumps go through RAX, so copy function pointer there + mov rcx, [rcx] ; Deference this to get real function pointer + TAILJMP_RAX +LEAF_END __jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub, _TEXT + +;; +;; void ConstrainedCallSupport_GetStubs(IntPtr *__jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub, +;; IntPtr *__jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub) +;; +LEAF_ENTRY ConstrainedCallSupport_GetStubs, _TEXT + lea rax, [__jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub] + mov [rcx], rax + lea rax, [__jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub] + mov [rdx], rax + ret +LEAF_END ConstrainedCallSupport_GetStubs, _TEXT + +;; +;; __jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub +;; +;; struct ConstrainedCallDesc +;; { +;; ULONG_PTR ExactTarget; +;; ULONG_PTR LookupFunc; // Put UniversalThunk here +;; } +;; +;; struct CommonCallingStubInputData +;; { +;; ULONG_PTR ConstrainedCallDesc; +;; ULONG_PTR DirectConstrainedCallResolver; +;; } +;; +;; r10 - Points at CommonCallingStubInputData +;; +;; +LEAF_ENTRY __jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub, _TEXT + mov r11, [r10] ; put ConstrainedCallDesc into r11 (Arg to LookupFunc/Temp for getting ExactTarget) + mov rax, [r11] ; put ExactTarget into rax + test rax, rax ; compare against null + jnz JumpToTarget ; if not null, we don't need to call helper to get result. Just jump + ; If we reach here, we need to use a universal thunk to call the LookupFunc + mov rax, [r11 + POINTER_SIZE] ; Get Universal thunk function pointer into rax + mov r10, [r10 + POINTER_SIZE] ; Put DirectConstrainedCallResolver into r10 for UniversalTransitionThunk call +JumpToTarget: + TAILJMP_RAX +LEAF_END __jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub, _TEXT + +end diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/MethodEntrypointStubs.S b/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/MethodEntrypointStubs.S new file mode 100644 index 0000000000..4071c4038c --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/MethodEntrypointStubs.S @@ -0,0 +1,12 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +.intel_syntax noprefix + +#include <../../Runtime/unix/unixasmmacros.inc> + +LEAF_ENTRY MethodEntrypointStubs_SetupPointers, _TEXT + // TODO: implement + ret +LEAF_END MethodEntrypointStubs_SetupPointers, _TEXT diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/MethodEntrypointStubs.asm b/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/MethodEntrypointStubs.asm new file mode 100644 index 0000000000..f0c212b123 --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/MethodEntrypointStubs.asm @@ -0,0 +1,67 @@ +;; Licensed to the .NET Foundation under one or more agreements. +;; The .NET Foundation licenses this file to you under the MIT license. +;; See the LICENSE file in the project root for more information. + +LEAF_ENTRY macro Name, Section + Section segment para 'CODE' + align 16 + public Name + Name proc +endm + +LEAF_END macro Name, Section + Name endp + Section ends +endm + +.data + +g_methodEntrypointThunk qword 0 ; The method which operates on universal transition +g_universalTransition qword 0 ; The address of Redhawk's UniversalTransition thunk + +.code + +; - TAILCALL_RAX: ("jmp rax") should be used for tailcalls, this emits an instruction +; sequence which is recognized by the unwinder as a valid epilogue terminator +TAILJMP_RAX TEXTEQU + +PointerSize equ 8 + +;; +;; __jmpstub__MethodEntrypointStubs_CommonCallingStub(?) +;; Used when we dynamically need a VTableResolver not pre-generated +;; +;; r10 contains a pointer to a VTableResolverStruct +;; struct MethodEntryPointStubInfo +;; { +;; IntPtr targetCodePointer; +;; IntPtr MethodEntrypointStructPointer; +;; }; +;; +LEAF_ENTRY __jmpstub__MethodEntrypointStubs_CommonCallingStub, _TEXT + ;; r10 <- stub info + mov rax, [r10] + cmp rax, 0 + je SLOW_PATH + mov rax, [r10] + TAILJMP_RAX +SLOW_PATH: + mov r11, [r10 + 8] + mov r10, g_methodEntrypointThunk + mov rax, g_universalTransition + TAILJMP_RAX +LEAF_END __jmpstub__MethodEntrypointStubs_CommonCallingStub, _TEXT + +;; Returns the size of the pre-generated thunks +;; IntPtr MethodEntrypointStubs_SetupPointers( +;; IntPtr universalTransition, +;; IntPtr methodEntrypointThunk) +;; +LEAF_ENTRY MethodEntrypointStubs_SetupPointers, _TEXT + mov g_universalTransition, rcx + mov g_methodEntrypointThunk, rdx + lea rax, [__jmpstub__MethodEntrypointStubs_CommonCallingStub] + ret +LEAF_END MethodEntrypointStubs_SetupPointers, _TEXT + +end diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/VTableResolver.S b/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/VTableResolver.S new file mode 100644 index 0000000000..cc2d7068b8 --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/VTableResolver.S @@ -0,0 +1,17 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +.intel_syntax noprefix + +#include <../../Runtime/unix/unixasmmacros.inc> + +LEAF_ENTRY VTableResolver_Init, _TEXT + // TODO: implement + ret +LEAF_END VTableResolver_Init, _TEXT + +LEAF_ENTRY VTableResolver_GetCommonCallingStub, _TEXT + // TODO: implement + ret +LEAF_END VTableResolver_GetCommonCallingStub, _TEXT diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/VTableResolver.asm b/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/VTableResolver.asm new file mode 100644 index 0000000000..8f540bdcc7 --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/amd64/VTableResolver.asm @@ -0,0 +1,221 @@ +;; Licensed to the .NET Foundation under one or more agreements. +;; The .NET Foundation licenses this file to you under the MIT license. +;; See the LICENSE file in the project root for more information. + +LEAF_ENTRY macro Name, Section + Section segment para 'CODE' + align 16 + public Name + Name proc +endm + +LEAF_END macro Name, Section + Name endp + Section ends +endm + +.data + +g_vtableResolveCallback qword 0 ; The vtableresolve method +g_universalTransition qword 0 ; The address of Redhawk's UniversalTransition thunk + +.code + +; - TAILCALL_RAX: ("jmp rax") should be used for tailcalls, this emits an instruction +; sequence which is recognized by the unwinder as a valid epilogue terminator +TAILJMP_RAX TEXTEQU + +;; +;; When an EEType is created its vTable entries will be initially filled with calls to the vTableThunk for the appropriate +;; slot number. When the thunk is invoked it'll check to see if the slot has already been resolved. If so then just call +;; the universal thunk, otherwise call to do the resolution which will also update the vtable slot and then call +;; the universal thunk +;; + +VTableThunkSize equ 30h +;; TODO - do something similar to Redhawk's asmoffsets to compute the value at compile time +EETypeVTableOffset equ 18h +PointerSize equ 8 + +;; +;; __jmpstub__VTableResolver_CommonCallingStub(?) +;; Used when we dynamically need a VTableResolver not pre-generated +;; +;; r10 contains a pointer to a VTableResolverStruct +;; struct VTableResolverStruct +;; { +;; int offsetFromStartOfEETypePtr; +;; IntPtr VTableThunkAddress; +;; }; +;; +LEAF_ENTRY __jmpstub__VTableResolver_CommonCallingStub, _TEXT + ;; r10 <- stub info + ;; rcx is the this pointer to the call being made + mov rax, [rcx] + ;; rax is the EEType pointer add the VTableOffset + slot_number * pointer size to get the vtable entry + mov r11, [r10] + ;; r11 now has offset from start of EEType to interesting slot + + ;; compare the that value to the address of the thunk being executed and if the values are equal then + ;; call to the resolver otherwise call the method + + mov rax, [rax + r11] + cmp rax, [r10 + 8] + je SLOW_DYNAMIC_STUB + TAILJMP_RAX +SLOW_DYNAMIC_STUB: + mov r10, g_vtableResolveCallback + mov rax, g_universalTransition + TAILJMP_RAX +LEAF_END __jmpstub__VTableResolver_CommonCallingStub, _TEXT + +;; Returns the size of the pre-generated thunks +;; int VTableResolver_Init(IntPtr *__jmpstub__VTableResolverSlot0, +;; IntPtr vtableResolveCallback, +;; IntPtr universalTransition, +;; int *slotCount) +;; +LEAF_ENTRY VTableResolver_Init, _TEXT + lea rax, [__jmpstub__VTableSlot0] + mov [rcx], rax + mov g_vtableResolveCallback, rdx + mov g_universalTransition, r8 + mov rax, 100 ;; 100 Pregenerated Stubs + mov [r9], rax + mov rax, VTableThunkSize ;; Thunk size + ret +LEAF_END VTableResolver_Init, _TEXT + +;; void* VTableResolver_GetCommonCallingStub() +;; - Get the address of the common calling stub +LEAF_ENTRY VTableResolver_GetCommonCallingStub, _TEXT + lea rax, [__jmpstub__VTableResolver_CommonCallingStub] + ret +LEAF_END VTableResolver_GetCommonCallingStub, _TEXT + +VTableThunkDecl macro name, slot_number + +LEAF_ENTRY name, _TEXT +ALIGN 16 ; The alignment here forces the thunks to be the same size which gives all of the macros the same size and allows us to index + ;; rcx is the this pointer to the call being made + mov rax, [rcx] + mov r11, EETypeVTableOffset + slot_number * PointerSize + ;; rax is the EEType pointer add the VTableOffset + slot_number * pointer size to get the vtable entry + ;; compare the that value to the address of the thunk being executed and if the values are equal then + ;; call to the resolver otherwise call the method + mov rax, [rax + r11] + lea r10, name + cmp rax, r10 + je SLOW + TAILJMP_RAX +SLOW: + ;; r11 is already set to the EEType offset + mov r10, g_vtableResolveCallback + mov rax, g_universalTransition + TAILJMP_RAX +LEAF_END name, _TEXT + + endm + +VTableThunkDecl __jmpstub__VTableSlot0,0 +VTableThunkDecl __jmpstub__VTableSlot1,1 +VTableThunkDecl __jmpstub__VTableSlot2,2 +VTableThunkDecl __jmpstub__VTableSlot3,3 +VTableThunkDecl __jmpstub__VTableSlot4,4 +VTableThunkDecl __jmpstub__VTableSlot5,5 +VTableThunkDecl __jmpstub__VTableSlot6,6 +VTableThunkDecl __jmpstub__VTableSlot7,7 +VTableThunkDecl __jmpstub__VTableSlot8,8 +VTableThunkDecl __jmpstub__VTableSlot9,9 +VTableThunkDecl __jmpstub__VTableSlot10,10 +VTableThunkDecl __jmpstub__VTableSlot11,11 +VTableThunkDecl __jmpstub__VTableSlot12,12 +VTableThunkDecl __jmpstub__VTableSlot13,13 +VTableThunkDecl __jmpstub__VTableSlot14,14 +VTableThunkDecl __jmpstub__VTableSlot15,15 +VTableThunkDecl __jmpstub__VTableSlot16,16 +VTableThunkDecl __jmpstub__VTableSlot17,17 +VTableThunkDecl __jmpstub__VTableSlot18,18 +VTableThunkDecl __jmpstub__VTableSlot19,19 +VTableThunkDecl __jmpstub__VTableSlot20,20 +VTableThunkDecl __jmpstub__VTableSlot21,21 +VTableThunkDecl __jmpstub__VTableSlot22,22 +VTableThunkDecl __jmpstub__VTableSlot23,23 +VTableThunkDecl __jmpstub__VTableSlot24,24 +VTableThunkDecl __jmpstub__VTableSlot25,25 +VTableThunkDecl __jmpstub__VTableSlot26,26 +VTableThunkDecl __jmpstub__VTableSlot27,27 +VTableThunkDecl __jmpstub__VTableSlot28,28 +VTableThunkDecl __jmpstub__VTableSlot29,29 +VTableThunkDecl __jmpstub__VTableSlot30,30 +VTableThunkDecl __jmpstub__VTableSlot31,31 +VTableThunkDecl __jmpstub__VTableSlot32,32 +VTableThunkDecl __jmpstub__VTableSlot33,33 +VTableThunkDecl __jmpstub__VTableSlot34,34 +VTableThunkDecl __jmpstub__VTableSlot35,35 +VTableThunkDecl __jmpstub__VTableSlot36,36 +VTableThunkDecl __jmpstub__VTableSlot37,37 +VTableThunkDecl __jmpstub__VTableSlot38,38 +VTableThunkDecl __jmpstub__VTableSlot39,39 +VTableThunkDecl __jmpstub__VTableSlot40,40 +VTableThunkDecl __jmpstub__VTableSlot41,41 +VTableThunkDecl __jmpstub__VTableSlot42,42 +VTableThunkDecl __jmpstub__VTableSlot43,43 +VTableThunkDecl __jmpstub__VTableSlot44,44 +VTableThunkDecl __jmpstub__VTableSlot45,45 +VTableThunkDecl __jmpstub__VTableSlot46,46 +VTableThunkDecl __jmpstub__VTableSlot47,47 +VTableThunkDecl __jmpstub__VTableSlot48,48 +VTableThunkDecl __jmpstub__VTableSlot49,49 +VTableThunkDecl __jmpstub__VTableSlot50,50 +VTableThunkDecl __jmpstub__VTableSlot51,51 +VTableThunkDecl __jmpstub__VTableSlot52,52 +VTableThunkDecl __jmpstub__VTableSlot53,53 +VTableThunkDecl __jmpstub__VTableSlot54,54 +VTableThunkDecl __jmpstub__VTableSlot55,55 +VTableThunkDecl __jmpstub__VTableSlot56,56 +VTableThunkDecl __jmpstub__VTableSlot57,57 +VTableThunkDecl __jmpstub__VTableSlot58,58 +VTableThunkDecl __jmpstub__VTableSlot59,59 +VTableThunkDecl __jmpstub__VTableSlot60,60 +VTableThunkDecl __jmpstub__VTableSlot61,61 +VTableThunkDecl __jmpstub__VTableSlot62,62 +VTableThunkDecl __jmpstub__VTableSlot63,63 +VTableThunkDecl __jmpstub__VTableSlot64,64 +VTableThunkDecl __jmpstub__VTableSlot65,65 +VTableThunkDecl __jmpstub__VTableSlot66,66 +VTableThunkDecl __jmpstub__VTableSlot67,67 +VTableThunkDecl __jmpstub__VTableSlot68,68 +VTableThunkDecl __jmpstub__VTableSlot69,69 +VTableThunkDecl __jmpstub__VTableSlot70,70 +VTableThunkDecl __jmpstub__VTableSlot71,71 +VTableThunkDecl __jmpstub__VTableSlot72,72 +VTableThunkDecl __jmpstub__VTableSlot73,73 +VTableThunkDecl __jmpstub__VTableSlot74,74 +VTableThunkDecl __jmpstub__VTableSlot75,75 +VTableThunkDecl __jmpstub__VTableSlot76,76 +VTableThunkDecl __jmpstub__VTableSlot77,77 +VTableThunkDecl __jmpstub__VTableSlot78,78 +VTableThunkDecl __jmpstub__VTableSlot79,79 +VTableThunkDecl __jmpstub__VTableSlot80,80 +VTableThunkDecl __jmpstub__VTableSlot81,81 +VTableThunkDecl __jmpstub__VTableSlot82,82 +VTableThunkDecl __jmpstub__VTableSlot83,83 +VTableThunkDecl __jmpstub__VTableSlot84,84 +VTableThunkDecl __jmpstub__VTableSlot85,85 +VTableThunkDecl __jmpstub__VTableSlot86,86 +VTableThunkDecl __jmpstub__VTableSlot87,87 +VTableThunkDecl __jmpstub__VTableSlot88,88 +VTableThunkDecl __jmpstub__VTableSlot89,89 +VTableThunkDecl __jmpstub__VTableSlot90,90 +VTableThunkDecl __jmpstub__VTableSlot91,91 +VTableThunkDecl __jmpstub__VTableSlot92,92 +VTableThunkDecl __jmpstub__VTableSlot93,93 +VTableThunkDecl __jmpstub__VTableSlot94,94 +VTableThunkDecl __jmpstub__VTableSlot95,95 +VTableThunkDecl __jmpstub__VTableSlot96,96 +VTableThunkDecl __jmpstub__VTableSlot97,97 +VTableThunkDecl __jmpstub__VTableSlot98,98 +VTableThunkDecl __jmpstub__VTableSlot99,99 + +end diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/arm/ConstrainedCallSupportHelpers.S b/external/corert/src/Native/System.Private.TypeLoader.Native/arm/ConstrainedCallSupportHelpers.S new file mode 100644 index 0000000000..71cd483cef --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/arm/ConstrainedCallSupportHelpers.S @@ -0,0 +1,13 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +.syntax unified +.thumb + +#include <../../Runtime/unix/unixasmmacros.inc> + +LEAF_ENTRY ConstrainedCallSupport_GetStubs, _TEXT + // TODO: implement + bx lr +LEAF_END ConstrainedCallSupport_GetStubs, _TEXT diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/arm/ConstrainedCallSupportHelpers.asm b/external/corert/src/Native/System.Private.TypeLoader.Native/arm/ConstrainedCallSupportHelpers.asm new file mode 100644 index 0000000000..1f04e2a437 --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/arm/ConstrainedCallSupportHelpers.asm @@ -0,0 +1,78 @@ +;; Licensed to the .NET Foundation under one or more agreements. +;; The .NET Foundation licenses this file to you under the MIT license. +;; See the LICENSE file in the project root for more information. + +#include "kxarm.h" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; DATA SECTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ConstrainedCall Support Helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; +;; Note: The "__jmpstub__" prefix is used to indicate to debugger +;; that it must step-through this stub when it encounters it while +;; stepping. +;; + ;; + ;; sp-4 - AddressOfAddressOfFunctionToCallAfterDereferencingThis + ;; + LEAF_ENTRY __jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub + ldr r12, [sp, #-4] + ldr r12, [r12] + ldr r0, [r0] + bx r12 + LEAF_END __jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub + +;; +;; void ConstrainedCallSupport_GetStubs(IntPtr *__jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub, +;; IntPtr *__jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub) +;; + LEAF_ENTRY ConstrainedCallSupport_GetStubs + ldr r12, =__jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub + str r12, [r0] + ldr r12, =__jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub + str r12, [r1] + bx lr + LEAF_END ConstrainedCallSupport_GetStubs + +;; +;; __jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub +;; +;; struct ConstrainedCallDesc +;; { +;; ULONG_PTR ExactTarget; +;; ULONG_PTR LookupFunc; // Put UniversalThunk here +;; } +;; +;; struct CommonCallingStubInputData +;; { +;; ULONG_PTR ConstrainedCallDesc; +;; ULONG_PTR DirectConstrainedCallResolver; +;; } +;; +;; sp-4 - Points at CommonCallingStubInputData +;; +;; + LEAF_ENTRY __jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub + ldr r12, [sp, #-4] ; put CommonCallingStubInputData into r12 (Temp for getting ExactTarget) + ldr r12, [r12] ; put ConstrainedCallDesc into r12 (Temp for getting ExactTarget) + ldr r12, [r12] ; put ExactTarget into r12 + cmp r12, 0 ; Is ExactTarget null? + beq NeedHelperCall ; if null use a helper call + bx r12 ; Otherwise tail-call the ExactTarget +NeedHelperCall + ;; Setup arguments for UniversalThunk and call it. + ldr r12, [sp, #-4] ; put CommonCallingStubInputData into r12 (Temp for getting ConstrainedCallDesc) + ldr r12, [r12] ; put ConstrainedCallDesc into r12 + str r12, [sp, #-8] ; put ConstrainedCallDesc into sp-8 (red zone location of custom calling convention for universal thunk) + + ldr r12, [sp, #-4] ; put CommonCallingStubInputData into r12 (Temp for getting DirectConstrainedCallResolver) + ldr r12, [r12, #4] ; put DirectConstrainedCallResolver into r12 + str r12, [sp, #-4] ; put DirectConstrainedCallResolver into sp-4 (red zone location of custom calling convention for universal thunk) + + ldr r12, [sp, #-8] ; put ConstrainedCallDesc into r12 (Temp for getting ExactTarget) + ldr r12, [r12, #4] ; put LookupFunc into r12 (This should be universal thunk pointer) + bx r12 ; Tail-Call Universal thunk + LEAF_END __jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub + + END diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/arm/MethodEntrypointStubs.S b/external/corert/src/Native/System.Private.TypeLoader.Native/arm/MethodEntrypointStubs.S new file mode 100644 index 0000000000..0df54c4923 --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/arm/MethodEntrypointStubs.S @@ -0,0 +1,13 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +.syntax unified +.thumb + +#include <../../Runtime/unix/unixasmmacros.inc> + +LEAF_ENTRY MethodEntrypointStubs_SetupPointers, _TEXT + // TODO: implement + bx lr +LEAF_END MethodEntrypointStubs_SetupPointers, _TEXT diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/arm/MethodEntrypointStubs.asm b/external/corert/src/Native/System.Private.TypeLoader.Native/arm/MethodEntrypointStubs.asm new file mode 100644 index 0000000000..0e0cdcc5da --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/arm/MethodEntrypointStubs.asm @@ -0,0 +1,5 @@ +;; Licensed to the .NET Foundation under one or more agreements. +;; The .NET Foundation licenses this file to you under the MIT license. +;; See the LICENSE file in the project root for more information. + + END diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/arm/VTableResolver.S b/external/corert/src/Native/System.Private.TypeLoader.Native/arm/VTableResolver.S new file mode 100644 index 0000000000..7d62752423 --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/arm/VTableResolver.S @@ -0,0 +1,18 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +.syntax unified +.thumb + +#include <../../Runtime/unix/unixasmmacros.inc> + +LEAF_ENTRY VTableResolver_Init, _TEXT + // TODO: implement + bx lr +LEAF_END VTableResolver_Init, _TEXT + +LEAF_ENTRY VTableResolver_GetCommonCallingStub, _TEXT + // TODO: implement + bx lr +LEAF_END VTableResolver_GetCommonCallingStub, _TEXT diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/arm/VTableResolver.asm b/external/corert/src/Native/System.Private.TypeLoader.Native/arm/VTableResolver.asm new file mode 100644 index 0000000000..36e244e931 --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/arm/VTableResolver.asm @@ -0,0 +1,163 @@ +;; Licensed to the .NET Foundation under one or more agreements. +;; The .NET Foundation licenses this file to you under the MIT license. +;; See the LICENSE file in the project root for more information. + +#include "kxarm.h" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; DATA SECTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + DATAAREA + +g_vtableResolveCallback DCD 0 ; The vtableresolve method + EXPORT g_vtableResolveCallback +g_universalTransition DCD 0 ; The address of Redhawk's UniversalTransition thunk + +#define VTableThunkSize 0x20 +;; TODO - do something similar to Redhawk's asmoffsets to compute the value at compile time +#define EETypeVTableOffset 0x14 +#define PointerSize 4 +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ConstrainedCall Support Helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + + TEXTAREA +;; +;; Note: The "__jmpstub__" prefix is used to indicate to debugger +;; that it must step-through this stub when it encounters it while +;; stepping. +;; + +;; Returns the size of the pre-generated thunks +;; int VTableResolver_Init(IntPtr *__jmpstub__VTableResolverSlot0, +;; IntPtr vtableResolveCallback, +;; IntPtr universalTransition, +;; int *slotCount) +;; + LEAF_ENTRY VTableResolver_Init + ldr r12, __jmpstub__VTableSlot000 + add r12, r12, 1 ; Add thumb bit + str r12, [r0] + ldr r12, =g_vtableResolveCallback + str r1, [r12] + ldr r12, =g_universalTransition + str r2, [r12] + mov r12, 100 ; This file defines 100 slot helpers + str r12, [r3] + mov r0, VTableThunkSize ; Each thunk is VTableThunkSize in bytes + bx lr + LEAF_END VTableResolver_Init + +;; void* VTableResolver_GetCommonCallingStub() +;; - Get the address of the common calling stub + LEAF_ENTRY VTableResolver_GetCommonCallingStub + ldr r0, __jmpstub__VTableResolver_CommonCallingStub + bx lr + LEAF_END VTableResolver_GetCommonCallingStub + +;; +;; __jmpstub__VTableResolver_CommonCallingStub(?) +;; Used when we dynamically need a VTableResolver not pre-generated +;; +;; sp-4 contains a pointer to a VTableResolverStruct +;; struct VTableResolverStruct +;; { +;; int offsetFromStartOfEETypePtr; +;; IntPtr VTableThunkAddress; +;; }; +;; + LEAF_ENTRY __jmpstub__VTableResolver_CommonCallingStub + ;; Custom calling convention: + ;; red zone has pointer to the VTableResolverStruct + ;; Copy red zone value into r12 so that the PROLOG_PUSH doesn't destroy it + PROLOG_NOP ldr r12, [sp, #-4] + PROLOG_PUSH {r3} + PROLOG_PUSH {r1-r2} + ldr r2, [r0] + ;; r2 is the EEType pointer add the VTableOffset + slot_number * pointer size to get the vtable entry + ;; compare the that value to the address of the thunk being executed and if the values are equal then + ;; call to the resolver otherwise call the method + ldr r1, [r12] + ;; r1 is the offset from start of EEType to interesting slot + ldr r3, [r2,r1] + ;; r3 is now the function pointer in the vtable + ldr r2,[r12,#4] + ;; is now the address of the function pointer that serves as the entry point for this particular instantiation + ;; of __jmpstub__VTableResolver_CommonCallingStub + cmp r2,r3 + beq __jmpstub__JumpToVTableResolver + mov r12,r3 ; Move the target function pointer to r12 + EPILOG_POP {r1,r2} + EPILOG_POP {r3} + EPILOG_BRANCH_REG r12 + LEAF_END __jmpstub__VTableResolver_CommonCallingStub + +;; stub for dispatch will come in with r1 set to EETypeVTableOffset + ($slot_number * PointerSize), +;; and r1, r2 and r3 of the function we really want to call pushed on the stack + LEAF_ENTRY __jmpstub__JumpToVTableResolver + mov r3, r1 + POP {r1,r2} + str r3, [sp, #-4] ; Store slot number into red zone at appropriate spot + POP {r3} + ldr r12, =g_vtableResolveCallback + ldr r12, [r12] + str r12, [sp, #-4] ; Store vtable resolve callback into red zone + ldr r12, =g_universalTransition + ldr r12, [r12] + bx r12 + LEAF_END __jmpstub__VTableResolver_Init + + + MACRO + VTableThunkDecl $name, $slot_number + ALIGN 16 ; The alignment here forces the thunks to be the same size which gives all of the macros the same size and allows us to index + LEAF_ENTRY __jmpstub__$name + ;; rcx is the this pointer to the call being made + PUSH {r3} + PUSH {r1,r2} ; Push r1,r2 + ldr r2, [r0] + ;; r2 is the EEType pointer add the VTableOffset + slot_number * pointer size to get the vtable entry + ;; compare the that value to the address of the thunk being executed and if the values are equal then + ;; call to the resolver otherwise call the method + mov r1, EETypeVTableOffset + ($slot_number * PointerSize) + ldr r3, [r2,r1] + ; r3 is now the function pointer in the vtable + ldr r2,=__jmpstub__$name + cmp r2,r3 + beq JumpVTableResolver$name + mov r12,r3 ; Move the target function pointer to r12 before popping r2 and r3. We used r3 instead of r12 here so that + ; we could use the 2 byte thumb instructions and the whole thunk could fit in less than 32 bytes + POP {r1,r2,r3} + bx r12 +JumpVTableResolver$name + b __jmpstub__JumpToVTableResolver + LEAF_END __jmpstub__$name + MEND + + MACRO + VTableThunkDeclTen $slotnumberDecimal + VTableThunkDecl VTableSlot$slotnumberDecimal0,$slotnumberDecimal0 + VTableThunkDecl VTableSlot$slotnumberDecimal1,$slotnumberDecimal1 + VTableThunkDecl VTableSlot$slotnumberDecimal2,$slotnumberDecimal2 + VTableThunkDecl VTableSlot$slotnumberDecimal3,$slotnumberDecimal3 + VTableThunkDecl VTableSlot$slotnumberDecimal4,$slotnumberDecimal4 + VTableThunkDecl VTableSlot$slotnumberDecimal5,$slotnumberDecimal5 + VTableThunkDecl VTableSlot$slotnumberDecimal6,$slotnumberDecimal6 + VTableThunkDecl VTableSlot$slotnumberDecimal7,$slotnumberDecimal7 + VTableThunkDecl VTableSlot$slotnumberDecimal8,$slotnumberDecimal8 + VTableThunkDecl VTableSlot$slotnumberDecimal9,$slotnumberDecimal9 + MEND + + MACRO + VTableThunkDeclHundred $slotnumberPerHundred + VTableThunkDeclTen $slotnumberPerHundred0 + VTableThunkDeclTen $slotnumberPerHundred1 + VTableThunkDeclTen $slotnumberPerHundred2 + VTableThunkDeclTen $slotnumberPerHundred3 + VTableThunkDeclTen $slotnumberPerHundred4 + VTableThunkDeclTen $slotnumberPerHundred5 + VTableThunkDeclTen $slotnumberPerHundred6 + VTableThunkDeclTen $slotnumberPerHundred7 + VTableThunkDeclTen $slotnumberPerHundred8 + VTableThunkDeclTen $slotnumberPerHundred9 + MEND + + VTableThunkDeclHundred 0 + + END diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/arm64/ConstrainedCallSupportHelpers.asm b/external/corert/src/Native/System.Private.TypeLoader.Native/arm64/ConstrainedCallSupportHelpers.asm new file mode 100644 index 0000000000..f38b392c41 --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/arm64/ConstrainedCallSupportHelpers.asm @@ -0,0 +1,67 @@ +;; Licensed to the .NET Foundation under one or more agreements. +;; The .NET Foundation licenses this file to you under the MIT license. +;; See the LICENSE file in the project root for more information. + +#include "ksarm64.h" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; DATA SECTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +POINTER_SIZE equ 0x08 + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ConstrainedCall Support Helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; +;; Note: The "__jmpstub__" prefix is used to indicate to debugger +;; that it must step-through this stub when it encounters it while +;; stepping. +;; +;; INPUT: xip0: AddressOfAddressOfFunctionToCallAfterDereferencingThis +;; + LEAF_ENTRY __jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub + ldr x12, [xip0] ; Load tail jump target + ldr x0, [x0] ; Dereference this to get real function pointer + ret x12 + LEAF_END __jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub + +;; +;; void ConstrainedCallSupport_GetStubs(IntPtr *__jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub, +;; IntPtr *__jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub) +;; + LEAF_ENTRY ConstrainedCallSupport_GetStubs + ldr x12, =__jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub + str x12, [x0] + ldr x12, =__jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub + str x12, [x1] + ret + LEAF_END ConstrainedCallSupport_GetStubs + +;; +;; __jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub +;; +;; struct ConstrainedCallDesc +;; { +;; ULONG_PTR ExactTarget; +;; ULONG_PTR LookupFunc; // Put UniversalThunk here +;; } +;; +;; struct CommonCallingStubInputData +;; { +;; ULONG_PTR ConstrainedCallDesc; +;; ULONG_PTR DirectConstrainedCallResolver; +;; } +;; +;; INPUT: xip0: Points at CommonCallingStubInputData +;; +;; + LEAF_ENTRY __jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub + ldr xip1, [xip0] ; put ConstrainedCallDesc into xip1 (Arg to LookupFunc/Temp for getting ExactTarget) + ldr x12, [xip1] ; put ExactTarget into x12 + cbnz x12, JumpToTarget ; compare against null + ; If we reach here, we need to use a universal thunk to call the LookupFunc + ldr x12, [xip1, #POINTER_SIZE] ; Get Universal thunk function pointer into x12 + ldr xip0, [xip0, #POINTER_SIZE] ; Put DirectConstrainedCallResolver into xip0 for UniversalTransitionThunk call +JumpToTarget + ret x12 + LEAF_END __jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub + + END diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/arm64/MethodEntrypointStubs.asm b/external/corert/src/Native/System.Private.TypeLoader.Native/arm64/MethodEntrypointStubs.asm new file mode 100644 index 0000000000..0e0cdcc5da --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/arm64/MethodEntrypointStubs.asm @@ -0,0 +1,5 @@ +;; Licensed to the .NET Foundation under one or more agreements. +;; The .NET Foundation licenses this file to you under the MIT license. +;; See the LICENSE file in the project root for more information. + + END diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/arm64/VTableResolver.asm b/external/corert/src/Native/System.Private.TypeLoader.Native/arm64/VTableResolver.asm new file mode 100644 index 0000000000..d223958508 --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/arm64/VTableResolver.asm @@ -0,0 +1,155 @@ +;; Licensed to the .NET Foundation under one or more agreements. +;; The .NET Foundation licenses this file to you under the MIT license. +;; See the LICENSE file in the project root for more information. + +#include "kxarm64.h" + + DATAAREA + +g_vtableResolveCallback DCQ 0 ; Address of virtual dispatch resolution callback +g_universalTransition DCQ 0 ; Address of RhpUniversalTransition thunk + +VTableThunkSize EQU 0x20 +;; TODO - do something similar to Redhawk's asmoffsets to compute the value at compile time +EETypeVTableOffset EQU 0x18 +PointerSize EQU 8 + + TEXTAREA + +;; +;; When an EEType is created, its VTable entries are initially filled with calls to the VTableSlot thunks for the appropriate +;; slot numbers. When the thunk is invoked, it checks whether the slot has already been resolved. If yes, then it just calls +;; the universal thunk. Otherwise, it calls the dispatch resolution callback, which will update the VTable slot and then call +;; the universal thunk. +;; + +;; +;; Note: The "__jmpstub__" prefix is used to indicate to debugger +;; that it must step-through this stub when it encounters it while +;; stepping. +;; + + ;; int VTableResolver_Init(IntPtr *__jmpstub__VTableResolverSlot0, + ;; IntPtr vtableResolveCallback, + ;; IntPtr universalTransition, + ;; int *slotCount) + ;; Returns the size of the pre-generated thunks. + ;; + LEAF_ENTRY VTableResolver_Init + adr x9, __jmpstub__VTableSlot00 + str x9, [x0] + ADDROF x10, g_vtableResolveCallback + str x1, [x10] + ADDROF x11, g_universalTransition + str x2, [x11] + mov x12, 100 ; This file defines 100 slot helpers + str x12, [x3] + mov x0, VTableThunkSize ; Each thunk is VTableThunkSize in bytes + ret + LEAF_END VTableResolver_Init + + ;; void* VTableResolver_GetCommonCallingStub() + ;; Returns the address of the common calling stub. + ;; + LEAF_ENTRY VTableResolver_GetCommonCallingStub + adr x0, __jmpstub__VTableResolver_CommonCallingStub + ret + LEAF_END VTableResolver_GetCommonCallingStub + + ;; __jmpstub__VTableResolver_CommonCallingStub(?) + ;; Used when we dynamically need a VTableResolver not pre-generated. + ;; + ;; xip0 contains a pointer to a VTableResolverStruct + ;; struct VTableResolverStruct + ;; { + ;; IntPtr offsetFromStartOfEETypePtr; + ;; IntPtr VTableThunkAddress; + ;; }; + ;; + LEAF_ENTRY __jmpstub__VTableResolver_CommonCallingStub + ;; Load the EEType pointer and add (EETypeVTableOffset + $slot_number * PointerSize) to calculate the VTable slot + ;; address. Compare the pointer stored in the slot to the address of the thunk being executed. If the values are + ;; equal, call the dispatch resolution callback; otherwise, call the function pointer stored in the slot. + + ;; x9 = EEType pointer (x0 is the "this" pointer for the call being made) + ldr x9, [x0] + ;; xip1 = slot offset relative to EEType + ldr xip1, [xip0] + ;; x10 = function pointer stored in the slot + ldr x10, [x9,xip1] + ;; x11 = address of this thunk + ldr x11, [xip0,#PointerSize] + ;; Compare two pointers + cmp x10, x11 + ;; If the method is not resolved yet, resolve it first + beq __jmpstub__JumpToVTableResolver + ;; Otherwise, just call it + br x10 + LEAF_END __jmpstub__VTableResolver_CommonCallingStub + + ;; Calls the dispatch resolution callback with xip1 set to EETypeVTableOffset + ($slot_number * PointerSize) + LEAF_ENTRY __jmpstub__JumpToVTableResolver + ADDROF xip0, g_vtableResolveCallback + ldr xip0, [xip0] + ADDROF x9, g_universalTransition + ldr x9, [x9] + br x9 + LEAF_END __jmpstub__VTableResolver_Init + + MACRO + VTableThunkDecl $name, $slot_number + ;; Force all thunks to be the same size, which allows us to index + ALIGN 16 + LEAF_ENTRY __jmpstub__$name + ;; Load the EEType pointer and add (EETypeVTableOffset + $slot_number * PointerSize) to calculate the VTable slot + ;; address. Compare the pointer stored in the slot to the address of the thunk being executed. If the values are + ;; equal, call the dispatch resolution callback; otherwise, call the function pointer stored in the slot. + + ;; x9 = EEType pointer (x0 is the "this" pointer for the call being made) + ldr x9, [x0] + ;; xip1 = slot offset relative to EEType + mov xip1, EETypeVTableOffset + ($slot_number * PointerSize) + ;; x10 = function pointer stored in the slot + ldr x10, [x9,xip1] + ;; x11 = address of this thunk + adr x11, __jmpstub__$name + ;; Compare two pointers + cmp x10, x11 + ;; If the method is not resolved yet, resolve it first + beq __jmpstub__JumpToVTableResolver + ;; Otherwise, just call it + br x10 + LEAF_END __jmpstub__$name + MEND + + MACRO + VTableThunkDeclTen $slotnumberDecimal + VTableThunkDecl VTableSlot$slotnumberDecimal0,$slotnumberDecimal0 + VTableThunkDecl VTableSlot$slotnumberDecimal1,$slotnumberDecimal1 + VTableThunkDecl VTableSlot$slotnumberDecimal2,$slotnumberDecimal2 + VTableThunkDecl VTableSlot$slotnumberDecimal3,$slotnumberDecimal3 + VTableThunkDecl VTableSlot$slotnumberDecimal4,$slotnumberDecimal4 + VTableThunkDecl VTableSlot$slotnumberDecimal5,$slotnumberDecimal5 + VTableThunkDecl VTableSlot$slotnumberDecimal6,$slotnumberDecimal6 + VTableThunkDecl VTableSlot$slotnumberDecimal7,$slotnumberDecimal7 + VTableThunkDecl VTableSlot$slotnumberDecimal8,$slotnumberDecimal8 + VTableThunkDecl VTableSlot$slotnumberDecimal9,$slotnumberDecimal9 + MEND + + MACRO + VTableThunkDeclHundred $slotnumberPerHundred + VTableThunkDeclTen $slotnumberPerHundred0 + VTableThunkDeclTen $slotnumberPerHundred1 + VTableThunkDeclTen $slotnumberPerHundred2 + VTableThunkDeclTen $slotnumberPerHundred3 + VTableThunkDeclTen $slotnumberPerHundred4 + VTableThunkDeclTen $slotnumberPerHundred5 + VTableThunkDeclTen $slotnumberPerHundred6 + VTableThunkDeclTen $slotnumberPerHundred7 + VTableThunkDeclTen $slotnumberPerHundred8 + VTableThunkDeclTen $slotnumberPerHundred9 + MEND + + VTableThunkDeclHundred "" + + END diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/i386/ConstrainedCallSupportHelpers.asm b/external/corert/src/Native/System.Private.TypeLoader.Native/i386/ConstrainedCallSupportHelpers.asm new file mode 100644 index 0000000000..8b3298180e --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/i386/ConstrainedCallSupportHelpers.asm @@ -0,0 +1,100 @@ +;; Licensed to the .NET Foundation under one or more agreements. +;; The .NET Foundation licenses this file to you under the MIT license. +;; See the LICENSE file in the project root for more information. + +.586 +.model flat +option casemap:none +.code + +;; ----------------------------------------------------------------------------------------------------------- +;; standard macros +;; ----------------------------------------------------------------------------------------------------------- +LEAF_ENTRY macro Name, Section + Section segment para 'CODE' + public Name + Name proc +endm + +LEAF_END macro Name, Section + Name endp + Section ends +endm + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; DATA SECTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ConstrainedCall Support Helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + + +;; +;; Note: The "__jmpstub__" prefix is used to indicate to debugger +;; that it must step-through this stub when it encounters it while +;; stepping. +;; + +;; +;; __jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub +;; +;; eax - AddressOfAddressOfFunctionToCallAfterDereferencingThis +;; +LEAF_ENTRY __jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub, _TEXT + mov eax, [eax] ; Get function pointer to call + mov ecx, [ecx] ; Deference this to get real this pointer + jmp eax +LEAF_END __jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub, _TEXT + +;; +;; void ConstrainedCallSupport_GetStubs(IntPtr *__jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub, +;; IntPtr *__jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub) +;; +LEAF_ENTRY ConstrainedCallSupport_GetStubs, _TEXT + lea eax, [__jmpstub__ConstrainedCallSupport_DerefThisAndCall_CommonCallingStub] + mov ecx, [esp+04h] + mov [ecx], eax + lea eax, [__jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub] + mov ecx, [esp+08h] + mov [ecx], eax + retn 8h +LEAF_END ConstrainedCallSupport_GetStubs, _TEXT + +;; +;; __jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub +;; +;; struct ConstrainedCallDesc +;; { +;; ULONG_PTR ExactTarget; +;; ULONG_PTR LookupFunc; // Put UniversalThunk here +;; } +;; +;; struct CommonCallingStubInputData +;; { +;; ULONG_PTR ConstrainedCallDesc; +;; ULONG_PTR DirectConstrainedCallResolver; +;; } +;; +;; eax - Points at CommonCallingStubInputData +;; +;; +LEAF_ENTRY __jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub, _TEXT +;; eax points at CommonCallingStubInputData + push eax ; save eax + mov eax,[eax] ; put ConstrainedCallDesc in eax + mov eax,[eax] ; Load ExactTarget into eax + test eax,eax ; Check ExactTarget for null + jz NeedsHelperCall + add esp,4 ; Adjust eax back to what it was before the first instruction push + jmp eax ; TailCall exact target +NeedsHelperCall: + pop eax ; Restore back to exact state that was present at start of function +;; eax points at CommonCallingStubInputData + push ebp + mov ebp, esp + push [eax] ; First argument (ConstrainedCallDesc) + push [eax+4] ; Second argument (DirectConstrainedCallResolver) + mov eax,[eax] ; Load ConstrainedCallDesc into eax + mov eax,[eax+4] ; Load Universal Thunk address into eax + jmp eax +LEAF_END __jmpstub__ConstrainedCallSupport_DirectConstrainedCallCommonStub, _TEXT + +end diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/i386/MethodEntrypointStubs.asm b/external/corert/src/Native/System.Private.TypeLoader.Native/i386/MethodEntrypointStubs.asm new file mode 100644 index 0000000000..026e0aa6da --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/i386/MethodEntrypointStubs.asm @@ -0,0 +1,5 @@ +;; Licensed to the .NET Foundation under one or more agreements. +;; The .NET Foundation licenses this file to you under the MIT license. +;; See the LICENSE file in the project root for more information. + +end \ No newline at end of file diff --git a/external/corert/src/Native/System.Private.TypeLoader.Native/i386/VTableResolver.asm b/external/corert/src/Native/System.Private.TypeLoader.Native/i386/VTableResolver.asm new file mode 100644 index 0000000000..d81948578a --- /dev/null +++ b/external/corert/src/Native/System.Private.TypeLoader.Native/i386/VTableResolver.asm @@ -0,0 +1,246 @@ +;; Licensed to the .NET Foundation under one or more agreements. +;; The .NET Foundation licenses this file to you under the MIT license. +;; See the LICENSE file in the project root for more information. + +.586 +.model flat +option casemap:none + +;; ----------------------------------------------------------------------------------------------------------- +;; standard macros +;; ----------------------------------------------------------------------------------------------------------- +LEAF_ENTRY macro Name, Section + Section segment para 'CODE' + public Name + Name proc +endm + +LEAF_END macro Name, Section + Name endp + Section ends +endm + +;; +;; When an EEType is created its vTable entries will be initially filled with calls to the vTableThunk for the appropriate +;; slot number. When the thunk is invoked it'll check to see if the slot has already been resolved. If so then just call +;; the universal thunk, otherwise call to do the resolution which will also update the vtable slot and then call +;; the universal thunk +;; + +VTableThunkSize equ 20h +;; TODO - do something similar to Redhawk's asmoffsets to compute the value at compile time +EETypeVTableOffset equ 14h +PointerSize equ 4 + +.data + +g_vtableResolveCallback dword 0 ; The vtableresolve method +g_universalTransition dword 0 ; The address of Redhawk's UniversalTransition thunk + +.code + +;; +;; __jmpstub__VTableResolver_CommonCallingStub(?) +;; Used when we dynamically need a VTableResolver not pre-generated +;; +;; eax contains a pointer to a VTableResolverStruct +;; struct VTableResolverStruct +;; { +;; int offsetFromStartOfEETypePtr; +;; IntPtr VTableThunkAddress; +;; }; +;; +LEAF_ENTRY __jmpstub__VTableResolver_CommonCallingStub, _TEXT + ;; eax <- stub info + push esi + push edi + mov esi, [eax] ; Get EEType offset into esi + + mov edi, [eax + 4] + ;; edi now has specific address of the exact thunk being processed here + + ;; ecx is the this pointer to the call being made + mov eax, [ecx] + ;; eax is the EEType pointer add the VTableOffset + slot_number * pointer size to get the vtable entry + + ;; compare the that value to the address of the thunk being executed and if the values are equal then + ;; call to the resolver otherwise call the method + + mov eax, [eax + esi] + cmp eax, edi + je SLOW_DYNAMIC_STUB + pop edi + pop esi + jmp eax +SLOW_DYNAMIC_STUB: + ;; Capture EEType offset into eax + mov eax,esi + + ;; Restore edi and esi so that we can set up the call into the universal transition thunk + pop edi + pop esi + + jmp __jmpstub__JumpToVTableResolver +LEAF_END __jmpstub__VTableResolver_CommonCallingStub, _TEXT + +;; Returns the size of the pre-generated thunks +;; int VTableResolver_Init(IntPtr *__jmpstub__VTableResolverSlot0, +;; IntPtr vtableResolveCallback, +;; IntPtr universalTransition, +;; int *slotCount) +;; +LEAF_ENTRY VTableResolver_Init, _TEXT + lea eax, dword ptr [__jmpstub__VTableSlot0] + mov ecx, [esp+04h] + mov [ecx], eax + mov ecx, [esp+08h] + mov g_vtableResolveCallback, ecx + mov ecx, [esp+0Ch] + mov g_universalTransition, ecx + mov ecx, [esp+10h] + mov eax, 100 ;; 100 Pregenerated thunks + mov [ecx], eax + mov eax, VTableThunkSize + ret +LEAF_END VTableResolver_Init, _TEXT + +;; void* VTableResolver_GetCommonCallingStub() +;; - Get the address of the common calling stub +LEAF_ENTRY VTableResolver_GetCommonCallingStub, _TEXT + lea eax, [__jmpstub__VTableResolver_CommonCallingStub] + ret +LEAF_END VTableResolver_GetCommonCallingStub, _TEXT + + +;; stub for dispatch will come in with eax set to EETypeVTableOffset + ($slot_number * PointerSize), +LEAF_ENTRY __jmpstub__JumpToVTableResolver, _TEXT + push ebp + mov ebp, esp + push eax ; First argument + push g_vtableResolveCallback + jmp g_universalTransition +LEAF_END __jmpstub__JumpToVTableResolver, _TEXT + + +VTableThunkDecl macro name, slot_number + +ALIGN 16 ; The alignment here forces the thunks to be the same size which gives all of the macros the same size and allows us to index +LEAF_ENTRY name, _TEXT + ;; rcx is the this pointer to the call being made + mov eax, [ecx] + ;; eax is the EEType pointer add the VTableOffset + slot_number * pointer size to get the vtable entry + ;; compare the that value to the address of the thunk being executed and if the values are equal then + ;; call to the resolver otherwise call the method + mov eax, [eax + EETypeVTableOffset + slot_number * PointerSize] + cmp eax, name + je SLOW + jmp eax +SLOW: + mov eax, EETypeVTableOffset + slot_number * PointerSize + jmp __jmpstub__JumpToVTableResolver +LEAF_END name, _TEXT + + endm + +VTableThunkDecl __jmpstub__VTableSlot0,0 +VTableThunkDecl __jmpstub__VTableSlot1,1 +VTableThunkDecl __jmpstub__VTableSlot2,2 +VTableThunkDecl __jmpstub__VTableSlot3,3 +VTableThunkDecl __jmpstub__VTableSlot4,4 +VTableThunkDecl __jmpstub__VTableSlot5,5 +VTableThunkDecl __jmpstub__VTableSlot6,6 +VTableThunkDecl __jmpstub__VTableSlot7,7 +VTableThunkDecl __jmpstub__VTableSlot8,8 +VTableThunkDecl __jmpstub__VTableSlot9,9 +VTableThunkDecl __jmpstub__VTableSlot10,10 +VTableThunkDecl __jmpstub__VTableSlot11,11 +VTableThunkDecl __jmpstub__VTableSlot12,12 +VTableThunkDecl __jmpstub__VTableSlot13,13 +VTableThunkDecl __jmpstub__VTableSlot14,14 +VTableThunkDecl __jmpstub__VTableSlot15,15 +VTableThunkDecl __jmpstub__VTableSlot16,16 +VTableThunkDecl __jmpstub__VTableSlot17,17 +VTableThunkDecl __jmpstub__VTableSlot18,18 +VTableThunkDecl __jmpstub__VTableSlot19,19 +VTableThunkDecl __jmpstub__VTableSlot20,20 +VTableThunkDecl __jmpstub__VTableSlot21,21 +VTableThunkDecl __jmpstub__VTableSlot22,22 +VTableThunkDecl __jmpstub__VTableSlot23,23 +VTableThunkDecl __jmpstub__VTableSlot24,24 +VTableThunkDecl __jmpstub__VTableSlot25,25 +VTableThunkDecl __jmpstub__VTableSlot26,26 +VTableThunkDecl __jmpstub__VTableSlot27,27 +VTableThunkDecl __jmpstub__VTableSlot28,28 +VTableThunkDecl __jmpstub__VTableSlot29,29 +VTableThunkDecl __jmpstub__VTableSlot30,30 +VTableThunkDecl __jmpstub__VTableSlot31,31 +VTableThunkDecl __jmpstub__VTableSlot32,32 +VTableThunkDecl __jmpstub__VTableSlot33,33 +VTableThunkDecl __jmpstub__VTableSlot34,34 +VTableThunkDecl __jmpstub__VTableSlot35,35 +VTableThunkDecl __jmpstub__VTableSlot36,36 +VTableThunkDecl __jmpstub__VTableSlot37,37 +VTableThunkDecl __jmpstub__VTableSlot38,38 +VTableThunkDecl __jmpstub__VTableSlot39,39 +VTableThunkDecl __jmpstub__VTableSlot40,40 +VTableThunkDecl __jmpstub__VTableSlot41,41 +VTableThunkDecl __jmpstub__VTableSlot42,42 +VTableThunkDecl __jmpstub__VTableSlot43,43 +VTableThunkDecl __jmpstub__VTableSlot44,44 +VTableThunkDecl __jmpstub__VTableSlot45,45 +VTableThunkDecl __jmpstub__VTableSlot46,46 +VTableThunkDecl __jmpstub__VTableSlot47,47 +VTableThunkDecl __jmpstub__VTableSlot48,48 +VTableThunkDecl __jmpstub__VTableSlot49,49 +VTableThunkDecl __jmpstub__VTableSlot50,50 +VTableThunkDecl __jmpstub__VTableSlot51,51 +VTableThunkDecl __jmpstub__VTableSlot52,52 +VTableThunkDecl __jmpstub__VTableSlot53,53 +VTableThunkDecl __jmpstub__VTableSlot54,54 +VTableThunkDecl __jmpstub__VTableSlot55,55 +VTableThunkDecl __jmpstub__VTableSlot56,56 +VTableThunkDecl __jmpstub__VTableSlot57,57 +VTableThunkDecl __jmpstub__VTableSlot58,58 +VTableThunkDecl __jmpstub__VTableSlot59,59 +VTableThunkDecl __jmpstub__VTableSlot60,60 +VTableThunkDecl __jmpstub__VTableSlot61,61 +VTableThunkDecl __jmpstub__VTableSlot62,62 +VTableThunkDecl __jmpstub__VTableSlot63,63 +VTableThunkDecl __jmpstub__VTableSlot64,64 +VTableThunkDecl __jmpstub__VTableSlot65,65 +VTableThunkDecl __jmpstub__VTableSlot66,66 +VTableThunkDecl __jmpstub__VTableSlot67,67 +VTableThunkDecl __jmpstub__VTableSlot68,68 +VTableThunkDecl __jmpstub__VTableSlot69,69 +VTableThunkDecl __jmpstub__VTableSlot70,70 +VTableThunkDecl __jmpstub__VTableSlot71,71 +VTableThunkDecl __jmpstub__VTableSlot72,72 +VTableThunkDecl __jmpstub__VTableSlot73,73 +VTableThunkDecl __jmpstub__VTableSlot74,74 +VTableThunkDecl __jmpstub__VTableSlot75,75 +VTableThunkDecl __jmpstub__VTableSlot76,76 +VTableThunkDecl __jmpstub__VTableSlot77,77 +VTableThunkDecl __jmpstub__VTableSlot78,78 +VTableThunkDecl __jmpstub__VTableSlot79,79 +VTableThunkDecl __jmpstub__VTableSlot80,80 +VTableThunkDecl __jmpstub__VTableSlot81,81 +VTableThunkDecl __jmpstub__VTableSlot82,82 +VTableThunkDecl __jmpstub__VTableSlot83,83 +VTableThunkDecl __jmpstub__VTableSlot84,84 +VTableThunkDecl __jmpstub__VTableSlot85,85 +VTableThunkDecl __jmpstub__VTableSlot86,86 +VTableThunkDecl __jmpstub__VTableSlot87,87 +VTableThunkDecl __jmpstub__VTableSlot88,88 +VTableThunkDecl __jmpstub__VTableSlot89,89 +VTableThunkDecl __jmpstub__VTableSlot90,90 +VTableThunkDecl __jmpstub__VTableSlot91,91 +VTableThunkDecl __jmpstub__VTableSlot92,92 +VTableThunkDecl __jmpstub__VTableSlot93,93 +VTableThunkDecl __jmpstub__VTableSlot94,94 +VTableThunkDecl __jmpstub__VTableSlot95,95 +VTableThunkDecl __jmpstub__VTableSlot96,96 +VTableThunkDecl __jmpstub__VTableSlot97,97 +VTableThunkDecl __jmpstub__VTableSlot98,98 +VTableThunkDecl __jmpstub__VTableSlot99,99 + +end diff --git a/external/corert/src/Native/gc/gc.cpp.REMOVED.git-id b/external/corert/src/Native/gc/gc.cpp.REMOVED.git-id index bca1a86f64..1e7a08ce4c 100644 --- a/external/corert/src/Native/gc/gc.cpp.REMOVED.git-id +++ b/external/corert/src/Native/gc/gc.cpp.REMOVED.git-id @@ -1 +1 @@ -5c673c0be456a05ff7800344fbd9e8a2b0dae42e \ No newline at end of file +b48b4f71be9160cf016d37003e9891bd65e97fae \ No newline at end of file diff --git a/external/corert/src/Native/gc/gcrecord.h b/external/corert/src/Native/gc/gcrecord.h index fff1fc5c8b..5fa1ef88c2 100644 --- a/external/corert/src/Native/gc/gcrecord.h +++ b/external/corert/src/Native/gc/gcrecord.h @@ -407,16 +407,16 @@ struct gc_history_global gc_reason reason; int pause_mode; uint32_t mem_pressure; - uint32_t global_mechanims_p; + uint32_t global_mechanisms_p; void set_mechanism_p (gc_global_mechanism_p mechanism) { - global_mechanims_p |= (1 << mechanism); + global_mechanisms_p |= (1 << mechanism); } BOOL get_mechanism_p (gc_global_mechanism_p mechanism) { - return (global_mechanims_p & (1 << mechanism)); + return (global_mechanisms_p & (1 << mechanism)); } void print(); diff --git a/external/corert/src/Native/gc/handletable.cpp b/external/corert/src/Native/gc/handletable.cpp index 2b598528c5..1b685ab44e 100644 --- a/external/corert/src/Native/gc/handletable.cpp +++ b/external/corert/src/Native/gc/handletable.cpp @@ -933,7 +933,7 @@ void HndEnumHandles(HHANDLETABLE hTable, const uint32_t *puType, uint32_t uTypeC * * Multiple type scanning entrypoint for GC. * - * This entrypoint is provided for GC-time scnas of the handle table ONLY. It + * This entrypoint is provided for GC-time scans of the handle table ONLY. It * enables ephemeral scanning of the table, and optionally ages the write barrier * as it scans. * diff --git a/external/corert/src/Native/gc/unix/gcenv.unix.cpp b/external/corert/src/Native/gc/unix/gcenv.unix.cpp index 07259c0f24..819049b426 100644 --- a/external/corert/src/Native/gc/unix/gcenv.unix.cpp +++ b/external/corert/src/Native/gc/unix/gcenv.unix.cpp @@ -57,6 +57,12 @@ static_assert(sizeof(uint64_t) == 8, "unsigned long isn't 8 bytes"); #include #include // sysconf +#if defined(_ARM_) || defined(_ARM64_) +#define SYSCONF_GET_NUMPROCS _SC_NPROCESSORS_CONF +#else +#define SYSCONF_GET_NUMPROCS _SC_NPROCESSORS_ONLN +#endif + // The number of milliseconds in a second. static const int tccSecondsToMilliSeconds = 1000; @@ -84,7 +90,7 @@ static pthread_mutex_t g_flushProcessWriteBuffersMutex; bool GCToOSInterface::Initialize() { // Calculate and cache the number of processors on this machine - int cpuCount = sysconf(_SC_NPROCESSORS_ONLN); + int cpuCount = sysconf(SYSCONF_GET_NUMPROCS); if (cpuCount == -1) { return false; diff --git a/external/corert/src/Native/gen-buildsys-clang.sh b/external/corert/src/Native/gen-buildsys-clang.sh index fed57d1226..38c31c0640 100755 --- a/external/corert/src/Native/gen-buildsys-clang.sh +++ b/external/corert/src/Native/gen-buildsys-clang.sh @@ -109,8 +109,12 @@ if [[ -n "$CROSSCOMPILE" ]]; then echo "ROOTFS_DIR not set for crosscompile" exit 1 fi - cmake_extra_defines="$cmake_extra_defines -C $1/cross/$build_arch/tryrun.cmake" - cmake_extra_defines="$cmake_extra_defines -DCMAKE_TOOLCHAIN_FILE=$1/cross/$build_arch/toolchain.cmake" + if [[ -z $CONFIG_DIR ]]; then + CONFIG_DIR="$1/cross" + fi + export TARGET_BUILD_ARCH=$build_arch + cmake_extra_defines="$cmake_extra_defines -C $CONFIG_DIR/tryrun.cmake" + cmake_extra_defines="$cmake_extra_defines -DCMAKE_TOOLCHAIN_FILE=$CONFIG_DIR/toolchain.cmake" fi if [ $build_arch == "wasm" ]; then diff --git a/external/corert/src/Native/gen-buildsys-win.bat b/external/corert/src/Native/gen-buildsys-win.bat index fa10ef0a44..60fa962e5f 100644 --- a/external/corert/src/Native/gen-buildsys-win.bat +++ b/external/corert/src/Native/gen-buildsys-win.bat @@ -25,7 +25,7 @@ for /f "delims=" %%a in ('powershell -NoProfile -ExecutionPolicy ByPass "& %~dp0 if "%3" == "wasm" ( emcmake "%CMakePath%" "-DEMSCRIPTEN_GENERATE_BITCODE_STATIC_LIBRARIES=1" "-DCMAKE_TOOLCHAIN_FILE=%EMSCRIPTEN%/cmake/Modules/Platform/Emscripten.cmake" "-DCLR_CMAKE_TARGET_ARCH=%3" "-DCMAKE_BUILD_TYPE=%4" -G "NMake Makefiles" %1 ) else ( - "%CMakePath%" "-DCLR_CMAKE_TARGET_ARCH=%3" -G "%__CmakeGenerator%" %1 + "%CMakePath%" "-DCLR_CMAKE_TARGET_ARCH=%3" "-DOBJWRITER_BUILD=%__ObjWriterBuild%" -G "%__CmakeGenerator%" %1 ) endlocal GOTO :DONE diff --git a/external/corert/src/Native/jitinterface/CMakeLists.txt b/external/corert/src/Native/jitinterface/CMakeLists.txt index 46c071c8ad..5262e0d8cb 100644 --- a/external/corert/src/Native/jitinterface/CMakeLists.txt +++ b/external/corert/src/Native/jitinterface/CMakeLists.txt @@ -7,15 +7,23 @@ set(NATIVE_SOURCES corinfoexception.cpp ) +set (JIT_SOURCES + CodeHeap.cpp + JITCodeManager.cpp + ../Runtime/coreclr/GCInfoDecoder.cpp +) + if(WIN32 AND CLR_CMAKE_PLATFORM_ARCH_AMD64) - set(NATIVE_SOURCES ${NATIVE_SOURCES} - CodeHeap.cpp - JITCodeManager.cpp - ../Runtime/coreclr/GCInfoDecoder.cpp - ) add_definitions(-DGCINFODECODER_NO_EE) add_definitions(-DFEATURE_REDHAWK) + add_definitions(-DFEATURE_SINGLE_MODULE_RUNTIME) + + add_library(System.Private.Jit.Native + STATIC + ${NATIVE_SOURCES} + ${JIT_SOURCES} + ) endif(WIN32 AND CLR_CMAKE_PLATFORM_ARCH_AMD64) add_library(jitinterface @@ -27,4 +35,5 @@ install (TARGETS jitinterface DESTINATION tools) if(WIN32) target_link_libraries(jitinterface ntdll.lib) install (FILES ${CMAKE_CURRENT_BINARY_DIR}/$/jitinterface.pdb DESTINATION tools) + install (TARGETS System.Private.Jit.Native DESTINATION sdk) endif(WIN32) diff --git a/external/corert/src/Native/jitinterface/CodeHeap.cpp b/external/corert/src/Native/jitinterface/CodeHeap.cpp index 1adc206ea2..468bd25885 100644 --- a/external/corert/src/Native/jitinterface/CodeHeap.cpp +++ b/external/corert/src/Native/jitinterface/CodeHeap.cpp @@ -18,13 +18,23 @@ static void *s_topAddress = nullptr; static DWORD s_pageSize = 0; extern HMODULE s_hRuntime; +#if FEATURE_SINGLE_MODULE_RUNTIME +extern "C" void RhpNewArray(); +#endif + void InitMemoryStatics() { std::call_once(s_staticInit, []() { HMODULE module = s_hRuntime; if (module != NULL) + { +#if FEATURE_SINGLE_MODULE_RUNTIME + s_mrtAddr = &RhpNewArray; +#else s_mrtAddr = GetProcAddress(module, "RhpNewArray"); +#endif + } assert(s_mrtAddr != nullptr); diff --git a/external/corert/src/Native/jitinterface/JITCodeManager.cpp b/external/corert/src/Native/jitinterface/JITCodeManager.cpp index 198671f14e..11a1088be0 100644 --- a/external/corert/src/Native/jitinterface/JITCodeManager.cpp +++ b/external/corert/src/Native/jitinterface/JITCodeManager.cpp @@ -46,14 +46,24 @@ HMODULE s_hRuntime = NULL; pfnRegisterCodeManager s_pfnRegisterCodeManager; pfnUnregisterCodeManager s_pfnUnregisterCodeManager; +#if FEATURE_SINGLE_MODULE_RUNTIME +extern "C" bool RegisterCodeManager(ICodeManager * pCodeManager, PTR_VOID pvStartRange, UInt32 cbRange); +extern "C" void UnregisterCodeManager(ICodeManager * pCodeManager); +#endif + bool InitializeCodeManagerRuntime() { std::call_once(s_RuntimeInit, []() { if (s_hRuntime != NULL) { +#if FEATURE_SINGLE_MODULE_RUNTIME + s_pfnRegisterCodeManager = &RegisterCodeManager; + s_pfnUnregisterCodeManager = &UnregisterCodeManager; +#else s_pfnRegisterCodeManager = (pfnRegisterCodeManager)GetProcAddress(s_hRuntime, "RegisterCodeManager"); s_pfnUnregisterCodeManager = (pfnUnregisterCodeManager)GetProcAddress(s_hRuntime, "UnregisterCodeManager"); +#endif } }); @@ -259,7 +269,7 @@ bool JITCodeManager::Initialize() // Note that main method bodies will not have an entry in the map. PTR_RUNTIME_FUNCTION JITCodeManager::AllocRuntimeFunction(PTR_RUNTIME_FUNCTION mainMethod, DWORD beginAddr, DWORD endAddr, DWORD unwindData) { - ReaderWriterLock::WriteHolder lh(&m_lock); + SlimReaderWriterLock::WriteHolder lh(&m_lock); m_runtimeFunctions.push_back(RUNTIME_FUNCTION()); PTR_RUNTIME_FUNCTION method = &m_runtimeFunctions.back(); @@ -278,7 +288,7 @@ PTR_RUNTIME_FUNCTION JITCodeManager::AllocRuntimeFunction(PTR_RUNTIME_FUNCTION m void JITCodeManager::UpdateRuntimeFunctionTable() { - ReaderWriterLock::WriteHolder lh(&m_lock); + SlimReaderWriterLock::WriteHolder lh(&m_lock); PTR_RUNTIME_FUNCTION pFunctionTable = &m_runtimeFunctions[0]; DWORD nEntryCount = (DWORD)m_runtimeFunctions.size(); @@ -381,7 +391,7 @@ bool JITCodeManager::FindMethodInfo(PTR_VOID ControlPC, if (RelativePC >= m_cbRange) return false; - ReaderWriterLock::ReadHolder lh(&m_lock); + SlimReaderWriterLock::ReadHolder lh(&m_lock); int MethodIndex = LookupUnwindInfoForMethod((UInt32)RelativePC, m_pRuntimeFunctionTable, 0, m_nRuntimeFunctionTable - 1); @@ -420,7 +430,7 @@ bool JITCodeManager::IsFunclet(MethodInfo * pMethInfo) JITMethodInfo * pMethodInfo = (JITMethodInfo *)pMethInfo; // A funclet will have an entry in funclet to main method map - ReaderWriterLock::ReadHolder lh(&m_lock); + SlimReaderWriterLock::ReadHolder lh(&m_lock); return m_FuncletToMainMethodMap.find(pMethodInfo->runtimeFunction.BeginAddress) != m_FuncletToMainMethodMap.end(); } diff --git a/external/corert/src/Native/jitinterface/JITCodeManager.h b/external/corert/src/Native/jitinterface/JITCodeManager.h index aeff8bc899..991cb0d65d 100644 --- a/external/corert/src/Native/jitinterface/JITCodeManager.h +++ b/external/corert/src/Native/jitinterface/JITCodeManager.h @@ -51,19 +51,19 @@ typedef DPTR(struct _UNWIND_INFO) PTR_UNWIND_INFO; typedef DPTR(union _UNWIND_CODE) PTR_UNWIND_CODE; #endif // target_amd64 -class ReaderWriterLock : private SRWLOCK +class SlimReaderWriterLock : private SRWLOCK { public: - ReaderWriterLock() + SlimReaderWriterLock() { ::InitializeSRWLock(this); } class ReadHolder { - ReaderWriterLock * m_pLock; + SlimReaderWriterLock * m_pLock; public: - ReadHolder(ReaderWriterLock * pLock) + ReadHolder(SlimReaderWriterLock * pLock) : m_pLock(pLock) { ::AcquireSRWLockShared(m_pLock); @@ -77,10 +77,10 @@ public: class WriteHolder { - ReaderWriterLock * m_pLock; + SlimReaderWriterLock * m_pLock; public: - WriteHolder(ReaderWriterLock * pLock) + WriteHolder(SlimReaderWriterLock * pLock) : m_pLock(pLock) { ::AcquireSRWLockExclusive(m_pLock); @@ -167,7 +167,7 @@ class JITCodeManager : ICodeManager UInt32 m_cbRange; // lock to protect m_runtimeFunctions and m_FuncletToMainMethodMap - ReaderWriterLock m_lock; + SlimReaderWriterLock m_lock; std::vector m_runtimeFunctions; PTR_RUNTIME_FUNCTION m_pRuntimeFunctionTable; diff --git a/external/corert/src/Native/jitinterface/dllexport.h b/external/corert/src/Native/jitinterface/dllexport.h index 4b28b7ba1c..eac5f387f8 100644 --- a/external/corert/src/Native/jitinterface/dllexport.h +++ b/external/corert/src/Native/jitinterface/dllexport.h @@ -2,22 +2,39 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. + +// *** +// Define default C export attributes +// *** #ifdef _WIN32 -#define DLL_EXPORT extern "C" __declspec(dllexport) +#define DLL_EXPORT extern "C" __declspec(dllexport) #else -#define DLL_EXPORT extern "C" __attribute((visibility("default"))) -#endif +#define DLL_EXPORT extern "C" __attribute((visibility("default"))) +#endif // _WIN32 -#ifdef __i386__ -#if !defined(__stdcall) -#define __stdcall __attribute__((stdcall)) -#endif +// *** +// Define default call conventions +// *** +#ifndef _X86_ -#else - -#if !defined(__stdcall) +#define DEFAULT_CALL_CONV +#define __cdecl #define __stdcall + +#else // _X86_ + +#ifndef __stdcall +#define __stdcall __attribute__((stdcall)) #endif +#ifdef PLATFORM_UNIX +#define DEFAULT_CALL_CONV +#else +#define DEFAULT_CALL_CONV __stdcall #endif + +#endif // _X86_ + + +#define STDMETHODCALLTYPE DEFAULT_CALL_CONV diff --git a/external/corert/src/Native/jitinterface/jithost.cpp b/external/corert/src/Native/jitinterface/jithost.cpp index 62770ddcab..f433cf5b1c 100644 --- a/external/corert/src/Native/jitinterface/jithost.cpp +++ b/external/corert/src/Native/jitinterface/jithost.cpp @@ -6,27 +6,15 @@ #include "dllexport.h" -#ifdef _X86_ -#ifdef PLATFORM_UNIX -#define DEFAULT_CALL_CONV __cdecl -#else -#define DEFAULT_CALL_CONV __stdcall -#endif -#else -#define DEFAULT_CALL_CONV -#define __cdecl -#define __stdcall -#endif - class JitConfigProvider { public: - virtual int DEFAULT_CALL_CONV getIntConfigValue( + virtual int getIntConfigValue( const wchar_t* name, int defaultValue ) = 0; - virtual int DEFAULT_CALL_CONV getStringConfigValue( + virtual int getStringConfigValue( const wchar_t* name, wchar_t* retBuffer, int retBufferLength @@ -48,12 +36,12 @@ public: JitHost(JitConfigProvider* pConfigProvider) : pConfigProvider(pConfigProvider) { } - virtual void* allocateMemory(size_t size, bool usePageAllocator = false) + virtual void* allocateMemory(size_t size) { return malloc(size); } - virtual void freeMemory(void* block, bool usePageAllocator = false) + virtual void freeMemory(void* block) { free(block); } @@ -88,6 +76,17 @@ public: { free(value); } + + virtual void* allocateSlab(size_t size, size_t* pActualSize) + { + *pActualSize = size; + return allocateMemory(size); + } + + virtual void freeSlab(void* slab, size_t actualSize) + { + freeMemory(slab); + } }; DLL_EXPORT void* GetJitHost(JitConfigProvider* pConfigProvider) diff --git a/external/corert/src/Native/jitinterface/jitinterface.cpp b/external/corert/src/Native/jitinterface/jitinterface.cpp index acdcfa39e3..e18036465e 100644 --- a/external/corert/src/Native/jitinterface/jitinterface.cpp +++ b/external/corert/src/Native/jitinterface/jitinterface.cpp @@ -67,32 +67,32 @@ public: { } - virtual void __stdcall QueryInterface() { NotImplemented(); } - virtual void __stdcall AddRef() { NotImplemented(); } - virtual void __stdcall Release() { NotImplemented(); } + virtual void STDMETHODCALLTYPE QueryInterface() { NotImplemented(); } + virtual void STDMETHODCALLTYPE AddRef() { NotImplemented(); } + virtual void STDMETHODCALLTYPE Release() { NotImplemented(); } // JIT only ever uses IEEMemoryManager::ClrVirtualAlloc/IEEMemoryManager::ClrVirtualFree - virtual void * __stdcall ClrVirtualAlloc(void * lpAddress, size_t dwSize, uint32_t flAllocationType, uint32_t flProtect) + virtual void * STDMETHODCALLTYPE ClrVirtualAlloc(void * lpAddress, size_t dwSize, uint32_t flAllocationType, uint32_t flProtect) { return malloc(dwSize); } - virtual uint32_t __stdcall ClrVirtualFree(void * lpAddress, size_t dwSize, uint32_t dwFreeType) + virtual uint32_t STDMETHODCALLTYPE ClrVirtualFree(void * lpAddress, size_t dwSize, uint32_t dwFreeType) { free(lpAddress); return 1; } - virtual void __stdcall ClrVirtualQuery() { NotImplemented(); } - virtual void __stdcall ClrVirtualProtect() { NotImplemented(); } - virtual void __stdcall ClrGetProcessHeap() { NotImplemented(); } - virtual void __stdcall ClrHeapCreate() { NotImplemented(); } - virtual void __stdcall ClrHeapDestroy() { NotImplemented(); } - virtual void __stdcall ClrHeapAlloc() { NotImplemented(); } - virtual void __stdcall ClrHeapFree() { NotImplemented(); } - virtual void __stdcall ClrHeapValidate() { NotImplemented(); } - virtual void __stdcall ClrGetProcessExecutableHeap() { NotImplemented(); } + virtual void STDMETHODCALLTYPE ClrVirtualQuery() { NotImplemented(); } + virtual void STDMETHODCALLTYPE ClrVirtualProtect() { NotImplemented(); } + virtual void STDMETHODCALLTYPE ClrGetProcessHeap() { NotImplemented(); } + virtual void STDMETHODCALLTYPE ClrHeapCreate() { NotImplemented(); } + virtual void STDMETHODCALLTYPE ClrHeapDestroy() { NotImplemented(); } + virtual void STDMETHODCALLTYPE ClrHeapAlloc() { NotImplemented(); } + virtual void STDMETHODCALLTYPE ClrHeapFree() { NotImplemented(); } + virtual void STDMETHODCALLTYPE ClrHeapValidate() { NotImplemented(); } + virtual void STDMETHODCALLTYPE ClrGetProcessExecutableHeap() { NotImplemented(); } }; static EEMemoryManager eeMemoryManager; diff --git a/external/corert/src/Native/jitinterface/jitinterface.h b/external/corert/src/Native/jitinterface/jitinterface.h index 9902df6501..5d115bde59 100644 --- a/external/corert/src/Native/jitinterface/jitinterface.h +++ b/external/corert/src/Native/jitinterface/jitinterface.h @@ -164,6 +164,7 @@ struct JitInterfaceCallbacks void* (* GetDelegateCtor)(void * thisHandle, CorInfoException** ppException, void* methHnd, void* clsHnd, void* targetMethodHnd, void* pCtorData); void (* MethodCompileComplete)(void * thisHandle, CorInfoException** ppException, void* methHnd); void* (* getTailCallCopyArgsThunk)(void * thisHandle, CorInfoException** ppException, void* pSig, int flags); + bool (* convertPInvokeCalliToCall)(void * thisHandle, CorInfoException** ppException, void* pResolvedToken, bool mustConvert); void* (* getMemoryManager)(void * thisHandle, CorInfoException** ppException); void (* allocMem)(void * thisHandle, CorInfoException** ppException, unsigned int hotCodeSize, unsigned int coldCodeSize, unsigned int roDataSize, unsigned int xcptnsCount, int flag, void** hotCodeBlock, void** coldCodeBlock, void** roDataBlock); void (* reserveUnwindInfo)(void * thisHandle, CorInfoException** ppException, int isFunclet, int isColdCode, unsigned int unwindSize); @@ -1516,6 +1517,15 @@ public: return _ret; } + virtual bool convertPInvokeCalliToCall(void* pResolvedToken, bool mustConvert) + { + CorInfoException* pException = nullptr; + bool _ret = _callbacks->convertPInvokeCalliToCall(_thisHandle, &pException, pResolvedToken, mustConvert); + if (pException != nullptr) + throw pException; + return _ret; + } + virtual void* getMemoryManager(); virtual void allocMem(unsigned int hotCodeSize, unsigned int coldCodeSize, unsigned int roDataSize, unsigned int xcptnsCount, int flag, void** hotCodeBlock, void** coldCodeBlock, void** roDataBlock) { diff --git a/external/corert/src/Native/jitinterface/jitwrapper.cpp b/external/corert/src/Native/jitinterface/jitwrapper.cpp index ac5264b7db..069ef07392 100644 --- a/external/corert/src/Native/jitinterface/jitwrapper.cpp +++ b/external/corert/src/Native/jitinterface/jitwrapper.cpp @@ -27,11 +27,11 @@ private: unsigned __int64 corJitFlags; }; -static const GUID JITEEVersionIdentifier = { /* 0ba106c8-81a0-407f-99a1-928448c1eb62 */ - 0x0ba106c8, - 0x81a0, - 0x407f, - {0x99, 0xa1, 0x92, 0x84, 0x48, 0xc1, 0xeb, 0x62} +static const GUID JITEEVersionIdentifier = { /* 45aafd4d-1d23-4647-9ce1-cf09a2677ca0 */ + 0x45aafd4d, + 0x1d23, + 0x4647, + {0x9c, 0xe1, 0xcf, 0x09, 0xa2, 0x67, 0x7c, 0xa0} }; class Jit diff --git a/external/corert/src/Native/libunwind/include/libunwind.h b/external/corert/src/Native/libunwind/include/libunwind.h index 59187798d3..2e11f48d96 100644 --- a/external/corert/src/Native/libunwind/include/libunwind.h +++ b/external/corert/src/Native/libunwind/include/libunwind.h @@ -124,7 +124,7 @@ extern int unw_init_local(unw_cursor_t *, unw_context_t *) LIBUNWIND_AVAIL; extern int unw_step(unw_cursor_t *) LIBUNWIND_AVAIL; extern int unw_get_reg(unw_cursor_t *, unw_regnum_t, unw_word_t *) LIBUNWIND_AVAIL; extern int unw_get_fpreg(unw_cursor_t *, unw_regnum_t, unw_fpreg_t *) LIBUNWIND_AVAIL; -extern int unw_set_reg(unw_cursor_t *, unw_regnum_t, unw_word_t) LIBUNWIND_AVAIL; +extern int unw_set_reg(unw_cursor_t *, unw_regnum_t, unw_word_t, unw_word_t *) LIBUNWIND_AVAIL; extern int unw_set_fpreg(unw_cursor_t *, unw_regnum_t, unw_fpreg_t) LIBUNWIND_AVAIL; extern int unw_resume(unw_cursor_t *) LIBUNWIND_AVAIL; diff --git a/external/corert/src/Native/libunwind/include/unwind.h b/external/corert/src/Native/libunwind/include/unwind.h index 1d163ca9af..a350f51add 100644 --- a/external/corert/src/Native/libunwind/include/unwind.h +++ b/external/corert/src/Native/libunwind/include/unwind.h @@ -200,7 +200,7 @@ _Unwind_VRS_Get(_Unwind_Context *context, _Unwind_VRS_RegClass regclass, extern _Unwind_VRS_Result _Unwind_VRS_Set(_Unwind_Context *context, _Unwind_VRS_RegClass regclass, uint32_t regno, _Unwind_VRS_DataRepresentation representation, - void *valuep); + void *valuep, uint32_t *pos); extern _Unwind_VRS_Result _Unwind_VRS_Pop(_Unwind_Context *context, _Unwind_VRS_RegClass regclass, @@ -212,7 +212,7 @@ _Unwind_VRS_Pop(_Unwind_Context *context, _Unwind_VRS_RegClass regclass, extern uintptr_t _Unwind_GetGR(struct _Unwind_Context *context, int index); extern void _Unwind_SetGR(struct _Unwind_Context *context, int index, - uintptr_t new_value); + uintptr_t new_value, uintptr_t *pos); extern uintptr_t _Unwind_GetIP(struct _Unwind_Context *context); extern void _Unwind_SetIP(struct _Unwind_Context *, uintptr_t new_value); @@ -240,8 +240,8 @@ uintptr_t _Unwind_GetGR(struct _Unwind_Context *context, int index) { _LIBUNWIND_EXPORT_UNWIND_LEVEL1 void _Unwind_SetGR(struct _Unwind_Context *context, int index, - uintptr_t value) { - _Unwind_VRS_Set(context, _UVRSC_CORE, (uint32_t)index, _UVRSD_UINT32, &value); + uintptr_t value,uintptr_t *pos) { + _Unwind_VRS_Set(context, _UVRSC_CORE, (uint32_t)index, _UVRSD_UINT32, &value, pos); } _LIBUNWIND_EXPORT_UNWIND_LEVEL1 @@ -253,7 +253,7 @@ uintptr_t _Unwind_GetIP(struct _Unwind_Context *context) { _LIBUNWIND_EXPORT_UNWIND_LEVEL1 void _Unwind_SetIP(struct _Unwind_Context *context, uintptr_t value) { uintptr_t thumb_bit = _Unwind_GetGR(context, 15) & ((uintptr_t)0x1); - _Unwind_SetGR(context, 15, value | thumb_bit); + _Unwind_SetGR(context, 15, value | thumb_bit, NULL); } #endif // _LIBUNWIND_ARM_EHABI diff --git a/external/corert/src/Native/libunwind/src/Unwind-EHABI.cpp b/external/corert/src/Native/libunwind/src/Unwind-EHABI.cpp index 18b82f8c81..31da198c4e 100644 --- a/external/corert/src/Native/libunwind/src/Unwind-EHABI.cpp +++ b/external/corert/src/Native/libunwind/src/Unwind-EHABI.cpp @@ -217,7 +217,7 @@ decode_eht_entry(const uint32_t* data, size_t* off, size_t* len) { // only by the personality routine. Fortunately, all existing assembler // implementations, including GNU assembler, LLVM integrated assembler, // and ARM assembler, assume that the unwind opcodes come after the - // personality rountine address. + // personality routine address. *off = 1; // First byte is size data. *len = (((data[1] >> 24) & 0xff) + 1) * 4; data++; // Skip the first word, which is the prel31 offset. @@ -259,7 +259,7 @@ _Unwind_VRS_Interpret(_Unwind_Context *context, const uint32_t *data, sp -= (((uint32_t)byte & 0x3f) << 2) + 4; else sp += ((uint32_t)byte << 2) + 4; - _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32, &sp); + _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32, &sp, NULL); } else { switch (byte & 0xf0) { case 0x80: { @@ -283,7 +283,7 @@ _Unwind_VRS_Interpret(_Unwind_Context *context, const uint32_t *data, _Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_R0 + reg, _UVRSD_UINT32, &sp); _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32, - &sp); + &sp, NULL); break; } case 0xa0: { @@ -325,7 +325,7 @@ _Unwind_VRS_Interpret(_Unwind_Context *context, const uint32_t *data, &sp); sp += 0x204 + (addend << 2); _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32, - &sp); + &sp, NULL); break; } case 0xb3: { @@ -411,7 +411,7 @@ _Unwind_VRS_Interpret(_Unwind_Context *context, const uint32_t *data, if (!wrotePC) { uint32_t lr; _Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_LR, _UVRSD_UINT32, &lr); - _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_IP, _UVRSD_UINT32, &lr); + _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_IP, _UVRSD_UINT32, &lr, NULL); } return _URC_CONTINUE_UNWIND; } @@ -559,7 +559,7 @@ static _Unwind_Reason_Code unwind_phase2(unw_context_t *uc, unw_cursor_t *cursor // // See #7.4.6 for details. unw_set_reg(cursor, UNW_REG_IP, - exception_object->unwinder_cache.reserved2); + exception_object->unwinder_cache.reserved2, NULL); resume = false; } @@ -753,7 +753,7 @@ static uint64_t ValueAsBitPattern(_Unwind_VRS_DataRepresentation representation, _LIBUNWIND_EXPORT _Unwind_VRS_Result _Unwind_VRS_Set(_Unwind_Context *context, _Unwind_VRS_RegClass regclass, uint32_t regno, _Unwind_VRS_DataRepresentation representation, - void *valuep) { + void *valuep, unw_word_t *pos) { _LIBUNWIND_TRACE_API("_Unwind_VRS_Set(context=%p, regclass=%d, reg=%d, " "rep=%d, value=0x%llX)", static_cast(context), regclass, regno, @@ -765,7 +765,7 @@ _Unwind_VRS_Set(_Unwind_Context *context, _Unwind_VRS_RegClass regclass, if (representation != _UVRSD_UINT32 || regno > 15) return _UVRSR_FAILED; return unw_set_reg(cursor, (unw_regnum_t)(UNW_ARM_R0 + regno), - *(unw_word_t *)valuep) == UNW_ESUCCESS + *(unw_word_t *)valuep,(unw_word_t *)pos) == UNW_ESUCCESS ? _UVRSR_OK : _UVRSR_FAILED; case _UVRSC_VFP: @@ -897,6 +897,7 @@ _Unwind_VRS_Pop(_Unwind_Context *context, _Unwind_VRS_RegClass regclass, // computed new stack location. See EHABI #7.5.4 table 3. bool poppedSP = false; uint32_t* sp; + uint32_t* pos; if (_Unwind_VRS_Get(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32, &sp) != _UVRSR_OK) { return _UVRSR_FAILED; @@ -904,17 +905,18 @@ _Unwind_VRS_Pop(_Unwind_Context *context, _Unwind_VRS_RegClass regclass, for (uint32_t i = 0; i < 16; ++i) { if (!(discriminator & static_cast(1 << i))) continue; + pos = sp; uint32_t value = *sp++; if (regclass == _UVRSC_CORE && i == 13) poppedSP = true; if (_Unwind_VRS_Set(context, regclass, i, - _UVRSD_UINT32, &value) != _UVRSR_OK) { + _UVRSD_UINT32, &value, pos) != _UVRSR_OK) { return _UVRSR_FAILED; } } if (!poppedSP) { return _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP, - _UVRSD_UINT32, &sp); + _UVRSD_UINT32, &sp, NULL); } return _UVRSR_OK; } @@ -939,14 +941,14 @@ _Unwind_VRS_Pop(_Unwind_Context *context, _Unwind_VRS_RegClass regclass, // SP is only 32-bit aligned so don't copy 64-bit at a time. uint64_t value = *sp++; value |= ((uint64_t)(*sp++)) << 32; - if (_Unwind_VRS_Set(context, regclass, i, representation, &value) != + if (_Unwind_VRS_Set(context, regclass, i, representation, &value, NULL) != _UVRSR_OK) return _UVRSR_FAILED; } if (representation == _UVRSD_VFPX) ++sp; return _Unwind_VRS_Set(context, _UVRSC_CORE, UNW_ARM_SP, _UVRSD_UINT32, - &sp); + &sp, NULL); } } _LIBUNWIND_ABORT("unsupported register class"); diff --git a/external/corert/src/Native/libunwind/src/UnwindCursor.hpp b/external/corert/src/Native/libunwind/src/UnwindCursor.hpp index f68eee18e9..17cd33c47a 100644 --- a/external/corert/src/Native/libunwind/src/UnwindCursor.hpp +++ b/external/corert/src/Native/libunwind/src/UnwindCursor.hpp @@ -628,9 +628,11 @@ UnwindCursor::UnwindCursor(unw_context_t *context, A &as) } template -UnwindCursor::UnwindCursor(A &as, void *) - : _addressSpace(as), _unwindInfoMissing(false), _isSignalFrame(false) { +UnwindCursor::UnwindCursor(A &as, void *arg) + : _addressSpace(as),_registers(arg), _unwindInfoMissing(false), + _isSignalFrame(false) { memset(&_info, 0, sizeof(_info)); + // FIXME // fill in _registers from thread arg } diff --git a/external/corert/src/Native/libunwind/src/config.h b/external/corert/src/Native/libunwind/src/config.h index bba0f9c9f1..d8bcac8821 100644 --- a/external/corert/src/Native/libunwind/src/config.h +++ b/external/corert/src/Native/libunwind/src/config.h @@ -42,13 +42,8 @@ #endif #else #if defined(__ARM_DWARF_EH__) || !defined(__arm__) - #define _LIBUNWIND_SUPPORT_COMPACT_UNWIND 0 #define _LIBUNWIND_SUPPORT_DWARF_UNWIND 1 #define _LIBUNWIND_SUPPORT_DWARF_INDEX 1 - #else - #define _LIBUNWIND_SUPPORT_COMPACT_UNWIND 0 - #define _LIBUNWIND_SUPPORT_DWARF_UNWIND 0 - #define _LIBUNWIND_SUPPORT_DWARF_INDEX 0 #endif #endif diff --git a/external/corert/src/Native/libunwind/src/libunwind.cpp b/external/corert/src/Native/libunwind/src/libunwind.cpp index c9e3ba15a7..00c0fc3776 100644 --- a/external/corert/src/Native/libunwind/src/libunwind.cpp +++ b/external/corert/src/Native/libunwind/src/libunwind.cpp @@ -171,14 +171,14 @@ _LIBUNWIND_EXPORT int unw_get_reg(unw_cursor_t *cursor, unw_regnum_t regNum, /// Set value of specified register at cursor position in stack frame. _LIBUNWIND_EXPORT int unw_set_reg(unw_cursor_t *cursor, unw_regnum_t regNum, - unw_word_t value) { + unw_word_t value, unw_word_t *pos) { _LIBUNWIND_TRACE_API("unw_set_reg(cursor=%p, regNum=%d, value=0x%llX)", static_cast(cursor), regNum, (long long)value); typedef LocalAddressSpace::pint_t pint_t; AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor; if (co->validReg(regNum)) { - co->setReg(regNum, (pint_t)value, 0); - // specical case altering IP to re-find info (being called by personality + co->setReg(regNum, (pint_t)value, (pint_t)pos); + // special case altering IP to re-find info (being called by personality // function) if (regNum == UNW_REG_IP) co->setInfoBasedOnIPRegister(false); diff --git a/external/corert/src/Runtime.Base/src/Internal/Runtime/CompilerServices/Unsafe.cs b/external/corert/src/Runtime.Base/src/Internal/Runtime/CompilerServices/Unsafe.cs index 705193a3c6..c63760b39b 100644 --- a/external/corert/src/Runtime.Base/src/Internal/Runtime/CompilerServices/Unsafe.cs +++ b/external/corert/src/Runtime.Base/src/Internal/Runtime/CompilerServices/Unsafe.cs @@ -21,8 +21,22 @@ namespace Internal.Runtime.CompilerServices /// /// Contains generic, low-level functionality for manipulating pointers. /// - public static class Unsafe + public static unsafe class Unsafe { + /// + /// Returns a pointer to the given by-ref parameter. + /// + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void* AsPointer(ref T value) + { + throw new PlatformNotSupportedException(); + + // ldarg.0 + // conv.u + // ret + } + [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SizeOf() @@ -83,5 +97,15 @@ namespace Internal.Runtime.CompilerServices { return ref AddByteOffset(ref source, (IntPtr)(elementOffset * (nint)SizeOf())); } + + /// + /// Reinterprets the given location as a reference to a value of type . + /// + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref T AsRef(in T source) + { + throw new PlatformNotSupportedException(); + } } } diff --git a/external/corert/src/Runtime.Base/src/Runtime.Base.csproj b/external/corert/src/Runtime.Base/src/Runtime.Base.csproj index daa602215a..58d17c3b94 100644 --- a/external/corert/src/Runtime.Base/src/Runtime.Base.csproj +++ b/external/corert/src/Runtime.Base/src/Runtime.Base.csproj @@ -77,6 +77,7 @@ + diff --git a/external/corert/src/Runtime.Base/src/System/Runtime/CachedInterfaceDispatch.cs b/external/corert/src/Runtime.Base/src/System/Runtime/CachedInterfaceDispatch.cs index 6ca1646c76..e4adb402e3 100644 --- a/external/corert/src/Runtime.Base/src/System/Runtime/CachedInterfaceDispatch.cs +++ b/external/corert/src/Runtime.Base/src/System/Runtime/CachedInterfaceDispatch.cs @@ -17,7 +17,7 @@ namespace System.Runtime unsafe private static IntPtr RhpCidResolve(IntPtr callerTransitionBlockParam, IntPtr pCell) { IntPtr locationOfThisPointer = callerTransitionBlockParam + TransitionBlock.GetThisOffset(); - object pObject = Unsafe.As(ref *(IntPtr*)locationOfThisPointer); + object pObject = Unsafe.As(ref *(IntPtr*)locationOfThisPointer); IntPtr dispatchResolveTarget = RhpCidResolve_Worker(pObject, pCell); if (dispatchResolveTarget == InternalCalls.RhpGetCastableObjectDispatchHelper()) diff --git a/external/corert/src/Runtime.Base/src/System/Runtime/CastableObjectSupport.cs b/external/corert/src/Runtime.Base/src/System/Runtime/CastableObjectSupport.cs index 20f0ce285e..5ed1679c58 100644 --- a/external/corert/src/Runtime.Base/src/System/Runtime/CastableObjectSupport.cs +++ b/external/corert/src/Runtime.Base/src/System/Runtime/CastableObjectSupport.cs @@ -324,7 +324,7 @@ namespace System.Runtime unsafe private static IntPtr RhpCastableObjectResolve(IntPtr callerTransitionBlockParam, IntPtr pCell) { IntPtr locationOfThisPointer = callerTransitionBlockParam + TransitionBlock.GetThisOffset(); - object pObject = Unsafe.As(ref *(IntPtr*)locationOfThisPointer); + object pObject = Unsafe.As(ref *(IntPtr*)locationOfThisPointer); DispatchCellInfo cellInfo; InternalCalls.RhpGetDispatchCellInfo(pCell, out cellInfo); @@ -343,7 +343,7 @@ namespace System.Runtime if (targetObject == null) EH.FailFastViaClasslib(RhFailFastReason.InternalError, null, pObject.EEType->GetAssociatedModuleAddress()); - Unsafe.As(ref *(IntPtr*)locationOfThisPointer) = targetObject; + Unsafe.As(ref *(IntPtr*)locationOfThisPointer) = targetObject; InternalCalls.RhpSetTLSDispatchCell(pCell); return InternalCalls.RhpGetTailCallTLSDispatchCell(); diff --git a/external/corert/src/Runtime.Base/src/System/Runtime/DispatchResolve.cs b/external/corert/src/Runtime.Base/src/System/Runtime/DispatchResolve.cs index c609d878b6..83d5571c0c 100644 --- a/external/corert/src/Runtime.Base/src/System/Runtime/DispatchResolve.cs +++ b/external/corert/src/Runtime.Base/src/System/Runtime/DispatchResolve.cs @@ -47,7 +47,7 @@ namespace System.Runtime while (pCur != null) { - UInt16 implSlotNumber; + ushort implSlotNumber; if (FindImplSlotForCurrentType( pCur, pItfType, itfSlotNumber, &implSlotNumber)) { @@ -76,8 +76,8 @@ namespace System.Runtime private static bool FindImplSlotForCurrentType(EEType* pTgtType, EEType* pItfType, - UInt16 itfSlotNumber, - UInt16* pImplSlotNumber) + ushort itfSlotNumber, + ushort* pImplSlotNumber) { bool fRes = false; @@ -117,8 +117,8 @@ namespace System.Runtime private static bool FindImplSlotInSimpleMap(EEType* pTgtType, EEType* pItfType, - UInt32 itfSlotNumber, - UInt16* pImplSlotNumber, + uint itfSlotNumber, + ushort* pImplSlotNumber, bool actuallyCheckVariance) { Debug.Assert(pTgtType->HasDispatchMap, "Missing dispatch map"); @@ -226,7 +226,7 @@ namespace System.Runtime // arity of both had better be the same. Debug.Assert(itfArity == (int)pCurEntryType->GenericArity, "arity mismatch betweeen generic instantiations"); - if (TypeCast.TypeParametersAreCompatible(itfArity, pCurEntryInstantiation, pItfInstantiation, pItfVarianceInfo, fArrayCovariance)) + if (TypeCast.TypeParametersAreCompatible(itfArity, pCurEntryInstantiation, pItfInstantiation, pItfVarianceInfo, fArrayCovariance, null)) { *pImplSlotNumber = i->_usImplMethodSlot; return true; diff --git a/external/corert/src/Runtime.Base/src/System/Runtime/ExceptionHandling.cs b/external/corert/src/Runtime.Base/src/System/Runtime/ExceptionHandling.cs index 4d3cdf674f..b4e58dbad1 100644 --- a/external/corert/src/Runtime.Base/src/System/Runtime/ExceptionHandling.cs +++ b/external/corert/src/Runtime.Base/src/System/Runtime/ExceptionHandling.cs @@ -728,7 +728,11 @@ namespace System.Runtime Debug.Assert(isValid, "second-pass EH unwind failed unexpectedly"); DebugScanCallFrame(exInfo._passNumber, frameIter.ControlPC, frameIter.SP); - if (frameIter.SP == handlingFrameSP) + if ((frameIter.SP == handlingFrameSP) +#if ARM64 + && (frameIter.ControlPC == prevControlPC) +#endif + ) { // invoke only a partial second-pass here... InvokeSecondPass(ref exInfo, startIdx, catchingTryRegionIdx); diff --git a/external/corert/src/Runtime.Base/src/System/Runtime/InternalCalls.cs b/external/corert/src/Runtime.Base/src/System/Runtime/InternalCalls.cs index e647e3ab03..866247ac2c 100644 --- a/external/corert/src/Runtime.Base/src/System/Runtime/InternalCalls.cs +++ b/external/corert/src/Runtime.Base/src/System/Runtime/InternalCalls.cs @@ -72,13 +72,13 @@ namespace System.Runtime private static extern long RhpGetGcTotalMemory(); [RuntimeExport("RhStartNoGCRegion")] - internal static Int32 RhStartNoGCRegion(Int64 totalSize, bool hasLohSize, Int64 lohSize, bool disallowFullBlockingGC) + internal static int RhStartNoGCRegion(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC) { return RhpStartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC); } [RuntimeExport("RhEndNoGCRegion")] - internal static Int32 RhEndNoGCRegion() + internal static int RhEndNoGCRegion() { return RhpEndNoGCRegion(); } @@ -91,7 +91,7 @@ namespace System.Runtime [RuntimeImport(Redhawk.BaseName, "RhpGetNextFinalizableObject")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal static extern Object RhpGetNextFinalizableObject(); + internal static extern object RhpGetNextFinalizableObject(); // // internalcalls for System.Runtime.InteropServices.GCHandle. @@ -101,29 +101,29 @@ namespace System.Runtime [RuntimeImport(Redhawk.BaseName, "RhpHandleAlloc")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal static extern IntPtr RhpHandleAlloc(Object value, GCHandleType type); + internal static extern IntPtr RhpHandleAlloc(object value, GCHandleType type); // Allocate dependent handle. [RuntimeImport(Redhawk.BaseName, "RhpHandleAllocDependent")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal static extern IntPtr RhpHandleAllocDependent(Object primary, Object secondary); + internal static extern IntPtr RhpHandleAllocDependent(object primary, object secondary); // Allocate variable handle. [RuntimeImport(Redhawk.BaseName, "RhpHandleAllocVariable")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal static extern IntPtr RhpHandleAllocVariable(Object value, uint type); + internal static extern IntPtr RhpHandleAllocVariable(object value, uint type); [RuntimeImport(Redhawk.BaseName, "RhHandleGet")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal static extern Object RhHandleGet(IntPtr handle); + internal static extern object RhHandleGet(IntPtr handle); [RuntimeImport(Redhawk.BaseName, "RhHandleSet")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal static extern IntPtr RhHandleSet(IntPtr handle, Object value); + internal static extern IntPtr RhHandleSet(IntPtr handle, object value); // // internal calls for allocation @@ -188,7 +188,7 @@ namespace System.Runtime [RuntimeImport(Redhawk.BaseName, "RhpAssignRef")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal extern static unsafe void RhpAssignRef(ref Object address, object obj); + internal extern static unsafe void RhpAssignRef(ref object address, object obj); #if FEATURE_GC_STRESS // @@ -289,7 +289,7 @@ namespace System.Runtime [RuntimeImport(Redhawk.BaseName, "RhpGetEETypeRareFlags")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal extern static unsafe UInt32 RhpGetEETypeRareFlags(EEType* pEEType); + internal extern static unsafe uint RhpGetEETypeRareFlags(EEType* pEEType); // Retrieve the offset of the value embedded in a Nullable. [RuntimeImport(Redhawk.BaseName, "RhpGetNullableEETypeValueOffset")] @@ -428,7 +428,7 @@ namespace System.Runtime // Block the current thread until at least one object needs to be finalized (returns true) or // memory is low (returns false and the finalizer thread should initiate a garbage collection). [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] - internal static extern UInt32 RhpWaitForFinalizerRequest(); + internal static extern uint RhpWaitForFinalizerRequest(); // Indicate that the current round of finalizations is complete. [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] @@ -455,11 +455,11 @@ namespace System.Runtime // Enters a no GC region, possibly doing a blocking GC if there is not enough // memory available to satisfy the caller's request. [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] - internal static extern Int32 RhpStartNoGCRegion(Int64 totalSize, bool hasLohSize, Int64 lohSize, bool disallowFullBlockingGC); + internal static extern int RhpStartNoGCRegion(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC); // Exits a no GC region, possibly doing a GC to clean up the garbage that // the caller allocated. [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] - internal static extern Int32 RhpEndNoGCRegion(); + internal static extern int RhpEndNoGCRegion(); } } diff --git a/external/corert/src/Runtime.Base/src/System/Runtime/InteropServices/UnmanagedType.cs b/external/corert/src/Runtime.Base/src/System/Runtime/InteropServices/UnmanagedType.cs new file mode 100644 index 0000000000..143ed33c04 --- /dev/null +++ b/external/corert/src/Runtime.Base/src/System/Runtime/InteropServices/UnmanagedType.cs @@ -0,0 +1,8 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Runtime.InteropServices +{ + internal class UnmanagedType { } +} diff --git a/external/corert/src/Runtime.Base/src/System/Runtime/RuntimeExports.cs b/external/corert/src/Runtime.Base/src/System/Runtime/RuntimeExports.cs index db9b5de744..0c84e7c1f2 100644 --- a/external/corert/src/Runtime.Base/src/System/Runtime/RuntimeExports.cs +++ b/external/corert/src/Runtime.Base/src/System/Runtime/RuntimeExports.cs @@ -121,7 +121,7 @@ namespace System.Runtime } else { - return Unsafe.As(ref data); + return Unsafe.As(ref data); } } @@ -189,7 +189,7 @@ namespace System.Runtime throw ptrUnboxToEEType->GetClasslibException(ExceptionIDs.InvalidCast); } - Unsafe.As(ref data) = o; + Unsafe.As(ref data) = o; } } @@ -197,7 +197,7 @@ namespace System.Runtime // Unbox helpers with RyuJIT conventions // [RuntimeExport("RhUnbox2")] - public static unsafe ref byte RhUnbox2(EETypePtr pUnboxToEEType, Object obj) + public static unsafe ref byte RhUnbox2(EETypePtr pUnboxToEEType, object obj) { EEType* ptrUnboxToEEType = (EEType*)pUnboxToEEType.ToPointer(); if ((obj == null) || !UnboxAnyTypeCompare(obj.EEType, ptrUnboxToEEType)) @@ -209,7 +209,7 @@ namespace System.Runtime } [RuntimeExport("RhUnboxNullable")] - public static unsafe void RhUnboxNullable(ref byte data, EETypePtr pUnboxToEEType, Object obj) + public static unsafe void RhUnboxNullable(ref byte data, EETypePtr pUnboxToEEType, object obj) { EEType* ptrUnboxToEEType = (EEType*)pUnboxToEEType.ToPointer(); if ((obj != null) && !TypeCast.AreTypesEquivalentInternal(obj.EEType, ptrUnboxToEEType->NullableType)) @@ -235,7 +235,7 @@ namespace System.Runtime return; } - TypeCast.CheckArrayStore(array, Unsafe.As(ref data)); + TypeCast.CheckArrayStore(array, Unsafe.As(ref data)); } [RuntimeExport("RhBoxAndNullCheck")] @@ -245,13 +245,13 @@ namespace System.Runtime if (ptrEEType->IsValueType) return true; else - return Unsafe.As(ref data) != null; + return Unsafe.As(ref data) != null; } #pragma warning disable 169 // The field 'System.Runtime.RuntimeExports.Wrapper.o' is never used. private class Wrapper { - private Object _o; + private object _o; } #pragma warning restore 169 diff --git a/external/corert/src/Runtime.Base/src/System/Runtime/TypeCast.cs b/external/corert/src/Runtime.Base/src/System/Runtime/TypeCast.cs index 568892a652..5d6ad53867 100644 --- a/external/corert/src/Runtime.Base/src/System/Runtime/TypeCast.cs +++ b/external/corert/src/Runtime.Base/src/System/Runtime/TypeCast.cs @@ -111,7 +111,7 @@ namespace System.Runtime // parameters are compatible. // NOTE: using general assignable path for the cache because of the cost of the variance checks - if (CastCache.AreTypesAssignableInternal(pObjType, pTargetType, AssignmentVariation.BoxedSource)) + if (CastCache.AreTypesAssignableInternal(pObjType, pTargetType, AssignmentVariation.BoxedSource, null)) return obj; return null; } @@ -154,7 +154,7 @@ namespace System.Runtime } [RuntimeExport("RhTypeCast_CheckCastClass")] - public static unsafe object CheckCastClass(Object obj, void* pvTargetEEType) + public static unsafe object CheckCastClass(object obj, void* pvTargetEEType) { // a null value can be cast to anything if (obj == null) @@ -174,7 +174,7 @@ namespace System.Runtime } [RuntimeExport("RhTypeCast_CheckUnbox")] - public static unsafe void CheckUnbox(Object obj, byte expectedCorElementType) + public static unsafe void CheckUnbox(object obj, byte expectedCorElementType) { if (obj == null) { @@ -230,7 +230,7 @@ namespace System.Runtime } if (CastCache.AreTypesAssignableInternal(pObjType->RelatedParameterType, pTargetType->RelatedParameterType, - AssignmentVariation.AllowSizeEquivalence)) + AssignmentVariation.AllowSizeEquivalence, null)) { return obj; } @@ -239,7 +239,7 @@ namespace System.Runtime } [RuntimeExport("RhTypeCast_CheckCastArray")] - public static unsafe object CheckCastArray(Object obj, void* pvTargetEEType) + public static unsafe object CheckCastArray(object obj, void* pvTargetEEType) { // a null value can be cast to anything if (obj == null) @@ -269,7 +269,7 @@ namespace System.Runtime EEType* pTargetType = (EEType*)pvTargetType; EEType* pObjType = obj.EEType; - if (CastCache.AreTypesAssignableInternal_SourceNotTarget_BoxedSource(pObjType, pTargetType)) + if (CastCache.AreTypesAssignableInternal_SourceNotTarget_BoxedSource(pObjType, pTargetType, null)) return obj; // If object type implements ICastable then there's one more way to check whether it implements @@ -333,7 +333,7 @@ namespace System.Runtime // TODO!! END REMOVE THIS CODE WHEN WE REMOVE ICASTABLE } - internal static unsafe bool ImplementsInterface(EEType* pObjType, EEType* pTargetType) + internal static unsafe bool ImplementsInterface(EEType* pObjType, EEType* pTargetType, EETypePairList* pVisited) { Debug.Assert(!pTargetType->IsParameterizedType, "did not expect paramterized type"); Debug.Assert(pTargetType->IsInterface, "IsInstanceOfInterface called with non-interface EEType"); @@ -413,7 +413,8 @@ namespace System.Runtime pInterfaceInstantiation, pTargetInstantiation, pTargetVarianceInfo, - fArrayCovariance)) + fArrayCovariance, + pVisited)) return true; } } @@ -435,7 +436,7 @@ namespace System.Runtime } // Compare two types to see if they are compatible via generic variance. - private static unsafe bool TypesAreCompatibleViaGenericVariance(EEType* pSourceType, EEType* pTargetType) + private static unsafe bool TypesAreCompatibleViaGenericVariance(EEType* pSourceType, EEType* pTargetType, EETypePairList* pVisited) { EEType* pTargetGenericType = pTargetType->GenericDefinition; EEType* pSourceGenericType = pSourceType->GenericDefinition; @@ -466,7 +467,8 @@ namespace System.Runtime pSourceInstantiation, pTargetInstantiation, pTargetVarianceInfo, - false)) + false, + pVisited)) { return true; } @@ -484,7 +486,8 @@ namespace System.Runtime EETypeRef* pSourceInstantiation, EETypeRef* pTargetInstantiation, GenericVariance* pVarianceInfo, - bool fForceCovariance) + bool fForceCovariance, + EETypePairList* pVisited) { // Walk through the instantiations comparing the cast compatibility of each pair // of type args. @@ -519,7 +522,7 @@ namespace System.Runtime // class Foo : ICovariant is ICovariant // class Foo : ICovariant is ICovariant - if (!CastCache.AreTypesAssignableInternal(pSourceArgType, pTargetArgType, AssignmentVariation.Normal)) + if (!CastCache.AreTypesAssignableInternal(pSourceArgType, pTargetArgType, AssignmentVariation.Normal, pVisited)) return false; break; @@ -534,7 +537,7 @@ namespace System.Runtime // This call is just like the call for Covariance above except true is passed // to the fAllowSizeEquivalence parameter to allow the int/uint matching to work - if (!CastCache.AreTypesAssignableInternal(pSourceArgType, pTargetArgType, AssignmentVariation.AllowSizeEquivalence)) + if (!CastCache.AreTypesAssignableInternal(pSourceArgType, pTargetArgType, AssignmentVariation.AllowSizeEquivalence, pVisited)) return false; break; @@ -549,7 +552,7 @@ namespace System.Runtime // class Foo : IContravariant is IContravariant // class Foo : IContravariant is IContravariant - if (!CastCache.AreTypesAssignableInternal(pTargetArgType, pSourceArgType, AssignmentVariation.Normal)) + if (!CastCache.AreTypesAssignableInternal(pTargetArgType, pSourceArgType, AssignmentVariation.Normal, pVisited)) return false; break; @@ -594,7 +597,7 @@ namespace System.Runtime return AreTypesEquivalentInternal(pSourceType, pNullableType); } - return CastCache.AreTypesAssignableInternal(pSourceType, pTargetType, AssignmentVariation.BoxedSource); + return CastCache.AreTypesAssignableInternal(pSourceType, pTargetType, AssignmentVariation.BoxedSource, null); } // Internally callable version of the export method above. Has two additional flags: @@ -602,7 +605,7 @@ namespace System.Runtime // compatible with Object, ValueType and Enum (if applicable) // fAllowSizeEquivalence : allow identically sized integral types and enums to be considered // equivalent (currently used only for array element types) - internal static unsafe bool AreTypesAssignableInternal(EEType* pSourceType, EEType* pTargetType, AssignmentVariation variation) + internal static unsafe bool AreTypesAssignableInternal(EEType* pSourceType, EEType* pTargetType, AssignmentVariation variation, EETypePairList* pVisited) { bool fBoxedSource = ((variation & AssignmentVariation.BoxedSource) == AssignmentVariation.BoxedSource); bool fAllowSizeEquivalence = ((variation & AssignmentVariation.AllowSizeEquivalence) == AssignmentVariation.AllowSizeEquivalence); @@ -622,12 +625,12 @@ namespace System.Runtime if (!fBoxedSource && pSourceType->IsValueType) return false; - if (ImplementsInterface(pSourceType, pTargetType)) + if (ImplementsInterface(pSourceType, pTargetType, pVisited)) return true; // Are the types compatible due to generic variance? if (pTargetType->HasGenericVariance && pSourceType->HasGenericVariance) - return TypesAreCompatibleViaGenericVariance(pSourceType, pTargetType); + return TypesAreCompatibleViaGenericVariance(pSourceType, pTargetType, pVisited); return false; } @@ -667,7 +670,7 @@ namespace System.Runtime // here handles array covariance as well as IFoo[] -> Foo[] etc. We are not using // AssignmentVariation.BoxedSource because int[] is not assignable to object[]. return CastCache.AreTypesAssignableInternal(pSourceType->RelatedParameterType, - pTargetType->RelatedParameterType, AssignmentVariation.AllowSizeEquivalence); + pTargetType->RelatedParameterType, AssignmentVariation.AllowSizeEquivalence, pVisited); } } @@ -723,7 +726,7 @@ namespace System.Runtime // deriving from user delegate classes any further all we have to check here is that the // uninstantiated generic delegate definitions are the same and the type parameters are // compatible. - return TypesAreCompatibleViaGenericVariance(pSourceType, pTargetType); + return TypesAreCompatibleViaGenericVariance(pSourceType, pTargetType, pVisited); } // Is the source type derived from the target type? @@ -734,7 +737,7 @@ namespace System.Runtime } [RuntimeExport("RhTypeCast_CheckCastInterface")] - public static unsafe object CheckCastInterface(Object obj, void* pvTargetEEType) + public static unsafe object CheckCastInterface(object obj, void* pvTargetEEType) { // a null value can be cast to anything if (obj == null) @@ -745,7 +748,7 @@ namespace System.Runtime EEType* pTargetType = (EEType*)pvTargetEEType; EEType* pObjType = obj.EEType; - if (CastCache.AreTypesAssignableInternal_SourceNotTarget_BoxedSource(pObjType, pTargetType)) + if (CastCache.AreTypesAssignableInternal_SourceNotTarget_BoxedSource(pObjType, pTargetType, null)) return obj; Exception castError = null; @@ -779,7 +782,7 @@ namespace System.Runtime Debug.Assert(array.EEType->IsArray, "first argument must be an array"); EEType* arrayElemType = array.EEType->RelatedParameterType; - if (CastCache.AreTypesAssignableInternal(obj.EEType, arrayElemType, AssignmentVariation.BoxedSource)) + if (CastCache.AreTypesAssignableInternal(obj.EEType, arrayElemType, AssignmentVariation.BoxedSource, null)) return; // If object type implements ICastable then there's one more way to check whether it implements @@ -842,7 +845,7 @@ namespace System.Runtime { EEType* arrayElemType = array.EEType->RelatedParameterType; - if (!CastCache.AreTypesAssignableInternal(obj.EEType, arrayElemType, AssignmentVariation.BoxedSource)) + if (!CastCache.AreTypesAssignableInternal(obj.EEType, arrayElemType, AssignmentVariation.BoxedSource, null)) { // If object type implements ICastable then there's one more way to check whether it implements // the interface. @@ -858,7 +861,7 @@ namespace System.Runtime // Both bounds and type check are ok. // Call write barrier directly. Assigning object reference would call slower checked write barrier. - ref Object rawData = ref Unsafe.As(ref array.GetRawSzArrayData()); + ref object rawData = ref Unsafe.As(ref array.GetRawSzArrayData()); InternalCalls.RhpAssignRef(ref Unsafe.Add(ref rawData, index), obj); } else @@ -870,7 +873,7 @@ namespace System.Runtime } [RuntimeExport("RhpLdelemaRef")] - public static unsafe ref Object LdelemaRef(Array array, int index, IntPtr elementType) + public static unsafe ref object LdelemaRef(Array array, int index, IntPtr elementType) { Debug.Assert(array.EEType->IsArray, "first argument must be an array"); @@ -885,7 +888,7 @@ namespace System.Runtime throw array.EEType->GetClasslibException(ExceptionIDs.ArrayTypeMismatch); } - ref Object rawData = ref Unsafe.As(ref array.GetRawSzArrayData()); + ref object rawData = ref Unsafe.As(ref array.GetRawSzArrayData()); return ref Unsafe.Add(ref rawData, index); } @@ -976,13 +979,13 @@ namespace System.Runtime } [RuntimeExport("RhTypeCast_CheckCast2")] // Helper with RyuJIT calling convention - public static unsafe object CheckCast2(void* pvTargetType, Object obj) + public static unsafe object CheckCast2(void* pvTargetType, object obj) { return CheckCast(obj, pvTargetType); } [RuntimeExport("RhTypeCast_CheckCast")] - public static unsafe object CheckCast(Object obj, void* pvTargetType) + public static unsafe object CheckCast(object obj, void* pvTargetType) { // @TODO: consider using the cache directly, but beware of ICastable in the interface case EEType* pTargetType = (EEType*)pvTargetType; @@ -1034,6 +1037,33 @@ namespace System.Runtime } } + internal unsafe struct EETypePairList + { + private EEType* _eetype1; + private EEType* _eetype2; + private EETypePairList* _next; + + public EETypePairList(EEType* pEEType1, EEType* pEEType2, EETypePairList* pNext) + { + _eetype1 = pEEType1; + _eetype2 = pEEType2; + _next = pNext; + } + + public static bool Exists(EETypePairList* pList, EEType* pEEType1, EEType* pEEType2) + { + while (pList != null) + { + if (pList->_eetype1 == pEEType1 && pList->_eetype2 == pEEType2) + return true; + if (pList->_eetype1 == pEEType2 && pList->_eetype2 == pEEType1) + return true; + pList = pList->_next; + } + return false; + } + } + // source type + target type + assignment variation -> true/false [System.Runtime.CompilerServices.EagerStaticClassConstructionAttribute] private static class CastCache @@ -1103,7 +1133,7 @@ namespace System.Runtime public EEType* TargetType { get { return (EEType*)_targetType; } } } - public static unsafe bool AreTypesAssignableInternal(EEType* pSourceType, EEType* pTargetType, AssignmentVariation variation) + public static unsafe bool AreTypesAssignableInternal(EEType* pSourceType, EEType* pTargetType, AssignmentVariation variation, EETypePairList* pVisited) { // Important special case -- it breaks infinite recursion in CastCache itself! if (pSourceType == pTargetType) @@ -1112,7 +1142,7 @@ namespace System.Runtime Key key = new Key(pSourceType, pTargetType, variation); Entry entry = LookupInCache(s_cache, ref key); if (entry == null) - return CacheMiss(ref key); + return CacheMiss(ref key, pVisited); return entry.Result; } @@ -1124,13 +1154,13 @@ namespace System.Runtime // 2. Force inlining (This particular variant is only used in a small number of dispatch scenarios that are particularly // high in performance impact.) [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe bool AreTypesAssignableInternal_SourceNotTarget_BoxedSource(EEType* pSourceType, EEType* pTargetType) + public static unsafe bool AreTypesAssignableInternal_SourceNotTarget_BoxedSource(EEType* pSourceType, EEType* pTargetType, EETypePairList* pVisited) { Debug.Assert(pSourceType != pTargetType, "target is source"); Key key = new Key(pSourceType, pTargetType, AssignmentVariation.BoxedSource); Entry entry = LookupInCache(s_cache, ref key); if (entry == null) - return CacheMiss(ref key); + return CacheMiss(ref key, pVisited); return entry.Result; } @@ -1149,8 +1179,14 @@ namespace System.Runtime return entry; } - private static unsafe bool CacheMiss(ref Key key) + private static unsafe bool CacheMiss(ref Key key, EETypePairList* pVisited) { + // + // First, check if we previously visited the input types pair, to avoid infinite recursions + // + if (EETypePairList.Exists(pVisited, key.SourceType, key.TargetType)) + return false; + bool result = false; bool previouslyCached = false; @@ -1177,7 +1213,8 @@ namespace System.Runtime // if (!previouslyCached) { - result = TypeCast.AreTypesAssignableInternal(key.SourceType, key.TargetType, key.Variation); + EETypePairList newList = new EETypePairList(key.SourceType, key.TargetType, pVisited); + result = TypeCast.AreTypesAssignableInternal(key.SourceType, key.TargetType, key.Variation, &newList); } // diff --git a/external/corert/src/Runtime.Base/src/System/Runtime/__Finalizer.cs b/external/corert/src/Runtime.Base/src/System/Runtime/__Finalizer.cs index 6fd7d7ea3f..0dbc18de44 100644 --- a/external/corert/src/Runtime.Base/src/System/Runtime/__Finalizer.cs +++ b/external/corert/src/Runtime.Base/src/System/Runtime/__Finalizer.cs @@ -58,7 +58,7 @@ namespace System.Runtime // Drain the queue of finalizable objects. while (true) { - Object target = InternalCalls.RhpGetNextFinalizableObject(); + object target = InternalCalls.RhpGetNextFinalizableObject(); if (target == null) return; diff --git a/external/corert/src/System.Private.CoreLib/shared/Internal/Padding.cs b/external/corert/src/System.Private.CoreLib/shared/Internal/Padding.cs new file mode 100644 index 0000000000..14bf998bab --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/Internal/Padding.cs @@ -0,0 +1,26 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.InteropServices; + +namespace Internal +{ + /// A class for common padding constants and eventually routines. + internal static class PaddingHelpers + { + /// A size greater than or equal to the size of the most common CPU cache lines. +#if ARM64 + internal const int CACHE_LINE_SIZE = 128; +#else + internal const int CACHE_LINE_SIZE = 64; +#endif + } + + /// Padding structure used to minimize false sharing + [StructLayout(LayoutKind.Explicit, Size = PaddingHelpers.CACHE_LINE_SIZE - sizeof(int))] + internal struct PaddingFor32 + { + } +} + diff --git a/external/corert/src/System.Private.CoreLib/shared/Internal/Runtime/CompilerServices/Unsafe.cs b/external/corert/src/System.Private.CoreLib/shared/Internal/Runtime/CompilerServices/Unsafe.cs index aeff3ce2ca..03d3f85211 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Internal/Runtime/CompilerServices/Unsafe.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Internal/Runtime/CompilerServices/Unsafe.cs @@ -357,6 +357,17 @@ namespace Internal.Runtime.CompilerServices return ref Unsafe.As(ref *(byte*)source); } + /// + /// Reinterprets the given location as a reference to a value of type . + /// + [Intrinsic] + [NonVersionable] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref T AsRef(in T source) + { + throw new PlatformNotSupportedException(); + } + /// /// Determines the byte offset from origin to target from the given references. /// diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/Interop.Errors.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/Interop.Errors.cs index 4248434db3..9cb05809db 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/Interop.Errors.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/Interop.Errors.cs @@ -75,11 +75,13 @@ internal static partial class Interop ENOTCONN = 0x10038, // The socket is not connected. ENOTDIR = 0x10039, // Not a directory or a symbolic link to a directory. ENOTEMPTY = 0x1003A, // Directory not empty. + ENOTRECOVERABLE = 0x1003B, // State not recoverable. ENOTSOCK = 0x1003C, // Not a socket. ENOTSUP = 0x1003D, // Not supported (same value as EOPNOTSUP). ENOTTY = 0x1003E, // Inappropriate I/O control operation. ENXIO = 0x1003F, // No such device or address. EOVERFLOW = 0x10040, // Value too large to be stored in data type. + EOWNERDEAD = 0x10041, // Previous owner died. EPERM = 0x10042, // Operation not permitted. EPIPE = 0x10043, // Broken pipe. EPROTO = 0x10044, // Protocol error. @@ -186,7 +188,7 @@ internal static partial class Interop internal static extern int ConvertErrorPalToPlatform(Error error); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_StrErrorR")] - private static unsafe extern byte* StrErrorR(int platformErrno, byte* buffer, int bufferSize); + private static extern unsafe byte* StrErrorR(int platformErrno, byte* buffer, int bufferSize); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Casing.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Casing.cs index 25536d483a..503a864d69 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Casing.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Casing.cs @@ -12,12 +12,12 @@ internal static partial class Interop internal static partial class Globalization { [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ChangeCase")] - internal unsafe static extern void ChangeCase(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper); + internal static extern unsafe void ChangeCase(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ChangeCaseInvariant")] - internal unsafe static extern void ChangeCaseInvariant(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper); + internal static extern unsafe void ChangeCaseInvariant(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ChangeCaseTurkish")] - internal unsafe static extern void ChangeCaseTurkish(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper); + internal static extern unsafe void ChangeCaseTurkish(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs index 08aa6113d7..aeeb60ff77 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs @@ -12,48 +12,46 @@ internal static partial class Interop internal static partial class Globalization { [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetSortHandle")] - internal unsafe static extern ResultCode GetSortHandle(byte[] localeName, out SafeSortHandle sortHandle); + internal static extern unsafe ResultCode GetSortHandle(byte[] localeName, out SafeSortHandle sortHandle); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CloseSortHandle")] - internal unsafe static extern void CloseSortHandle(IntPtr handle); + internal static extern unsafe void CloseSortHandle(IntPtr handle); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CompareString")] - internal unsafe static extern int CompareString(SafeSortHandle sortHandle, char* lpStr1, int cwStr1Len, char* lpStr2, int cwStr2Len, CompareOptions options); + internal static extern unsafe int CompareString(SafeSortHandle sortHandle, char* lpStr1, int cwStr1Len, char* lpStr2, int cwStr2Len, CompareOptions options); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOf")] - internal unsafe static extern int IndexOf(SafeSortHandle sortHandle, string target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options, int* matchLengthPtr); - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOf")] - internal unsafe static extern int IndexOf(SafeSortHandle sortHandle, char* target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options, int* matchLengthPtr); + internal static extern unsafe int IndexOf(SafeSortHandle sortHandle, char* target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options, int* matchLengthPtr); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_LastIndexOf")] - internal unsafe static extern int LastIndexOf(SafeSortHandle sortHandle, string target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options); + internal static extern unsafe int LastIndexOf(SafeSortHandle sortHandle, char* target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOfOrdinalIgnoreCase")] - internal unsafe static extern int IndexOfOrdinalIgnoreCase(string target, int cwTargetLength, char* pSource, int cwSourceLength, bool findLast); + internal static extern unsafe int IndexOfOrdinalIgnoreCase(string target, int cwTargetLength, char* pSource, int cwSourceLength, bool findLast); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOfOrdinalIgnoreCase")] - internal unsafe static extern int IndexOfOrdinalIgnoreCase(char* target, int cwTargetLength, char* pSource, int cwSourceLength, bool findLast); + internal static extern unsafe int IndexOfOrdinalIgnoreCase(char* target, int cwTargetLength, char* pSource, int cwSourceLength, bool findLast); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_StartsWith")] [return: MarshalAs(UnmanagedType.Bool)] - internal unsafe static extern bool StartsWith(SafeSortHandle sortHandle, char* target, int cwTargetLength, char* source, int cwSourceLength, CompareOptions options); + internal static extern unsafe bool StartsWith(SafeSortHandle sortHandle, char* target, int cwTargetLength, char* source, int cwSourceLength, CompareOptions options); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_EndsWith")] [return: MarshalAs(UnmanagedType.Bool)] - internal unsafe static extern bool EndsWith(SafeSortHandle sortHandle, char* target, int cwTargetLength, char* source, int cwSourceLength, CompareOptions options); + internal static extern unsafe bool EndsWith(SafeSortHandle sortHandle, char* target, int cwTargetLength, char* source, int cwSourceLength, CompareOptions options); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_StartsWith")] [return: MarshalAs(UnmanagedType.Bool)] - internal unsafe static extern bool StartsWith(SafeSortHandle sortHandle, string target, int cwTargetLength, string source, int cwSourceLength, CompareOptions options); + internal static extern unsafe bool StartsWith(SafeSortHandle sortHandle, string target, int cwTargetLength, string source, int cwSourceLength, CompareOptions options); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_EndsWith")] [return: MarshalAs(UnmanagedType.Bool)] - internal unsafe static extern bool EndsWith(SafeSortHandle sortHandle, string target, int cwTargetLength, string source, int cwSourceLength, CompareOptions options); + internal static extern unsafe bool EndsWith(SafeSortHandle sortHandle, string target, int cwTargetLength, string source, int cwSourceLength, CompareOptions options); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetSortKey")] - internal unsafe static extern int GetSortKey(SafeSortHandle sortHandle, string str, int strLength, byte* sortKey, int sortKeyLength, CompareOptions options); + internal static extern unsafe int GetSortKey(SafeSortHandle sortHandle, string str, int strLength, byte* sortKey, int sortKeyLength, CompareOptions options); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CompareStringOrdinalIgnoreCase")] - internal unsafe static extern int CompareStringOrdinalIgnoreCase(char* lpStr1, int cwStr1Len, char* lpStr2, int cwStr2Len); + internal static extern unsafe int CompareStringOrdinalIgnoreCase(char* lpStr1, int cwStr1Len, char* lpStr2, int cwStr2Len); [DllImport(Libraries.GlobalizationNative, EntryPoint = "GlobalizationNative_GetSortVersion")] internal static extern int GetSortVersion(SafeSortHandle sortHandle); diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Idna.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Idna.cs index af2373946c..89b6c3cebe 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Idna.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Idna.cs @@ -13,9 +13,9 @@ internal static partial class Interop internal const int UseStd3AsciiRules = 0x2; [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ToAscii")] - internal static unsafe extern int ToAscii(uint flags, char* src, int srcLen, char* dstBuffer, int dstBufferCapacity); + internal static extern unsafe int ToAscii(uint flags, char* src, int srcLen, char* dstBuffer, int dstBufferCapacity); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ToUnicode")] - internal static unsafe extern int ToUnicode(uint flags, char* src, int srcLen, char* dstBuffer, int dstBufferCapacity); + internal static extern unsafe int ToUnicode(uint flags, char* src, int srcLen, char* dstBuffer, int dstBufferCapacity); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs index 09527f0a08..b6f5fbec1c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs @@ -12,29 +12,29 @@ internal static partial class Interop { [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleName")] [return: MarshalAs(UnmanagedType.Bool)] - internal unsafe static extern bool GetLocaleName(string localeName, [Out] StringBuilder value, int valueLength); + internal static extern unsafe bool GetLocaleName(string localeName, [Out] StringBuilder value, int valueLength); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleInfoString")] [return: MarshalAs(UnmanagedType.Bool)] - internal unsafe static extern bool GetLocaleInfoString(string localeName, uint localeStringData, [Out] StringBuilder value, int valueLength); + internal static extern unsafe bool GetLocaleInfoString(string localeName, uint localeStringData, [Out] StringBuilder value, int valueLength); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetDefaultLocaleName")] [return: MarshalAs(UnmanagedType.Bool)] - internal unsafe static extern bool GetDefaultLocaleName([Out] StringBuilder value, int valueLength); + internal static extern unsafe bool GetDefaultLocaleName([Out] StringBuilder value, int valueLength); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleTimeFormat")] [return: MarshalAs(UnmanagedType.Bool)] - internal unsafe static extern bool GetLocaleTimeFormat(string localeName, bool shortFormat, [Out] StringBuilder value, int valueLength); + internal static extern unsafe bool GetLocaleTimeFormat(string localeName, bool shortFormat, [Out] StringBuilder value, int valueLength); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleInfoInt")] [return: MarshalAs(UnmanagedType.Bool)] - internal unsafe static extern bool GetLocaleInfoInt(string localeName, uint localeNumberData, ref int value); + internal static extern unsafe bool GetLocaleInfoInt(string localeName, uint localeNumberData, ref int value); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleInfoGroupingSizes")] [return: MarshalAs(UnmanagedType.Bool)] - internal unsafe static extern bool GetLocaleInfoGroupingSizes(string localeName, uint localeGroupingData, ref int primaryGroupSize, ref int secondaryGroupSize); + internal static extern unsafe bool GetLocaleInfoGroupingSizes(string localeName, uint localeGroupingData, ref int primaryGroupSize, ref int secondaryGroupSize); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocales")] - internal unsafe static extern int GetLocales([Out] Char[] value, int valueLength); + internal static extern unsafe int GetLocales([Out] char[] value, int valueLength); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.GetRandomBytes.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.GetRandomBytes.cs index 62156e8d8e..e911b13583 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.GetRandomBytes.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.GetRandomBytes.cs @@ -11,7 +11,7 @@ internal partial class Interop internal unsafe partial class Sys { [DllImport(Interop.Libraries.SystemNative, EntryPoint = "SystemNative_GetNonCryptographicallySecureRandomBytes")] - internal static unsafe extern void GetNonCryptographicallySecureRandomBytes(byte* buffer, int length); + internal static extern unsafe void GetNonCryptographicallySecureRandomBytes(byte* buffer, int length); } internal static unsafe void GetRandomBytes(byte* buffer, int length) diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.Read.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.Read.cs index 812ae348dc..1be5e789c2 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.Read.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.Read.cs @@ -20,6 +20,6 @@ internal static partial class Interop /// Note - on fail. the position of the stream may change depending on the platform; consult man 2 read for more info /// [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Read", SetLastError = true)] - internal static unsafe extern int Read(SafeFileHandle fd, byte* buffer, int count); + internal static extern unsafe int Read(SafeFileHandle fd, byte* buffer, int count); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.Write.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.Write.cs index c14fc26263..0636615a8b 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.Write.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.Write.cs @@ -19,9 +19,9 @@ internal static partial class Interop /// Returns the number of bytes written on success; otherwise, returns -1 and sets errno /// [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Write", SetLastError = true)] - internal static unsafe extern int Write(SafeFileHandle fd, byte* buffer, int bufferSize); + internal static extern unsafe int Write(SafeFileHandle fd, byte* buffer, int bufferSize); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Write", SetLastError = true)] - internal static unsafe extern int Write(int fd, byte* buffer, int bufferSize); + internal static extern unsafe int Write(int fd, byte* buffer, int bufferSize); } } diff --git a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegCloseKey.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCloseKey.cs similarity index 63% rename from external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegCloseKey.cs rename to external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCloseKey.cs index 2b55f97814..375376d52a 100644 --- a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegCloseKey.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCloseKey.cs @@ -2,15 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; internal partial class Interop { - internal partial class mincore + internal partial class Advapi32 { - [DllImport(Libraries.Registry_L1)] - internal extern static int RegCloseKey(IntPtr hKey); + [DllImport(Libraries.Advapi32)] + internal static extern int RegCloseKey(IntPtr hKey); } } diff --git a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegCreateKeyEx.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCreateKeyEx.cs similarity index 71% rename from external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegCreateKeyEx.cs rename to external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCreateKeyEx.cs index 8f9d3eed31..e5219064bc 100644 --- a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegCreateKeyEx.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCreateKeyEx.cs @@ -8,19 +8,19 @@ using System.Runtime.InteropServices; internal partial class Interop { - internal partial class mincore + internal partial class Advapi32 { // Note: RegCreateKeyEx won't set the last error on failure - it returns // an error code if it fails. - [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegCreateKeyExW")] + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegCreateKeyExW")] internal static extern int RegCreateKeyEx( SafeRegistryHandle hKey, - String lpSubKey, + string lpSubKey, int Reserved, - String lpClass, + string lpClass, int dwOptions, int samDesired, - ref Kernel32.SECURITY_ATTRIBUTES secAttrs, + ref Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs, out SafeRegistryHandle hkResult, out int lpdwDisposition); } diff --git a/external/corert/src/Common/src/Interop/Windows/advapi32/Interop.RegSetValueEx.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteKeyEx.cs similarity index 55% rename from external/corert/src/Common/src/Interop/Windows/advapi32/Interop.RegSetValueEx.cs rename to external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteKeyEx.cs index 59e038d959..4429515cdd 100644 --- a/external/corert/src/Common/src/Interop/Windows/advapi32/Interop.RegSetValueEx.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteKeyEx.cs @@ -2,16 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; -using Microsoft.Win32; -using Microsoft.Win32.SafeHandles; internal partial class Interop { internal partial class Advapi32 { - [DllImport("advapi32.dll", CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")] - internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName, int Reserved, RegistryValueKind dwType, string lpData, int cbData); + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegDeleteKeyExW")] + internal static extern int RegDeleteKeyEx(SafeRegistryHandle hKey, string lpSubKey, int samDesired, int Reserved); } } diff --git a/external/corert/src/Common/src/Interop/Windows/advapi32/Interop.RegDeleteValue.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteValue.cs similarity index 73% rename from external/corert/src/Common/src/Interop/Windows/advapi32/Interop.RegDeleteValue.cs rename to external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteValue.cs index 91369a01fc..b8044bc79d 100644 --- a/external/corert/src/Common/src/Interop/Windows/advapi32/Interop.RegDeleteValue.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteValue.cs @@ -2,15 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; internal partial class Interop { internal partial class Advapi32 { - [DllImport("advapi32.dll", CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegDeleteValueW")] - internal static extern int RegDeleteValue(SafeRegistryHandle hKey, String lpValueName); + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegDeleteValueW")] + internal static extern int RegDeleteValue(SafeRegistryHandle hKey, string lpValueName); } } diff --git a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegEnumKeyEx.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumKeyEx.cs similarity index 77% rename from external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegEnumKeyEx.cs rename to external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumKeyEx.cs index 6196c98b06..bedf282773 100644 --- a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegEnumKeyEx.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumKeyEx.cs @@ -9,13 +9,13 @@ using System.Text; internal partial class Interop { - internal partial class mincore + internal partial class Advapi32 { - [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegEnumKeyExW")] + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegEnumKeyExW")] internal static extern unsafe int RegEnumKeyEx( SafeRegistryHandle hKey, int dwIndex, - char* lpName, + char[] lpName, ref int lpcbName, int[] lpReserved, [Out]StringBuilder lpClass, diff --git a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegEnumValue.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumValue.cs similarity index 76% rename from external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegEnumValue.cs rename to external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumValue.cs index 6d88c517cc..e02ba98fef 100644 --- a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegEnumValue.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumValue.cs @@ -8,13 +8,13 @@ using System.Runtime.InteropServices; internal partial class Interop { - internal partial class mincore + internal partial class Advapi32 { - [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegEnumValueW")] + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegEnumValueW")] internal static extern unsafe int RegEnumValue( SafeRegistryHandle hKey, int dwIndex, - char* lpValueName, + char[] lpValueName, ref int lpcbValueName, IntPtr lpReserved_MustBeZero, int[] lpType, diff --git a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegFlushKey.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegFlushKey.cs similarity index 83% rename from external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegFlushKey.cs rename to external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegFlushKey.cs index 25f8ff2401..8f72798f87 100644 --- a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegFlushKey.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegFlushKey.cs @@ -7,9 +7,9 @@ using System.Runtime.InteropServices; internal partial class Interop { - internal partial class mincore + internal partial class Advapi32 { - [DllImport(Libraries.Registry_L1)] + [DllImport(Libraries.Advapi32)] internal static extern int RegFlushKey(SafeRegistryHandle hKey); } } diff --git a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegOpenKeyEx.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegOpenKeyEx.cs similarity index 72% rename from external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegOpenKeyEx.cs rename to external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegOpenKeyEx.cs index 9e8d9382fb..86b6bcae29 100644 --- a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegOpenKeyEx.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegOpenKeyEx.cs @@ -8,9 +8,9 @@ using System.Runtime.InteropServices; internal partial class Interop { - internal partial class mincore + internal partial class Advapi32 { - [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegOpenKeyExW")] + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegOpenKeyExW")] internal static extern int RegOpenKeyEx( SafeRegistryHandle hKey, string lpSubKey, @@ -19,7 +19,7 @@ internal partial class Interop out SafeRegistryHandle hkResult); - [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegOpenKeyExW")] + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegOpenKeyExW")] internal static extern int RegOpenKeyEx( IntPtr hKey, string lpSubKey, diff --git a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegQueryInfoKey.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryInfoKey.cs similarity index 83% rename from external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegQueryInfoKey.cs rename to external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryInfoKey.cs index 19a6884407..2df2092885 100644 --- a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegQueryInfoKey.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryInfoKey.cs @@ -9,9 +9,9 @@ using System.Text; internal partial class Interop { - internal partial class mincore + internal partial class Advapi32 { - [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryInfoKeyW")] + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryInfoKeyW")] internal static extern int RegQueryInfoKey( SafeRegistryHandle hKey, [Out]StringBuilder lpClass, diff --git a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegQueryValueEx.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryValueEx.cs similarity index 65% rename from external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegQueryValueEx.cs rename to external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryValueEx.cs index 10e5c430fb..c6a8798179 100644 --- a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegQueryValueEx.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryValueEx.cs @@ -9,9 +9,9 @@ using System.Text; internal partial class Interop { - internal partial class mincore + internal partial class Advapi32 { - [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx( SafeRegistryHandle hKey, string lpValueName, @@ -20,7 +20,7 @@ internal partial class Interop [Out] byte[] lpData, ref int lpcbData); - [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx( SafeRegistryHandle hKey, string lpValueName, @@ -29,28 +29,28 @@ internal partial class Interop ref int lpData, ref int lpcbData); - [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx( SafeRegistryHandle hKey, - String lpValueName, + string lpValueName, int[] lpReserved, ref int lpType, ref long lpData, ref int lpcbData); - [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx( SafeRegistryHandle hKey, - String lpValueName, + string lpValueName, int[] lpReserved, ref int lpType, [Out] char[] lpData, ref int lpcbData); - [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx( SafeRegistryHandle hKey, - String lpValueName, + string lpValueName, int[] lpReserved, ref int lpType, [Out]StringBuilder lpData, diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegSetValueEx.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegSetValueEx.cs new file mode 100644 index 0000000000..d46f84809a --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegSetValueEx.cs @@ -0,0 +1,59 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.Win32; +using Microsoft.Win32.SafeHandles; +using System; +using System.Runtime.InteropServices; + +internal partial class Interop +{ + internal partial class Advapi32 + { + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")] + internal static extern int RegSetValueEx( + SafeRegistryHandle hKey, + string lpValueName, + int Reserved, + RegistryValueKind dwType, + byte[] lpData, + int cbData); + + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")] + internal static extern int RegSetValueEx( + SafeRegistryHandle hKey, + string lpValueName, + int Reserved, + RegistryValueKind dwType, + char[] lpData, + int cbData); + + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")] + internal static extern int RegSetValueEx( + SafeRegistryHandle hKey, + string lpValueName, + int Reserved, + RegistryValueKind dwType, + ref int lpData, + int cbData); + + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")] + internal static extern int RegSetValueEx( + SafeRegistryHandle hKey, + string lpValueName, + int Reserved, + RegistryValueKind dwType, + ref long lpData, + int cbData); + + [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")] + internal static extern int RegSetValueEx( + SafeRegistryHandle hKey, + string lpValueName, + int Reserved, + RegistryValueKind dwType, + string lpData, + int cbData); + } +} diff --git a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegistryOptions.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegistryConstants.cs similarity index 91% rename from external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegistryOptions.cs rename to external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegistryConstants.cs index 4c95a8b1f0..bdb89702f8 100644 --- a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.RegistryOptions.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegistryConstants.cs @@ -4,23 +4,23 @@ internal partial class Interop { - internal partial class mincore + internal partial class Advapi32 { - internal partial class RegistryOptions + internal static class RegistryOptions { internal const int REG_OPTION_NON_VOLATILE = 0x0000; // (default) keys are persisted beyond reboot/unload internal const int REG_OPTION_VOLATILE = 0x0001; // All keys created by the function are volatile internal const int REG_OPTION_CREATE_LINK = 0x0002; // They key is a symbolic link - internal const int REG_OPTION_BACKUP_RESTORE = 0x0004; // Use SE_BACKUP_NAME process special privileges + internal const int REG_OPTION_BACKUP_RESTORE = 0x0004; // Use SE_BACKUP_NAME process special privileges } - internal partial class RegistryView + internal static class RegistryView { internal const int KEY_WOW64_64KEY = 0x0100; internal const int KEY_WOW64_32KEY = 0x0200; } - internal partial class RegistryOperations + internal static class RegistryOperations { internal const int KEY_QUERY_VALUE = 0x0001; internal const int KEY_SET_VALUE = 0x0002; @@ -47,7 +47,7 @@ internal partial class Interop internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL; } - internal partial class RegistryValues + internal static class RegistryValues { internal const int REG_NONE = 0; // No value type internal const int REG_SZ = 1; // Unicode nul terminated string @@ -62,4 +62,4 @@ internal partial class Interop internal const int REG_QWORD = 11; // 64-bit number } } -} +} \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.GetRandomBytes.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.GetRandomBytes.cs new file mode 100644 index 0000000000..4d75163d4b --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.GetRandomBytes.cs @@ -0,0 +1,29 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +internal partial class Interop +{ + internal static unsafe void GetRandomBytes(byte* buffer, int length) + { + Debug.Assert(buffer != null); + Debug.Assert(length >= 0); + + BCrypt.NTSTATUS status = BCrypt.BCryptGenRandom(IntPtr.Zero, buffer, length, BCrypt.BCRYPT_USE_SYSTEM_PREFERRED_RNG); + if (status != BCrypt.NTSTATUS.STATUS_SUCCESS) + { + if (status == BCrypt.NTSTATUS.STATUS_NO_MEMORY) + { + throw new OutOfMemoryException(); + } + else + { + throw new InvalidOperationException(); + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs index bc357125b5..9d072a3b01 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs @@ -10,35 +10,9 @@ internal partial class Interop { internal partial class BCrypt { - internal static unsafe int BCryptGenRandom(byte* pbBuffer, int count) - { - Debug.Assert(pbBuffer != null); - Debug.Assert(count >= 0); - - return BCryptGenRandom(IntPtr.Zero, pbBuffer, count, BCRYPT_USE_SYSTEM_PREFERRED_RNG); - } - - private const int BCRYPT_USE_SYSTEM_PREFERRED_RNG = 0x00000002; - internal const int STATUS_SUCCESS = 0x0; - internal const int STATUS_NO_MEMORY = unchecked((int)0xC0000017); + internal const int BCRYPT_USE_SYSTEM_PREFERRED_RNG = 0x00000002; [DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)] - private static unsafe extern int BCryptGenRandom(IntPtr hAlgorithm, byte* pbBuffer, int cbBuffer, int dwFlags); - } - - internal static unsafe void GetRandomBytes(byte* buffer, int length) - { - int status = BCrypt.BCryptGenRandom(buffer, length); - if (status != BCrypt.STATUS_SUCCESS) - { - if (status == BCrypt.STATUS_NO_MEMORY) - { - throw new OutOfMemoryException(); - } - else - { - throw new InvalidOperationException(); - } - } + internal static extern unsafe NTSTATUS BCryptGenRandom(IntPtr hAlgorithm, byte* pbBuffer, int cbBuffer, int dwFlags); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.NTSTATUS.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.NTSTATUS.cs new file mode 100644 index 0000000000..29aaa2904b --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.NTSTATUS.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +internal partial class Interop +{ + internal partial class BCrypt + { + internal enum NTSTATUS : uint + { + STATUS_SUCCESS = 0x0, + STATUS_NOT_FOUND = 0xc0000225, + STATUS_INVALID_PARAMETER = 0xc000000d, + STATUS_NO_MEMORY = 0xc0000017, + STATUS_AUTH_TAG_MISMATCH = 0xc000a002, + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Interop.Libraries.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Interop.Libraries.cs index 45d910bfcc..398d18a2a0 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Interop.Libraries.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Interop.Libraries.cs @@ -6,11 +6,13 @@ internal static partial class Interop { internal static partial class Libraries { + internal const string Advapi32 = "advapi32.dll"; internal const string BCrypt = "BCrypt.dll"; internal const string Crypt32 = "crypt32.dll"; internal const string Kernel32 = "kernel32.dll"; internal const string Ole32 = "ole32.dll"; internal const string OleAut32 = "oleaut32.dll"; internal const string User32 = "user32.dll"; + internal const string NtDll = "ntdll.dll"; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs index 96ed922a84..ff41f939f1 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs @@ -10,7 +10,6 @@ internal partial class Interop internal partial class Kernel32 { [DllImport(Libraries.Kernel32, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(IntPtr handle); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs new file mode 100644 index 0000000000..b13cdfd03f --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs @@ -0,0 +1,15 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +internal static partial class Interop +{ + internal static partial class Kernel32 + { + internal const int MAXIMUM_ALLOWED = 0x02000000; + internal const int SYNCHRONIZE = 0x00100000; + internal const int MUTEX_MODIFY_STATE = 0x00000001; + internal const int SEMAPHORE_MODIFY_STATE = 0x00000002; + internal const int EVENT_MODIFY_STATE = 0x00000002; + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.EventWaitHandle.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.EventWaitHandle.cs new file mode 100644 index 0000000000..b562e527e7 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.EventWaitHandle.cs @@ -0,0 +1,28 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.Win32.SafeHandles; +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Kernel32 + { + internal const uint CREATE_EVENT_INITIAL_SET = 0x2; + internal const uint CREATE_EVENT_MANUAL_RESET = 0x1; + + [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] + internal static extern bool SetEvent(SafeWaitHandle handle); + + [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] + internal static extern bool ResetEvent(SafeWaitHandle handle); + + [DllImport(Interop.Libraries.Kernel32, EntryPoint = "CreateEventExW", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern SafeWaitHandle CreateEventEx(IntPtr lpSecurityAttributes, string name, uint flags, uint desiredAccess); + + [DllImport(Interop.Libraries.Kernel32, EntryPoint = "OpenEventW", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern SafeWaitHandle OpenEvent(uint desiredAccess, bool inheritHandle, string name); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FileTypes.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FileTypes.cs index 1d306665b1..9d52f1f4f4 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FileTypes.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FileTypes.cs @@ -8,6 +8,7 @@ internal partial class Interop { internal partial class FileTypes { + internal const int FILE_TYPE_UNKNOWN = 0x0000; internal const int FILE_TYPE_DISK = 0x0001; internal const int FILE_TYPE_CHAR = 0x0002; internal const int FILE_TYPE_PIPE = 0x0003; diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindClose.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindClose.cs index 03d8c8b323..fcf9254aca 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindClose.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindClose.cs @@ -11,6 +11,6 @@ internal partial class Interop internal partial class Kernel32 { [DllImport(Libraries.Kernel32, SetLastError = true)] - internal extern static bool FindClose(IntPtr hFindFile); + internal static extern bool FindClose(IntPtr hFindFile); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindFirstFileEx.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindFirstFileEx.cs index 80b1ddd28d..dcb86ec9b6 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindFirstFileEx.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindFirstFileEx.cs @@ -19,7 +19,7 @@ internal partial class Interop internal static SafeFindHandle FindFirstFile(string fileName, ref WIN32_FIND_DATA data) { - fileName = PathInternal.EnsureExtendedPrefixOverMaxPath(fileName); + fileName = PathInternal.EnsureExtendedPrefixIfNeeded(fileName); // use FindExInfoBasic since we don't care about short name and it has better perf return FindFirstFileExPrivate(fileName, FINDEX_INFO_LEVELS.FindExInfoBasic, ref data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, 0); diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FormatMessage.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FormatMessage.cs index 94722b6c8b..3ea12d7cf0 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FormatMessage.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FormatMessage.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Text; using System.Runtime.InteropServices; internal partial class Interop @@ -14,99 +13,76 @@ internal partial class Interop private const int FORMAT_MESSAGE_FROM_HMODULE = 0x00000800; private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; - - + private const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; private const int ERROR_INSUFFICIENT_BUFFER = 0x7A; [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, EntryPoint = "FormatMessageW", SetLastError = true, BestFitMapping = true)] - private static extern int FormatMessage( + private static extern unsafe int FormatMessage( int dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, - [Out] StringBuilder lpBuffer, + void* lpBuffer, int nSize, - IntPtr[] arguments); + IntPtr arguments); /// /// Returns a string message for the specified Win32 error code. /// - internal static string GetMessage(int errorCode) + internal static string GetMessage(int errorCode) => + GetMessage(errorCode, IntPtr.Zero); + + internal static unsafe string GetMessage(int errorCode, IntPtr moduleHandle) { - return GetMessage(IntPtr.Zero, errorCode); - } - - internal static string GetMessage(IntPtr moduleHandle, int errorCode) - { - var sb = new StringBuilder(InitialBufferSize); - do - { - string errorMsg; - if (TryGetErrorMessage(moduleHandle, errorCode, sb, out errorMsg)) - { - return errorMsg; - } - else - { - // increase the capacity of the StringBuilder. - sb.Capacity *= BufferSizeIncreaseFactor; - } - } - while (sb.Capacity < MaxAllowedBufferSize); - - // If you come here then a size as large as 65K is also not sufficient and so we give the generic errorMsg. - return string.Format("Unknown error (0x{0:x})", errorCode); - } - - private static bool TryGetErrorMessage(IntPtr moduleHandle, int errorCode, StringBuilder sb, out string errorMsg) - { - errorMsg = ""; - int flags = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY; if (moduleHandle != IntPtr.Zero) { flags |= FORMAT_MESSAGE_FROM_HMODULE; } - int result = FormatMessage(flags, moduleHandle, (uint)errorCode, 0, sb, sb.Capacity, null); - if (result != 0) + // First try to format the message into the stack based buffer. Most error messages willl fit. + Span stackBuffer = stackalloc char[256]; // arbitrary stack limit + fixed (char* bufferPtr = &MemoryMarshal.GetReference(stackBuffer)) { - int i = sb.Length; - while (i > 0) + int length = FormatMessage(flags, moduleHandle, unchecked((uint)errorCode), 0, bufferPtr, stackBuffer.Length, IntPtr.Zero); + if (length > 0) { - char ch = sb[i - 1]; - if (ch > 32 && ch != '.') break; - i--; + return GetAndTrimString(stackBuffer.Slice(0, length)); } - errorMsg = sb.ToString(0, i); - } - else if (Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER) - { - return false; - } - else - { - errorMsg = string.Format("Unknown error (0x{0:x})", errorCode); } - return true; + // We got back an error. If the error indicated that there wasn't enough room to store + // the error message, then call FormatMessage again, but this time rather than passing in + // a buffer, have the method allocate one, which we then need to free. + if (Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER) + { + IntPtr nativeMsgPtr = default; + try + { + int length = FormatMessage(flags | FORMAT_MESSAGE_ALLOCATE_BUFFER, moduleHandle, unchecked((uint)errorCode), 0, &nativeMsgPtr, 0, IntPtr.Zero); + if (length > 0) + { + return GetAndTrimString(new Span((char*)nativeMsgPtr, length)); + } + } + finally + { + Marshal.FreeHGlobal(nativeMsgPtr); + } + } + + // Couldn't get a message, so manufacture one. + return string.Format("Unknown error (0x{0:x})", errorCode); } - // Windows API FormatMessage lets you format a message string given an errorcode. - // Unlike other APIs this API does not support a way to query it for the total message size. - // - // So the API can only be used in one of these two ways. - // a. You pass a buffer of appropriate size and get the resource. - // b. Windows creates a buffer and passes the address back and the onus of releasing the buffer lies on the caller. - // - // Since the error code is coming from the user, it is not possible to know the size in advance. - // Unfortunately we can't use option b. since the buffer can only be freed using LocalFree and it is a private API on onecore. - // Also, using option b is ugly for the managed code and could cause memory leak in situations where freeing is unsuccessful. - // - // As a result we use the following approach. - // We initially call the API with a buffer size of 256 and then gradually increase the size in case of failure until we reach the maximum allowed limit of 65K. - private const int InitialBufferSize = 256; - private const int BufferSizeIncreaseFactor = 4; - private const int MaxAllowedBufferSize = 65 * 1024; + private static string GetAndTrimString(Span buffer) + { + int length = buffer.Length; + while (length > 0 && buffer[length - 1] <= 32) + { + length--; // trim off spaces and non-printable ASCII chars at the end of the resource + } + return buffer.Slice(0, length).ToString(); + } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs index c07a1683a5..faa57cc2f1 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs @@ -10,6 +10,6 @@ internal partial class Interop internal partial class Kernel32 { [DllImport(Libraries.Kernel32, SetLastError = true)] - internal extern static int GetFileType(SafeHandle hFile); + internal static extern int GetFileType(SafeHandle hFile); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs index 06030450ca..197b0a9be5 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs @@ -13,17 +13,6 @@ internal partial class Interop /// WARNING: This method does not implicitly handle long paths. Use GetFullPathName or PathHelper. /// [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false, ExactSpelling = true)] -#if PROJECTN - internal static extern unsafe uint GetFullPathNameW(string path, uint numBufferChars, char* buffer, IntPtr mustBeZero); - - // Works around https://devdiv.visualstudio.com/web/wi.aspx?pcguid=011b8bdf-6d56-4f87-be0d-0092136884d9&id=575202 - internal static unsafe uint GetFullPathNameW(string path, uint numBufferChars, ref char buffer, IntPtr mustBeZero) - { - fixed (char* pBuffer = &buffer) - return GetFullPathNameW(path, numBufferChars, pBuffer, mustBeZero); - } -#else - internal static extern uint GetFullPathNameW(string path, uint numBufferChars, ref char buffer, IntPtr mustBeZero); -#endif + internal static extern uint GetFullPathNameW(ref char lpFileName, uint nBufferLength, ref char lpBuffer, IntPtr lpFilePart); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs index 09e98d0c95..81b4d096f5 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs @@ -13,17 +13,6 @@ internal partial class Interop /// WARNING: This method does not implicitly handle long paths. Use GetFullPath/PathHelper. /// [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false, ExactSpelling = true)] -#if PROJECTN - internal static extern unsafe uint GetLongPathNameW(ref char lpszShortPath, char* lpszLongPath, uint cchBuffer); - - // Works around https://devdiv.visualstudio.com/web/wi.aspx?pcguid=011b8bdf-6d56-4f87-be0d-0092136884d9&id=575202 - internal static unsafe uint GetLongPathNameW(ref char lpszShortPath, ref char lpszLongPath, uint cchBuffer) - { - fixed (char* plpszLongPath = &lpszLongPath) - return GetLongPathNameW(ref lpszShortPath, plpszLongPath, cchBuffer); - } -#else internal static extern uint GetLongPathNameW(ref char lpszShortPath, ref char lpszLongPath, uint cchBuffer); -#endif } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs index 36673895b4..97e1d82847 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Text; using System.Runtime.InteropServices; internal partial class Interop @@ -11,6 +9,6 @@ internal partial class Interop internal partial class Kernel32 { [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)] - internal static extern uint GetTempFileNameW(string tmpPath, string prefix, uint uniqueIdOrZero, [Out]StringBuilder tmpFileName); + internal static extern uint GetTempFileNameW(ref char lpPathName, string lpPrefixString, uint uUnique, ref char lpTempFileName); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempPathW.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempPathW.cs index ff2783be26..7f7bb775c8 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempPathW.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempPathW.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.IO; -using System.Text; using System.Runtime.InteropServices; internal partial class Interop @@ -11,6 +9,6 @@ internal partial class Interop internal partial class Kernel32 { [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, BestFitMapping = false)] - internal static extern uint GetTempPathW(int bufferLen, [Out]StringBuilder buffer); + internal static extern uint GetTempPathW(int bufferLen, ref char buffer); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Globalization.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Globalization.cs index ed0ada8411..2227d59b0e 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Globalization.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Globalization.cs @@ -18,13 +18,13 @@ internal static partial class Interop internal const int COMPARE_STRING = 0x0001; [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal extern static unsafe int LCIDToLocaleName(int locale, char *pLocaleName, int cchName, uint dwFlags); + internal static extern unsafe int LCIDToLocaleName(int locale, char *pLocaleName, int cchName, uint dwFlags); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal extern static int LocaleNameToLCID(string lpName, uint dwFlags); + internal static extern int LocaleNameToLCID(string lpName, uint dwFlags); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal extern static unsafe int LCMapStringEx( + internal static extern unsafe int LCMapStringEx( string lpLocaleName, uint dwMapFlags, char* lpSrcStr, @@ -36,7 +36,7 @@ internal static partial class Interop IntPtr sortHandle); [DllImport("kernel32.dll", EntryPoint = "FindNLSStringEx")] - internal extern static unsafe int FindNLSStringEx( + internal static extern unsafe int FindNLSStringEx( char* lpLocaleName, uint dwFindNLSStringFlags, char* lpStringSource, @@ -49,7 +49,7 @@ internal static partial class Interop IntPtr sortHandle); [DllImport("kernel32.dll", EntryPoint = "CompareStringEx")] - internal extern static unsafe int CompareStringEx( + internal static extern unsafe int CompareStringEx( char* lpLocaleName, uint dwCmpFlags, char* lpString1, @@ -61,7 +61,7 @@ internal static partial class Interop IntPtr lParam); [DllImport("kernel32.dll", EntryPoint = "CompareStringOrdinal")] - internal extern static unsafe int CompareStringOrdinal( + internal static extern unsafe int CompareStringOrdinal( char* lpString1, int cchCount1, char* lpString2, @@ -69,7 +69,7 @@ internal static partial class Interop bool bIgnoreCase); [DllImport("kernel32.dll", EntryPoint = "FindStringOrdinal")] - internal extern static unsafe int FindStringOrdinal( + internal static extern unsafe int FindStringOrdinal( uint dwFindStringOrdinalFlags, char* lpStringSource, int cchSource, @@ -78,7 +78,7 @@ internal static partial class Interop int bIgnoreCase); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal extern static unsafe bool IsNLSDefinedString( + internal static extern unsafe bool IsNLSDefinedString( int Function, uint dwFlags, IntPtr lpVersionInformation, @@ -94,26 +94,26 @@ internal static partial class Interop internal static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, void* lpLCData, int cchData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal extern static bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, void* lParam, IntPtr reserved); + internal static extern bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, void* lParam, IntPtr reserved); internal delegate BOOL EnumLocalesProcEx(char* lpLocaleString, uint dwFlags, void* lParam); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal extern static int ResolveLocaleName(string lpNameToResolve, char* lpLocaleName, int cchLocaleName); + internal static extern int ResolveLocaleName(string lpNameToResolve, char* lpLocaleName, int cchLocaleName); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal extern static bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, void* lParam); + internal static extern bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, void* lParam); internal delegate BOOL EnumTimeFormatsProcEx(char* lpTimeFormatString, void* lParam); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal extern static int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, out int lpValue); + internal static extern int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, out int lpValue); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal extern static int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, IntPtr lpValue); + internal static extern int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, IntPtr lpValue); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal extern static bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, void* lParam); + internal static extern bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, void* lParam); internal delegate BOOL EnumCalendarInfoProcExEx(char* lpCalendarInfoString, uint Calendar, IntPtr lpReserved, void* lParam); @@ -128,6 +128,6 @@ internal static partial class Interop } [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal extern static unsafe bool GetNLSVersionEx(int function, string localeName, NlsVersionInfoEx* lpVersionInformation); + internal static extern unsafe bool GetNLSVersionEx(int function, string localeName, NlsVersionInfoEx* lpVersionInformation); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MUI.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MUI.cs index 6ed7aa2dc4..8d97c03546 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MUI.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MUI.cs @@ -13,6 +13,6 @@ internal static partial class Interop internal const uint MUI_PREFERRED_UI_LANGUAGES = 0x10; [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] - internal static extern bool GetFileMUIPath(uint flags, String filePath, [Out] StringBuilder language, ref int languageLength, [Out] StringBuilder fileMuiPath, ref int fileMuiPathLength, ref Int64 enumerator); + internal static extern bool GetFileMUIPath(uint flags, string filePath, [Out] StringBuilder language, ref int languageLength, [Out] StringBuilder fileMuiPath, ref int fileMuiPathLength, ref long enumerator); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MultiByteToWideChar.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MultiByteToWideChar.cs new file mode 100644 index 0000000000..158e4db3fd --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MultiByteToWideChar.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.InteropServices; + +internal partial class Interop +{ + internal partial class Kernel32 + { + [DllImport(Libraries.Kernel32)] + internal static extern unsafe int MultiByteToWideChar( + uint CodePage, uint dwFlags, + byte* lpMultiByteStr, int cbMultiByte, + char* lpWideCharStr, int cchWideChar); + + internal const uint MB_PRECOMPOSED = 0x00000001; + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Mutex.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Mutex.cs new file mode 100644 index 0000000000..cbb306e4f7 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Mutex.cs @@ -0,0 +1,24 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.Win32.SafeHandles; +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Kernel32 + { + internal const uint CREATE_MUTEX_INITIAL_OWNER = 0x1; + + [DllImport(Interop.Libraries.Kernel32, EntryPoint = "OpenMutexW", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern SafeWaitHandle OpenMutex(uint desiredAccess, bool inheritHandle, string name); + + [DllImport(Interop.Libraries.Kernel32, EntryPoint = "CreateMutexExW", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern SafeWaitHandle CreateMutexEx(IntPtr lpMutexAttributes, string name, uint flags, uint desiredAccess); + + [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] + internal static extern bool ReleaseMutex(SafeWaitHandle handle); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Semaphore.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Semaphore.cs new file mode 100644 index 0000000000..94648a7077 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Semaphore.cs @@ -0,0 +1,22 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.Win32.SafeHandles; +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Kernel32 + { + [DllImport(Interop.Libraries.Kernel32, EntryPoint = "OpenSemaphoreW", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern SafeWaitHandle OpenSemaphore(uint desiredAccess, bool inheritHandle, string name); + + [DllImport(Libraries.Kernel32, EntryPoint = "CreateSemaphoreExW", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern SafeWaitHandle CreateSemaphoreEx(IntPtr lpSecurityAttributes, int initialCount, int maximumCount, string name, uint flags, uint desiredAccess); + + [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] + internal static extern bool ReleaseSemaphore(SafeWaitHandle handle, int releaseCount, out int previousCount); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.TimeZone.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.TimeZone.cs index 05f13ac8ed..68d4583b54 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.TimeZone.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.TimeZone.cs @@ -86,7 +86,7 @@ internal static partial class Interop internal const uint TIME_ZONE_ID_INVALID = unchecked((uint)-1); [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] - internal extern static uint GetDynamicTimeZoneInformation(out TIME_DYNAMIC_ZONE_INFORMATION pTimeZoneInformation); + internal static extern uint GetDynamicTimeZoneInformation(out TIME_DYNAMIC_ZONE_INFORMATION pTimeZoneInformation); [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] internal static extern uint GetTimeZoneInformation(out TIME_ZONE_INFORMATION lpTimeZoneInformation); diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/NtDll/NtQueryInformationFile.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/NtDll/NtQueryInformationFile.cs new file mode 100644 index 0000000000..4ba39a74e2 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/NtDll/NtQueryInformationFile.cs @@ -0,0 +1,46 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.Win32.SafeHandles; +using System; +using System.Runtime.InteropServices; + +internal partial class Interop +{ + internal partial class NtDll + { + [DllImport(Libraries.NtDll, ExactSpelling = true)] + unsafe internal static extern int NtQueryInformationFile( + SafeFileHandle FileHandle, + out IO_STATUS_BLOCK IoStatusBlock, + void* FileInformation, + uint Length, + uint FileInformationClass); + + [StructLayout(LayoutKind.Sequential)] + internal struct IO_STATUS_BLOCK + { + IO_STATUS Status; + IntPtr Information; + } + + // This isn't an actual Windows type, we have to separate it out as the size of IntPtr varies by architecture + // and we can't specify the size at compile time to offset the Information pointer in the status block. + [StructLayout(LayoutKind.Explicit)] + internal struct IO_STATUS + { + [FieldOffset(0)] + int Status; + + [FieldOffset(0)] + IntPtr Pointer; + } + + internal const uint FileModeInformation = 16; + internal const uint FILE_SYNCHRONOUS_IO_ALERT = 0x00000010; + internal const uint FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020; + + internal const int STATUS_INVALID_HANDLE = unchecked((int)0xC0000008); + } +} diff --git a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.CoCreateGuid.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Ole32/Interop.CoCreateGuid.cs similarity index 65% rename from external/corert/src/Common/src/Interop/Windows/mincore/Interop.CoCreateGuid.cs rename to external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Ole32/Interop.CoCreateGuid.cs index ac3bad5825..57accbe7c0 100644 --- a/external/corert/src/Common/src/Interop/Windows/mincore/Interop.CoCreateGuid.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Ole32/Interop.CoCreateGuid.cs @@ -7,9 +7,9 @@ using System.Runtime.InteropServices; internal static partial class Interop { - internal static partial class mincore + internal static partial class Ole32 { - [DllImport("api-ms-win-core-com-l1-1-0.dll")] - internal extern static int CoCreateGuid(out Guid pguid); + [DllImport(Interop.Libraries.Ole32)] + internal static extern int CoCreateGuid(out Guid guid); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs index 1af2b3fce9..be902b0c58 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs @@ -14,6 +14,6 @@ internal partial class Interop internal static extern SafeBSTRHandle SysAllocStringLen(IntPtr src, uint len); [DllImport(Libraries.OleAut32, CharSet = CharSet.Unicode)] - internal static extern IntPtr SysAllocStringLen(String src, int len); + internal static extern IntPtr SysAllocStringLen(string src, int len); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/Registry.cs b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/Registry.cs new file mode 100644 index 0000000000..bc4ee082a0 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/Registry.cs @@ -0,0 +1,104 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics; + +namespace Microsoft.Win32 +{ + /// Registry encapsulation. Contains members representing all top level system keys. +#if REGISTRY_ASSEMBLY + public +#else + internal +#endif + static class Registry + { + /// Current User Key. This key should be used as the root for all user specific settings. + public static readonly RegistryKey CurrentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default); + + /// Local Machine key. This key should be used as the root for all machine specific settings. + public static readonly RegistryKey LocalMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default); + + /// Classes Root Key. This is the root key of class information. + public static readonly RegistryKey ClassesRoot = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Default); + + /// Users Root Key. This is the root of users. + public static readonly RegistryKey Users = RegistryKey.OpenBaseKey(RegistryHive.Users, RegistryView.Default); + + /// Performance Root Key. This is where dynamic performance data is stored on NT. + public static readonly RegistryKey PerformanceData = RegistryKey.OpenBaseKey(RegistryHive.PerformanceData, RegistryView.Default); + + /// Current Config Root Key. This is where current configuration information is stored. + public static readonly RegistryKey CurrentConfig = RegistryKey.OpenBaseKey(RegistryHive.CurrentConfig, RegistryView.Default); + + /// + /// Parse a keyName and returns the basekey for it. + /// It will also store the subkey name in the out parameter. + /// If the keyName is not valid, we will throw ArgumentException. + /// The return value shouldn't be null. + /// + private static RegistryKey GetBaseKeyFromKeyName(string keyName, out string subKeyName) + { + if (keyName == null) + { + throw new ArgumentNullException(nameof(keyName)); + } + + int i = keyName.IndexOf('\\'); + int length = i != -1 ? i : keyName.Length; + + // Determine the potential base key from the length. + RegistryKey baseKey = null; + switch (length) + { + case 10: baseKey = Users; break; // HKEY_USERS + case 17: baseKey = char.ToUpperInvariant(keyName[6]) == 'L' ? ClassesRoot : CurrentUser; break; // HKEY_C[L]ASSES_ROOT, otherwise HKEY_CURRENT_USER + case 18: baseKey = LocalMachine; break; // HKEY_LOCAL_MACHINE + case 19: baseKey = CurrentConfig; break; // HKEY_CURRENT_CONFIG + case 21: baseKey = PerformanceData; break; // HKEY_PERFORMANCE_DATA + } + + // If a potential base key was found, see if keyName actually starts with the potential base key's name. + if (baseKey != null && keyName.StartsWith(baseKey.Name, StringComparison.OrdinalIgnoreCase)) + { + subKeyName = (i == -1 || i == keyName.Length) ? + string.Empty : + keyName.Substring(i + 1, keyName.Length - i - 1); + + return baseKey; + } + + throw new ArgumentException(SR.Format(SR.Arg_RegInvalidKeyName, nameof(keyName)), nameof(keyName)); + } + + public static object GetValue(string keyName, string valueName, object defaultValue) + { + string subKeyName; + RegistryKey basekey = GetBaseKeyFromKeyName(keyName, out subKeyName); + + using (RegistryKey key = basekey.OpenSubKey(subKeyName)) + { + return key?.GetValue(valueName, defaultValue); + } + } + + public static void SetValue(string keyName, string valueName, object value) + { + SetValue(keyName, valueName, value, RegistryValueKind.Unknown); + } + + public static void SetValue(string keyName, string valueName, object value, RegistryValueKind valueKind) + { + string subKeyName; + RegistryKey basekey = GetBaseKeyFromKeyName(keyName, out subKeyName); + + using (RegistryKey key = basekey.CreateSubKey(subKeyName)) + { + Debug.Assert(key != null, "An exception should be thrown if failed!"); + key.SetValue(valueName, value, valueKind); + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryHive.cs b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/RegistryHive.cs similarity index 99% rename from external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryHive.cs rename to external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/RegistryHive.cs index 57a5de393b..0f1e9541c8 100644 --- a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryHive.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/RegistryHive.cs @@ -21,4 +21,4 @@ namespace Microsoft.Win32 PerformanceData = unchecked((int)0x80000004), CurrentConfig = unchecked((int)0x80000005), } -} +} \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryOptions.cs b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/RegistryOptions.cs similarity index 66% rename from external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryOptions.cs rename to external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/RegistryOptions.cs index 90b6a3dd75..201a6df0ec 100644 --- a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryOptions.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/RegistryOptions.cs @@ -14,7 +14,7 @@ namespace Microsoft.Win32 #endif enum RegistryOptions { - None = Interop.mincore.RegistryOptions.REG_OPTION_NON_VOLATILE, // 0x0000 - Volatile = Interop.mincore.RegistryOptions.REG_OPTION_VOLATILE, // 0x0001 + None = Interop.Advapi32.RegistryOptions.REG_OPTION_NON_VOLATILE, // 0x0000 + Volatile = Interop.Advapi32.RegistryOptions.REG_OPTION_VOLATILE, // 0x0001 }; } diff --git a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryValueKind.cs b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/RegistryValueKind.cs similarity index 51% rename from external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryValueKind.cs rename to external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/RegistryValueKind.cs index 4cf10c8dfe..bc6efcc06f 100644 --- a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryValueKind.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/RegistryValueKind.cs @@ -11,13 +11,13 @@ namespace Microsoft.Win32 #endif enum RegistryValueKind { - String = Interop.mincore.RegistryValues.REG_SZ, - ExpandString = Interop.mincore.RegistryValues.REG_EXPAND_SZ, - Binary = Interop.mincore.RegistryValues.REG_BINARY, - DWord = Interop.mincore.RegistryValues.REG_DWORD, - MultiString = Interop.mincore.RegistryValues.REG_MULTI_SZ, - QWord = Interop.mincore.RegistryValues.REG_QWORD, + String = Interop.Advapi32.RegistryValues.REG_SZ, + ExpandString = Interop.Advapi32.RegistryValues.REG_EXPAND_SZ, + Binary = Interop.Advapi32.RegistryValues.REG_BINARY, + DWord = Interop.Advapi32.RegistryValues.REG_DWORD, + MultiString = Interop.Advapi32.RegistryValues.REG_MULTI_SZ, + QWord = Interop.Advapi32.RegistryValues.REG_QWORD, Unknown = 0, // REG_NONE is defined as zero but BCL None = unchecked((int)0xFFFFFFFF), // mistakenly overrode this value. - } // Now instead of using Interop.mincore.RegistryValues.REG_NONE we use "-1". + } // Now instead of using Interop.Kernel32.RegistryValues.REG_NONE we use "-1". } diff --git a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryValueOptions.cs b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/RegistryValueOptions.cs similarity index 100% rename from external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryValueOptions.cs rename to external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/RegistryValueOptions.cs diff --git a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryView.cs b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/RegistryView.cs similarity index 64% rename from external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryView.cs rename to external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/RegistryView.cs index 2256e2d7e2..0d6b3038e8 100644 --- a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryView.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/RegistryView.cs @@ -14,7 +14,7 @@ namespace Microsoft.Win32 enum RegistryView { Default = 0, // 0x0000 operate on the default registry view - Registry64 = Interop.mincore.RegistryView.KEY_WOW64_64KEY, // 0x0100 operate on the 64-bit registry view - Registry32 = Interop.mincore.RegistryView.KEY_WOW64_32KEY, // 0x0200 operate on the 32-bit registry view + Registry64 = Interop.Advapi32.RegistryView.KEY_WOW64_64KEY, // 0x0100 operate on the 64-bit registry view + Registry32 = Interop.Advapi32.RegistryView.KEY_WOW64_32KEY, // 0x0200 operate on the 32-bit registry view }; } diff --git a/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs index b284c116ba..52973f2abb 100644 --- a/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs @@ -11,9 +11,6 @@ namespace Microsoft.Win32.SafeHandles { public sealed class SafeFileHandle : SafeHandleZeroOrMinusOneIsInvalid { - /// A handle value of -1. - private static readonly IntPtr s_invalidHandle = new IntPtr(-1); - private SafeFileHandle() : this(ownsHandle: true) { } @@ -21,7 +18,7 @@ namespace Microsoft.Win32.SafeHandles private SafeFileHandle(bool ownsHandle) : base(ownsHandle) { - SetHandle(s_invalidHandle); + SetHandle(new IntPtr(-1)); } public SafeFileHandle(IntPtr preexistingHandle, bool ownsHandle) : this(ownsHandle) diff --git a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs similarity index 71% rename from external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs rename to external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs index 83814f6ec1..9b668047a9 100644 --- a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs @@ -11,9 +11,9 @@ namespace Microsoft.Win32.SafeHandles #else internal #endif - sealed partial class SafeRegistryHandle : SafeHandle + sealed partial class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid { protected override bool ReleaseHandle() => - Interop.mincore.RegCloseKey(handle) == Interop.Errors.ERROR_SUCCESS; + Interop.Advapi32.RegCloseKey(handle) == Interop.Errors.ERROR_SUCCESS; } } diff --git a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs similarity index 57% rename from external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs rename to external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs index 158b286836..ae35b03d54 100644 --- a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs +++ b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs @@ -3,20 +3,21 @@ // See the LICENSE file in the project root for more information. using System; -using System.Runtime.InteropServices; namespace Microsoft.Win32.SafeHandles { +#if REGISTRY_ASSEMBLY + public +#else internal - sealed partial class SafeRegistryHandle : SafeHandle +#endif + sealed partial class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid { - internal SafeRegistryHandle() : base(IntPtr.Zero, true) { } + internal SafeRegistryHandle() : base(true) { } - public SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(IntPtr.Zero, ownsHandle) + public SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) { SetHandle(preexistingHandle); } - - public override bool IsInvalid => handle == IntPtr.Zero || handle == new IntPtr(-1); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs new file mode 100644 index 0000000000..66f17f0af7 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs @@ -0,0 +1,11 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace Microsoft.Win32.SafeHandles +{ + public sealed partial class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid + { + protected override bool ReleaseHandle() => Interop.Kernel32.CloseHandle(handle); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs new file mode 100644 index 0000000000..edb0cdfcaf --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +namespace Microsoft.Win32.SafeHandles +{ + public sealed partial class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid + { + // Called by P/Invoke marshaler + private SafeWaitHandle() : base(true) + { + } + + public SafeWaitHandle(IntPtr existingHandle, bool ownsHandle) : base(ownsHandle) + { + SetHandle(existingHandle); + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems b/external/corert/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems index 0b3f971b17..af1b99a301 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems +++ b/external/corert/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems @@ -20,11 +20,13 @@ + + @@ -46,17 +48,24 @@ - + + - + + + + + + + @@ -75,7 +84,10 @@ + + + @@ -83,9 +95,11 @@ + + @@ -94,6 +108,7 @@ + @@ -101,6 +116,8 @@ + + @@ -114,6 +131,7 @@ + @@ -128,6 +146,7 @@ + @@ -158,6 +177,7 @@ + @@ -194,13 +214,14 @@ + + - @@ -218,6 +239,7 @@ + @@ -235,6 +257,7 @@ + @@ -245,6 +268,8 @@ + + @@ -259,6 +284,7 @@ + @@ -300,8 +326,19 @@ + + + + + + + + + + + @@ -313,12 +350,14 @@ + + @@ -358,11 +397,14 @@ + + + @@ -371,6 +413,7 @@ + @@ -391,6 +434,7 @@ + @@ -414,6 +458,7 @@ + @@ -422,6 +467,7 @@ + @@ -443,6 +489,7 @@ + @@ -451,6 +498,14 @@ + + + + + + + + @@ -463,6 +518,7 @@ + @@ -491,16 +547,19 @@ + + + - + @@ -520,6 +579,7 @@ + @@ -531,19 +591,29 @@ + + + + + + + + + + @@ -552,6 +622,7 @@ + @@ -663,11 +734,12 @@ + + - @@ -687,6 +759,7 @@ + @@ -696,12 +769,13 @@ + - + @@ -709,6 +783,7 @@ + @@ -717,6 +792,7 @@ + @@ -727,17 +803,39 @@ - - - - - + + + + + + + + + + + + + + + + + + + + + + + + - + + + + @@ -745,9 +843,18 @@ + + + + + + + + + @@ -789,6 +896,7 @@ + @@ -796,6 +904,7 @@ + @@ -804,4 +913,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/external/corert/src/System.Private.CoreLib/shared/System/AccessViolationException.cs b/external/corert/src/System.Private.CoreLib/shared/System/AccessViolationException.cs index 280d9b8a97..a66f2a892e 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/AccessViolationException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/AccessViolationException.cs @@ -26,13 +26,13 @@ namespace System HResult = HResults.E_POINTER; } - public AccessViolationException(String message) + public AccessViolationException(string message) : base(message) { HResult = HResults.E_POINTER; } - public AccessViolationException(String message, Exception innerException) + public AccessViolationException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.E_POINTER; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ApplicationException.cs b/external/corert/src/System.Private.CoreLib/shared/System/ApplicationException.cs index f36e2c1274..cac29196bf 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ApplicationException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ApplicationException.cs @@ -39,13 +39,13 @@ namespace System // message, its HRESULT set to COR_E_APPLICATION, // and its ExceptionInfo reference set to null. // - public ApplicationException(String message) + public ApplicationException(string message) : base(message) { HResult = HResults.COR_E_APPLICATION; } - public ApplicationException(String message, Exception innerException) + public ApplicationException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_APPLICATION; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ArgumentException.cs b/external/corert/src/System.Private.CoreLib/shared/System/ArgumentException.cs index 8a8fe3e5e4..5a918063e7 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ArgumentException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ArgumentException.cs @@ -23,7 +23,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ArgumentException : SystemException { - private String _paramName; + private string _paramName; // Creates a new ArgumentException with its message // string set to the empty string. @@ -36,26 +36,26 @@ namespace System // Creates a new ArgumentException with its message // string set to message. // - public ArgumentException(String message) + public ArgumentException(string message) : base(message) { HResult = HResults.COR_E_ARGUMENT; } - public ArgumentException(String message, Exception innerException) + public ArgumentException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_ARGUMENT; } - public ArgumentException(String message, String paramName, Exception innerException) + public ArgumentException(string message, string paramName, Exception innerException) : base(message, innerException) { _paramName = paramName; HResult = HResults.COR_E_ARGUMENT; } - public ArgumentException(String message, String paramName) + public ArgumentException(string message, string paramName) : base(message) { _paramName = paramName; @@ -74,14 +74,14 @@ namespace System info.AddValue("ParamName", _paramName, typeof(string)); } - public override String Message + public override string Message { get { - String s = base.Message; - if (!String.IsNullOrEmpty(_paramName)) + string s = base.Message; + if (!string.IsNullOrEmpty(_paramName)) { - String resourceString = SR.Format(SR.Arg_ParamName_Name, _paramName); + string resourceString = SR.Format(SR.Arg_ParamName_Name, _paramName); return s + Environment.NewLine + resourceString; } else @@ -89,7 +89,7 @@ namespace System } } - public virtual String ParamName + public virtual string ParamName { get { return _paramName; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ArgumentNullException.cs b/external/corert/src/System.Private.CoreLib/shared/System/ArgumentNullException.cs index 80e43cc265..edc38f2a4c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ArgumentNullException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ArgumentNullException.cs @@ -30,19 +30,19 @@ namespace System HResult = HResults.E_POINTER; } - public ArgumentNullException(String paramName) + public ArgumentNullException(string paramName) : base(SR.ArgumentNull_Generic, paramName) { HResult = HResults.E_POINTER; } - public ArgumentNullException(String message, Exception innerException) + public ArgumentNullException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.E_POINTER; } - public ArgumentNullException(String paramName, String message) + public ArgumentNullException(string paramName, string message) : base(message, paramName) { HResult = HResults.E_POINTER; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ArgumentOutOfRangeException.cs b/external/corert/src/System.Private.CoreLib/shared/System/ArgumentOutOfRangeException.cs index 604caa8ee8..8d91561ce4 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ArgumentOutOfRangeException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ArgumentOutOfRangeException.cs @@ -22,7 +22,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ArgumentOutOfRangeException : ArgumentException { - private Object _actualValue; + private object _actualValue; // Creates a new ArgumentOutOfRangeException with its message // string set to a default message explaining an argument was out of range. @@ -32,19 +32,19 @@ namespace System HResult = HResults.COR_E_ARGUMENTOUTOFRANGE; } - public ArgumentOutOfRangeException(String paramName) + public ArgumentOutOfRangeException(string paramName) : base(SR.Arg_ArgumentOutOfRangeException, paramName) { HResult = HResults.COR_E_ARGUMENTOUTOFRANGE; } - public ArgumentOutOfRangeException(String paramName, String message) + public ArgumentOutOfRangeException(string paramName, string message) : base(message, paramName) { HResult = HResults.COR_E_ARGUMENTOUTOFRANGE; } - public ArgumentOutOfRangeException(String message, Exception innerException) + public ArgumentOutOfRangeException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_ARGUMENTOUTOFRANGE; @@ -53,7 +53,7 @@ namespace System // We will not use this in the classlibs, but we'll provide it for // anyone that's really interested so they don't have to stick a bunch // of printf's in their code. - public ArgumentOutOfRangeException(String paramName, Object actualValue, String message) + public ArgumentOutOfRangeException(string paramName, object actualValue, string message) : base(message, paramName) { _actualValue = actualValue; @@ -72,14 +72,14 @@ namespace System info.AddValue("ActualValue", _actualValue, typeof(object)); } - public override String Message + public override string Message { get { - String s = base.Message; + string s = base.Message; if (_actualValue != null) { - String valueMessage = SR.Format(SR.ArgumentOutOfRange_ActualValue, _actualValue.ToString()); + string valueMessage = SR.Format(SR.ArgumentOutOfRange_ActualValue, _actualValue.ToString()); if (s == null) return valueMessage; return s + Environment.NewLine + valueMessage; @@ -92,7 +92,7 @@ namespace System // Note - we don't set this anywhere in the class libraries in // version 1, but it might come in handy for other developers who // want to avoid sticking printf's in their code. - public virtual Object ActualValue + public virtual object ActualValue { get { return _actualValue; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ArithmeticException.cs b/external/corert/src/System.Private.CoreLib/shared/System/ArithmeticException.cs index 606f1debfd..46492cab56 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ArithmeticException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ArithmeticException.cs @@ -34,13 +34,13 @@ namespace System // message, its HRESULT set to COR_E_ARITHMETIC, // and its ExceptionInfo reference set to null. // - public ArithmeticException(String message) + public ArithmeticException(string message) : base(message) { HResult = HResults.COR_E_ARITHMETIC; } - public ArithmeticException(String message, Exception innerException) + public ArithmeticException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_ARITHMETIC; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ArraySegment.cs b/external/corert/src/System.Private.CoreLib/shared/System/ArraySegment.cs index 3a13595e83..b2bd417806 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ArraySegment.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ArraySegment.cs @@ -131,7 +131,7 @@ namespace System System.Array.Copy(_array, _offset, destination._array, destination._offset, _count); } - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (obj is ArraySegment) return Equals((ArraySegment)obj); @@ -289,7 +289,7 @@ namespace System bool ICollection.Remove(T item) { ThrowHelper.ThrowNotSupportedException(); - return default(bool); + return default; } #endregion diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ArrayTypeMismatchException.cs b/external/corert/src/System.Private.CoreLib/shared/System/ArrayTypeMismatchException.cs index 49820f58f5..2f60fd4ea5 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ArrayTypeMismatchException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ArrayTypeMismatchException.cs @@ -34,13 +34,13 @@ namespace System // message, its HRESULT set to COR_E_ARRAYTYPEMISMATCH, // and its ExceptionInfo reference set to null. // - public ArrayTypeMismatchException(String message) + public ArrayTypeMismatchException(string message) : base(message) { HResult = HResults.COR_E_ARRAYTYPEMISMATCH; } - public ArrayTypeMismatchException(String message, Exception innerException) + public ArrayTypeMismatchException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_ARRAYTYPEMISMATCH; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/BadImageFormatException.cs b/external/corert/src/System.Private.CoreLib/shared/System/BadImageFormatException.cs index 1743075a6f..c8cb65c64a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/BadImageFormatException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/BadImageFormatException.cs @@ -21,8 +21,8 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public partial class BadImageFormatException : SystemException { - private String _fileName; // The name of the corrupt PE file. - private String _fusionLog = null; // fusion log (when applicable) + private string _fileName; // The name of the corrupt PE file. + private string _fusionLog = null; // fusion log (when applicable) public BadImageFormatException() : base(SR.Arg_BadImageFormatException) @@ -30,25 +30,25 @@ namespace System HResult = HResults.COR_E_BADIMAGEFORMAT; } - public BadImageFormatException(String message) + public BadImageFormatException(string message) : base(message) { HResult = HResults.COR_E_BADIMAGEFORMAT; } - public BadImageFormatException(String message, Exception inner) + public BadImageFormatException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_BADIMAGEFORMAT; } - public BadImageFormatException(String message, String fileName) : base(message) + public BadImageFormatException(string message, string fileName) : base(message) { HResult = HResults.COR_E_BADIMAGEFORMAT; _fileName = fileName; } - public BadImageFormatException(String message, String fileName, Exception inner) + public BadImageFormatException(string message, string fileName, Exception inner) : base(message, inner) { HResult = HResults.COR_E_BADIMAGEFORMAT; @@ -69,7 +69,7 @@ namespace System info.AddValue("BadImageFormat_FusionLog", _fusionLog, typeof(string)); } - public override String Message + public override string Message { get { @@ -91,14 +91,14 @@ namespace System } } - public String FileName + public string FileName { get { return _fileName; } } - public override String ToString() + public override string ToString() { - String s = GetType().ToString() + ": " + Message; + string s = GetType().ToString() + ": " + Message; if (_fileName != null && _fileName.Length != 0) s += Environment.NewLine + SR.Format(SR.IO_FileName_Name, _fileName); @@ -121,7 +121,7 @@ namespace System return s; } - public String FusionLog + public string FusionLog { get { return _fusionLog; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/BitConverter.cs b/external/corert/src/System.Private.CoreLib/shared/System/BitConverter.cs index e3cf20eb6a..8a8101ddce 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/BitConverter.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/BitConverter.cs @@ -376,7 +376,7 @@ namespace System if (length > (int.MaxValue / 3)) { - // (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB + // (int.MaxValue / 3) == 715,827,882 Bytes == 699 MB throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3))); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Boolean.cs b/external/corert/src/System.Private.CoreLib/shared/System/Boolean.cs index fd56082f9b..4daf6f3f96 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Boolean.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Boolean.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ -using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Versioning; @@ -20,12 +19,12 @@ namespace System { [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Boolean : IComparable, IConvertible, IComparable, IEquatable + public readonly struct Boolean : IComparable, IConvertible, IComparable, IEquatable { // // Member Variables // - private bool m_value; // Do not rename (binary serialization) + private readonly bool m_value; // Do not rename (binary serialization) // The true value. // @@ -42,11 +41,11 @@ namespace System // The internal string representation of true. // - internal const String TrueLiteral = "True"; + internal const string TrueLiteral = "True"; // The internal string representation of false. // - internal const String FalseLiteral = "False"; + internal const string FalseLiteral = "False"; // @@ -55,11 +54,11 @@ namespace System // The public string representation of true. // - public static readonly String TrueString = TrueLiteral; + public static readonly string TrueString = TrueLiteral; // The public string representation of false. // - public static readonly String FalseString = FalseLiteral; + public static readonly string FalseString = FalseLiteral; // // Overriden Instance Methods @@ -82,7 +81,7 @@ namespace System **Exceptions: None. ==============================================================================*/ // Converts the boolean value of this instance to a String. - public override String ToString() + public override string ToString() { if (false == m_value) { @@ -91,41 +90,57 @@ namespace System return TrueLiteral; } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return ToString(); } public bool TryFormat(Span destination, out int charsWritten) { - string s = m_value ? TrueLiteral : FalseLiteral; - - if (s.AsSpan().TryCopyTo(destination)) + if (m_value) { - charsWritten = s.Length; - return true; + if ((uint)destination.Length > 3) // uint cast, per https://github.com/dotnet/coreclr/issues/18688 + { + destination[0] = 'T'; + destination[1] = 'r'; + destination[2] = 'u'; + destination[3] = 'e'; + charsWritten = 4; + return true; + } } else { - charsWritten = 0; - return false; + if ((uint)destination.Length > 4) + { + destination[0] = 'F'; + destination[1] = 'a'; + destination[2] = 'l'; + destination[3] = 's'; + destination[4] = 'e'; + charsWritten = 5; + return true; + } } + + charsWritten = 0; + return false; } // Determines whether two Boolean objects are equal. - public override bool Equals(Object obj) + public override bool Equals(object obj) { //If it's not a boolean, we're definitely not equal - if (!(obj is Boolean)) + if (!(obj is bool)) { return false; } - return (m_value == ((Boolean)obj).m_value); + return (m_value == ((bool)obj).m_value); } [NonVersionable] - public bool Equals(Boolean obj) + public bool Equals(bool obj) { return m_value == obj; } @@ -137,18 +152,18 @@ namespace System // // Returns a value less than zero if this object // - public int CompareTo(Object obj) + public int CompareTo(object obj) { if (obj == null) { return 1; } - if (!(obj is Boolean)) + if (!(obj is bool)) { throw new ArgumentException(SR.Arg_MustBeBoolean); } - if (m_value == ((Boolean)obj).m_value) + if (m_value == ((bool)obj).m_value) { return 0; } @@ -159,7 +174,7 @@ namespace System return 1; } - public int CompareTo(Boolean value) + public int CompareTo(bool value) { if (m_value == value) { @@ -176,20 +191,41 @@ namespace System // Static Methods // + // Custom string compares for early application use by config switches, etc + // + internal static bool IsTrueStringIgnoreCase(ReadOnlySpan value) + { + return (value.Length == 4 && + (value[0] == 't' || value[0] == 'T') && + (value[1] == 'r' || value[1] == 'R') && + (value[2] == 'u' || value[2] == 'U') && + (value[3] == 'e' || value[3] == 'E')); + } + + internal static bool IsFalseStringIgnoreCase(ReadOnlySpan value) + { + return (value.Length == 5 && + (value[0] == 'f' || value[0] == 'F') && + (value[1] == 'a' || value[1] == 'A') && + (value[2] == 'l' || value[2] == 'L') && + (value[3] == 's' || value[3] == 'S') && + (value[4] == 'e' || value[4] == 'E')); + } + // Determines whether a String represents true or false. // - public static Boolean Parse(String value) + public static bool Parse(string value) { if (value == null) throw new ArgumentNullException(nameof(value)); return Parse(value.AsSpan()); } public static bool Parse(ReadOnlySpan value) => - TryParse(value, out bool result) ? result : throw new FormatException(SR.Format_BadBoolean); + TryParse(value, out bool result) ? result : throw new FormatException(SR.Format(SR.Format_BadBoolean, new string(value))); // Determines whether a String represents true or false. // - public static Boolean TryParse(String value, out Boolean result) + public static bool TryParse(string value, out bool result) { if (value == null) { @@ -202,15 +238,13 @@ namespace System public static bool TryParse(ReadOnlySpan value, out bool result) { - ReadOnlySpan trueSpan = TrueLiteral.AsSpan(); - if (StringSpanHelpers.Equals(trueSpan, value, StringComparison.OrdinalIgnoreCase)) + if (IsTrueStringIgnoreCase(value)) { result = true; return true; } - ReadOnlySpan falseSpan = FalseLiteral.AsSpan(); - if (StringSpanHelpers.Equals(falseSpan, value, StringComparison.OrdinalIgnoreCase)) + if (IsFalseStringIgnoreCase(value)) { result = false; return true; @@ -219,13 +253,13 @@ namespace System // Special case: Trim whitespace as well as null characters. value = TrimWhiteSpaceAndNull(value); - if (StringSpanHelpers.Equals(trueSpan, value, StringComparison.OrdinalIgnoreCase)) + if (IsTrueStringIgnoreCase(value)) { result = true; return true; } - if (StringSpanHelpers.Equals(falseSpan, value, StringComparison.OrdinalIgnoreCase)) + if (IsFalseStringIgnoreCase(value)) { result = false; return true; @@ -242,7 +276,7 @@ namespace System int start = 0; while (start < value.Length) { - if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar) + if (!char.IsWhiteSpace(value[start]) && value[start] != nullChar) { break; } @@ -252,7 +286,7 @@ namespace System int end = value.Length - 1; while (end >= start) { - if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar) + if (!char.IsWhiteSpace(value[end]) && value[end] != nullChar) { break; } @@ -332,7 +366,7 @@ namespace System return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -342,7 +376,7 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/ArrayPool.cs b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/ArrayPool.cs index 77a07f7fa5..22ad7821f0 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/ArrayPool.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/ArrayPool.cs @@ -33,9 +33,7 @@ namespace System.Buffers /// optimized for very fast access speeds, at the expense of more memory consumption. /// The shared pool instance is created lazily on first access. /// - public static ArrayPool Shared { get; } = - typeof(T) == typeof(byte) || typeof(T) == typeof(char) ? new TlsOverPerCoreLockedStacksArrayPool() : - Create(); + public static ArrayPool Shared { get; } = new TlsOverPerCoreLockedStacksArrayPool(); /// /// Creates a new instance using default configuration options. diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/ArrayPoolEventSource.cs b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/ArrayPoolEventSource.cs index b2d0dbd32d..d0563c4977 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/ArrayPoolEventSource.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/ArrayPoolEventSource.cs @@ -86,5 +86,19 @@ namespace System.Buffers /// [Event(3, Level = EventLevel.Verbose)] internal void BufferReturned(int bufferId, int bufferSize, int poolId) => WriteEvent(3, bufferId, bufferSize, poolId); + + /// + /// Event raised when we attempt to free a buffer due to inactivity or memory pressure (by no longer + /// referencing it). It is possible (although not commmon) this buffer could be rented as we attempt + /// to free it. A rent event before or after this event for the same ID, is a rare, but expected case. + /// + [Event(4, Level = EventLevel.Informational)] + internal void BufferTrimmed(int bufferId, int bufferSize, int poolId) => WriteEvent(4, bufferId, bufferSize, poolId); + + /// + /// Event raised when we check to trim buffers. + /// + [Event(5, Level = EventLevel.Informational)] + internal void BufferTrimPoll(int milliseconds, int pressure) => WriteEvent(5, milliseconds, pressure); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/IMemoryOwner.cs b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/IMemoryOwner.cs new file mode 100644 index 0000000000..44f16c5827 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/IMemoryOwner.cs @@ -0,0 +1,17 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Buffers +{ + /// + /// Owner of Memory that is responsible for disposing the underlying memory appropriately. + /// + public interface IMemoryOwner : IDisposable + { + /// + /// Returns a Memory. + /// + Memory Memory { get; } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/IPinnable.cs b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/IPinnable.cs new file mode 100644 index 0000000000..623e716a05 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/IPinnable.cs @@ -0,0 +1,25 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Buffers +{ + /// + /// Provides a mechanism for pinning and unpinning objects to prevent the GC from moving them. + /// + public interface IPinnable + { + /// + /// Call this method to indicate that the IPinnable object can not be moved by the garbage collector. + /// The address of the pinned object can be taken. + /// The offset to the element within the memory at which the returned points to. + /// + MemoryHandle Pin(int elementIndex); + + /// + /// Call this method to indicate that the IPinnable object no longer needs to be pinned. + /// The garbage collector is free to move the object now. + /// + void Unpin(); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/IRetainable.cs b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/IRetainable.cs deleted file mode 100644 index 6ac508859c..0000000000 --- a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/IRetainable.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime; -using System.Runtime.CompilerServices; - -namespace System.Buffers -{ - /// - /// Provides a mechanism for manual lifetime management. - /// - public interface IRetainable - { - /// - /// Call this method to indicate that the IRetainable object is in use. - /// Do not dispose until Release is called. - /// - void Retain(); - /// - /// Call this method to indicate that the IRetainable object is no longer in use. - /// The object can now be disposed. - /// - bool Release(); - } -} \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/MemoryHandle.cs b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/MemoryHandle.cs index 7544038629..b218534c52 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/MemoryHandle.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/MemoryHandle.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Runtime; using System.Runtime.InteropServices; namespace System.Buffers @@ -12,53 +11,48 @@ namespace System.Buffers /// public unsafe struct MemoryHandle : IDisposable { - private IRetainable _retainable; private void* _pointer; private GCHandle _handle; + private IPinnable _pinnable; /// /// Creates a new memory handle for the memory. /// - /// reference to manually managed object - /// pointer to memory, or null if a pointer was not provided when the handle was created + /// pointer to memory + /// reference to manually managed object, or default if there is no memory manager /// handle used to pin array buffers [CLSCompliant(false)] - public MemoryHandle(IRetainable retainable, void* pointer = null, GCHandle handle = default(GCHandle)) + public MemoryHandle(void* pointer, GCHandle handle = default, IPinnable pinnable = default) { - _retainable = retainable; _pointer = pointer; _handle = handle; + _pinnable = pinnable; } /// - /// Returns the pointer to memory, or null if a pointer was not provided when the handle was created. + /// Returns the pointer to memory, where the memory is assumed to be pinned and hence the address won't change. /// [CLSCompliant(false)] public void* Pointer => _pointer; /// - /// Returns false if the pointer to memory is null. + /// Frees the pinned handle and releases IPinnable. /// - public bool HasPointer => _pointer != null; - - /// - /// Frees the pinned handle and releases IRetainable. - /// - public void Dispose() + public void Dispose() { if (_handle.IsAllocated) { _handle.Free(); } - if (_retainable != null) + if (_pinnable != null) { - _retainable.Release(); - _retainable = null; + _pinnable.Unpin(); + _pinnable = null; } _pointer = null; } } -} \ No newline at end of file +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/MemoryManager.cs b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/MemoryManager.cs new file mode 100644 index 0000000000..1b235b538e --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/MemoryManager.cs @@ -0,0 +1,75 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.CompilerServices; + +namespace System.Buffers +{ + /// + /// Manager of that provides the implementation. + /// + public abstract class MemoryManager : IMemoryOwner, IPinnable + { + /// + /// Returns a . + /// + public virtual Memory Memory => new Memory(this, GetSpan().Length); + + /// + /// Returns a span wrapping the underlying memory. + /// + public abstract Span GetSpan(); + + /// + /// Returns a handle to the memory that has been pinned and hence its address can be taken. + /// + /// The offset to the element within the memory at which the returned points to. (default = 0) + public abstract MemoryHandle Pin(int elementIndex = 0); + + /// + /// Lets the garbage collector know that the object is free to be moved now. + /// + public abstract void Unpin(); + + /// + /// Returns a for the current . + /// + /// The element count in the memory, starting at offset 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected Memory CreateMemory(int length) => new Memory(this, length); + + /// + /// Returns a for the current . + /// + /// The offset to the element which the returned memory starts at. + /// The element count in the memory, starting at element offset . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected Memory CreateMemory(int start, int length) => new Memory(this, start, length); + + /// + /// Returns an array segment. + /// Returns the default array segment if not overriden. + /// + protected internal virtual bool TryGetArray(out ArraySegment segment) + { + segment = default; + return false; + } + + /// + /// Implements IDisposable. + /// + void IDisposable.Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// + /// Clean up of any leftover managed and unmanaged resources. + /// + protected abstract void Dispose(bool disposing); + + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/OwnedMemory.cs b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/OwnedMemory.cs deleted file mode 100644 index eade1feff3..0000000000 --- a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/OwnedMemory.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime; -using System.Runtime.CompilerServices; - -namespace System.Buffers -{ - /// - /// Owner of Memory that provides appropriate lifetime management mechanisms for it. - /// - public abstract class OwnedMemory : IDisposable, IRetainable - { - /// - /// The number of items in the Memory. - /// - public abstract int Length { get; } - - /// - /// Returns a span wrapping the underlying memory. - /// - public abstract Span Span { get; } - - /// - /// Returns a Memory if the underlying memory has not been freed. - /// - /// - /// Thrown when the underlying memory has already been disposed. - /// - public Memory Memory - { - get - { - if (IsDisposed) - { - ThrowHelper.ThrowObjectDisposedException_MemoryDisposed(); - } - return new Memory(owner: this, 0, Length); - } - } - - /// - /// Returns a handle for the array that has been pinned and hence its address can be taken - /// - public abstract MemoryHandle Pin(int byteOffset = 0); - - /// - /// Returns an array segment. - /// - protected internal abstract bool TryGetArray(out ArraySegment arraySegment); - - /// - /// Implements IDisposable. - /// - /// - /// Throw when there are still retained references to the memory - /// - public void Dispose() - { - if (IsRetained) - { - ThrowHelper.ThrowInvalidOperationException_OutstandingReferences(); - } - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Clean up of any leftover managed and unmanaged resources. - /// - protected abstract void Dispose(bool disposing); - - /// - /// Return true if someone is holding a reference to the memory. - /// - protected abstract bool IsRetained { get; } - - /// - /// Return true if the underlying memory has been freed. - /// - public abstract bool IsDisposed { get; } - - /// - /// Implements IRetainable. Prevent accidental disposal of the memory. - /// - public abstract void Retain(); - - /// - /// Implements IRetainable. The memory can now be diposed. - /// - public abstract bool Release(); - - } -} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/Text/FormattingHelpers.CountDigits.cs b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/Text/FormattingHelpers.CountDigits.cs new file mode 100644 index 0000000000..b6140adbad --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/Text/FormattingHelpers.CountDigits.cs @@ -0,0 +1,161 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Runtime.CompilerServices; + +namespace System.Buffers.Text +{ + internal static partial class FormattingHelpers + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int CountDigits(ulong value) + { + int digits = 1; + uint part; + if (value >= 10000000) + { + if (value >= 100000000000000) + { + part = (uint)(value / 100000000000000); + digits += 14; + } + else + { + part = (uint)(value / 10000000); + digits += 7; + } + } + else + { + part = (uint)value; + } + + if (part < 10) + { + // no-op + } + else if (part < 100) + { + digits += 1; + } + else if (part < 1000) + { + digits += 2; + } + else if (part < 10000) + { + digits += 3; + } + else if (part < 100000) + { + digits += 4; + } + else if (part < 1000000) + { + digits += 5; + } + else + { + Debug.Assert(part < 10000000); + digits += 6; + } + + return digits; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int CountDigits(uint value) + { + int digits = 1; + if (value >= 100000) + { + value = value / 100000; + digits += 5; + } + + if (value < 10) + { + // no-op + } + else if (value < 100) + { + digits += 1; + } + else if (value < 1000) + { + digits += 2; + } + else if (value < 10000) + { + digits += 3; + } + else + { + Debug.Assert(value < 100000); + digits += 4; + } + + return digits; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int CountHexDigits(ulong value) + { + // TODO: When x86 intrinsic support comes online, experiment with implementing this using lzcnt. + // return 16 - (int)((uint)Lzcnt.LeadingZeroCount(value | 1) >> 3); + + int digits = 1; + + if (value > 0xFFFFFFFF) + { + digits += 8; + value >>= 0x20; + } + if (value > 0xFFFF) + { + digits += 4; + value >>= 0x10; + } + if (value > 0xFF) + { + digits += 2; + value >>= 0x8; + } + if (value > 0xF) + digits++; + + return digits; + } + + + // Counts the number of trailing '0' digits in a decimal number. + // e.g., value = 0 => retVal = 0, valueWithoutTrailingZeros = 0 + // value = 1234 => retVal = 0, valueWithoutTrailingZeros = 1234 + // value = 320900 => retVal = 2, valueWithoutTrailingZeros = 3209 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int CountDecimalTrailingZeros(uint value, out uint valueWithoutTrailingZeros) + { + int zeroCount = 0; + + if (value != 0) + { + while (true) + { + uint temp = value / 10; + if (value != (temp * 10)) + { + break; + } + + value = temp; + zeroCount++; + } + } + + valueWithoutTrailingZeros = value; + return zeroCount; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs index 64c5cebe85..96efb0d521 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs @@ -2,9 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.Win32; +using System; +using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; +using Internal.Runtime.Augments; +using Internal.Runtime.CompilerServices; namespace System.Buffers { @@ -22,7 +25,6 @@ namespace System.Buffers { // TODO: #7747: "Investigate optimizing ArrayPool heuristics" // - Explore caching in TLS more than one array per size per thread, and moving stale buffers to the global queue. - // - Explore dumping stale buffers from the global queue, similar to PinnableBufferCache (maybe merging them). // - Explore changing the size of each per-core bucket, potentially dynamically or based on other factors like array size. // - Explore changing number of buckets and what sizes of arrays are cached. // - Investigate whether false sharing is causing any issues, in particular on LockedStack's count and the contents of its array. @@ -46,6 +48,15 @@ namespace System.Buffers [ThreadStatic] private static T[][] t_tlsBuckets; + private int _callbackCreated; + + private readonly static bool s_trimBuffers = GetTrimBuffers(); + + /// + /// Used to keep track of all thread local buckets for trimming if needed + /// + private static readonly ConditionalWeakTable s_allTlsBuckets = s_trimBuffers ? new ConditionalWeakTable() : null; + /// Initialize the pool. public TlsOverPerCoreLockedStacksArrayPool() { @@ -180,15 +191,24 @@ namespace System.Buffers { t_tlsBuckets = tlsBuckets = new T[NumBuckets][]; tlsBuckets[bucketIndex] = array; + if (s_trimBuffers) + { + s_allTlsBuckets.Add(tlsBuckets, null); + if (Interlocked.Exchange(ref _callbackCreated, 1) != 1) + { + Gen2GcCallback.Register(Gen2GcCallbackFunc, this); + } + } } else { T[] prev = tlsBuckets[bucketIndex]; tlsBuckets[bucketIndex] = array; + if (prev != null) { - PerCoreLockedStacks bucket = _buckets[bucketIndex] ?? CreatePerCoreLockedStacks(bucketIndex); - bucket.TryPush(prev); + PerCoreLockedStacks stackBucket = _buckets[bucketIndex] ?? CreatePerCoreLockedStacks(bucketIndex); + stackBucket.TryPush(prev); } } } @@ -201,6 +221,103 @@ namespace System.Buffers } } + public bool Trim() + { + int milliseconds = Environment.TickCount; + MemoryPressure pressure = GetMemoryPressure(); + + ArrayPoolEventSource log = ArrayPoolEventSource.Log; + if (log.IsEnabled()) + log.BufferTrimPoll(milliseconds, (int)pressure); + + foreach (PerCoreLockedStacks bucket in _buckets) + { + bucket?.Trim((uint)milliseconds, Id, pressure, _bucketArraySizes); + } + + if (pressure == MemoryPressure.High) + { + // Under high pressure, release all thread locals + if (log.IsEnabled()) + { + foreach (KeyValuePair tlsBuckets in s_allTlsBuckets) + { + T[][] buckets = tlsBuckets.Key; + for (int i = 0; i < buckets.Length; i++) + { + T[] buffer = Interlocked.Exchange(ref buckets[i], null); + if (buffer != null) + { + // As we don't want to take a perf hit in the rent path it + // is possible that a buffer could be rented as we "free" it. + log.BufferTrimmed(buffer.GetHashCode(), buffer.Length, Id); + } + } + } + } + else + { + foreach (KeyValuePair tlsBuckets in s_allTlsBuckets) + { + T[][] buckets = tlsBuckets.Key; + Array.Clear(buckets, 0, buckets.Length); + } + } + } + + return true; + } + + /// + /// This is the static function that is called from the gen2 GC callback. + /// The input object is the instance we want the callback on. + /// + /// + /// The reason that we make this function static and take the instance as a parameter is that + /// we would otherwise root the instance to the Gen2GcCallback object, leaking the instance even when + /// the application no longer needs it. + /// + private static bool Gen2GcCallbackFunc(object target) + { + return ((TlsOverPerCoreLockedStacksArrayPool)(target)).Trim(); + } + + private enum MemoryPressure + { + Low, + Medium, + High + } + + private static MemoryPressure GetMemoryPressure() + { + const double HighPressureThreshold = .90; // Percent of GC memory pressure threshold we consider "high" + const double MediumPressureThreshold = .70; // Percent of GC memory pressure threshold we consider "medium" + + GC.GetMemoryInfo(out uint threshold, out _, out uint lastLoad, out _, out _); + if (lastLoad >= threshold * HighPressureThreshold) + { + return MemoryPressure.High; + } + else if (lastLoad >= threshold * MediumPressureThreshold) + { + return MemoryPressure.Medium; + } + return MemoryPressure.Low; + } + + private static bool GetTrimBuffers() + { + // Environment uses ArrayPool, so we have to hit the API directly. +#if !CORECLR + // P/Invokes are different for CoreCLR/RT- for RT we'll not allow + // enabling/disabling for now. + return true; +#else + return CLRConfig.GetBoolValueWithFallbacks("System.Buffers.ArrayPool.TrimShared", "DOTNET_SYSTEM_BUFFERS_ARRAYPOOL_TRIMSHARED", defaultValue: true); +#endif + } + /// /// Stores a set of stacks of arrays, with one stack per core. /// @@ -228,7 +345,7 @@ namespace System.Buffers // Try to push on to the associated stack first. If that fails, // round-robin through the other stacks. LockedStack[] stacks = _perCoreStacks; - int index = Environment.CurrentExecutionId % stacks.Length; + int index = RuntimeThread.GetCurrentProcessorId() % stacks.Length; for (int i = 0; i < stacks.Length; i++) { if (stacks[index].TryPush(array)) return; @@ -244,7 +361,7 @@ namespace System.Buffers // round-robin through the other stacks. T[] arr; LockedStack[] stacks = _perCoreStacks; - int index = Environment.CurrentExecutionId % stacks.Length; + int index = RuntimeThread.GetCurrentProcessorId() % stacks.Length; for (int i = 0; i < stacks.Length; i++) { if ((arr = stacks[index].TryPop()) != null) return arr; @@ -252,6 +369,16 @@ namespace System.Buffers } return null; } + + public bool Trim(uint tickCount, int id, MemoryPressure pressure, int[] bucketSizes) + { + LockedStack[] stacks = _perCoreStacks; + for (int i = 0; i < stacks.Length; i++) + { + stacks[i].Trim(tickCount, id, pressure, bucketSizes[i]); + } + return true; + } } /// Provides a simple stack of arrays, protected by a lock. @@ -259,6 +386,7 @@ namespace System.Buffers { private readonly T[][] _arrays = new T[MaxBuffersPerArraySizePerCore][]; private int _count; + private uint _firstStackItemMS; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryPush(T[] array) @@ -267,6 +395,12 @@ namespace System.Buffers Monitor.Enter(this); if (_count < MaxBuffersPerArraySizePerCore) { + if (s_trimBuffers && _count == 0) + { + // Stash the time the bottom of the stack was filled + _firstStackItemMS = (uint)Environment.TickCount; + } + _arrays[_count++] = array; enqueued = true; } @@ -287,6 +421,76 @@ namespace System.Buffers Monitor.Exit(this); return arr; } + + public void Trim(uint tickCount, int id, MemoryPressure pressure, int bucketSize) + { + const uint StackTrimAfterMS = 60 * 1000; // Trim after 60 seconds for low/moderate pressure + const uint StackHighTrimAfterMS = 10 * 1000; // Trim after 10 seconds for high pressure + const uint StackRefreshMS = StackTrimAfterMS / 4; // Time bump after trimming (1/4 trim time) + const int StackLowTrimCount = 1; // Trim one item when pressure is low + const int StackMediumTrimCount = 2; // Trim two items when pressure is moderate + const int StackHighTrimCount = MaxBuffersPerArraySizePerCore; // Trim all items when pressure is high + const int StackLargeBucket = 16384; // If the bucket is larger than this we'll trim an extra when under high pressure + const int StackModerateTypeSize = 16; // If T is larger than this we'll trim an extra when under high pressure + const int StackLargeTypeSize = 32; // If T is larger than this we'll trim an extra (additional) when under high pressure + + if (_count == 0) + return; + uint trimTicks = pressure == MemoryPressure.High ? StackHighTrimAfterMS : StackTrimAfterMS; + + lock (this) + { + if (_count > 0 && _firstStackItemMS > tickCount || (tickCount - _firstStackItemMS) > trimTicks) + { + // We've wrapped the tick count or elapsed enough time since the + // first item went into the stack. Drop the top item so it can + // be collected and make the stack look a little newer. + + ArrayPoolEventSource log = ArrayPoolEventSource.Log; + int trimCount = StackLowTrimCount; + switch (pressure) + { + case MemoryPressure.High: + trimCount = StackHighTrimCount; + + // When pressure is high, aggressively trim larger arrays. + if (bucketSize > StackLargeBucket) + { + trimCount++; + } + if (Unsafe.SizeOf() > StackModerateTypeSize) + { + trimCount++; + } + if (Unsafe.SizeOf() > StackLargeTypeSize) + { + trimCount++; + } + break; + case MemoryPressure.Medium: + trimCount = StackMediumTrimCount; + break; + } + + while (_count > 0 && trimCount-- > 0) + { + T[] array = _arrays[--_count]; + _arrays[_count] = null; + + if (log.IsEnabled()) + { + log.BufferTrimmed(array.GetHashCode(), array.Length, id); + } + } + + if (_count > 0 && _firstStackItemMS < uint.MaxValue - StackRefreshMS) + { + // Give the remaining items a bit more time + _firstStackItemMS += StackRefreshMS; + } + } + } + } } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/Utilities.cs b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/Utilities.cs index 4f115fe9dd..b675100b03 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Buffers/Utilities.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Buffers/Utilities.cs @@ -12,14 +12,19 @@ namespace System.Buffers [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int SelectBucketIndex(int bufferSize) { + Debug.Assert(bufferSize >= 0); + + // bufferSize of 0 will underflow here, causing a huge + // index which the caller will discard because it is not + // within the bounds of the bucket array. uint bitsRemaining = ((uint)bufferSize - 1) >> 4; int poolIndex = 0; if (bitsRemaining > 0xFFFF) { bitsRemaining >>= 16; poolIndex = 16; } - if (bitsRemaining > 0xFF) { bitsRemaining >>= 8; poolIndex += 8; } - if (bitsRemaining > 0xF) { bitsRemaining >>= 4; poolIndex += 4; } - if (bitsRemaining > 0x3) { bitsRemaining >>= 2; poolIndex += 2; } - if (bitsRemaining > 0x1) { bitsRemaining >>= 1; poolIndex += 1; } + if (bitsRemaining > 0xFF) { bitsRemaining >>= 8; poolIndex += 8; } + if (bitsRemaining > 0xF) { bitsRemaining >>= 4; poolIndex += 4; } + if (bitsRemaining > 0x3) { bitsRemaining >>= 2; poolIndex += 2; } + if (bitsRemaining > 0x1) { bitsRemaining >>= 1; poolIndex += 1; } return poolIndex + (int)bitsRemaining; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Byte.cs b/external/corert/src/System.Private.CoreLib/shared/System/Byte.cs index 13ceb7573d..da1f9147b9 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Byte.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Byte.cs @@ -12,9 +12,9 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Byte : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct Byte : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private byte m_value; // Do not rename (binary serialization) + private readonly byte m_value; // Do not rename (binary serialization) // The maximum value that a Byte may represent: 255. public const byte MaxValue = (byte)0xFF; @@ -29,37 +29,37 @@ namespace System // null is considered to be less than any instance. // If object is not of type byte, this method throws an ArgumentException. // - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) { return 1; } - if (!(value is Byte)) + if (!(value is byte)) { throw new ArgumentException(SR.Arg_MustBeByte); } - return m_value - (((Byte)value).m_value); + return m_value - (((byte)value).m_value); } - public int CompareTo(Byte value) + public int CompareTo(byte value) { return m_value - value; } // Determines whether two Byte objects are equal. - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is Byte)) + if (!(obj is byte)) { return false; } - return m_value == ((Byte)obj).m_value; + return m_value == ((byte)obj).m_value; } [NonVersionable] - public bool Equals(Byte obj) + public bool Equals(byte obj) { return m_value == obj; } @@ -70,20 +70,20 @@ namespace System return m_value; } - public static byte Parse(String s) + public static byte Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } - public static byte Parse(String s, NumberStyles style) + public static byte Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, style, NumberFormatInfo.CurrentInfo); } - public static byte Parse(String s, IFormatProvider provider) + public static byte Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); @@ -92,7 +92,7 @@ namespace System // Parses an unsigned byte from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. - public static byte Parse(String s, NumberStyles style, IFormatProvider provider) + public static byte Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -121,7 +121,7 @@ namespace System return (byte)i; } - public static bool TryParse(String s, out Byte result) + public static bool TryParse(string s, out byte result) { if (s == null) { @@ -137,7 +137,7 @@ namespace System return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } - public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Byte result) + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out byte result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -156,7 +156,7 @@ namespace System return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } - private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out Byte result) + private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out byte result) { result = 0; int i; @@ -172,33 +172,29 @@ namespace System return true; } - public override String ToString() + public override string ToString() { - return Number.FormatInt32(m_value, null, null); + return Number.FormatUInt32(m_value, null, null); } - public String ToString(String format) + public string ToString(string format) { - return Number.FormatInt32(m_value, format, null); + return Number.FormatUInt32(m_value, format, null); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { - return Number.FormatInt32(m_value, null, provider); + return Number.FormatUInt32(m_value, null, provider); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { - return Number.FormatInt32(m_value, format, provider); + return Number.FormatUInt32(m_value, format, provider); } - // TODO https://github.com/dotnet/corefx/issues/25337: Remove this overload once corefx is updated to target the new signatures - public bool TryFormat(Span destination, out int charsWritten, string format, IFormatProvider provider) => - TryFormat(destination, out charsWritten, (ReadOnlySpan)format, provider); - public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default, IFormatProvider provider = null) { - return Number.TryFormatInt32(m_value, format, provider, destination, out charsWritten); + return Number.TryFormatUInt32(m_value, format, provider, destination, out charsWritten); } // @@ -270,7 +266,7 @@ namespace System return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -280,7 +276,7 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Byte", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Char.cs b/external/corert/src/System.Private.CoreLib/shared/System/Char.cs index d3ed1f5b68..8c743369b1 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Char.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Char.cs @@ -21,12 +21,12 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Char : IComparable, IComparable, IEquatable, IConvertible + public readonly struct Char : IComparable, IComparable, IEquatable, IConvertible { // // Member Variables // - private char m_value; // Do not rename (binary serialization) + private readonly char m_value; // Do not rename (binary serialization) // // Public Constants @@ -87,7 +87,7 @@ namespace System // Return the Unicode category for Unicode character <= 0x00ff. private static UnicodeCategory GetLatin1UnicodeCategory(char ch) { - Debug.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f"); + Debug.Assert(IsLatin1(ch), "char.GetLatin1UnicodeCategory(): ch should be <= 007f"); return (UnicodeCategory)(s_categoryForLatin1[(int)ch]); } @@ -107,17 +107,17 @@ namespace System // Used for comparing two boxed Char objects. // - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is Char)) + if (!(obj is char)) { return false; } - return (m_value == ((Char)obj).m_value); + return (m_value == ((char)obj).m_value); } [System.Runtime.Versioning.NonVersionable] - public bool Equals(Char obj) + public bool Equals(char obj) { return m_value == obj; } @@ -128,34 +128,34 @@ namespace System // null is considered to be less than any instance. // If object is not of type Char, this method throws an ArgumentException. // - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) { return 1; } - if (!(value is Char)) + if (!(value is char)) { throw new ArgumentException(SR.Arg_MustBeChar); } - return (m_value - ((Char)value).m_value); + return (m_value - ((char)value).m_value); } - public int CompareTo(Char value) + public int CompareTo(char value) { return (m_value - value); } // Overrides System.Object.ToString. - public override String ToString() + public override string ToString() { - return Char.ToString(m_value); + return char.ToString(m_value); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { - return Char.ToString(m_value); + return char.ToString(m_value); } // @@ -168,7 +168,7 @@ namespace System // Provides a string representation of a character. public static string ToString(char c) => string.CreateFromChar(c); - public static char Parse(String s) + public static char Parse(string s) { if (s == null) { @@ -182,7 +182,7 @@ namespace System return s[0]; } - public static bool TryParse(String s, out Char result) + public static bool TryParse(string s, out char result) { result = '\0'; if (s == null) @@ -201,7 +201,7 @@ namespace System // Static Methods // /*=================================ISDIGIT====================================== - **A wrapper for Char. Returns a boolean indicating whether ** + **A wrapper for char. Returns a boolean indicating whether ** **character c is considered to be a digit. ** ==============================================================================*/ // Determines whether a character is a digit. @@ -233,7 +233,7 @@ namespace System } /*=================================ISLETTER===================================== - **A wrapper for Char. Returns a boolean indicating whether ** + **A wrapper for char. Returns a boolean indicating whether ** **character c is considered to be a letter. ** ==============================================================================*/ // Determines whether a character is a letter. @@ -271,7 +271,7 @@ namespace System } /*===============================ISWHITESPACE=================================== - **A wrapper for Char. Returns a boolean indicating whether ** + **A wrapper for char. Returns a boolean indicating whether ** **character c is considered to be a whitespace character. ** ==============================================================================*/ // Determines whether a character is whitespace. @@ -393,7 +393,7 @@ namespace System } /*=================================TOUPPER====================================== - **A wrapper for Char.toUpperCase. Converts character c to its ** + **A wrapper for char.ToUpperCase. Converts character c to its ** **uppercase equivalent. If c is already an uppercase character or is not an ** **alphabetic, nothing happens. ** ==============================================================================*/ @@ -425,7 +425,7 @@ namespace System } /*=================================TOLOWER====================================== - **A wrapper for Char.toLowerCase. Converts character c to its ** + **A wrapper for char.ToLowerCase. Converts character c to its ** **lowercase equivalent. If c is already a lowercase character or is not an ** **alphabetic, nothing happens. ** ==============================================================================*/ @@ -512,7 +512,7 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Double")); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Decimal")); } @@ -522,7 +522,7 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } @@ -535,7 +535,7 @@ namespace System return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Control); } - public static bool IsControl(String s, int index) + public static bool IsControl(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -552,7 +552,7 @@ namespace System } - public static bool IsDigit(String s, int index) + public static bool IsDigit(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -568,7 +568,7 @@ namespace System return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.DecimalDigitNumber); } - public static bool IsLetter(String s, int index) + public static bool IsLetter(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -589,7 +589,7 @@ namespace System return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(s, index))); } - public static bool IsLetterOrDigit(String s, int index) + public static bool IsLetterOrDigit(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -605,7 +605,7 @@ namespace System return CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(s, index)); } - public static bool IsLower(String s, int index) + public static bool IsLower(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -655,7 +655,7 @@ namespace System return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(c))); } - public static bool IsNumber(String s, int index) + public static bool IsNumber(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -683,7 +683,7 @@ namespace System // //////////////////////////////////////////////////////////////////////// - public static bool IsPunctuation(String s, int index) + public static bool IsPunctuation(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -732,7 +732,7 @@ namespace System return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(c))); } - public static bool IsSeparator(String s, int index) + public static bool IsSeparator(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -753,7 +753,7 @@ namespace System return (c >= HIGH_SURROGATE_START && c <= LOW_SURROGATE_END); } - public static bool IsSurrogate(String s, int index) + public static bool IsSurrogate(string s, int index) { if (s == null) { @@ -792,7 +792,7 @@ namespace System return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(c))); } - public static bool IsSymbol(String s, int index) + public static bool IsSymbol(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -809,7 +809,7 @@ namespace System } - public static bool IsUpper(String s, int index) + public static bool IsUpper(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -830,7 +830,7 @@ namespace System return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.UppercaseLetter); } - public static bool IsWhiteSpace(String s, int index) + public static bool IsWhiteSpace(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -856,7 +856,7 @@ namespace System return CharUnicodeInfo.GetUnicodeCategory((int)c); } - public static UnicodeCategory GetUnicodeCategory(String s, int index) + public static UnicodeCategory GetUnicodeCategory(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -876,7 +876,7 @@ namespace System return CharUnicodeInfo.GetNumericValue(c); } - public static double GetNumericValue(String s, int index) + public static double GetNumericValue(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -896,7 +896,7 @@ namespace System return ((c >= CharUnicodeInfo.HIGH_SURROGATE_START) && (c <= CharUnicodeInfo.HIGH_SURROGATE_END)); } - public static bool IsHighSurrogate(String s, int index) + public static bool IsHighSurrogate(string s, int index) { if (s == null) { @@ -917,7 +917,7 @@ namespace System return ((c >= CharUnicodeInfo.LOW_SURROGATE_START) && (c <= CharUnicodeInfo.LOW_SURROGATE_END)); } - public static bool IsLowSurrogate(String s, int index) + public static bool IsLowSurrogate(string s, int index) { if (s == null) { @@ -933,7 +933,7 @@ namespace System /*================================= IsSurrogatePair ============================ ** Check if the string specified by the index starts with a surrogate pair. ==============================================================================*/ - public static bool IsSurrogatePair(String s, int index) + public static bool IsSurrogatePair(string s, int index) { if (s == null) { @@ -972,7 +972,7 @@ namespace System ** Convert an UTF32 value into a surrogate pair. ==============================================================================*/ - public static String ConvertFromUtf32(int utf32) + public static string ConvertFromUtf32(int utf32) { // For UTF32 values from U+00D800 ~ U+00DFFF, we should throw. They // are considered as irregular code unit sequence, but they are not illegal. @@ -984,7 +984,7 @@ namespace System if (utf32 < UNICODE_PLANE01_START) { // This is a BMP character. - return (Char.ToString((char)utf32)); + return (char.ToString((char)utf32)); } unsafe @@ -1025,7 +1025,7 @@ namespace System ** This method throws if a low surrogate is seen without preceding a high-surrogate. ==============================================================================*/ - public static int ConvertToUtf32(String s, int index) + public static int ConvertToUtf32(string s, int index) { if (s == null) { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/CharEnumerator.cs b/external/corert/src/System.Private.CoreLib/shared/System/CharEnumerator.cs index ea9915a7c4..ca60705d99 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/CharEnumerator.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/CharEnumerator.cs @@ -19,11 +19,11 @@ namespace System { public sealed class CharEnumerator : IEnumerator, IEnumerator, IDisposable, ICloneable { - private String _str; + private string _str; private int _index; private char _currentElement; - internal CharEnumerator(String str) + internal CharEnumerator(string str) { _str = str; _index = -1; @@ -54,7 +54,7 @@ namespace System _str = null; } - Object IEnumerator.Current + object IEnumerator.Current { get { return Current; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs index 6fcedc09ab..e22fb5bb91 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs @@ -52,7 +52,7 @@ namespace System.Collections // If a doesn't implement IComparable and b does, -(b.CompareTo(a)) is returned. // Otherwise an exception is thrown. // - public int Compare(Object a, Object b) + public int Compare(object a, object b) { if (a == b) return 0; if (a == null) return -1; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/CompatibleComparer.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/CompatibleComparer.cs new file mode 100644 index 0000000000..587fd68391 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/CompatibleComparer.cs @@ -0,0 +1,61 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +#pragma warning disable 618 // obsolete types + +namespace System.Collections +{ + internal sealed class CompatibleComparer : IEqualityComparer + { + private readonly IHashCodeProvider _hcp; + private readonly IComparer _comparer; + + internal CompatibleComparer(IHashCodeProvider hashCodeProvider, IComparer comparer) + { + _hcp = hashCodeProvider; + _comparer = comparer; + } + + internal IHashCodeProvider HashCodeProvider => _hcp; + + internal IComparer Comparer => _comparer; + + public new bool Equals(object a, object b) => Compare(a, b) == 0; + + public int Compare(object a, object b) + { + if (a == b) + return 0; + if (a == null) + return -1; + if (b == null) + return 1; + + if (_comparer != null) + { + return _comparer.Compare(a, b); + } + + IComparable ia = a as IComparable; + if (ia != null) + { + return ia.CompareTo(b); + } + + throw new ArgumentException(SR.Argument_ImplementIComparable); + } + + public int GetHashCode(object obj) + { + if (obj == null) + { + throw new ArgumentNullException(nameof(obj)); + } + + return _hcp != null ? + _hcp.GetHashCode(obj) : + obj.GetHashCode(); + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Collections/Concurrent/LowLevelConcurrentQueue.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueue.cs similarity index 52% rename from external/corert/src/System.Private.CoreLib/src/System/Collections/Concurrent/LowLevelConcurrentQueue.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueue.cs index 5e799db68e..63880b09f5 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Collections/Concurrent/LowLevelConcurrentQueue.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueue.cs @@ -2,20 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ -// -// A lock-free, concurrent queue primitive, and its associated debugger view type. -// -// This is a stripped-down version of ConcurrentQueue, for use from within the System.Threading -// surface to eliminate a dependency on System.Collections.Concurrent. -// Please try to keep this in sync with the public ConcurrentQueue implementation. -// -// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- - using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; -using System.Runtime.Serialization; using System.Threading; namespace System.Collections.Concurrent @@ -25,11 +14,12 @@ namespace System.Collections.Concurrent /// /// Specifies the type of elements in the queue. /// - /// All public and protected members of are thread-safe and may be used + /// All public and protected members of are thread-safe and may be used /// concurrently from multiple threads. /// [DebuggerDisplay("Count = {Count}")] - internal class LowLevelConcurrentQueue : /* IProducerConsumerCollection, */ IReadOnlyCollection + [DebuggerTypeProxy(typeof(IProducerConsumerCollectionDebugView<>))] + public class ConcurrentQueue : IProducerConsumerCollection, IReadOnlyCollection { // This implementation provides an unbounded, multi-producer multi-consumer queue // that supports the standard Enqueue/TryDequeue operations, as well as support for @@ -62,47 +52,19 @@ namespace System.Collections.Concurrent /// Lock used to protect cross-segment operations, including any updates to or /// and any operations that need to get a consistent view of them. /// - [NonSerialized] - private Lock _crossSegmentLock; + private object _crossSegmentLock; /// The current tail segment. - [NonSerialized] - private volatile Segment _tail; + private volatile ConcurrentQueueSegment _tail; /// The current head segment. - [NonSerialized] - private volatile Segment _head; - /// Field used to temporarily store the contents of the queue for serialization. - private T[] _serializationArray; + private volatile ConcurrentQueueSegment _head; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public LowLevelConcurrentQueue() + public ConcurrentQueue() { - _crossSegmentLock = new Lock(); - _tail = _head = new Segment(InitialSegmentLength); - } - - /// Set the data array to be serialized. - [OnSerializing] - private void OnSerializing(StreamingContext context) - { - _serializationArray = ToArray(); - } - - /// Clear the data array that was serialized. - [OnSerialized] - private void OnSerialized(StreamingContext context) - { - _serializationArray = null; - } - - /// Construct the queue from the deserialized . - [OnDeserialized] - private void OnDeserialized(StreamingContext context) - { - Debug.Assert(_serializationArray != null); - InitializeFromCollection(_serializationArray); - _serializationArray = null; + _crossSegmentLock = new object(); + _tail = _head = new ConcurrentQueueSegment(InitialSegmentLength); } /// @@ -111,10 +73,10 @@ namespace System.Collections.Concurrent /// A collection from which to copy elements. private void InitializeFromCollection(IEnumerable collection) { - _crossSegmentLock = new Lock(); + _crossSegmentLock = new object(); // Determine the initial segment size. We'll use the default, - // unless the collection is known to be larger than than, in which + // unless the collection is known to be larger than that, in which // case we round its length up to a power of 2, as all segments must // be a power of 2 in length. int length = InitialSegmentLength; @@ -124,12 +86,12 @@ namespace System.Collections.Concurrent int count = c.Count; if (count > length) { - length = Math.Min(RoundUpToPowerOf2(count), MaxSegmentLength); + length = Math.Min(ConcurrentQueueSegment.RoundUpToPowerOf2(count), MaxSegmentLength); } } // Initialize the segment and add all of the data to it. - _tail = _head = new Segment(length); + _tail = _head = new ConcurrentQueueSegment(length); foreach (T item in collection) { Enqueue(item); @@ -137,31 +99,122 @@ namespace System.Collections.Concurrent } /// - /// Initializes a new instance of the class that contains elements copied + /// Initializes a new instance of the class that contains elements copied /// from the specified collection. /// /// - /// The collection whose elements are copied to the new . + /// The collection whose elements are copied to the new . /// /// The argument is null. - public LowLevelConcurrentQueue(IEnumerable collection) + public ConcurrentQueue(IEnumerable collection) { if (collection == null) { - throw new ArgumentNullException(nameof(collection)); + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } InitializeFromCollection(collection); } + /// + /// Copies the elements of the to an , starting at a particular index. + /// + /// + /// The one-dimensional Array that is the destination of the + /// elements copied from the . must have + /// zero-based indexing. + /// + /// The zero-based index in at which copying begins. + /// is a null reference (Nothing in + /// Visual Basic). + /// is less than + /// zero. + /// + /// is multidimensional. -or- + /// does not have zero-based indexing. -or- + /// is equal to or greater than the length of the + /// -or- The number of elements in the source is + /// greater than the available space from to the end of the destination + /// . -or- The type of the source cannot be cast automatically to the type of the + /// destination . + /// + void ICollection.CopyTo(Array array, int index) + { + // Special-case when the Array is actually a T[], taking a faster path + T[] szArray = array as T[]; + if (szArray != null) + { + CopyTo(szArray, index); + return; + } + + // Validate arguments. + if (array == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + } + + // Otherwise, fall back to the slower path that first copies the contents + // to an array, and then uses that array's non-generic CopyTo to do the copy. + ToArray().CopyTo(array, index); + } + + /// + /// Gets a value indicating whether access to the is + /// synchronized with the SyncRoot. + /// + /// true if access to the is synchronized + /// with the SyncRoot; otherwise, false. For , this property always + /// returns false. + bool ICollection.IsSynchronized => false; // always false, as true implies synchronization via SyncRoot + + /// + /// Gets an object that can be used to synchronize access to the . This property is not supported. + /// + /// The SyncRoot property is not supported. + object ICollection.SyncRoot { get { ThrowHelper.ThrowNotSupportedException(ExceptionResource.ConcurrentCollection_SyncRoot_NotSupported); return default; } } + /// Returns an enumerator that iterates through a collection. /// An that can be used to iterate through the collection. IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)this).GetEnumerator(); /// - /// Gets a value that indicates whether the is empty. + /// Attempts to add an object to the . /// - /// true if the is empty; otherwise, false. + /// The object to add to the . The value can be a null + /// reference (Nothing in Visual Basic) for reference types. + /// + /// true if the object was added successfully; otherwise, false. + /// For , this operation will always add the object to the + /// end of the + /// and return true. + bool IProducerConsumerCollection.TryAdd(T item) + { + Enqueue(item); + return true; + } + + /// + /// Attempts to remove and return an object from the . + /// + /// + /// When this method returns, if the operation was successful, contains the + /// object removed. If no object was available to be removed, the value is unspecified. + /// + /// true if an element was removed and returned successfully; otherwise, false. + /// For , this operation will attempt to remove the object + /// from the beginning of the . + /// + bool IProducerConsumerCollection.TryTake(out T item) => TryDequeue(out item); + + /// + /// Gets a value that indicates whether the is empty. + /// + /// true if the is empty; otherwise, false. /// /// For determining whether the collection contains any items, use of this property is recommended /// rather than retrieving the number of items from the property and comparing it @@ -181,12 +234,12 @@ namespace System.Collections.Concurrent } } - /// Copies the elements stored in the to a new array. - /// A new array containing a snapshot of elements copied from the . + /// Copies the elements stored in the to a new array. + /// A new array containing a snapshot of elements copied from the . public T[] ToArray() { // Snap the current contents for enumeration. - Segment head, tail; + ConcurrentQueueSegment head, tail; int headHead, tailTail; SnapForObservation(out head, out headHead, out tail, out tailTail); @@ -211,9 +264,9 @@ namespace System.Collections.Concurrent } /// - /// Gets the number of elements contained in the . + /// Gets the number of elements contained in the . /// - /// The number of elements contained in the . + /// The number of elements contained in the . /// /// For determining whether the collection contains any items, use of the /// property is recommended rather than retrieving the number of items from the @@ -223,26 +276,24 @@ namespace System.Collections.Concurrent { get { - Segment head, tail; - int headHead, headTail, tailHead, tailTail; var spinner = new SpinWait(); while (true) { // Capture the head and tail, as well as the head's head and tail. - head = _head; - tail = _tail; - headHead = Volatile.Read(ref head._headAndTail.Head); - headTail = Volatile.Read(ref head._headAndTail.Tail); + ConcurrentQueueSegment head = _head; + ConcurrentQueueSegment tail = _tail; + int headHead = Volatile.Read(ref head._headAndTail.Head); + int headTail = Volatile.Read(ref head._headAndTail.Tail); if (head == tail) { - // There was a single segment in the queue. If the captured - // values still (or again) represent reality, return the segment's - // count. A single segment should be the most common case once the - // queue's size has stabilized after segments have grown to - // the point where growing is no longer needed. + // There was a single segment in the queue. If the captured segments still + // match, then we can trust the values to compute the segment's count. (It's + // theoretically possible the values could have looped around and still exactly match, + // but that would required at least ~4 billion elements to have been enqueued and + // dequeued between the reads.) if (head == _head && - head == _tail && + tail == _tail && headHead == Volatile.Read(ref head._headAndTail.Head) && headTail == Volatile.Read(ref head._headAndTail.Tail)) { @@ -251,11 +302,10 @@ namespace System.Collections.Concurrent } else if (head._nextSegment == tail) { - // There were two segments in the queue. Get the positions - // from the tail, and if the captured values still (or again) match - // reality, return the sum of the counts from both segments. - tailHead = Volatile.Read(ref tail._headAndTail.Head); - tailTail = Volatile.Read(ref tail._headAndTail.Tail); + // There were two segments in the queue. Get the positions from the tail, and as above, + // if the captured values match the previous reads, return the sum of the counts from both segments. + int tailHead = Volatile.Read(ref tail._headAndTail.Head); + int tailTail = Volatile.Read(ref tail._headAndTail.Tail); if (head == _head && tail == _tail && headHead == Volatile.Read(ref head._headAndTail.Head) && @@ -263,17 +313,52 @@ namespace System.Collections.Concurrent tailHead == Volatile.Read(ref tail._headAndTail.Head) && tailTail == Volatile.Read(ref tail._headAndTail.Tail)) { - // We got stable values, so we can just compute the sizes based on those - // values and return the sum of the counts of the segments. return GetCount(head, headHead, headTail) + GetCount(tail, tailHead, tailTail); } } else { - // There were more than two segments. Take the slower path, where we freeze the - // queue and then count the now stable segments. - SnapForObservation(out head, out headHead, out tail, out tailTail); - return unchecked((int)GetCount(head, headHead, tail, tailTail)); + // There were more than two segments in the queue. Fall back to taking the cross-segment lock, + // which will ensure that the head and tail segments we read are stable (since the lock is needed to change them); + // for the two-segment case above, we can simply rely on subsequent comparisons, but for the two+ case, we need + // to be able to trust the internal segments between the head and tail. + lock (_crossSegmentLock) + { + // Now that we hold the lock, re-read the previously captured head and tail segments and head positions. + // If either has changed, start over. + if (head == _head && tail == _tail) + { + // Get the positions from the tail, and as above, if the captured values match the previous reads, + // we can use the values to compute the count of the head and tail segments. + int tailHead = Volatile.Read(ref tail._headAndTail.Head); + int tailTail = Volatile.Read(ref tail._headAndTail.Tail); + if (headHead == Volatile.Read(ref head._headAndTail.Head) && + headTail == Volatile.Read(ref head._headAndTail.Tail) && + tailHead == Volatile.Read(ref tail._headAndTail.Head) && + tailTail == Volatile.Read(ref tail._headAndTail.Tail)) + { + // We got stable values for the head and tail segments, so we can just compute the sizes + // based on those and add them. Note that this and the below additions to count may overflow: previous + // implementations allowed that, so we don't check, either, and it is theoretically possible for the + // queue to store more than int.MaxValue items. + int count = GetCount(head, headHead, headTail) + GetCount(tail, tailHead, tailTail); + + // Now add the counts for each internal segment. Since there were segments before these, + // for counting purposes we consider them to start at the 0th element, and since there is at + // least one segment after each, each was frozen, so we can count until each's frozen tail. + // With the cross-segment lock held, we're guaranteed that all of these internal segments are + // consistent, as the head and tail segment can't be changed while we're holding the lock, and + // dequeueing and enqueueing can only be done from the head and tail segments, which these aren't. + for (ConcurrentQueueSegment s = head._nextSegment; s != tail; s = s._nextSegment) + { + Debug.Assert(s._frozenForEnqueues, "Internal segment must be frozen as there's a following segment."); + count += s._headAndTail.Tail - s.FreezeOffset; + } + + return count; + } + } + } } // We raced with enqueues/dequeues and captured an inconsistent picture of the queue. @@ -284,7 +369,7 @@ namespace System.Collections.Concurrent } /// Computes the number of items in a segment based on a fixed head and tail in that segment. - private static int GetCount(Segment s, int head, int tail) + private static int GetCount(ConcurrentQueueSegment s, int head, int tail) { if (head != tail && head != tail - s.FreezeOffset) { @@ -296,7 +381,7 @@ namespace System.Collections.Concurrent } /// Gets the number of items in snapped region. - private static long GetCount(Segment head, int headHead, Segment tail, int tailTail) + private static long GetCount(ConcurrentQueueSegment head, int headHead, ConcurrentQueueSegment tail, int tailTail) { // All of the segments should have been both frozen for enqueues and preserved for observation. // Validate that here for head and tail; we'll validate it for intermediate segments later. @@ -332,7 +417,7 @@ namespace System.Collections.Concurrent // Since there were segments before these, for our purposes we consider them to start at // the 0th element, and since there is at least one segment after each, each was frozen // by the time we snapped it, so we can iterate until each's frozen tail. - for (Segment s = head._nextSegment; s != tail; s = s._nextSegment) + for (ConcurrentQueueSegment s = head._nextSegment; s != tail; s = s._nextSegment) { Debug.Assert(s._preservedForObservation); Debug.Assert(s._frozenForEnqueues); @@ -351,12 +436,12 @@ namespace System.Collections.Concurrent } /// - /// Copies the elements to an existing one-dimensional elements to an existing one-dimensional Array, starting at the specified array index. /// /// The one-dimensional Array that is the /// destination of the elements copied from the - /// . The Array must have zero-based + /// . The Array must have zero-based /// indexing. /// The zero-based index in at which copying /// begins. @@ -366,7 +451,7 @@ namespace System.Collections.Concurrent /// zero. /// is equal to or greater than the /// length of the - /// -or- The number of elements in the source is greater than the + /// -or- The number of elements in the source is greater than the /// available space from to the end of the destination . /// @@ -374,15 +459,15 @@ namespace System.Collections.Concurrent { if (array == null) { - throw new ArgumentNullException(nameof(array)); + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0) { - throw new ArgumentOutOfRangeException(nameof(index)); + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } // Snap for enumeration - Segment head, tail; + ConcurrentQueueSegment head, tail; int headHead, tailTail; SnapForObservation(out head, out headHead, out tail, out tailTail); @@ -390,7 +475,7 @@ namespace System.Collections.Concurrent long count = GetCount(head, headHead, tail, tailTail); if (index > array.Length - count) { - throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } // Copy the items to the target array @@ -405,9 +490,9 @@ namespace System.Collections.Concurrent Debug.Assert(count == i - index); } - /// Returns an enumerator that iterates through the . + /// Returns an enumerator that iterates through the . /// An enumerator for the contents of the . + /// cref="ConcurrentQueue{T}"/>. /// /// The enumeration represents a moment-in-time snapshot of the contents /// of the queue. It does not reflect any updates to the collection after @@ -416,7 +501,7 @@ namespace System.Collections.Concurrent /// public IEnumerator GetEnumerator() { - Segment head, tail; + ConcurrentQueueSegment head, tail; int headHead, tailTail; SnapForObservation(out head, out headHead, out tail, out tailTail); return Enumerate(head, headHead, tail, tailTail); @@ -427,9 +512,9 @@ namespace System.Collections.Concurrent /// After this call returns, the specified region can be enumerated any number /// of times and will not change. /// - private void SnapForObservation(out Segment head, out int headHead, out Segment tail, out int tailTail) + private void SnapForObservation(out ConcurrentQueueSegment head, out int headHead, out ConcurrentQueueSegment tail, out int tailTail) { - using (LockHolder.Hold(_crossSegmentLock)) // _head and _tail may only change while the lock is held. + lock (_crossSegmentLock) // _head and _tail may only change while the lock is held. { // Snap the head and tail head = _head; @@ -440,7 +525,7 @@ namespace System.Collections.Concurrent // Mark them and all segments in between as preserving, and ensure no additional items // can be added to the tail. - for (Segment s = head; ; s = s._nextSegment) + for (ConcurrentQueueSegment s = head; ; s = s._nextSegment) { s._preservedForObservation = true; if (s == tail) break; @@ -457,7 +542,7 @@ namespace System.Collections.Concurrent } /// Gets the item stored in the th entry in . - private T GetItemWhenAvailable(Segment segment, int i) + private T GetItemWhenAvailable(ConcurrentQueueSegment segment, int i) { Debug.Assert(segment._preservedForObservation); @@ -479,7 +564,7 @@ namespace System.Collections.Concurrent return segment._slots[i].Item; } - private IEnumerator Enumerate(Segment head, int headHead, Segment tail, int tailTail) + private IEnumerator Enumerate(ConcurrentQueueSegment head, int headHead, ConcurrentQueueSegment tail, int tailTail) { Debug.Assert(head._preservedForObservation); Debug.Assert(head._frozenForEnqueues); @@ -512,7 +597,7 @@ namespace System.Collections.Concurrent { // Each segment between head and tail, not including head and tail. Since there were // segments before these, for our purposes we consider it to start at the 0th element. - for (Segment s = head._nextSegment; s != tail; s = s._nextSegment) + for (ConcurrentQueueSegment s = head._nextSegment; s != tail; s = s._nextSegment) { Debug.Assert(s._preservedForObservation, "Would have had to been preserved as a segment part of enumeration"); Debug.Assert(s._frozenForEnqueues, "Would have had to be frozen for enqueues as it's intermediate"); @@ -534,21 +619,9 @@ namespace System.Collections.Concurrent } } - /// Round the specified value up to the next power of 2, if it isn't one already. - private static int RoundUpToPowerOf2(int i) - { - --i; - i |= i >> 1; - i |= i >> 2; - i |= i >> 4; - i |= i >> 8; - i |= i >> 16; - return i + 1; - } - - /// Adds an object to the end of the . + /// Adds an object to the end of the . /// - /// The object to add to the end of the . + /// The object to add to the end of the . /// The value can be a null reference (Nothing in Visual Basic) for reference types. /// public void Enqueue(T item) @@ -567,7 +640,7 @@ namespace System.Collections.Concurrent { while (true) { - Segment tail = _tail; + ConcurrentQueueSegment tail = _tail; // Try to append to the existing tail. if (tail.TryEnqueue(item)) @@ -578,7 +651,7 @@ namespace System.Collections.Concurrent // If we were unsuccessful, take the lock so that we can compare and manipulate // the tail. Assuming another enqueuer hasn't already added a new segment, // do so, then loop around to try enqueueing again. - using (LockHolder.Hold(_crossSegmentLock)) // _head and _tail may only change while the lock is held. + lock (_crossSegmentLock) { if (tail == _tail) { @@ -595,7 +668,7 @@ namespace System.Collections.Concurrent // this will help to avoid wasted memory, and if they're not, we'll // relatively quickly grow again to a larger size. int nextSize = tail._preservedForObservation ? InitialSegmentLength : Math.Min(tail.Capacity * 2, MaxSegmentLength); - var newTail = new Segment(nextSize); + var newTail = new ConcurrentQueueSegment(nextSize); // Hook up the new tail. tail._nextSegment = newTail; @@ -607,7 +680,7 @@ namespace System.Collections.Concurrent /// /// Attempts to remove and return the object at the beginning of the . + /// cref="ConcurrentQueue{T}"/>. /// /// /// When this method returns, if the operation was successful, contains the @@ -615,7 +688,7 @@ namespace System.Collections.Concurrent /// /// /// true if an element was removed and returned from the beginning of the - /// successfully; otherwise, false. + /// successfully; otherwise, false. /// public bool TryDequeue(out T result) => _head.TryDequeue(out result) || // fast-path that operates just on the head segment @@ -627,7 +700,7 @@ namespace System.Collections.Concurrent while (true) { // Get the current head - Segment head = _head; + ConcurrentQueueSegment head = _head; // Try to take. If we're successful, we're done. if (head.TryDequeue(out item)) @@ -640,7 +713,7 @@ namespace System.Collections.Concurrent // check and this check, another item could have arrived). if (head._nextSegment == null) { - item = default(T); + item = default; return false; } @@ -657,7 +730,7 @@ namespace System.Collections.Concurrent // This segment is frozen (nothing more can be added) and empty (nothing is in it). // Update head to point to the next segment in the list, assuming no one's beat us to it. - using (LockHolder.Hold(_crossSegmentLock)) // _head and _tail may only change while the lock is held. + lock (_crossSegmentLock) { if (head == _head) { @@ -668,12 +741,12 @@ namespace System.Collections.Concurrent } /// - /// Attempts to return an object from the beginning of the + /// Attempts to return an object from the beginning of the /// without removing it. /// /// /// When this method returns, contains an object from - /// the beginning of the or default(T) + /// the beginning of the or default(T) /// if the operation failed. /// /// true if and object was returned successfully; otherwise, false. @@ -685,19 +758,19 @@ namespace System.Collections.Concurrent /// Attempts to retrieve the value for the first element in the queue. /// The value of the first element, if found. - /// true if the result is neede; otherwise false if only the true/false outcome is needed. + /// true if the result is needed; otherwise false if only the true/false outcome is needed. /// true if an element was found; otherwise, false. private bool TryPeek(out T result, bool resultUsed) { // Starting with the head segment, look through all of the segments // for the first one we can find that's not empty. - Segment s = _head; + ConcurrentQueueSegment s = _head; while (true) { // Grab the next segment from this one, before we peek. // This is to be able to see whether the value has changed // during the peek operation. - Segment next = Volatile.Read(ref s._nextSegment); + ConcurrentQueueSegment next = Volatile.Read(ref s._nextSegment); // Peek at the segment. If we find an element, we're done. if (s.TryPeek(out result, resultUsed)) @@ -734,16 +807,16 @@ namespace System.Collections.Concurrent // and we'll traverse to that segment. } - result = default(T); + result = default; return false; } /// - /// Removes all objects from the . + /// Removes all objects from the . /// public void Clear() { - using (LockHolder.Hold(_crossSegmentLock)) // _head and _tail may only change while the lock is held. + lock (_crossSegmentLock) { // Simply substitute a new segment for the existing head/tail, // as is done in the constructor. Operations currently in flight @@ -754,315 +827,8 @@ namespace System.Collections.Concurrent // be dropped, we first freeze it; that'll force enqueuers to take // this lock to synchronize and see the new tail. _tail.EnsureFrozenForEnqueues(); - _tail = _head = new Segment(InitialSegmentLength); + _tail = _head = new ConcurrentQueueSegment(InitialSegmentLength); } } - - /// - /// Provides a multi-producer, multi-consumer thread-safe bounded segment. When the queue is full, - /// enqueues fail and return false. When the queue is empty, dequeues fail and return null. - /// These segments are linked together to form the unbounded . - /// - [DebuggerDisplay("Capacity = {Capacity}")] - private sealed class Segment - { - // Segment design is inspired by the algorithm outlined at: - // http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue - - /// The array of items in this queue. Each slot contains the item in that slot and its "sequence number". - internal readonly Slot[] _slots; - /// Mask for quickly accessing a position within the queue's array. - internal readonly int _slotsMask; - /// The head and tail positions, with padding to help avoid false sharing contention. - /// Dequeueing happens from the head, enqueueing happens at the tail. - internal PaddedHeadAndTail _headAndTail; // mutable struct: do not make this readonly - - /// Indicates whether the segment has been marked such that dequeues don't overwrite the removed data. - internal bool _preservedForObservation; - /// Indicates whether the segment has been marked such that no additional items may be enqueued. - internal bool _frozenForEnqueues; - /// The segment following this one in the queue, or null if this segment is the last in the queue. - internal Segment _nextSegment; - - /// Creates the segment. - /// - /// The maximum number of elements the segment can contain. Must be a power of 2. - /// - public Segment(int boundedLength) - { - // Validate the length - Debug.Assert(boundedLength >= 2, $"Must be >= 2, got {boundedLength}"); - Debug.Assert((boundedLength & (boundedLength - 1)) == 0, $"Must be a power of 2, got {boundedLength}"); - - // Initialize the slots and the mask. The mask is used as a way of quickly doing "% _slots.Length", - // instead letting us do "& _slotsMask". - _slots = new Slot[boundedLength]; - _slotsMask = boundedLength - 1; - - // Initialize the sequence number for each slot. The sequence number provides a ticket that - // allows dequeuers to know whether they can dequeue and enqueuers to know whether they can - // enqueue. An enqueuer at position N can enqueue when the sequence number is N, and a dequeuer - // for position N can dequeue when the sequence number is N + 1. When an enqueuer is done writing - // at position N, it sets the sequence number to N so that a dequeuer will be able to dequeue, - // and when a dequeuer is done dequeueing at position N, it sets the sequence number to N + _slots.Length, - // so that when an enqueuer loops around the slots, it'll find that the sequence number at - // position N is N. This also means that when an enqueuer finds that at position N the sequence - // number is < N, there is still a value in that slot, i.e. the segment is full, and when a - // dequeuer finds that the value in a slot is < N + 1, there is nothing currently available to - // dequeue. (It is possible for multiple enqueuers to enqueue concurrently, writing into - // subsequent slots, and to have the first enqueuer take longer, so that the slots for 1, 2, 3, etc. - // may have values, but the 0th slot may still be being filled... in that case, TryDequeue will - // return false.) - for (int i = 0; i < _slots.Length; i++) - { - _slots[i].SequenceNumber = i; - } - } - - /// Gets the number of elements this segment can store. - internal int Capacity => _slots.Length; - - /// Gets the "freeze offset" for this segment. - internal int FreezeOffset => _slots.Length * 2; - - /// - /// Ensures that the segment will not accept any subsequent enqueues that aren't already underway. - /// - /// - /// When we mark a segment as being frozen for additional enqueues, - /// we set the bool, but that's mostly - /// as a small helper to avoid marking it twice. The real marking comes - /// by modifying the Tail for the segment, increasing it by this - /// . This effectively knocks it off the - /// sequence expected by future enqueuers, such that any additional enqueuer - /// will be unable to enqueue due to it not lining up with the expected - /// sequence numbers. This value is chosen specially so that Tail will grow - /// to a value that maps to the same slot but that won't be confused with - /// any other enqueue/dequeue sequence number. - /// - internal void EnsureFrozenForEnqueues() // must only be called while queue's segment lock is held - { - if (!_frozenForEnqueues) // flag used to ensure we don't increase the Tail more than once if frozen more than once - { - _frozenForEnqueues = true; - - // Increase the tail by FreezeOffset, spinning until we're successful in doing so. - var spinner = new SpinWait(); - while (true) - { - int tail = Volatile.Read(ref _headAndTail.Tail); - if (Interlocked.CompareExchange(ref _headAndTail.Tail, tail + FreezeOffset, tail) == tail) - { - break; - } - spinner.SpinOnce(); - } - } - } - - /// Tries to dequeue an element from the queue. - public bool TryDequeue(out T item) - { - // Loop in case of contention... - var spinner = new SpinWait(); - while (true) - { - // Get the head at which to try to dequeue. - int currentHead = Volatile.Read(ref _headAndTail.Head); - int slotsIndex = currentHead & _slotsMask; - - // Read the sequence number for the head position. - int sequenceNumber = Volatile.Read(ref _slots[slotsIndex].SequenceNumber); - - // We can dequeue from this slot if it's been filled by an enqueuer, which - // would have left the sequence number at pos+1. - int diff = sequenceNumber - (currentHead + 1); - if (diff == 0) - { - // We may be racing with other dequeuers. Try to reserve the slot by incrementing - // the head. Once we've done that, no one else will be able to read from this slot, - // and no enqueuer will be able to read from this slot until we've written the new - // sequence number. WARNING: The next few lines are not reliable on a runtime that - // supports thread aborts. If a thread abort were to sneak in after the CompareExchange - // but before the Volatile.Write, enqueuers trying to enqueue into this slot would - // spin indefinitely. If this implementation is ever used on such a platform, this - // if block should be wrapped in a finally / prepared region. - if (Interlocked.CompareExchange(ref _headAndTail.Head, currentHead + 1, currentHead) == currentHead) - { - // Successfully reserved the slot. Note that after the above CompareExchange, other threads - // trying to dequeue from this slot will end up spinning until we do the subsequent Write. - item = _slots[slotsIndex].Item; - if (!Volatile.Read(ref _preservedForObservation)) - { - // If we're preserving, though, we don't zero out the slot, as we need it for - // enumerations, peeking, ToArray, etc. And we don't update the sequence number, - // so that an enqueuer will see it as full and be forced to move to a new segment. - _slots[slotsIndex].Item = default(T); - Volatile.Write(ref _slots[slotsIndex].SequenceNumber, currentHead + _slots.Length); - } - return true; - } - } - else if (diff < 0) - { - // The sequence number was less than what we needed, which means this slot doesn't - // yet contain a value we can dequeue, i.e. the segment is empty. Technically it's - // possible that multiple enqueuers could have written concurrently, with those - // getting later slots actually finishing first, so there could be elements after - // this one that are available, but we need to dequeue in order. So before declaring - // failure and that the segment is empty, we check the tail to see if we're actually - // empty or if we're just waiting for items in flight or after this one to become available. - bool frozen = _frozenForEnqueues; - int currentTail = Volatile.Read(ref _headAndTail.Tail); - if (currentTail - currentHead <= 0 || (frozen && (currentTail - FreezeOffset - currentHead <= 0))) - { - item = default(T); - return false; - } - - // It's possible it could have become frozen after we checked _frozenForEnqueues - // and before reading the tail. That's ok: in that rare race condition, we just - // loop around again. - } - - // Lost a race. Spin a bit, then try again. - spinner.SpinOnce(); - } - } - - /// Tries to peek at an element from the queue, without removing it. - public bool TryPeek(out T result, bool resultUsed) - { - if (resultUsed) - { - // In order to ensure we don't get a torn read on the value, we mark the segment - // as preserving for observation. Additional items can still be enqueued to this - // segment, but no space will be freed during dequeues, such that the segment will - // no longer be reusable. - _preservedForObservation = true; - Interlocked.MemoryBarrier(); - } - - // Loop in case of contention... - var spinner = new SpinWait(); - while (true) - { - // Get the head at which to try to peek. - int currentHead = Volatile.Read(ref _headAndTail.Head); - int slotsIndex = currentHead & _slotsMask; - - // Read the sequence number for the head position. - int sequenceNumber = Volatile.Read(ref _slots[slotsIndex].SequenceNumber); - - // We can peek from this slot if it's been filled by an enqueuer, which - // would have left the sequence number at pos+1. - int diff = sequenceNumber - (currentHead + 1); - if (diff == 0) - { - result = resultUsed ? _slots[slotsIndex].Item : default(T); - return true; - } - else if (diff < 0) - { - // The sequence number was less than what we needed, which means this slot doesn't - // yet contain a value we can peek, i.e. the segment is empty. Technically it's - // possible that multiple enqueuers could have written concurrently, with those - // getting later slots actually finishing first, so there could be elements after - // this one that are available, but we need to peek in order. So before declaring - // failure and that the segment is empty, we check the tail to see if we're actually - // empty or if we're just waiting for items in flight or after this one to become available. - bool frozen = _frozenForEnqueues; - int currentTail = Volatile.Read(ref _headAndTail.Tail); - if (currentTail - currentHead <= 0 || (frozen && (currentTail - FreezeOffset - currentHead <= 0))) - { - result = default(T); - return false; - } - - // It's possible it could have become frozen after we checked _frozenForEnqueues - // and before reading the tail. That's ok: in that rare race condition, we just - // loop around again. - } - - // Lost a race. Spin a bit, then try again. - spinner.SpinOnce(); - } - } - - /// - /// Attempts to enqueue the item. If successful, the item will be stored - /// in the queue and true will be returned; otherwise, the item won't be stored, and false - /// will be returned. - /// - public bool TryEnqueue(T item) - { - // Loop in case of contention... - var spinner = new SpinWait(); - while (true) - { - // Get the tail at which to try to return. - int currentTail = Volatile.Read(ref _headAndTail.Tail); - int slotsIndex = currentTail & _slotsMask; - - // Read the sequence number for the tail position. - int sequenceNumber = Volatile.Read(ref _slots[slotsIndex].SequenceNumber); - - // The slot is empty and ready for us to enqueue into it if its sequence - // number matches the slot. - int diff = sequenceNumber - currentTail; - if (diff == 0) - { - // We may be racing with other enqueuers. Try to reserve the slot by incrementing - // the tail. Once we've done that, no one else will be able to write to this slot, - // and no dequeuer will be able to read from this slot until we've written the new - // sequence number. WARNING: The next few lines are not reliable on a runtime that - // supports thread aborts. If a thread abort were to sneak in after the CompareExchange - // but before the Volatile.Write, other threads will spin trying to access this slot. - // If this implementation is ever used on such a platform, this if block should be - // wrapped in a finally / prepared region. - if (Interlocked.CompareExchange(ref _headAndTail.Tail, currentTail + 1, currentTail) == currentTail) - { - // Successfully reserved the slot. Note that after the above CompareExchange, other threads - // trying to return will end up spinning until we do the subsequent Write. - _slots[slotsIndex].Item = item; - Volatile.Write(ref _slots[slotsIndex].SequenceNumber, currentTail + 1); - return true; - } - } - else if (diff < 0) - { - // The sequence number was less than what we needed, which means this slot still - // contains a value, i.e. the segment is full. Technically it's possible that multiple - // dequeuers could have read concurrently, with those getting later slots actually - // finishing first, so there could be spaces after this one that are available, but - // we need to enqueue in order. - return false; - } - - // Lost a race. Spin a bit, then try again. - spinner.SpinOnce(); - } - } - - /// Represents a slot in the queue. - [StructLayout(LayoutKind.Auto)] - [DebuggerDisplay("Item = {Item}, SequenceNumber = {SequenceNumber}")] - internal struct Slot - { - /// The item. - public T Item; - /// The sequence number for this slot, used to synchronize between enqueuers and dequeuers. - public int SequenceNumber; - } - } - } - - /// Padded head and tail indices, to avoid false sharing between producers and consumers. - [DebuggerDisplay("Head = {Head}, Tail = {Tail}")] - [StructLayout(LayoutKind.Explicit, Size = 192)] // padding before/between/after fields based on typical cache line size of 64 - internal struct PaddedHeadAndTail - { - [FieldOffset(64)] public int Head; - [FieldOffset(128)] public int Tail; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueueSegment.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueueSegment.cs new file mode 100644 index 0000000000..12e92d0e07 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueueSegment.cs @@ -0,0 +1,332 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading; + +namespace System.Collections.Concurrent +{ + /// + /// Provides a multi-producer, multi-consumer thread-safe bounded segment. When the queue is full, + /// enqueues fail and return false. When the queue is empty, dequeues fail and return null. + /// These segments are linked together to form the unbounded . + /// + [DebuggerDisplay("Capacity = {Capacity}")] + internal sealed class ConcurrentQueueSegment + { + // Segment design is inspired by the algorithm outlined at: + // http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue + + /// The array of items in this queue. Each slot contains the item in that slot and its "sequence number". + internal readonly Slot[] _slots; + /// Mask for quickly accessing a position within the queue's array. + internal readonly int _slotsMask; + /// The head and tail positions, with padding to help avoid false sharing contention. + /// Dequeuing happens from the head, enqueuing happens at the tail. + internal PaddedHeadAndTail _headAndTail; // mutable struct: do not make this readonly + + /// Indicates whether the segment has been marked such that dequeues don't overwrite the removed data. + internal bool _preservedForObservation; + /// Indicates whether the segment has been marked such that no additional items may be enqueued. + internal bool _frozenForEnqueues; +#pragma warning disable 0649 // some builds don't assign to this field + /// The segment following this one in the queue, or null if this segment is the last in the queue. + internal ConcurrentQueueSegment _nextSegment; +#pragma warning restore 0649 + + /// Creates the segment. + /// + /// The maximum number of elements the segment can contain. Must be a power of 2. + /// + internal ConcurrentQueueSegment(int boundedLength) + { + // Validate the length + Debug.Assert(boundedLength >= 2, $"Must be >= 2, got {boundedLength}"); + Debug.Assert((boundedLength & (boundedLength - 1)) == 0, $"Must be a power of 2, got {boundedLength}"); + + // Initialize the slots and the mask. The mask is used as a way of quickly doing "% _slots.Length", + // instead letting us do "& _slotsMask". + _slots = new Slot[boundedLength]; + _slotsMask = boundedLength - 1; + + // Initialize the sequence number for each slot. The sequence number provides a ticket that + // allows dequeuers to know whether they can dequeue and enqueuers to know whether they can + // enqueue. An enqueuer at position N can enqueue when the sequence number is N, and a dequeuer + // for position N can dequeue when the sequence number is N + 1. When an enqueuer is done writing + // at position N, it sets the sequence number to N + 1 so that a dequeuer will be able to dequeue, + // and when a dequeuer is done dequeueing at position N, it sets the sequence number to N + _slots.Length, + // so that when an enqueuer loops around the slots, it'll find that the sequence number at + // position N is N. This also means that when an enqueuer finds that at position N the sequence + // number is < N, there is still a value in that slot, i.e. the segment is full, and when a + // dequeuer finds that the value in a slot is < N + 1, there is nothing currently available to + // dequeue. (It is possible for multiple enqueuers to enqueue concurrently, writing into + // subsequent slots, and to have the first enqueuer take longer, so that the slots for 1, 2, 3, etc. + // may have values, but the 0th slot may still be being filled... in that case, TryDequeue will + // return false.) + for (int i = 0; i < _slots.Length; i++) + { + _slots[i].SequenceNumber = i; + } + } + + /// Round the specified value up to the next power of 2, if it isn't one already. + internal static int RoundUpToPowerOf2(int i) + { + // Based on https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 + --i; + i |= i >> 1; + i |= i >> 2; + i |= i >> 4; + i |= i >> 8; + i |= i >> 16; + return i + 1; + } + + /// Gets the number of elements this segment can store. + internal int Capacity => _slots.Length; + + /// Gets the "freeze offset" for this segment. + internal int FreezeOffset => _slots.Length * 2; + + /// + /// Ensures that the segment will not accept any subsequent enqueues that aren't already underway. + /// + /// + /// When we mark a segment as being frozen for additional enqueues, + /// we set the bool, but that's mostly + /// as a small helper to avoid marking it twice. The real marking comes + /// by modifying the Tail for the segment, increasing it by this + /// . This effectively knocks it off the + /// sequence expected by future enqueuers, such that any additional enqueuer + /// will be unable to enqueue due to it not lining up with the expected + /// sequence numbers. This value is chosen specially so that Tail will grow + /// to a value that maps to the same slot but that won't be confused with + /// any other enqueue/dequeue sequence number. + /// + internal void EnsureFrozenForEnqueues() // must only be called while queue's segment lock is held + { + if (!_frozenForEnqueues) // flag used to ensure we don't increase the Tail more than once if frozen more than once + { + _frozenForEnqueues = true; + + // Increase the tail by FreezeOffset, spinning until we're successful in doing so. + var spinner = new SpinWait(); + while (true) + { + int tail = Volatile.Read(ref _headAndTail.Tail); + if (Interlocked.CompareExchange(ref _headAndTail.Tail, tail + FreezeOffset, tail) == tail) + { + break; + } + spinner.SpinOnce(); + } + } + } + + /// Tries to dequeue an element from the queue. + public bool TryDequeue(out T item) + { + // Loop in case of contention... + var spinner = new SpinWait(); + while (true) + { + // Get the head at which to try to dequeue. + int currentHead = Volatile.Read(ref _headAndTail.Head); + int slotsIndex = currentHead & _slotsMask; + + // Read the sequence number for the head position. + int sequenceNumber = Volatile.Read(ref _slots[slotsIndex].SequenceNumber); + + // We can dequeue from this slot if it's been filled by an enqueuer, which + // would have left the sequence number at pos+1. + int diff = sequenceNumber - (currentHead + 1); + if (diff == 0) + { + // We may be racing with other dequeuers. Try to reserve the slot by incrementing + // the head. Once we've done that, no one else will be able to read from this slot, + // and no enqueuer will be able to read from this slot until we've written the new + // sequence number. WARNING: The next few lines are not reliable on a runtime that + // supports thread aborts. If a thread abort were to sneak in after the CompareExchange + // but before the Volatile.Write, enqueuers trying to enqueue into this slot would + // spin indefinitely. If this implementation is ever used on such a platform, this + // if block should be wrapped in a finally / prepared region. + if (Interlocked.CompareExchange(ref _headAndTail.Head, currentHead + 1, currentHead) == currentHead) + { + // Successfully reserved the slot. Note that after the above CompareExchange, other threads + // trying to dequeue from this slot will end up spinning until we do the subsequent Write. + item = _slots[slotsIndex].Item; + if (!Volatile.Read(ref _preservedForObservation)) + { + // If we're preserving, though, we don't zero out the slot, as we need it for + // enumerations, peeking, ToArray, etc. And we don't update the sequence number, + // so that an enqueuer will see it as full and be forced to move to a new segment. + _slots[slotsIndex].Item = default(T); + Volatile.Write(ref _slots[slotsIndex].SequenceNumber, currentHead + _slots.Length); + } + return true; + } + } + else if (diff < 0) + { + // The sequence number was less than what we needed, which means this slot doesn't + // yet contain a value we can dequeue, i.e. the segment is empty. Technically it's + // possible that multiple enqueuers could have written concurrently, with those + // getting later slots actually finishing first, so there could be elements after + // this one that are available, but we need to dequeue in order. So before declaring + // failure and that the segment is empty, we check the tail to see if we're actually + // empty or if we're just waiting for items in flight or after this one to become available. + bool frozen = _frozenForEnqueues; + int currentTail = Volatile.Read(ref _headAndTail.Tail); + if (currentTail - currentHead <= 0 || (frozen && (currentTail - FreezeOffset - currentHead <= 0))) + { + item = default(T); + return false; + } + + // It's possible it could have become frozen after we checked _frozenForEnqueues + // and before reading the tail. That's ok: in that rare race condition, we just + // loop around again. + } + + // Lost a race. Spin a bit, then try again. + spinner.SpinOnce(); + } + } + + /// Tries to peek at an element from the queue, without removing it. + public bool TryPeek(out T result, bool resultUsed) + { + if (resultUsed) + { + // In order to ensure we don't get a torn read on the value, we mark the segment + // as preserving for observation. Additional items can still be enqueued to this + // segment, but no space will be freed during dequeues, such that the segment will + // no longer be reusable. + _preservedForObservation = true; + Interlocked.MemoryBarrier(); + } + + // Loop in case of contention... + var spinner = new SpinWait(); + while (true) + { + // Get the head at which to try to peek. + int currentHead = Volatile.Read(ref _headAndTail.Head); + int slotsIndex = currentHead & _slotsMask; + + // Read the sequence number for the head position. + int sequenceNumber = Volatile.Read(ref _slots[slotsIndex].SequenceNumber); + + // We can peek from this slot if it's been filled by an enqueuer, which + // would have left the sequence number at pos+1. + int diff = sequenceNumber - (currentHead + 1); + if (diff == 0) + { + result = resultUsed ? _slots[slotsIndex].Item : default(T); + return true; + } + else if (diff < 0) + { + // The sequence number was less than what we needed, which means this slot doesn't + // yet contain a value we can peek, i.e. the segment is empty. Technically it's + // possible that multiple enqueuers could have written concurrently, with those + // getting later slots actually finishing first, so there could be elements after + // this one that are available, but we need to peek in order. So before declaring + // failure and that the segment is empty, we check the tail to see if we're actually + // empty or if we're just waiting for items in flight or after this one to become available. + bool frozen = _frozenForEnqueues; + int currentTail = Volatile.Read(ref _headAndTail.Tail); + if (currentTail - currentHead <= 0 || (frozen && (currentTail - FreezeOffset - currentHead <= 0))) + { + result = default(T); + return false; + } + + // It's possible it could have become frozen after we checked _frozenForEnqueues + // and before reading the tail. That's ok: in that rare race condition, we just + // loop around again. + } + + // Lost a race. Spin a bit, then try again. + spinner.SpinOnce(); + } + } + + /// + /// Attempts to enqueue the item. If successful, the item will be stored + /// in the queue and true will be returned; otherwise, the item won't be stored, and false + /// will be returned. + /// + public bool TryEnqueue(T item) + { + // Loop in case of contention... + var spinner = new SpinWait(); + while (true) + { + // Get the tail at which to try to return. + int currentTail = Volatile.Read(ref _headAndTail.Tail); + int slotsIndex = currentTail & _slotsMask; + + // Read the sequence number for the tail position. + int sequenceNumber = Volatile.Read(ref _slots[slotsIndex].SequenceNumber); + + // The slot is empty and ready for us to enqueue into it if its sequence + // number matches the slot. + int diff = sequenceNumber - currentTail; + if (diff == 0) + { + // We may be racing with other enqueuers. Try to reserve the slot by incrementing + // the tail. Once we've done that, no one else will be able to write to this slot, + // and no dequeuer will be able to read from this slot until we've written the new + // sequence number. WARNING: The next few lines are not reliable on a runtime that + // supports thread aborts. If a thread abort were to sneak in after the CompareExchange + // but before the Volatile.Write, other threads will spin trying to access this slot. + // If this implementation is ever used on such a platform, this if block should be + // wrapped in a finally / prepared region. + if (Interlocked.CompareExchange(ref _headAndTail.Tail, currentTail + 1, currentTail) == currentTail) + { + // Successfully reserved the slot. Note that after the above CompareExchange, other threads + // trying to return will end up spinning until we do the subsequent Write. + _slots[slotsIndex].Item = item; + Volatile.Write(ref _slots[slotsIndex].SequenceNumber, currentTail + 1); + return true; + } + } + else if (diff < 0) + { + // The sequence number was less than what we needed, which means this slot still + // contains a value, i.e. the segment is full. Technically it's possible that multiple + // dequeuers could have read concurrently, with those getting later slots actually + // finishing first, so there could be spaces after this one that are available, but + // we need to enqueue in order. + return false; + } + + // Lost a race. Spin a bit, then try again. + spinner.SpinOnce(); + } + } + + /// Represents a slot in the queue. + [StructLayout(LayoutKind.Auto)] + [DebuggerDisplay("Item = {Item}, SequenceNumber = {SequenceNumber}")] + internal struct Slot + { + /// The item. + public T Item; + /// The sequence number for this slot, used to synchronize between enqueuers and dequeuers. + public int SequenceNumber; + } + } + + /// Padded head and tail indices, to avoid false sharing between producers and consumers. + [DebuggerDisplay("Head = {Head}, Tail = {Tail}")] + [StructLayout(LayoutKind.Explicit, Size = 3 * Internal.PaddingHelpers.CACHE_LINE_SIZE)] // padding before/between/after fields + internal struct PaddedHeadAndTail + { + [FieldOffset(1 * Internal.PaddingHelpers.CACHE_LINE_SIZE)] public int Head; + [FieldOffset(2 * Internal.PaddingHelpers.CACHE_LINE_SIZE)] public int Tail; + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Concurrent/IProducerConsumerCollection.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Concurrent/IProducerConsumerCollection.cs new file mode 100644 index 0000000000..9727150569 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Concurrent/IProducerConsumerCollection.cs @@ -0,0 +1,70 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.Diagnostics; + +namespace System.Collections.Concurrent +{ + /// + /// A common interface for all concurrent collections. + /// Defines methods to manipulate thread-safe collections intended for producer/consumer usage. + /// + /// Specifies the type of elements in the collection. + /// + /// All implementations of this interface must enable all members of this interface + /// to be used concurrently from multiple threads. + /// + public interface IProducerConsumerCollection : IEnumerable, ICollection + { + /// + /// Copies the elements of the to + /// an + /// , starting at a specified index. + /// + /// The one-dimensional that is the destination of + /// the elements copied from the . + /// The array must have zero-based indexing. + /// The zero-based index in at which copying + /// begins. + /// is a null reference (Nothing in + /// Visual Basic). + /// is less than + /// zero. + /// is equal to or greater than the + /// length of the + /// -or- The number of elements in the source is greater than the + /// available space from to the end of the destination . + /// + void CopyTo(T[] array, int index); + + /// + /// Attempts to add an object to the . + /// + /// The object to add to the . + /// true if the object was added successfully; otherwise, false. + /// The was invalid for this collection. + bool TryAdd(T item); + + /// + /// Attempts to remove and return an object from the . + /// + /// + /// When this method returns, if the object was removed and returned successfully, contains the removed object. If no object was available to be removed, the value is + /// unspecified. + /// + /// true if an object was removed and returned successfully; otherwise, false. + bool TryTake(out T item); + + /// + /// Copies the elements contained in the to a new array. + /// + /// A new array containing the elements copied from the . + T[] ToArray(); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Concurrent/IProducerConsumerCollectionDebugView.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Concurrent/IProducerConsumerCollectionDebugView.cs new file mode 100644 index 0000000000..0205e068ea --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Concurrent/IProducerConsumerCollectionDebugView.cs @@ -0,0 +1,41 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; + +namespace System.Collections.Concurrent +{ + /// + /// A debugger view of the IProducerConsumerCollection that makes it simple to browse the + /// collection's contents at a point in time. + /// + /// The type of elements stored within. + internal sealed class IProducerConsumerCollectionDebugView + { + private readonly IProducerConsumerCollection _collection; // The collection being viewed. + + /// + /// Constructs a new debugger view object for the provided collection object. + /// + /// A collection to browse in the debugger. + public IProducerConsumerCollectionDebugView(IProducerConsumerCollection collection) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + _collection = collection; + } + + /// + /// Returns a snapshot of the underlying collection's elements. + /// + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public T[] Items + { + get { return _collection.ToArray(); } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/DictionaryEntry.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/DictionaryEntry.cs index d0cbcb6663..eabb013761 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/DictionaryEntry.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/DictionaryEntry.cs @@ -16,18 +16,18 @@ namespace System.Collections #endif public struct DictionaryEntry { - private Object _key; // Do not rename (binary serialization) - private Object _value; // Do not rename (binary serialization) + private object _key; // Do not rename (binary serialization) + private object _value; // Do not rename (binary serialization) // Constructs a new DictionaryEnumerator by setting the Key // and Value fields appropriately. - public DictionaryEntry(Object key, Object value) + public DictionaryEntry(object key, object value) { _key = key; _value = value; } - public Object Key + public object Key { get { @@ -40,7 +40,7 @@ namespace System.Collections } } - public Object Value + public object Value { get { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/ArraySortHelper.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/ArraySortHelper.cs new file mode 100644 index 0000000000..03b9865044 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/ArraySortHelper.cs @@ -0,0 +1,1115 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/*============================================================ +** +** +** +** +** +** Purpose: class to sort arrays +** +** +===========================================================*/ + +using System.Diagnostics; +using System.Runtime.CompilerServices; + +namespace System.Collections.Generic +{ + #region ArraySortHelper for single arrays + + internal static class IntrospectiveSortUtilities + { + // This is the threshold where Introspective sort switches to Insertion sort. + // Empirically, 16 seems to speed up most cases without slowing down others, at least for integers. + // Large value types may benefit from a smaller number. + internal const int IntrosortSizeThreshold = 16; + + internal static int FloorLog2PlusOne(int n) + { + int result = 0; + while (n >= 1) + { + result++; + n = n / 2; + } + return result; + } + + internal static void ThrowOrIgnoreBadComparer(object comparer) + { + throw new ArgumentException(SR.Format(SR.Arg_BogusIComparer, comparer)); + } + } + + internal partial class ArraySortHelper + { + #region IArraySortHelper Members + + public void Sort(T[] keys, int index, int length, IComparer comparer) + { + Debug.Assert(keys != null, "Check the arguments in the caller!"); + Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); + + // Add a try block here to detect IComparers (or their + // underlying IComparables, etc) that are bogus. + try + { + if (comparer == null) + { + comparer = Comparer.Default; + } + + IntrospectiveSort(keys, index, length, comparer.Compare); + } + catch (IndexOutOfRangeException) + { + IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); + } + catch (Exception e) + { + throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); + } + } + + public int BinarySearch(T[] array, int index, int length, T value, IComparer comparer) + { + try + { + if (comparer == null) + { + comparer = Comparer.Default; + } + + return InternalBinarySearch(array, index, length, value, comparer); + } + catch (Exception e) + { + throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); + } + } + + #endregion + + internal static void Sort(T[] keys, int index, int length, Comparison comparer) + { + Debug.Assert(keys != null, "Check the arguments in the caller!"); + Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); + Debug.Assert(comparer != null, "Check the arguments in the caller!"); + + // Add a try block here to detect bogus comparisons + try + { + IntrospectiveSort(keys, index, length, comparer); + } + catch (IndexOutOfRangeException) + { + IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); + } + catch (Exception e) + { + throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); + } + } + + internal static int InternalBinarySearch(T[] array, int index, int length, T value, IComparer comparer) + { + Debug.Assert(array != null, "Check the arguments in the caller!"); + Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); + + int lo = index; + int hi = index + length - 1; + while (lo <= hi) + { + int i = lo + ((hi - lo) >> 1); + int order = comparer.Compare(array[i], value); + + if (order == 0) return i; + if (order < 0) + { + lo = i + 1; + } + else + { + hi = i - 1; + } + } + + return ~lo; + } + + private static void SwapIfGreater(T[] keys, Comparison comparer, int a, int b) + { + if (a != b) + { + if (comparer(keys[a], keys[b]) > 0) + { + T key = keys[a]; + keys[a] = keys[b]; + keys[b] = key; + } + } + } + + private static void Swap(T[] a, int i, int j) + { + if (i != j) + { + T t = a[i]; + a[i] = a[j]; + a[j] = t; + } + } + + internal static void IntrospectiveSort(T[] keys, int left, int length, Comparison comparer) + { + Debug.Assert(keys != null); + Debug.Assert(comparer != null); + Debug.Assert(left >= 0); + Debug.Assert(length >= 0); + Debug.Assert(length <= keys.Length); + Debug.Assert(length + left <= keys.Length); + + if (length < 2) + return; + + IntroSort(keys, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length), comparer); + } + + private static void IntroSort(T[] keys, int lo, int hi, int depthLimit, Comparison comparer) + { + Debug.Assert(keys != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi < keys.Length); + + while (hi > lo) + { + int partitionSize = hi - lo + 1; + if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold) + { + if (partitionSize == 1) + { + return; + } + if (partitionSize == 2) + { + SwapIfGreater(keys, comparer, lo, hi); + return; + } + if (partitionSize == 3) + { + SwapIfGreater(keys, comparer, lo, hi - 1); + SwapIfGreater(keys, comparer, lo, hi); + SwapIfGreater(keys, comparer, hi - 1, hi); + return; + } + + InsertionSort(keys, lo, hi, comparer); + return; + } + + if (depthLimit == 0) + { + Heapsort(keys, lo, hi, comparer); + return; + } + depthLimit--; + + int p = PickPivotAndPartition(keys, lo, hi, comparer); + // Note we've already partitioned around the pivot and do not have to move the pivot again. + IntroSort(keys, p + 1, hi, depthLimit, comparer); + hi = p - 1; + } + } + + private static int PickPivotAndPartition(T[] keys, int lo, int hi, Comparison comparer) + { + Debug.Assert(keys != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); + + // Compute median-of-three. But also partition them, since we've done the comparison. + int middle = lo + ((hi - lo) / 2); + + // Sort lo, mid and hi appropriately, then pick mid as the pivot. + SwapIfGreater(keys, comparer, lo, middle); // swap the low with the mid point + SwapIfGreater(keys, comparer, lo, hi); // swap the low with the high + SwapIfGreater(keys, comparer, middle, hi); // swap the middle with the high + + T pivot = keys[middle]; + Swap(keys, middle, hi - 1); + int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. + + while (left < right) + { + while (comparer(keys[++left], pivot) < 0) ; + while (comparer(pivot, keys[--right]) < 0) ; + + if (left >= right) + break; + + Swap(keys, left, right); + } + + // Put pivot in the right location. + Swap(keys, left, (hi - 1)); + return left; + } + + private static void Heapsort(T[] keys, int lo, int hi, Comparison comparer) + { + Debug.Assert(keys != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); + + int n = hi - lo + 1; + for (int i = n / 2; i >= 1; i = i - 1) + { + DownHeap(keys, i, n, lo, comparer); + } + for (int i = n; i > 1; i = i - 1) + { + Swap(keys, lo, lo + i - 1); + DownHeap(keys, 1, i - 1, lo, comparer); + } + } + + private static void DownHeap(T[] keys, int i, int n, int lo, Comparison comparer) + { + Debug.Assert(keys != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(lo < keys.Length); + + T d = keys[lo + i - 1]; + int child; + while (i <= n / 2) + { + child = 2 * i; + if (child < n && comparer(keys[lo + child - 1], keys[lo + child]) < 0) + { + child++; + } + if (!(comparer(d, keys[lo + child - 1]) < 0)) + break; + keys[lo + i - 1] = keys[lo + child - 1]; + i = child; + } + keys[lo + i - 1] = d; + } + + private static void InsertionSort(T[] keys, int lo, int hi, Comparison comparer) + { + Debug.Assert(keys != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi >= lo); + Debug.Assert(hi <= keys.Length); + + int i, j; + T t; + for (i = lo; i < hi; i++) + { + j = i; + t = keys[i + 1]; + while (j >= lo && comparer(t, keys[j]) < 0) + { + keys[j + 1] = keys[j]; + j--; + } + keys[j + 1] = t; + } + } + } + + internal partial class GenericArraySortHelper + where T : IComparable + { + // Do not add a constructor to this class because ArraySortHelper.CreateSortHelper will not execute it + + #region IArraySortHelper Members + + public void Sort(T[] keys, int index, int length, IComparer comparer) + { + Debug.Assert(keys != null, "Check the arguments in the caller!"); + Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); + + try + { + if (comparer == null || comparer == Comparer.Default) + { + IntrospectiveSort(keys, index, length); + } + else + { + ArraySortHelper.IntrospectiveSort(keys, index, length, comparer.Compare); + } + } + catch (IndexOutOfRangeException) + { + IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); + } + catch (Exception e) + { + throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); + } + } + + public int BinarySearch(T[] array, int index, int length, T value, IComparer comparer) + { + Debug.Assert(array != null, "Check the arguments in the caller!"); + Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); + + try + { + if (comparer == null || comparer == Comparer.Default) + { + return BinarySearch(array, index, length, value); + } + else + { + return ArraySortHelper.InternalBinarySearch(array, index, length, value, comparer); + } + } + catch (Exception e) + { + throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); + } + } + + #endregion + + // This function is called when the user doesn't specify any comparer. + // Since T is constrained here, we can call IComparable.CompareTo here. + // We can avoid boxing for value type and casting for reference types. + private static int BinarySearch(T[] array, int index, int length, T value) + { + int lo = index; + int hi = index + length - 1; + while (lo <= hi) + { + int i = lo + ((hi - lo) >> 1); + int order; + if (array[i] == null) + { + order = (value == null) ? 0 : -1; + } + else + { + order = array[i].CompareTo(value); + } + + if (order == 0) + { + return i; + } + + if (order < 0) + { + lo = i + 1; + } + else + { + hi = i - 1; + } + } + + return ~lo; + } + + private static void SwapIfGreaterWithItems(T[] keys, int a, int b) + { + Debug.Assert(keys != null); + Debug.Assert(0 <= a && a < keys.Length); + Debug.Assert(0 <= b && b < keys.Length); + + if (a != b) + { + if (keys[a] != null && keys[a].CompareTo(keys[b]) > 0) + { + T key = keys[a]; + keys[a] = keys[b]; + keys[b] = key; + } + } + } + + private static void Swap(T[] a, int i, int j) + { + if (i != j) + { + T t = a[i]; + a[i] = a[j]; + a[j] = t; + } + } + + internal static void IntrospectiveSort(T[] keys, int left, int length) + { + Debug.Assert(keys != null); + Debug.Assert(left >= 0); + Debug.Assert(length >= 0); + Debug.Assert(length <= keys.Length); + Debug.Assert(length + left <= keys.Length); + + if (length < 2) + return; + + IntroSort(keys, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length)); + } + + private static void IntroSort(T[] keys, int lo, int hi, int depthLimit) + { + Debug.Assert(keys != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi < keys.Length); + + while (hi > lo) + { + int partitionSize = hi - lo + 1; + if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold) + { + if (partitionSize == 1) + { + return; + } + if (partitionSize == 2) + { + SwapIfGreaterWithItems(keys, lo, hi); + return; + } + if (partitionSize == 3) + { + SwapIfGreaterWithItems(keys, lo, hi - 1); + SwapIfGreaterWithItems(keys, lo, hi); + SwapIfGreaterWithItems(keys, hi - 1, hi); + return; + } + + InsertionSort(keys, lo, hi); + return; + } + + if (depthLimit == 0) + { + Heapsort(keys, lo, hi); + return; + } + depthLimit--; + + int p = PickPivotAndPartition(keys, lo, hi); + // Note we've already partitioned around the pivot and do not have to move the pivot again. + IntroSort(keys, p + 1, hi, depthLimit); + hi = p - 1; + } + } + + private static int PickPivotAndPartition(T[] keys, int lo, int hi) + { + Debug.Assert(keys != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); + + // Compute median-of-three. But also partition them, since we've done the comparison. + int middle = lo + ((hi - lo) / 2); + + // Sort lo, mid and hi appropriately, then pick mid as the pivot. + SwapIfGreaterWithItems(keys, lo, middle); // swap the low with the mid point + SwapIfGreaterWithItems(keys, lo, hi); // swap the low with the high + SwapIfGreaterWithItems(keys, middle, hi); // swap the middle with the high + + T pivot = keys[middle]; + Swap(keys, middle, hi - 1); + int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. + + while (left < right) + { + if (pivot == null) + { + while (left < (hi - 1) && keys[++left] == null) ; + while (right > lo && keys[--right] != null) ; + } + else + { + while (pivot.CompareTo(keys[++left]) > 0) ; + while (pivot.CompareTo(keys[--right]) < 0) ; + } + + if (left >= right) + break; + + Swap(keys, left, right); + } + + // Put pivot in the right location. + Swap(keys, left, (hi - 1)); + return left; + } + + private static void Heapsort(T[] keys, int lo, int hi) + { + Debug.Assert(keys != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); + + int n = hi - lo + 1; + for (int i = n / 2; i >= 1; i = i - 1) + { + DownHeap(keys, i, n, lo); + } + for (int i = n; i > 1; i = i - 1) + { + Swap(keys, lo, lo + i - 1); + DownHeap(keys, 1, i - 1, lo); + } + } + + private static void DownHeap(T[] keys, int i, int n, int lo) + { + Debug.Assert(keys != null); + Debug.Assert(lo >= 0); + Debug.Assert(lo < keys.Length); + + T d = keys[lo + i - 1]; + int child; + while (i <= n / 2) + { + child = 2 * i; + if (child < n && (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(keys[lo + child]) < 0)) + { + child++; + } + if (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(d) < 0) + break; + keys[lo + i - 1] = keys[lo + child - 1]; + i = child; + } + keys[lo + i - 1] = d; + } + + private static void InsertionSort(T[] keys, int lo, int hi) + { + Debug.Assert(keys != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi >= lo); + Debug.Assert(hi <= keys.Length); + + int i, j; + T t; + for (i = lo; i < hi; i++) + { + j = i; + t = keys[i + 1]; + while (j >= lo && (t == null || t.CompareTo(keys[j]) < 0)) + { + keys[j + 1] = keys[j]; + j--; + } + keys[j + 1] = t; + } + } + } + + #endregion + + #region ArraySortHelper for paired key and value arrays + + internal partial class ArraySortHelper + { + public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer comparer) + { + Debug.Assert(keys != null, "Check the arguments in the caller!"); // Precondition on interface method + Debug.Assert(values != null, "Check the arguments in the caller!"); + Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); + + // Add a try block here to detect IComparers (or their + // underlying IComparables, etc) that are bogus. + try + { + if (comparer == null || comparer == Comparer.Default) + { + comparer = Comparer.Default; + } + + IntrospectiveSort(keys, values, index, length, comparer); + } + catch (IndexOutOfRangeException) + { + IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); + } + catch (Exception e) + { + throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); + } + } + + private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, IComparer comparer, int a, int b) + { + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(comparer != null); + Debug.Assert(0 <= a && a < keys.Length && a < values.Length); + Debug.Assert(0 <= b && b < keys.Length && b < values.Length); + + if (a != b) + { + if (comparer.Compare(keys[a], keys[b]) > 0) + { + TKey key = keys[a]; + keys[a] = keys[b]; + keys[b] = key; + + TValue value = values[a]; + values[a] = values[b]; + values[b] = value; + } + } + } + + private static void Swap(TKey[] keys, TValue[] values, int i, int j) + { + if (i != j) + { + TKey k = keys[i]; + keys[i] = keys[j]; + keys[j] = k; + + TValue v = values[i]; + values[i] = values[j]; + values[j] = v; + } + } + + internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length, IComparer comparer) + { + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(comparer != null); + Debug.Assert(left >= 0); + Debug.Assert(length >= 0); + Debug.Assert(length <= keys.Length); + Debug.Assert(length + left <= keys.Length); + Debug.Assert(length + left <= values.Length); + + if (length < 2) + return; + + IntroSort(keys, values, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length), comparer); + } + + private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit, IComparer comparer) + { + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi < keys.Length); + + while (hi > lo) + { + int partitionSize = hi - lo + 1; + if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold) + { + if (partitionSize == 1) + { + return; + } + if (partitionSize == 2) + { + SwapIfGreaterWithItems(keys, values, comparer, lo, hi); + return; + } + if (partitionSize == 3) + { + SwapIfGreaterWithItems(keys, values, comparer, lo, hi - 1); + SwapIfGreaterWithItems(keys, values, comparer, lo, hi); + SwapIfGreaterWithItems(keys, values, comparer, hi - 1, hi); + return; + } + + InsertionSort(keys, values, lo, hi, comparer); + return; + } + + if (depthLimit == 0) + { + Heapsort(keys, values, lo, hi, comparer); + return; + } + depthLimit--; + + int p = PickPivotAndPartition(keys, values, lo, hi, comparer); + // Note we've already partitioned around the pivot and do not have to move the pivot again. + IntroSort(keys, values, p + 1, hi, depthLimit, comparer); + hi = p - 1; + } + } + + private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi, IComparer comparer) + { + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); + + // Compute median-of-three. But also partition them, since we've done the comparison. + int middle = lo + ((hi - lo) / 2); + + // Sort lo, mid and hi appropriately, then pick mid as the pivot. + SwapIfGreaterWithItems(keys, values, comparer, lo, middle); // swap the low with the mid point + SwapIfGreaterWithItems(keys, values, comparer, lo, hi); // swap the low with the high + SwapIfGreaterWithItems(keys, values, comparer, middle, hi); // swap the middle with the high + + TKey pivot = keys[middle]; + Swap(keys, values, middle, hi - 1); + int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. + + while (left < right) + { + while (comparer.Compare(keys[++left], pivot) < 0) ; + while (comparer.Compare(pivot, keys[--right]) < 0) ; + + if (left >= right) + break; + + Swap(keys, values, left, right); + } + + // Put pivot in the right location. + Swap(keys, values, left, (hi - 1)); + return left; + } + + private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi, IComparer comparer) + { + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); + + int n = hi - lo + 1; + for (int i = n / 2; i >= 1; i = i - 1) + { + DownHeap(keys, values, i, n, lo, comparer); + } + for (int i = n; i > 1; i = i - 1) + { + Swap(keys, values, lo, lo + i - 1); + DownHeap(keys, values, 1, i - 1, lo, comparer); + } + } + + private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo, IComparer comparer) + { + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(lo < keys.Length); + + TKey d = keys[lo + i - 1]; + TValue dValue = values[lo + i - 1]; + int child; + while (i <= n / 2) + { + child = 2 * i; + if (child < n && comparer.Compare(keys[lo + child - 1], keys[lo + child]) < 0) + { + child++; + } + if (!(comparer.Compare(d, keys[lo + child - 1]) < 0)) + break; + keys[lo + i - 1] = keys[lo + child - 1]; + values[lo + i - 1] = values[lo + child - 1]; + i = child; + } + keys[lo + i - 1] = d; + values[lo + i - 1] = dValue; + } + + private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi, IComparer comparer) + { + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi >= lo); + Debug.Assert(hi <= keys.Length); + + int i, j; + TKey t; + TValue tValue; + for (i = lo; i < hi; i++) + { + j = i; + t = keys[i + 1]; + tValue = values[i + 1]; + while (j >= lo && comparer.Compare(t, keys[j]) < 0) + { + keys[j + 1] = keys[j]; + values[j + 1] = values[j]; + j--; + } + keys[j + 1] = t; + values[j + 1] = tValue; + } + } + } + + internal partial class GenericArraySortHelper + where TKey : IComparable + { + public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer comparer) + { + Debug.Assert(keys != null, "Check the arguments in the caller!"); + Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); + + // Add a try block here to detect IComparers (or their + // underlying IComparables, etc) that are bogus. + try + { + if (comparer == null || comparer == Comparer.Default) + { + IntrospectiveSort(keys, values, index, length); + } + else + { + ArraySortHelper.IntrospectiveSort(keys, values, index, length, comparer); + } + } + catch (IndexOutOfRangeException) + { + IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); + } + catch (Exception e) + { + throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); + } + } + + private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, int a, int b) + { + if (a != b) + { + if (keys[a] != null && keys[a].CompareTo(keys[b]) > 0) + { + TKey key = keys[a]; + keys[a] = keys[b]; + keys[b] = key; + + TValue value = values[a]; + values[a] = values[b]; + values[b] = value; + } + } + } + + private static void Swap(TKey[] keys, TValue[] values, int i, int j) + { + if (i != j) + { + TKey k = keys[i]; + keys[i] = keys[j]; + keys[j] = k; + + TValue v = values[i]; + values[i] = values[j]; + values[j] = v; + } + } + + internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length) + { + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(left >= 0); + Debug.Assert(length >= 0); + Debug.Assert(length <= keys.Length); + Debug.Assert(length + left <= keys.Length); + Debug.Assert(length + left <= values.Length); + + if (length < 2) + return; + + IntroSort(keys, values, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length)); + } + + private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit) + { + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi < keys.Length); + + while (hi > lo) + { + int partitionSize = hi - lo + 1; + if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold) + { + if (partitionSize == 1) + { + return; + } + if (partitionSize == 2) + { + SwapIfGreaterWithItems(keys, values, lo, hi); + return; + } + if (partitionSize == 3) + { + SwapIfGreaterWithItems(keys, values, lo, hi - 1); + SwapIfGreaterWithItems(keys, values, lo, hi); + SwapIfGreaterWithItems(keys, values, hi - 1, hi); + return; + } + + InsertionSort(keys, values, lo, hi); + return; + } + + if (depthLimit == 0) + { + Heapsort(keys, values, lo, hi); + return; + } + depthLimit--; + + int p = PickPivotAndPartition(keys, values, lo, hi); + // Note we've already partitioned around the pivot and do not have to move the pivot again. + IntroSort(keys, values, p + 1, hi, depthLimit); + hi = p - 1; + } + } + + private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi) + { + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); + + // Compute median-of-three. But also partition them, since we've done the comparison. + int middle = lo + ((hi - lo) / 2); + + // Sort lo, mid and hi appropriately, then pick mid as the pivot. + SwapIfGreaterWithItems(keys, values, lo, middle); // swap the low with the mid point + SwapIfGreaterWithItems(keys, values, lo, hi); // swap the low with the high + SwapIfGreaterWithItems(keys, values, middle, hi); // swap the middle with the high + + TKey pivot = keys[middle]; + Swap(keys, values, middle, hi - 1); + int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. + + while (left < right) + { + if (pivot == null) + { + while (left < (hi - 1) && keys[++left] == null) ; + while (right > lo && keys[--right] != null) ; + } + else + { + while (pivot.CompareTo(keys[++left]) > 0) ; + while (pivot.CompareTo(keys[--right]) < 0) ; + } + + if (left >= right) + break; + + Swap(keys, values, left, right); + } + + // Put pivot in the right location. + Swap(keys, values, left, (hi - 1)); + return left; + } + + private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi) + { + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); + + int n = hi - lo + 1; + for (int i = n / 2; i >= 1; i = i - 1) + { + DownHeap(keys, values, i, n, lo); + } + for (int i = n; i > 1; i = i - 1) + { + Swap(keys, values, lo, lo + i - 1); + DownHeap(keys, values, 1, i - 1, lo); + } + } + + private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo) + { + Debug.Assert(keys != null); + Debug.Assert(lo >= 0); + Debug.Assert(lo < keys.Length); + + TKey d = keys[lo + i - 1]; + TValue dValue = values[lo + i - 1]; + int child; + while (i <= n / 2) + { + child = 2 * i; + if (child < n && (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(keys[lo + child]) < 0)) + { + child++; + } + if (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(d) < 0) + break; + keys[lo + i - 1] = keys[lo + child - 1]; + values[lo + i - 1] = values[lo + child - 1]; + i = child; + } + keys[lo + i - 1] = d; + values[lo + i - 1] = dValue; + } + + private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi) + { + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi >= lo); + Debug.Assert(hi <= keys.Length); + + int i, j; + TKey t; + TValue tValue; + for (i = lo; i < hi; i++) + { + j = i; + t = keys[i + 1]; + tValue = values[i + 1]; + while (j >= lo && (t == null || t.CompareTo(keys[j]) < 0)) + { + keys[j + 1] = keys[j]; + values[j + 1] = values[j]; + j--; + } + keys[j + 1] = t; + values[j + 1] = tValue; + } + } + } + + #endregion +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/Dictionary.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/Dictionary.cs index 8fd8d91f0a..623257d3c0 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/Dictionary.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/Dictionary.cs @@ -2,14 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Collections; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Serialization; -#if MONO -using System.Diagnostics.Private; -#endif +using System.Threading; namespace System.Collections.Generic { @@ -38,7 +34,7 @@ namespace System.Collections.Generic [DebuggerDisplay("Count = {Count}")] [Serializable] #if !MONO - [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] + [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] #endif public class Dictionary : IDictionary, IDictionary, IReadOnlyDictionary, ISerializable, IDeserializationCallback { @@ -224,7 +220,7 @@ namespace System.Collections.Generic int i = FindEntry(key); if (i >= 0) return _entries[i].value; ThrowHelper.ThrowKeyNotFoundException(key); - return default(TValue); + return default; } set { @@ -240,9 +236,7 @@ namespace System.Collections.Generic } void ICollection>.Add(KeyValuePair keyValuePair) - { - Add(keyValuePair.Key, keyValuePair.Value); - } + => Add(keyValuePair.Key, keyValuePair.Value); bool ICollection>.Contains(KeyValuePair keyValuePair) { @@ -275,30 +269,43 @@ namespace System.Collections.Generic _count = 0; _freeList = -1; _freeCount = 0; - _version++; Array.Clear(_entries, 0, count); } } public bool ContainsKey(TKey key) - { - return FindEntry(key) >= 0; - } + => FindEntry(key) >= 0; public bool ContainsValue(TValue value) { + Entry[] entries = _entries; if (value == null) { for (int i = 0; i < _count; i++) { - if (_entries[i].hashCode >= 0 && _entries[i].value == null) return true; + if (entries[i].hashCode >= 0 && entries[i].value == null) return true; } } else { - for (int i = 0; i < _count; i++) + if (default(TValue) != null) { - if (_entries[i].hashCode >= 0 && EqualityComparer.Default.Equals(_entries[i].value, value)) return true; + // ValueType: Devirtualize with EqualityComparer.Default intrinsic + for (int i = 0; i < _count; i++) + { + if (entries[i].hashCode >= 0 && EqualityComparer.Default.Equals(entries[i].value, value)) return true; + } + } + else + { + // Object type: Shared Generic, EqualityComparer.Default won't devirtualize + // https://github.com/dotnet/coreclr/issues/17273 + // So cache in a local rather than get EqualityComparer per loop iteration + EqualityComparer defaultComparer = EqualityComparer.Default; + for (int i = 0; i < _count; i++) + { + if (entries[i].hashCode >= 0 && defaultComparer.Equals(entries[i].value, value)) return true; + } } } return false; @@ -311,7 +318,7 @@ namespace System.Collections.Generic ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (index < 0 || index > array.Length) + if ((uint)index > (uint)array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } @@ -333,14 +340,10 @@ namespace System.Collections.Generic } public Enumerator GetEnumerator() - { - return new Enumerator(this, Enumerator.KeyValuePair); - } + => new Enumerator(this, Enumerator.KeyValuePair); IEnumerator> IEnumerable>.GetEnumerator() - { - return new Enumerator(this, Enumerator.KeyValuePair); - } + => new Enumerator(this, Enumerator.KeyValuePair); public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { @@ -371,6 +374,7 @@ namespace System.Collections.Generic int i = -1; int[] buckets = _buckets; Entry[] entries = _entries; + int collisionCount = 0; if (buckets != null) { IEqualityComparer comparer = _comparer; @@ -379,17 +383,53 @@ namespace System.Collections.Generic int hashCode = key.GetHashCode() & 0x7FFFFFFF; // Value in _buckets is 1-based i = buckets[hashCode % buckets.Length] - 1; - do + if (default(TKey) != null) { - // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 - // Test in if to drop range check for following array access - if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && EqualityComparer.Default.Equals(entries[i].key, key))) + // ValueType: Devirtualize with EqualityComparer.Default intrinsic + do { - break; - } + // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 + // Test in if to drop range check for following array access + if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && EqualityComparer.Default.Equals(entries[i].key, key))) + { + break; + } - i = entries[i].next; - } while (true); + i = entries[i].next; + if (collisionCount >= entries.Length) + { + // The chain of entries forms a loop; which means a concurrent update has happened. + // Break out of the loop and throw, rather than looping forever. + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } + collisionCount++; + } while (true); + } + else + { + // Object type: Shared Generic, EqualityComparer.Default won't devirtualize + // https://github.com/dotnet/coreclr/issues/17273 + // So cache in a local rather than get EqualityComparer per loop iteration + EqualityComparer defaultComparer = EqualityComparer.Default; + do + { + // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 + // Test in if to drop range check for following array access + if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && defaultComparer.Equals(entries[i].key, key))) + { + break; + } + + i = entries[i].next; + if (collisionCount >= entries.Length) + { + // The chain of entries forms a loop; which means a concurrent update has happened. + // Break out of the loop and throw, rather than looping forever. + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } + collisionCount++; + } while (true); + } } else { @@ -407,6 +447,13 @@ namespace System.Collections.Generic } i = entries[i].next; + if (collisionCount >= entries.Length) + { + // The chain of entries forms a loop; which means a concurrent update has happened. + // Break out of the loop and throw, rather than looping forever. + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } + collisionCount++; } while (true); } } @@ -449,35 +496,87 @@ namespace System.Collections.Generic if (comparer == null) { - do + if (default(TKey) != null) { - // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 - // Test uint in if rather than loop condition to drop range check for following array access - if ((uint)i >= (uint)entries.Length) + // ValueType: Devirtualize with EqualityComparer.Default intrinsic + do { - break; - } - - if (entries[i].hashCode == hashCode && EqualityComparer.Default.Equals(entries[i].key, key)) - { - if (behavior == InsertionBehavior.OverwriteExisting) + // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 + // Test uint in if rather than loop condition to drop range check for following array access + if ((uint)i >= (uint)entries.Length) { - entries[i].value = value; - _version++; - return true; + break; } - if (behavior == InsertionBehavior.ThrowOnExisting) + if (entries[i].hashCode == hashCode && EqualityComparer.Default.Equals(entries[i].key, key)) { - ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key); + if (behavior == InsertionBehavior.OverwriteExisting) + { + entries[i].value = value; + _version++; + return true; + } + + if (behavior == InsertionBehavior.ThrowOnExisting) + { + ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key); + } + + return false; } - return false; - } + i = entries[i].next; + if (collisionCount >= entries.Length) + { + // The chain of entries forms a loop; which means a concurrent update has happened. + // Break out of the loop and throw, rather than looping forever. + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } + collisionCount++; + } while (true); + } + else + { + // Object type: Shared Generic, EqualityComparer.Default won't devirtualize + // https://github.com/dotnet/coreclr/issues/17273 + // So cache in a local rather than get EqualityComparer per loop iteration + EqualityComparer defaultComparer = EqualityComparer.Default; + do + { + // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 + // Test uint in if rather than loop condition to drop range check for following array access + if ((uint)i >= (uint)entries.Length) + { + break; + } - i = entries[i].next; - collisionCount++; - } while (true); + if (entries[i].hashCode == hashCode && defaultComparer.Equals(entries[i].key, key)) + { + if (behavior == InsertionBehavior.OverwriteExisting) + { + entries[i].value = value; + _version++; + return true; + } + + if (behavior == InsertionBehavior.ThrowOnExisting) + { + ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key); + } + + return false; + } + + i = entries[i].next; + if (collisionCount >= entries.Length) + { + // The chain of entries forms a loop; which means a concurrent update has happened. + // Break out of the loop and throw, rather than looping forever. + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } + collisionCount++; + } while (true); + } } else { @@ -508,14 +607,17 @@ namespace System.Collections.Generic } i = entries[i].next; + if (collisionCount >= entries.Length) + { + // The chain of entries forms a loop; which means a concurrent update has happened. + // Break out of the loop and throw, rather than looping forever. + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } collisionCount++; } while (true); } - // Can be improved with "Ref Local Reassignment" - // https://github.com/dotnet/csharplang/blob/master/proposals/ref-local-reassignment.md - bool resized = false; bool updateFreeList = false; int index; if (_freeCount > 0) @@ -530,14 +632,13 @@ namespace System.Collections.Generic if (count == entries.Length) { Resize(); - resized = true; + bucket = ref _buckets[hashCode % _buckets.Length]; } index = count; _count = count + 1; entries = _entries; } - ref int targetBucket = ref resized ? ref _buckets[hashCode % _buckets.Length] : ref bucket; ref Entry entry = ref entries[index]; if (updateFreeList) @@ -546,11 +647,11 @@ namespace System.Collections.Generic } entry.hashCode = hashCode; // Value in _buckets is 1-based - entry.next = targetBucket - 1; + entry.next = bucket - 1; entry.key = key; entry.value = value; // Value in _buckets is 1-based - targetBucket = index + 1; + bucket = index + 1; _version++; #if !MONO @@ -569,8 +670,7 @@ namespace System.Collections.Generic public virtual void OnDeserialization(object sender) { - SerializationInfo siInfo; - HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo); + HashHelpers.SerializationInfoTable.TryGetValue(this, out SerializationInfo siInfo); if (siInfo == null) { @@ -614,9 +714,7 @@ namespace System.Collections.Generic } private void Resize() - { - Resize(HashHelpers.ExpandPrime(_count), false); - } + => Resize(HashHelpers.ExpandPrime(_count), false); private void Resize(int newSize, bool forceNewHashCodes) { @@ -668,47 +766,56 @@ namespace System.Collections.Generic ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } - if (_buckets != null) + int[] buckets = _buckets; + Entry[] entries = _entries; + int collisionCount = 0; + if (buckets != null) { int hashCode = (_comparer?.GetHashCode(key) ?? key.GetHashCode()) & 0x7FFFFFFF; - int bucket = hashCode % _buckets.Length; + int bucket = hashCode % buckets.Length; int last = -1; - // Value in _buckets is 1-based - int i = _buckets[bucket] - 1; + // Value in buckets is 1-based + int i = buckets[bucket] - 1; while (i >= 0) { - ref Entry entry = ref _entries[i]; + ref Entry entry = ref entries[i]; if (entry.hashCode == hashCode && (_comparer?.Equals(entry.key, key) ?? EqualityComparer.Default.Equals(entry.key, key))) { if (last < 0) { - // Value in _buckets is 1-based - _buckets[bucket] = entry.next + 1; + // Value in buckets is 1-based + buckets[bucket] = entry.next + 1; } else { - _entries[last].next = entry.next; + entries[last].next = entry.next; } entry.hashCode = -1; entry.next = _freeList; if (RuntimeHelpers.IsReferenceOrContainsReferences()) { - entry.key = default(TKey); + entry.key = default; } if (RuntimeHelpers.IsReferenceOrContainsReferences()) { - entry.value = default(TValue); + entry.value = default; } _freeList = i; _freeCount++; - _version++; return true; } last = i; i = entry.next; + if (collisionCount >= entries.Length) + { + // The chain of entries forms a loop; which means a concurrent update has happened. + // Break out of the loop and throw, rather than looping forever. + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } + collisionCount++; } } return false; @@ -724,27 +831,30 @@ namespace System.Collections.Generic ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } - if (_buckets != null) + int[] buckets = _buckets; + Entry[] entries = _entries; + int collisionCount = 0; + if (buckets != null) { int hashCode = (_comparer?.GetHashCode(key) ?? key.GetHashCode()) & 0x7FFFFFFF; - int bucket = hashCode % _buckets.Length; + int bucket = hashCode % buckets.Length; int last = -1; - // Value in _buckets is 1-based - int i = _buckets[bucket] - 1; + // Value in buckets is 1-based + int i = buckets[bucket] - 1; while (i >= 0) { - ref Entry entry = ref _entries[i]; + ref Entry entry = ref entries[i]; if (entry.hashCode == hashCode && (_comparer?.Equals(entry.key, key) ?? EqualityComparer.Default.Equals(entry.key, key))) { if (last < 0) { - // Value in _buckets is 1-based - _buckets[bucket] = entry.next + 1; + // Value in buckets is 1-based + buckets[bucket] = entry.next + 1; } else { - _entries[last].next = entry.next; + entries[last].next = entry.next; } value = entry.value; @@ -754,23 +864,29 @@ namespace System.Collections.Generic if (RuntimeHelpers.IsReferenceOrContainsReferences()) { - entry.key = default(TKey); + entry.key = default; } if (RuntimeHelpers.IsReferenceOrContainsReferences()) { - entry.value = default(TValue); + entry.value = default; } _freeList = i; _freeCount++; - _version++; return true; } last = i; i = entry.next; + if (collisionCount >= entries.Length) + { + // The chain of entries forms a loop; which means a concurrent update has happened. + // Break out of the loop and throw, rather than looping forever. + ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); + } + collisionCount++; } } - value = default(TValue); + value = default; return false; } @@ -782,57 +898,37 @@ namespace System.Collections.Generic value = _entries[i].value; return true; } - value = default(TValue); + value = default; return false; } - public bool TryAdd(TKey key, TValue value) => TryInsert(key, value, InsertionBehavior.None); + public bool TryAdd(TKey key, TValue value) + => TryInsert(key, value, InsertionBehavior.None); - bool ICollection>.IsReadOnly - { - get { return false; } - } + bool ICollection>.IsReadOnly => false; void ICollection>.CopyTo(KeyValuePair[] array, int index) - { - CopyTo(array, index); - } + => CopyTo(array, index); void ICollection.CopyTo(Array array, int index) { if (array == null) - { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - } - if (array.Rank != 1) - { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); - } - if (array.GetLowerBound(0) != 0) - { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); - } - - if (index < 0 || index > array.Length) - { + if ((uint)index > (uint)array.Length) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); - } - if (array.Length - index < Count) - { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); - } - KeyValuePair[] pairs = array as KeyValuePair[]; - if (pairs != null) + if (array is KeyValuePair[] pairs) { CopyTo(pairs, index); } - else if (array is DictionaryEntry[]) + else if (array is DictionaryEntry[] dictEntryArray) { - DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; Entry[] entries = _entries; for (int i = 0; i < _count; i++) { @@ -870,9 +966,7 @@ namespace System.Collections.Generic } IEnumerator IEnumerable.GetEnumerator() - { - return new Enumerator(this, Enumerator.KeyValuePair); - } + => new Enumerator(this, Enumerator.KeyValuePair); /// /// Ensures that the dictionary can hold up to 'capacity' entries without any further expansion of its backing storage @@ -884,6 +978,7 @@ namespace System.Collections.Generic int currentCapacity = _entries == null ? 0 : _entries.Length; if (currentCapacity >= capacity) return currentCapacity; + _version++; if (_buckets == null) return Initialize(capacity); int newSize = HashHelpers.GetPrime(capacity); @@ -903,9 +998,7 @@ namespace System.Collections.Generic /// dictionary.TrimExcess(); /// public void TrimExcess() - { - TrimExcess(Count); - } + => TrimExcess(Count); /// /// Sets the capacity of this dictionary to hold up 'capacity' entries without any further expansion of its backing storage @@ -925,6 +1018,7 @@ namespace System.Collections.Generic return; int oldCount = _count; + _version++; Initialize(newSize); Entry[] entries = _entries; int[] buckets = _buckets; @@ -948,10 +1042,7 @@ namespace System.Collections.Generic _freeCount = 0; } - bool ICollection.IsSynchronized - { - get { return false; } - } + bool ICollection.IsSynchronized => false; object ICollection.SyncRoot { @@ -959,31 +1050,19 @@ namespace System.Collections.Generic { if (_syncRoot == null) { - System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); + Interlocked.CompareExchange(ref _syncRoot, new object(), null); } return _syncRoot; } } - bool IDictionary.IsFixedSize - { - get { return false; } - } + bool IDictionary.IsFixedSize => false; - bool IDictionary.IsReadOnly - { - get { return false; } - } + bool IDictionary.IsReadOnly => false; - ICollection IDictionary.Keys - { - get { return (ICollection)Keys; } - } + ICollection IDictionary.Keys => (ICollection)Keys; - ICollection IDictionary.Values - { - get { return (ICollection)Values; } - } + ICollection IDictionary.Values => (ICollection)Values; object IDictionary.this[object key] { @@ -1073,9 +1152,7 @@ namespace System.Collections.Generic } IDictionaryEnumerator IDictionary.GetEnumerator() - { - return new Enumerator(this, Enumerator.DictEntry); - } + => new Enumerator(this, Enumerator.DictEntry); void IDictionary.Remove(object key) { @@ -1091,11 +1168,11 @@ namespace System.Collections.Generic public struct Enumerator : IEnumerator>, IDictionaryEnumerator { - private Dictionary _dictionary; - private int _version; + private readonly Dictionary _dictionary; + private readonly int _version; private int _index; private KeyValuePair _current; - private int _getEnumeratorRetType; // What should Enumerator.Current return? + private readonly int _getEnumeratorRetType; // What should Enumerator.Current return? internal const int DictEntry = 1; internal const int KeyValuePair = 2; @@ -1117,7 +1194,7 @@ namespace System.Collections.Generic } // Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends. - // dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue + // dictionary.count+1 could be negative if dictionary.count is int.MaxValue while ((uint)_index < (uint)_dictionary._count) { ref Entry entry = ref _dictionary._entries[_index++]; @@ -1134,10 +1211,7 @@ namespace System.Collections.Generic return false; } - public KeyValuePair Current - { - get { return _current; } - } + public KeyValuePair Current => _current; public void Dispose() { @@ -1154,7 +1228,7 @@ namespace System.Collections.Generic if (_getEnumeratorRetType == DictEntry) { - return new System.Collections.DictionaryEntry(_current.Key, _current.Value); + return new DictionaryEntry(_current.Key, _current.Value); } else { @@ -1233,9 +1307,7 @@ namespace System.Collections.Generic } public Enumerator GetEnumerator() - { - return new Enumerator(_dictionary); - } + => new Enumerator(_dictionary); public void CopyTo(TKey[] array, int index) { @@ -1262,30 +1334,18 @@ namespace System.Collections.Generic } } - public int Count - { - get { return _dictionary.Count; } - } + public int Count => _dictionary.Count; - bool ICollection.IsReadOnly - { - get { return true; } - } + bool ICollection.IsReadOnly => true; void ICollection.Add(TKey item) - { - ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); - } + => ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); void ICollection.Clear() - { - ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); - } + => ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); bool ICollection.Contains(TKey item) - { - return _dictionary.ContainsKey(item); - } + => _dictionary.ContainsKey(item); bool ICollection.Remove(TKey item) { @@ -1294,44 +1354,25 @@ namespace System.Collections.Generic } IEnumerator IEnumerable.GetEnumerator() - { - return new Enumerator(_dictionary); - } + => new Enumerator(_dictionary); IEnumerator IEnumerable.GetEnumerator() - { - return new Enumerator(_dictionary); - } + => new Enumerator(_dictionary); void ICollection.CopyTo(Array array, int index) { if (array == null) - { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - } - if (array.Rank != 1) - { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); - } - if (array.GetLowerBound(0) != 0) - { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); - } - - if (index < 0 || index > array.Length) - { + if ((uint)index > (uint)array.Length) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); - } - if (array.Length - index < _dictionary.Count) - { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); - } - TKey[] keys = array as TKey[]; - if (keys != null) + if (array is TKey[] keys) { CopyTo(keys, index); } @@ -1359,24 +1400,18 @@ namespace System.Collections.Generic } } - bool ICollection.IsSynchronized - { - get { return false; } - } + bool ICollection.IsSynchronized => false; - object ICollection.SyncRoot - { - get { return ((ICollection)_dictionary).SyncRoot; } - } + object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; #if MONO [Serializable] #endif - public struct Enumerator : IEnumerator, System.Collections.IEnumerator + public struct Enumerator : IEnumerator, IEnumerator { - private Dictionary _dictionary; + private readonly Dictionary _dictionary; private int _index; - private int _version; + private readonly int _version; private TKey _currentKey; internal Enumerator(Dictionary dictionary) @@ -1384,7 +1419,7 @@ namespace System.Collections.Generic _dictionary = dictionary; _version = dictionary._version; _index = 0; - _currentKey = default(TKey); + _currentKey = default; } public void Dispose() @@ -1410,19 +1445,13 @@ namespace System.Collections.Generic } _index = _dictionary._count + 1; - _currentKey = default(TKey); + _currentKey = default; return false; } - public TKey Current - { - get - { - return _currentKey; - } - } + public TKey Current => _currentKey; - object System.Collections.IEnumerator.Current + object IEnumerator.Current { get { @@ -1435,7 +1464,7 @@ namespace System.Collections.Generic } } - void System.Collections.IEnumerator.Reset() + void IEnumerator.Reset() { if (_version != _dictionary._version) { @@ -1443,7 +1472,7 @@ namespace System.Collections.Generic } _index = 0; - _currentKey = default(TKey); + _currentKey = default; } } } @@ -1467,9 +1496,7 @@ namespace System.Collections.Generic } public Enumerator GetEnumerator() - { - return new Enumerator(_dictionary); - } + => new Enumerator(_dictionary); public void CopyTo(TValue[] array, int index) { @@ -1496,20 +1523,12 @@ namespace System.Collections.Generic } } - public int Count - { - get { return _dictionary.Count; } - } + public int Count => _dictionary.Count; - bool ICollection.IsReadOnly - { - get { return true; } - } + bool ICollection.IsReadOnly => true; void ICollection.Add(TValue item) - { - ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); - } + => ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); bool ICollection.Remove(TValue item) { @@ -1518,52 +1537,31 @@ namespace System.Collections.Generic } void ICollection.Clear() - { - ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); - } + => ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); bool ICollection.Contains(TValue item) - { - return _dictionary.ContainsValue(item); - } + => _dictionary.ContainsValue(item); IEnumerator IEnumerable.GetEnumerator() - { - return new Enumerator(_dictionary); - } + => new Enumerator(_dictionary); IEnumerator IEnumerable.GetEnumerator() - { - return new Enumerator(_dictionary); - } + => new Enumerator(_dictionary); void ICollection.CopyTo(Array array, int index) { if (array == null) - { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - } - if (array.Rank != 1) - { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); - } - if (array.GetLowerBound(0) != 0) - { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); - } - - if (index < 0 || index > array.Length) - { + if ((uint)index > (uint)array.Length) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); - } - if (array.Length - index < _dictionary.Count) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); - TValue[] values = array as TValue[]; - if (values != null) + if (array is TValue[] values) { CopyTo(values, index); } @@ -1591,24 +1589,18 @@ namespace System.Collections.Generic } } - bool ICollection.IsSynchronized - { - get { return false; } - } + bool ICollection.IsSynchronized => false; - object ICollection.SyncRoot - { - get { return ((ICollection)_dictionary).SyncRoot; } - } + object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; #if MONO [Serializable] #endif - public struct Enumerator : IEnumerator, System.Collections.IEnumerator + public struct Enumerator : IEnumerator, IEnumerator { - private Dictionary _dictionary; + private readonly Dictionary _dictionary; private int _index; - private int _version; + private readonly int _version; private TValue _currentValue; internal Enumerator(Dictionary dictionary) @@ -1616,7 +1608,7 @@ namespace System.Collections.Generic _dictionary = dictionary; _version = dictionary._version; _index = 0; - _currentValue = default(TValue); + _currentValue = default; } public void Dispose() @@ -1641,19 +1633,13 @@ namespace System.Collections.Generic } } _index = _dictionary._count + 1; - _currentValue = default(TValue); + _currentValue = default; return false; } - public TValue Current - { - get - { - return _currentValue; - } - } + public TValue Current => _currentValue; - object System.Collections.IEnumerator.Current + object IEnumerator.Current { get { @@ -1666,14 +1652,14 @@ namespace System.Collections.Generic } } - void System.Collections.IEnumerator.Reset() + void IEnumerator.Reset() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } _index = 0; - _currentValue = default(TValue); + _currentValue = default; } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/KeyNotFoundException.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/KeyNotFoundException.cs index 48eddb8745..3990e13784 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/KeyNotFoundException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/KeyNotFoundException.cs @@ -17,13 +17,13 @@ namespace System.Collections.Generic HResult = HResults.COR_E_KEYNOTFOUND; } - public KeyNotFoundException(String message) + public KeyNotFoundException(string message) : base(message) { HResult = HResults.COR_E_KEYNOTFOUND; } - public KeyNotFoundException(String message, Exception innerException) + public KeyNotFoundException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_KEYNOTFOUND; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/List.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/List.cs index 56bbea895e..698abe9cf5 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/List.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/List.cs @@ -5,6 +5,7 @@ using System.Collections.ObjectModel; using System.Diagnostics; using System.Runtime.CompilerServices; +using System.Threading; namespace System.Collections.Generic { @@ -17,8 +18,8 @@ namespace System.Collections.Generic [DebuggerTypeProxy(typeof(ICollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] [Serializable] - [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public class List : IList, System.Collections.IList, IReadOnlyList + [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] + public class List : IList, IList, IReadOnlyList { private const int DefaultCapacity = 4; @@ -63,8 +64,7 @@ namespace System.Collections.Generic if (collection == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); - ICollection c = collection as ICollection; - if (c != null) + if (collection is ICollection c) { int count = c.Count; if (count == 0) @@ -123,44 +123,26 @@ namespace System.Collections.Generic } // Read-only property describing how many elements are in the List. - public int Count - { - get - { - return _size; - } - } + public int Count => _size; - bool System.Collections.IList.IsFixedSize - { - get { return false; } - } + bool IList.IsFixedSize => false; // Is this List read-only? - bool ICollection.IsReadOnly - { - get { return false; } - } + bool ICollection.IsReadOnly => false; - bool System.Collections.IList.IsReadOnly - { - get { return false; } - } + bool IList.IsReadOnly => false; // Is this List synchronized (thread-safe)? - bool System.Collections.ICollection.IsSynchronized - { - get { return false; } - } + bool ICollection.IsSynchronized => false; // Synchronization root for this object. - object System.Collections.ICollection.SyncRoot + object ICollection.SyncRoot { get { if (_syncRoot == null) { - System.Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); + Interlocked.CompareExchange(ref _syncRoot, new object(), null); } return _syncRoot; } @@ -197,7 +179,7 @@ namespace System.Collections.Generic return ((value is T) || (value == null && default(T) == null)); } - object System.Collections.IList.this[int index] + object IList.this[int index] { get { @@ -225,9 +207,9 @@ namespace System.Collections.Generic [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T item) { - var array = _items; - var size = _size; _version++; + T[] array = _items; + int size = _size; if ((uint)size < (uint)array.Length) { _size = size + 1; @@ -243,13 +225,13 @@ namespace System.Collections.Generic [MethodImpl(MethodImplOptions.NoInlining)] private void AddWithResize(T item) { - var size = _size; + int size = _size; EnsureCapacity(size + 1); _size = size + 1; _items[size] = item; } - int System.Collections.IList.Add(Object item) + int IList.Add(object item) { ThrowHelper.IfNullAndNullsAreIllegalThenThrow(item, ExceptionArgument.item); @@ -270,14 +252,10 @@ namespace System.Collections.Generic // capacity or the new size, whichever is larger. // public void AddRange(IEnumerable collection) - { - InsertRange(_size, collection); - } + => InsertRange(_size, collection); public ReadOnlyCollection AsReadOnly() - { - return new ReadOnlyCollection(this); - } + => new ReadOnlyCollection(this); // Searches a section of the list for a given element using a binary search // algorithm. Elements of the list are compared to the search value using @@ -312,25 +290,20 @@ namespace System.Collections.Generic } public int BinarySearch(T item) - { - return BinarySearch(0, Count, item, null); - } + => BinarySearch(0, Count, item, null); public int BinarySearch(T item, IComparer comparer) - { - return BinarySearch(0, Count, item, comparer); - } - + => BinarySearch(0, Count, item, comparer); // Clears the contents of List. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { + _version++; if (RuntimeHelpers.IsReferenceOrContainsReferences()) { int size = _size; _size = 0; - _version++; if (size > 0) { Array.Clear(_items, 0, size); // Clear the elements so that the gc can reclaim the references. @@ -339,7 +312,6 @@ namespace System.Collections.Generic else { _size = 0; - _version++; } } @@ -360,7 +332,7 @@ namespace System.Collections.Generic return _size != 0 && IndexOf(item) != -1; } - bool System.Collections.IList.Contains(object item) + bool IList.Contains(object item) { if (IsCompatibleObject(item)) { @@ -388,13 +360,11 @@ namespace System.Collections.Generic // Copies this List into array, which must be of a // compatible array type. public void CopyTo(T[] array) - { - CopyTo(array, 0); - } + => CopyTo(array, 0); // Copies this List into array, which must be of a // compatible array type. - void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) + void ICollection.CopyTo(Array array, int arrayIndex) { if ((array != null) && (array.Rank != 1)) { @@ -452,9 +422,7 @@ namespace System.Collections.Generic } public bool Exists(Predicate match) - { - return FindIndex(match) != -1; - } + => FindIndex(match) != -1; public T Find(Predicate match) { @@ -470,7 +438,7 @@ namespace System.Collections.Generic return _items[i]; } } - return default(T); + return default; } public List FindAll(Predicate match) @@ -492,14 +460,10 @@ namespace System.Collections.Generic } public int FindIndex(Predicate match) - { - return FindIndex(0, _size, match); - } + => FindIndex(0, _size, match); public int FindIndex(int startIndex, Predicate match) - { - return FindIndex(startIndex, _size - startIndex, match); - } + => FindIndex(startIndex, _size - startIndex, match); public int FindIndex(int startIndex, int count, Predicate match) { @@ -540,18 +504,14 @@ namespace System.Collections.Generic return _items[i]; } } - return default(T); + return default; } public int FindLastIndex(Predicate match) - { - return FindLastIndex(_size - 1, _size, match); - } + => FindLastIndex(_size - 1, _size, match); public int FindLastIndex(int startIndex, Predicate match) - { - return FindLastIndex(startIndex, startIndex + 1, match); - } + => FindLastIndex(startIndex, startIndex + 1, match); public int FindLastIndex(int startIndex, int count, Predicate match) { @@ -622,19 +582,13 @@ namespace System.Collections.Generic // GetObject methods of the enumerator will throw an exception. // public Enumerator GetEnumerator() - { - return new Enumerator(this); - } + => new Enumerator(this); IEnumerator IEnumerable.GetEnumerator() - { - return new Enumerator(this); - } + => new Enumerator(this); - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return new Enumerator(this); - } + IEnumerator IEnumerable.GetEnumerator() + => new Enumerator(this); public List GetRange(int index, int count) { @@ -669,11 +623,9 @@ namespace System.Collections.Generic // search. // public int IndexOf(T item) - { - return Array.IndexOf(_items, item, 0, _size); - } + => Array.IndexOf(_items, item, 0, _size); - int System.Collections.IList.IndexOf(object item) + int IList.IndexOf(object item) { if (IsCompatibleObject(item)) { @@ -739,7 +691,7 @@ namespace System.Collections.Generic _version++; } - void System.Collections.IList.Insert(int index, Object item) + void IList.Insert(int index, object item) { ThrowHelper.IfNullAndNullsAreIllegalThenThrow(item, ExceptionArgument.item); @@ -770,9 +722,8 @@ namespace System.Collections.Generic ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } - ICollection c = collection as ICollection; - if (c != null) - { // if collection is ICollection + if (collection is ICollection c) + { int count = c.Count; if (count > 0) { @@ -905,7 +856,7 @@ namespace System.Collections.Generic return false; } - void System.Collections.IList.Remove(object item) + void IList.Remove(object item) { if (IsCompatibleObject(item)) { @@ -967,7 +918,7 @@ namespace System.Collections.Generic } if (RuntimeHelpers.IsReferenceOrContainsReferences()) { - _items[_size] = default(T); + _items[_size] = default; } _version++; } @@ -990,7 +941,6 @@ namespace System.Collections.Generic if (count > 0) { - int i = _size; _size -= count; if (index < _size) { @@ -1007,9 +957,7 @@ namespace System.Collections.Generic // Reverses the elements in this list. public void Reverse() - { - Reverse(0, Count); - } + => Reverse(0, Count); // Reverses the elements in a range of this list. Following a call to this // method, an element in the range given by index and count @@ -1041,16 +989,12 @@ namespace System.Collections.Generic // Sorts the elements in this list. Uses the default comparer and // Array.Sort. public void Sort() - { - Sort(0, Count, null); - } + => Sort(0, Count, null); // Sorts the elements in this list. Uses Array.Sort with the // provided comparer. public void Sort(IComparer comparer) - { - Sort(0, Count, comparer); - } + => Sort(0, Count, comparer); // Sorts the elements in a section of this list. The sort compares the // elements to each other using the given IComparer interface. If @@ -1150,9 +1094,9 @@ namespace System.Collections.Generic Debug.Assert(enumerable != null); Debug.Assert(!(enumerable is ICollection), "We should have optimized for this beforehand."); + _version++; // Even if the enumerable has no items, we can update _version. using (IEnumerator en = enumerable.GetEnumerator()) { - _version++; // Even if the enumerable has no items, we can update _version. while (en.MoveNext()) { @@ -1170,11 +1114,11 @@ namespace System.Collections.Generic } } - public struct Enumerator : IEnumerator, System.Collections.IEnumerator + public struct Enumerator : IEnumerator, IEnumerator { - private List _list; + private readonly List _list; private int _index; - private int _version; + private readonly int _version; private T _current; internal Enumerator(List list) @@ -1182,7 +1126,7 @@ namespace System.Collections.Generic _list = list; _index = 0; _version = list._version; - _current = default(T); + _current = default; } public void Dispose() @@ -1210,19 +1154,13 @@ namespace System.Collections.Generic } _index = _list._size + 1; - _current = default(T); + _current = default; return false; } - public T Current - { - get - { - return _current; - } - } + public T Current => _current; - object System.Collections.IEnumerator.Current + object IEnumerator.Current { get { @@ -1234,7 +1172,7 @@ namespace System.Collections.Generic } } - void System.Collections.IEnumerator.Reset() + void IEnumerator.Reset() { if (_version != _list._version) { @@ -1242,7 +1180,7 @@ namespace System.Collections.Generic } _index = 0; - _current = default(T); + _current = default; } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/NonRandomizedStringEqualityComparer.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/NonRandomizedStringEqualityComparer.cs index 72f62c2b9a..91b7820617 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/NonRandomizedStringEqualityComparer.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/NonRandomizedStringEqualityComparer.cs @@ -11,12 +11,8 @@ namespace System.Collections.Generic // keeps the performance not affected till we hit collision threshold and then we switch to the comparer which is using // randomized string hashing. [Serializable] // Required for compatibility with .NET Core 2.0 as we exposed the NonRandomizedStringEqualityComparer inside the serialization blob -#if CORERT - public -#else - internal -#endif - sealed class NonRandomizedStringEqualityComparer : EqualityComparer, ISerializable + // Needs to be public to support binary serialization compatibility + public sealed class NonRandomizedStringEqualityComparer : EqualityComparer, ISerializable { internal static new IEqualityComparer Default { get; } = new NonRandomizedStringEqualityComparer(); @@ -27,7 +23,7 @@ namespace System.Collections.Generic public sealed override bool Equals(string x, string y) => string.Equals(x, y); - public sealed override int GetHashCode(string obj) => obj?.GetLegacyNonRandomizedHashCode() ?? 0; + public sealed override int GetHashCode(string obj) => obj?.GetNonRandomizedHashCode() ?? 0; public void GetObjectData(SerializationInfo info, StreamingContext context) { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/ValueListBuilder.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/ValueListBuilder.cs index 5fbeeec9c3..aea6052f03 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/ValueListBuilder.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Generic/ValueListBuilder.cs @@ -3,7 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Buffers; -using System.Diagnostics.Private; +using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Collections.Generic @@ -21,7 +21,16 @@ namespace System.Collections.Generic _pos = 0; } - public int Length => _pos; + public int Length + { + get => _pos; + set + { + Debug.Assert(value >= 0); + Debug.Assert(value <= _span.Length); + _pos = value; + } + } public ref T this[int index] { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/HashHelpers.SerializationInfoTable.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/HashHelpers.SerializationInfoTable.cs new file mode 100644 index 0000000000..d91dfd878e --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/HashHelpers.SerializationInfoTable.cs @@ -0,0 +1,29 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +// Used by Hashtable and Dictionary's SeralizationInfo .ctor's to store the SeralizationInfo +// object until OnDeserialization is called. + +using System.Threading; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; + +namespace System.Collections +{ + internal static partial class HashHelpers + { + private static ConditionalWeakTable s_serializationInfoTable; + + public static ConditionalWeakTable SerializationInfoTable + { + get + { + if (s_serializationInfoTable == null) + Interlocked.CompareExchange(ref s_serializationInfoTable, new ConditionalWeakTable(), null); + + return s_serializationInfoTable; + } + } + } +} \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/HashHelpers.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/HashHelpers.cs index 49cff85b58..ba2c75c89c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/HashHelpers.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/HashHelpers.cs @@ -2,17 +2,18 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. + using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Runtime.Serialization; -using System.Threading; namespace System.Collections { - internal static class HashHelpers + internal static partial class HashHelpers { public const int HashCollisionThreshold = 100; + // This is the maximum prime smaller than Array.MaxArrayLength + public const int MaxPrimeArrayLength = 0x7FEFFFFD; + public const int HashPrime = 101; // Table of prime numbers to use as hash table sizes. @@ -26,12 +27,14 @@ namespace System.Collections // hashtable operations such as add. Having a prime guarantees that double // hashing does not lead to infinite loops. IE, your hash function will be // h1(key) + i*h2(key), 0 <= i < size. h2 and the size must be relatively prime. + // We prefer the low computation costs of higher prime numbers over the increased + // memory allocation of a fixed prime number i.e. when right sizing a HashSet. public static readonly int[] primes = { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, - 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369}; + 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 }; public static bool IsPrime(int candidate) { @@ -56,12 +59,13 @@ namespace System.Collections for (int i = 0; i < primes.Length; i++) { int prime = primes[i]; - if (prime >= min) return prime; + if (prime >= min) + return prime; } //outside of our predefined table. //compute the hard way. - for (int i = (min | 1); i < Int32.MaxValue; i += 2) + for (int i = (min | 1); i < int.MaxValue; i += 2) { if (IsPrime(i) && ((i - 1) % HashPrime != 0)) return i; @@ -74,7 +78,7 @@ namespace System.Collections { int newSize = 2 * oldSize; - // Allow the hashtables to grow to maximum possible size (~2G elements) before encoutering capacity overflow. + // Allow the hashtables to grow to maximum possible size (~2G elements) before encountering capacity overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast if ((uint)newSize > MaxPrimeArrayLength && MaxPrimeArrayLength > oldSize) { @@ -84,25 +88,5 @@ namespace System.Collections return GetPrime(newSize); } - - - // This is the maximum prime smaller than Array.MaxArrayLength - public const int MaxPrimeArrayLength = 0x7FEFFFFD; - - - // Used by Hashtable and Dictionary's SeralizationInfo .ctor's to store the SeralizationInfo - // object until OnDeserialization is called. - private static ConditionalWeakTable s_serializationInfoTable; - - internal static ConditionalWeakTable SerializationInfoTable - { - get - { - if (s_serializationInfoTable == null) - Interlocked.CompareExchange(ref s_serializationInfoTable, new ConditionalWeakTable(), null); - - return s_serializationInfoTable; - } - } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/Hashtable.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Hashtable.cs new file mode 100644 index 0000000000..1c3139d271 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/Hashtable.cs @@ -0,0 +1,1650 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/*============================================================ +** +** Class: Hashtable +** +** Purpose: Represents a collection of key/value pairs +** that are organized based on the hash code +** of the key. +** +===========================================================*/ + +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; +using System.Threading; + +namespace System.Collections +{ + // The Hashtable class represents a dictionary of associated keys and values + // with constant lookup time. + // + // Objects used as keys in a hashtable must implement the GetHashCode + // and Equals methods (or they can rely on the default implementations + // inherited from Object if key equality is simply reference + // equality). Furthermore, the GetHashCode and Equals methods of + // a key object must produce the same results given the same parameters for the + // entire time the key is present in the hashtable. In practical terms, this + // means that key objects should be immutable, at least for the time they are + // used as keys in a hashtable. + // + // When entries are added to a hashtable, they are placed into + // buckets based on the hashcode of their keys. Subsequent lookups of + // keys will use the hashcode of the keys to only search a particular bucket, + // thus substantially reducing the number of key comparisons required to find + // an entry. A hashtable's maximum load factor, which can be specified + // when the hashtable is instantiated, determines the maximum ratio of + // hashtable entries to hashtable buckets. Smaller load factors cause faster + // average lookup times at the cost of increased memory consumption. The + // default maximum load factor of 1.0 generally provides the best balance + // between speed and size. As entries are added to a hashtable, the hashtable's + // actual load factor increases, and when the actual load factor reaches the + // maximum load factor value, the number of buckets in the hashtable is + // automatically increased by approximately a factor of two (to be precise, the + // number of hashtable buckets is increased to the smallest prime number that + // is larger than twice the current number of hashtable buckets). + // + // Each object provides their own hash function, accessed by calling + // GetHashCode(). However, one can write their own object + // implementing IEqualityComparer and pass it to a constructor on + // the Hashtable. That hash function (and the equals method on the + // IEqualityComparer) would be used for all objects in the table. + // + [DebuggerTypeProxy(typeof(System.Collections.Hashtable.HashtableDebugView))] + [DebuggerDisplay("Count = {Count}")] + [Serializable] + [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] + public class Hashtable : IDictionary, ISerializable, IDeserializationCallback, ICloneable + { + /* + This Hashtable uses double hashing. There are hashsize buckets in the + table, and each bucket can contain 0 or 1 element. We use a bit to mark + whether there's been a collision when we inserted multiple elements + (ie, an inserted item was hashed at least a second time and we probed + this bucket, but it was already in use). Using the collision bit, we + can terminate lookups & removes for elements that aren't in the hash + table more quickly. We steal the most significant bit from the hash code + to store the collision bit. + + Our hash function is of the following form: + + h(key, n) = h1(key) + n*h2(key) + + where n is the number of times we've hit a collided bucket and rehashed + (on this particular lookup). Here are our hash functions: + + h1(key) = GetHash(key); // default implementation calls key.GetHashCode(); + h2(key) = 1 + (((h1(key) >> 5) + 1) % (hashsize - 1)); + + The h1 can return any number. h2 must return a number between 1 and + hashsize - 1 that is relatively prime to hashsize (not a problem if + hashsize is prime). (Knuth's Art of Computer Programming, Vol. 3, p. 528-9) + If this is true, then we are guaranteed to visit every bucket in exactly + hashsize probes, since the least common multiple of hashsize and h2(key) + will be hashsize * h2(key). (This is the first number where adding h2 to + h1 mod hashsize will be 0 and we will search the same bucket twice). + + We previously used a different h2(key, n) that was not constant. That is a + horrifically bad idea, unless you can prove that series will never produce + any identical numbers that overlap when you mod them by hashsize, for all + subranges from i to i+hashsize, for all i. It's not worth investigating, + since there was no clear benefit from using that hash function, and it was + broken. + + For efficiency reasons, we've implemented this by storing h1 and h2 in a + temporary, and setting a variable called seed equal to h1. We do a probe, + and if we collided, we simply add h2 to seed each time through the loop. + + A good test for h2() is to subclass Hashtable, provide your own implementation + of GetHash() that returns a constant, then add many items to the hash table. + Make sure Count equals the number of items you inserted. + + Note that when we remove an item from the hash table, we set the key + equal to buckets, if there was a collision in this bucket. Otherwise + we'd either wipe out the collision bit, or we'd still have an item in + the hash table. + + -- + */ + + private const int InitialSize = 3; + + private const string LoadFactorName = "LoadFactor"; // Do not rename (binary serialization) + private const string VersionName = "Version"; // Do not rename (binary serialization) + private const string ComparerName = "Comparer"; // Do not rename (binary serialization) + private const string HashCodeProviderName = "HashCodeProvider"; // Do not rename (binary serialization) + private const string HashSizeName = "HashSize"; // Must save buckets.Length. Do not rename (binary serialization) + private const string KeysName = "Keys"; // Do not rename (binary serialization) + private const string ValuesName = "Values"; // Do not rename (binary serialization) + private const string KeyComparerName = "KeyComparer"; // Do not rename (binary serialization) + + // Deleted entries have their key set to buckets + + // The hash table data. + // This cannot be serialized + private struct bucket + { + public object key; + public object val; + public int hash_coll; // Store hash code; sign bit means there was a collision. + } + + private bucket[] _buckets; + + // The total number of entries in the hash table. + private int _count; + + // The total number of collision bits set in the hashtable + private int _occupancy; + + private int _loadsize; + private float _loadFactor; + + private volatile int _version; + private volatile bool _isWriterInProgress; + + private ICollection _keys; + private ICollection _values; + + private IEqualityComparer _keycomparer; + private object _syncRoot; + + [Obsolete("Please use EqualityComparer property.")] + protected IHashCodeProvider hcp + { + get + { + if (_keycomparer is CompatibleComparer) + { + return ((CompatibleComparer)_keycomparer).HashCodeProvider; + } + else if (_keycomparer == null) + { + return null; + } + else + { + throw new ArgumentException(SR.Arg_CannotMixComparisonInfrastructure); + } + } + set + { + if (_keycomparer is CompatibleComparer) + { + CompatibleComparer keyComparer = (CompatibleComparer)_keycomparer; + _keycomparer = new CompatibleComparer(value, keyComparer.Comparer); + } + else if (_keycomparer == null) + { + _keycomparer = new CompatibleComparer(value, (IComparer)null); + } + else + { + throw new ArgumentException(SR.Arg_CannotMixComparisonInfrastructure); + } + } + } + + [Obsolete("Please use KeyComparer properties.")] + protected IComparer comparer + { + get + { + if (_keycomparer is CompatibleComparer) + { + return ((CompatibleComparer)_keycomparer).Comparer; + } + else if (_keycomparer == null) + { + return null; + } + else + { + throw new ArgumentException(SR.Arg_CannotMixComparisonInfrastructure); + } + } + set + { + if (_keycomparer is CompatibleComparer) + { + CompatibleComparer keyComparer = (CompatibleComparer)_keycomparer; + _keycomparer = new CompatibleComparer(keyComparer.HashCodeProvider, value); + } + else if (_keycomparer == null) + { + _keycomparer = new CompatibleComparer((IHashCodeProvider)null, value); + } + else + { + throw new ArgumentException(SR.Arg_CannotMixComparisonInfrastructure); + } + } + } + + + protected IEqualityComparer EqualityComparer + { + get + { + return _keycomparer; + } + } + + // Note: this constructor is a bogus constructor that does nothing + // and is for use only with SyncHashtable. + internal Hashtable(bool trash) + { + } + + // Constructs a new hashtable. The hashtable is created with an initial + // capacity of zero and a load factor of 1.0. + public Hashtable() : this(0, 1.0f) + { + } + + // Constructs a new hashtable with the given initial capacity and a load + // factor of 1.0. The capacity argument serves as an indication of + // the number of entries the hashtable will contain. When this number (or + // an approximation) is known, specifying it in the constructor can + // eliminate a number of resizing operations that would otherwise be + // performed when elements are added to the hashtable. + // + public Hashtable(int capacity) : this(capacity, 1.0f) + { + } + + // Constructs a new hashtable with the given initial capacity and load + // factor. The capacity argument serves as an indication of the + // number of entries the hashtable will contain. When this number (or an + // approximation) is known, specifying it in the constructor can eliminate + // a number of resizing operations that would otherwise be performed when + // elements are added to the hashtable. The loadFactor argument + // indicates the maximum ratio of hashtable entries to hashtable buckets. + // Smaller load factors cause faster average lookup times at the cost of + // increased memory consumption. A load factor of 1.0 generally provides + // the best balance between speed and size. + // + public Hashtable(int capacity, float loadFactor) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum); + if (!(loadFactor >= 0.1f && loadFactor <= 1.0f)) + throw new ArgumentOutOfRangeException(nameof(loadFactor), SR.Format(SR.ArgumentOutOfRange_HashtableLoadFactor, .1, 1.0)); + + // Based on perf work, .72 is the optimal load factor for this table. + _loadFactor = 0.72f * loadFactor; + + double rawsize = capacity / _loadFactor; + if (rawsize > int.MaxValue) + throw new ArgumentException(SR.Arg_HTCapacityOverflow, nameof(capacity)); + + // Avoid awfully small sizes + int hashsize = (rawsize > InitialSize) ? HashHelpers.GetPrime((int)rawsize) : InitialSize; + _buckets = new bucket[hashsize]; + + _loadsize = (int)(_loadFactor * hashsize); + _isWriterInProgress = false; + // Based on the current algorithm, loadsize must be less than hashsize. + Debug.Assert(_loadsize < hashsize, "Invalid hashtable loadsize!"); + } + + public Hashtable(int capacity, float loadFactor, IEqualityComparer equalityComparer) : this(capacity, loadFactor) + { + _keycomparer = equalityComparer; + } + + [Obsolete("Please use Hashtable(IEqualityComparer) instead.")] + public Hashtable(IHashCodeProvider hcp, IComparer comparer) + : this(0, 1.0f, hcp, comparer) + { + } + + public Hashtable(IEqualityComparer equalityComparer) : this(0, 1.0f, equalityComparer) + { + } + + [Obsolete("Please use Hashtable(int, IEqualityComparer) instead.")] + public Hashtable(int capacity, IHashCodeProvider hcp, IComparer comparer) + : this(capacity, 1.0f, hcp, comparer) + { + } + + public Hashtable(int capacity, IEqualityComparer equalityComparer) + : this(capacity, 1.0f, equalityComparer) + { + } + + // Constructs a new hashtable containing a copy of the entries in the given + // dictionary. The hashtable is created with a load factor of 1.0. + // + public Hashtable(IDictionary d) : this(d, 1.0f) + { + } + + // Constructs a new hashtable containing a copy of the entries in the given + // dictionary. The hashtable is created with the given load factor. + // + public Hashtable(IDictionary d, float loadFactor) + : this(d, loadFactor, (IEqualityComparer)null) + { + } + + [Obsolete("Please use Hashtable(IDictionary, IEqualityComparer) instead.")] + public Hashtable(IDictionary d, IHashCodeProvider hcp, IComparer comparer) + : this(d, 1.0f, hcp, comparer) + { + } + + public Hashtable(IDictionary d, IEqualityComparer equalityComparer) + : this(d, 1.0f, equalityComparer) + { + } + + [Obsolete("Please use Hashtable(int, float, IEqualityComparer) instead.")] + public Hashtable(int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer) + : this(capacity, loadFactor) + { + if (hcp != null || comparer != null) + { + _keycomparer = new CompatibleComparer(hcp, comparer); + } + } + + [Obsolete("Please use Hashtable(IDictionary, float, IEqualityComparer) instead.")] + public Hashtable(IDictionary d, float loadFactor, IHashCodeProvider hcp, IComparer comparer) + : this((d != null ? d.Count : 0), loadFactor, hcp, comparer) + { + if (d == null) + throw new ArgumentNullException(nameof(d), SR.ArgumentNull_Dictionary); + + IDictionaryEnumerator e = d.GetEnumerator(); + while (e.MoveNext()) + Add(e.Key, e.Value); + } + + public Hashtable(IDictionary d, float loadFactor, IEqualityComparer equalityComparer) + : this((d != null ? d.Count : 0), loadFactor, equalityComparer) + { + if (d == null) + throw new ArgumentNullException(nameof(d), SR.ArgumentNull_Dictionary); + + IDictionaryEnumerator e = d.GetEnumerator(); + while (e.MoveNext()) + Add(e.Key, e.Value); + } + + protected Hashtable(SerializationInfo info, StreamingContext context) + { + //We can't do anything with the keys and values until the entire graph has been deserialized + //and we have a reasonable estimate that GetHashCode is not going to fail. For the time being, + //we'll just cache this. The graph is not valid until OnDeserialization has been called. + HashHelpers.SerializationInfoTable.Add(this, info); + } + + // ?InitHash? is basically an implementation of classic DoubleHashing (see http://en.wikipedia.org/wiki/Double_hashing) + // + // 1) The only ?correctness? requirement is that the ?increment? used to probe + // a. Be non-zero + // b. Be relatively prime to the table size ?hashSize?. (This is needed to insure you probe all entries in the table before you ?wrap? and visit entries already probed) + // 2) Because we choose table sizes to be primes, we just need to insure that the increment is 0 < incr < hashSize + // + // Thus this function would work: Incr = 1 + (seed % (hashSize-1)) + // + // While this works well for ?uniformly distributed? keys, in practice, non-uniformity is common. + // In particular in practice we can see ?mostly sequential? where you get long clusters of keys that ?pack?. + // To avoid bad behavior you want it to be the case that the increment is ?large? even for ?small? values (because small + // values tend to happen more in practice). Thus we multiply ?seed? by a number that will make these small values + // bigger (and not hurt large values). We picked HashPrime (101) because it was prime, and if ?hashSize-1? is not a multiple of HashPrime + // (enforced in GetPrime), then incr has the potential of being every value from 1 to hashSize-1. The choice was largely arbitrary. + // + // Computes the hash function: H(key, i) = h1(key) + i*h2(key, hashSize). + // The out parameter seed is h1(key), while the out parameter + // incr is h2(key, hashSize). Callers of this function should + // add incr each time through a loop. + private uint InitHash(object key, int hashsize, out uint seed, out uint incr) + { + // Hashcode must be positive. Also, we must not use the sign bit, since + // that is used for the collision bit. + uint hashcode = (uint)GetHash(key) & 0x7FFFFFFF; + seed = (uint)hashcode; + // Restriction: incr MUST be between 1 and hashsize - 1, inclusive for + // the modular arithmetic to work correctly. This guarantees you'll + // visit every bucket in the table exactly once within hashsize + // iterations. Violate this and it'll cause obscure bugs forever. + // If you change this calculation for h2(key), update putEntry too! + incr = (uint)(1 + ((seed * HashHelpers.HashPrime) % ((uint)hashsize - 1))); + return hashcode; + } + + // Adds an entry with the given key and value to this hashtable. An + // ArgumentException is thrown if the key is null or if the key is already + // present in the hashtable. + // + public virtual void Add(object key, object value) + { + Insert(key, value, true); + } + + // Removes all entries from this hashtable. + public virtual void Clear() + { + Debug.Assert(!_isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized."); + + if (_count == 0 && _occupancy == 0) + return; + + _isWriterInProgress = true; + for (int i = 0; i < _buckets.Length; i++) + { + _buckets[i].hash_coll = 0; + _buckets[i].key = null; + _buckets[i].val = null; + } + + _count = 0; + _occupancy = 0; + UpdateVersion(); + _isWriterInProgress = false; + } + + // Clone returns a virtually identical copy of this hash table. This does + // a shallow copy - the Objects in the table aren't cloned, only the references + // to those Objects. + public virtual object Clone() + { + bucket[] lbuckets = _buckets; + Hashtable ht = new Hashtable(_count, _keycomparer); + ht._version = _version; + ht._loadFactor = _loadFactor; + ht._count = 0; + + int bucket = lbuckets.Length; + while (bucket > 0) + { + bucket--; + object keyv = lbuckets[bucket].key; + if ((keyv != null) && (keyv != lbuckets)) + { + ht[keyv] = lbuckets[bucket].val; + } + } + + return ht; + } + + // Checks if this hashtable contains the given key. + public virtual bool Contains(object key) + { + return ContainsKey(key); + } + + // Checks if this hashtable contains an entry with the given key. This is + // an O(1) operation. + // + public virtual bool ContainsKey(object key) + { + if (key == null) + { + throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); + } + + uint seed; + uint incr; + // Take a snapshot of buckets, in case another thread resizes table + bucket[] lbuckets = _buckets; + uint hashcode = InitHash(key, lbuckets.Length, out seed, out incr); + int ntry = 0; + + bucket b; + int bucketNumber = (int)(seed % (uint)lbuckets.Length); + do + { + b = lbuckets[bucketNumber]; + if (b.key == null) + { + return false; + } + if (((b.hash_coll & 0x7FFFFFFF) == hashcode) && + KeyEquals(b.key, key)) + return true; + bucketNumber = (int)(((long)bucketNumber + incr) % (uint)lbuckets.Length); + } while (b.hash_coll < 0 && ++ntry < lbuckets.Length); + return false; + } + + + + // Checks if this hashtable contains an entry with the given value. The + // values of the entries of the hashtable are compared to the given value + // using the Object.Equals method. This method performs a linear + // search and is thus be substantially slower than the ContainsKey + // method. + // + public virtual bool ContainsValue(object value) + { + if (value == null) + { + for (int i = _buckets.Length; --i >= 0;) + { + if (_buckets[i].key != null && _buckets[i].key != _buckets && _buckets[i].val == null) + return true; + } + } + else + { + for (int i = _buckets.Length; --i >= 0;) + { + object val = _buckets[i].val; + if (val != null && val.Equals(value)) + return true; + } + } + return false; + } + + // Copies the keys of this hashtable to a given array starting at a given + // index. This method is used by the implementation of the CopyTo method in + // the KeyCollection class. + private void CopyKeys(Array array, int arrayIndex) + { + Debug.Assert(array != null); + Debug.Assert(array.Rank == 1); + + bucket[] lbuckets = _buckets; + for (int i = lbuckets.Length; --i >= 0;) + { + object keyv = lbuckets[i].key; + if ((keyv != null) && (keyv != _buckets)) + { + array.SetValue(keyv, arrayIndex++); + } + } + } + + // Copies the keys of this hashtable to a given array starting at a given + // index. This method is used by the implementation of the CopyTo method in + // the KeyCollection class. + private void CopyEntries(Array array, int arrayIndex) + { + Debug.Assert(array != null); + Debug.Assert(array.Rank == 1); + + bucket[] lbuckets = _buckets; + for (int i = lbuckets.Length; --i >= 0;) + { + object keyv = lbuckets[i].key; + if ((keyv != null) && (keyv != _buckets)) + { + DictionaryEntry entry = new DictionaryEntry(keyv, lbuckets[i].val); + array.SetValue(entry, arrayIndex++); + } + } + } + + // Copies the values in this hash table to an array at + // a given index. Note that this only copies values, and not keys. + public virtual void CopyTo(Array array, int arrayIndex) + { + if (array == null) + throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Array); + if (array.Rank != 1) + throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); + if (arrayIndex < 0) + throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); + if (array.Length - arrayIndex < Count) + throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); + + CopyEntries(array, arrayIndex); + } + + // Copies the values in this Hashtable to an KeyValuePairs array. + // KeyValuePairs is different from Dictionary Entry in that it has special + // debugger attributes on its fields. + + internal virtual KeyValuePairs[] ToKeyValuePairsArray() + { + KeyValuePairs[] array = new KeyValuePairs[_count]; + int index = 0; + bucket[] lbuckets = _buckets; + for (int i = lbuckets.Length; --i >= 0;) + { + object keyv = lbuckets[i].key; + if ((keyv != null) && (keyv != _buckets)) + { + array[index++] = new KeyValuePairs(keyv, lbuckets[i].val); + } + } + + return array; + } + + + // Copies the values of this hashtable to a given array starting at a given + // index. This method is used by the implementation of the CopyTo method in + // the ValueCollection class. + private void CopyValues(Array array, int arrayIndex) + { + Debug.Assert(array != null); + Debug.Assert(array.Rank == 1); + + bucket[] lbuckets = _buckets; + for (int i = lbuckets.Length; --i >= 0;) + { + object keyv = lbuckets[i].key; + if ((keyv != null) && (keyv != _buckets)) + { + array.SetValue(lbuckets[i].val, arrayIndex++); + } + } + } + + // Returns the value associated with the given key. If an entry with the + // given key is not found, the returned value is null. + // + public virtual object this[object key] + { + get + { + if (key == null) + { + throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); + } + + uint seed; + uint incr; + + + // Take a snapshot of buckets, in case another thread does a resize + bucket[] lbuckets = _buckets; + uint hashcode = InitHash(key, lbuckets.Length, out seed, out incr); + int ntry = 0; + + bucket b; + int bucketNumber = (int)(seed % (uint)lbuckets.Length); + do + { + int currentversion; + + // A read operation on hashtable has three steps: + // (1) calculate the hash and find the slot number. + // (2) compare the hashcode, if equal, go to step 3. Otherwise end. + // (3) compare the key, if equal, go to step 4. Otherwise end. + // (4) return the value contained in the bucket. + // After step 3 and before step 4. A writer can kick in a remove the old item and add a new one + // in the same bucket. So in the reader we need to check if the hash table is modified during above steps. + // + // Writers (Insert, Remove, Clear) will set 'isWriterInProgress' flag before it starts modifying + // the hashtable and will ckear the flag when it is done. When the flag is cleared, the 'version' + // will be increased. We will repeat the reading if a writer is in progress or done with the modification + // during the read. + // + // Our memory model guarantee if we pick up the change in bucket from another processor, + // we will see the 'isWriterProgress' flag to be true or 'version' is changed in the reader. + // + SpinWait spin = new SpinWait(); + while (true) + { + // this is volatile read, following memory accesses can not be moved ahead of it. + currentversion = _version; + b = lbuckets[bucketNumber]; + + if (!_isWriterInProgress && (currentversion == _version)) + break; + + spin.SpinOnce(); + } + + if (b.key == null) + { + return null; + } + if (((b.hash_coll & 0x7FFFFFFF) == hashcode) && + KeyEquals(b.key, key)) + return b.val; + bucketNumber = (int)(((long)bucketNumber + incr) % (uint)lbuckets.Length); + } while (b.hash_coll < 0 && ++ntry < lbuckets.Length); + return null; + } + + set + { + Insert(key, value, false); + } + } + + // Increases the bucket count of this hashtable. This method is called from + // the Insert method when the actual load factor of the hashtable reaches + // the upper limit specified when the hashtable was constructed. The number + // of buckets in the hashtable is increased to the smallest prime number + // that is larger than twice the current number of buckets, and the entries + // in the hashtable are redistributed into the new buckets using the cached + // hashcodes. + private void expand() + { + int rawsize = HashHelpers.ExpandPrime(_buckets.Length); + rehash(rawsize); + } + + // We occasionally need to rehash the table to clean up the collision bits. + private void rehash() + { + rehash(_buckets.Length); + } + + private void UpdateVersion() + { + // Version might become negative when version is int.MaxValue, but the oddity will be still be correct. + // So we don't need to special case this. + _version++; + } + + private void rehash(int newsize) + { + // reset occupancy + _occupancy = 0; + + // Don't replace any internal state until we've finished adding to the + // new bucket[]. This serves two purposes: + // 1) Allow concurrent readers to see valid hashtable contents + // at all times + // 2) Protect against an OutOfMemoryException while allocating this + // new bucket[]. + bucket[] newBuckets = new bucket[newsize]; + + // rehash table into new buckets + int nb; + for (nb = 0; nb < _buckets.Length; nb++) + { + bucket oldb = _buckets[nb]; + if ((oldb.key != null) && (oldb.key != _buckets)) + { + int hashcode = oldb.hash_coll & 0x7FFFFFFF; + putEntry(newBuckets, oldb.key, oldb.val, hashcode); + } + } + + // New bucket[] is good to go - replace buckets and other internal state. + _isWriterInProgress = true; + _buckets = newBuckets; + _loadsize = (int)(_loadFactor * newsize); + UpdateVersion(); + _isWriterInProgress = false; + // minimum size of hashtable is 3 now and maximum loadFactor is 0.72 now. + Debug.Assert(_loadsize < newsize, "Our current implementation means this is not possible."); + } + + // Returns an enumerator for this hashtable. + // If modifications made to the hashtable while an enumeration is + // in progress, the MoveNext and Current methods of the + // enumerator will throw an exception. + // + IEnumerator IEnumerable.GetEnumerator() + { + return new HashtableEnumerator(this, HashtableEnumerator.DictEntry); + } + + // Returns a dictionary enumerator for this hashtable. + // If modifications made to the hashtable while an enumeration is + // in progress, the MoveNext and Current methods of the + // enumerator will throw an exception. + // + public virtual IDictionaryEnumerator GetEnumerator() + { + return new HashtableEnumerator(this, HashtableEnumerator.DictEntry); + } + + // Internal method to get the hash code for an Object. This will call + // GetHashCode() on each object if you haven't provided an IHashCodeProvider + // instance. Otherwise, it calls hcp.GetHashCode(obj). + protected virtual int GetHash(object key) + { + if (_keycomparer != null) + return _keycomparer.GetHashCode(key); + return key.GetHashCode(); + } + + // Is this Hashtable read-only? + public virtual bool IsReadOnly + { + get { return false; } + } + + public virtual bool IsFixedSize + { + get { return false; } + } + + // Is this Hashtable synchronized? See SyncRoot property + public virtual bool IsSynchronized + { + get { return false; } + } + + // Internal method to compare two keys. If you have provided an IComparer + // instance in the constructor, this method will call comparer.Compare(item, key). + // Otherwise, it will call item.Equals(key). + // + protected virtual bool KeyEquals(object item, object key) + { + Debug.Assert(key != null, "key can't be null here!"); + if (object.ReferenceEquals(_buckets, item)) + { + return false; + } + + if (object.ReferenceEquals(item, key)) + return true; + + if (_keycomparer != null) + return _keycomparer.Equals(item, key); + return item == null ? false : item.Equals(key); + } + + // Returns a collection representing the keys of this hashtable. The order + // in which the returned collection represents the keys is unspecified, but + // it is guaranteed to be buckets = newBuckets; the same order in which a collection returned by + // GetValues represents the values of the hashtable. + // + // The returned collection is live in the sense that any changes + // to the hash table are reflected in this collection. It is not + // a static copy of all the keys in the hash table. + // + public virtual ICollection Keys + { + get + { + if (_keys == null) + _keys = new KeyCollection(this); + return _keys; + } + } + + // Returns a collection representing the values of this hashtable. The + // order in which the returned collection represents the values is + // unspecified, but it is guaranteed to be the same order in which a + // collection returned by GetKeys represents the keys of the + // hashtable. + // + // The returned collection is live in the sense that any changes + // to the hash table are reflected in this collection. It is not + // a static copy of all the keys in the hash table. + // + public virtual ICollection Values + { + get + { + if (_values == null) + _values = new ValueCollection(this); + return _values; + } + } + + // Inserts an entry into this hashtable. This method is called from the Set + // and Add methods. If the add parameter is true and the given key already + // exists in the hashtable, an exception is thrown. + private void Insert(object key, object nvalue, bool add) + { + if (key == null) + { + throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); + } + + if (_count >= _loadsize) + { + expand(); + } + else if (_occupancy > _loadsize && _count > 100) + { + rehash(); + } + + uint seed; + uint incr; + // Assume we only have one thread writing concurrently. Modify + // buckets to contain new data, as long as we insert in the right order. + uint hashcode = InitHash(key, _buckets.Length, out seed, out incr); + int ntry = 0; + int emptySlotNumber = -1; // We use the empty slot number to cache the first empty slot. We chose to reuse slots + // create by remove that have the collision bit set over using up new slots. + int bucketNumber = (int)(seed % (uint)_buckets.Length); + do + { + // Set emptySlot number to current bucket if it is the first available bucket that we have seen + // that once contained an entry and also has had a collision. + // We need to search this entire collision chain because we have to ensure that there are no + // duplicate entries in the table. + if (emptySlotNumber == -1 && (_buckets[bucketNumber].key == _buckets) && (_buckets[bucketNumber].hash_coll < 0))//(((buckets[bucketNumber].hash_coll & unchecked(0x80000000))!=0))) + emptySlotNumber = bucketNumber; + + // Insert the key/value pair into this bucket if this bucket is empty and has never contained an entry + // OR + // This bucket once contained an entry but there has never been a collision + if ((_buckets[bucketNumber].key == null) || + (_buckets[bucketNumber].key == _buckets && ((_buckets[bucketNumber].hash_coll & unchecked(0x80000000)) == 0))) + { + // If we have found an available bucket that has never had a collision, but we've seen an available + // bucket in the past that has the collision bit set, use the previous bucket instead + if (emptySlotNumber != -1) // Reuse slot + bucketNumber = emptySlotNumber; + + // We pretty much have to insert in this order. Don't set hash + // code until the value & key are set appropriately. + _isWriterInProgress = true; + _buckets[bucketNumber].val = nvalue; + _buckets[bucketNumber].key = key; + _buckets[bucketNumber].hash_coll |= (int)hashcode; + _count++; + UpdateVersion(); + _isWriterInProgress = false; + + return; + } + + // The current bucket is in use + // OR + // it is available, but has had the collision bit set and we have already found an available bucket + if (((_buckets[bucketNumber].hash_coll & 0x7FFFFFFF) == hashcode) && + KeyEquals(_buckets[bucketNumber].key, key)) + { + if (add) + { + throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate__, _buckets[bucketNumber].key, key)); + } + _isWriterInProgress = true; + _buckets[bucketNumber].val = nvalue; + UpdateVersion(); + _isWriterInProgress = false; + + return; + } + + // The current bucket is full, and we have therefore collided. We need to set the collision bit + // unless we have remembered an available slot previously. + if (emptySlotNumber == -1) + {// We don't need to set the collision bit here since we already have an empty slot + if (_buckets[bucketNumber].hash_coll >= 0) + { + _buckets[bucketNumber].hash_coll |= unchecked((int)0x80000000); + _occupancy++; + } + } + + bucketNumber = (int)(((long)bucketNumber + incr) % (uint)_buckets.Length); + } while (++ntry < _buckets.Length); + + // This code is here if and only if there were no buckets without a collision bit set in the entire table + if (emptySlotNumber != -1) + { + // We pretty much have to insert in this order. Don't set hash + // code until the value & key are set appropriately. + _isWriterInProgress = true; + _buckets[emptySlotNumber].val = nvalue; + _buckets[emptySlotNumber].key = key; + _buckets[emptySlotNumber].hash_coll |= (int)hashcode; + _count++; + UpdateVersion(); + _isWriterInProgress = false; + + return; + } + + // If you see this assert, make sure load factor & count are reasonable. + // Then verify that our double hash function (h2, described at top of file) + // meets the requirements described above. You should never see this assert. + Debug.Fail("hash table insert failed! Load factor too high, or our double hashing function is incorrect."); + throw new InvalidOperationException(SR.InvalidOperation_HashInsertFailed); + } + + private void putEntry(bucket[] newBuckets, object key, object nvalue, int hashcode) + { + Debug.Assert(hashcode >= 0, "hashcode >= 0"); // make sure collision bit (sign bit) wasn't set. + + uint seed = (uint)hashcode; + uint incr = unchecked((uint)(1 + ((seed * HashHelpers.HashPrime) % ((uint)newBuckets.Length - 1)))); + int bucketNumber = (int)(seed % (uint)newBuckets.Length); + do + { + if ((newBuckets[bucketNumber].key == null) || (newBuckets[bucketNumber].key == _buckets)) + { + newBuckets[bucketNumber].val = nvalue; + newBuckets[bucketNumber].key = key; + newBuckets[bucketNumber].hash_coll |= hashcode; + return; + } + + if (newBuckets[bucketNumber].hash_coll >= 0) + { + newBuckets[bucketNumber].hash_coll |= unchecked((int)0x80000000); + _occupancy++; + } + bucketNumber = (int)(((long)bucketNumber + incr) % (uint)newBuckets.Length); + } while (true); + } + + // Removes an entry from this hashtable. If an entry with the specified + // key exists in the hashtable, it is removed. An ArgumentException is + // thrown if the key is null. + // + public virtual void Remove(object key) + { + if (key == null) + { + throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); + } + + Debug.Assert(!_isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized."); + + uint seed; + uint incr; + // Assuming only one concurrent writer, write directly into buckets. + uint hashcode = InitHash(key, _buckets.Length, out seed, out incr); + int ntry = 0; + + bucket b; + int bn = (int)(seed % (uint)_buckets.Length); // bucketNumber + do + { + b = _buckets[bn]; + if (((b.hash_coll & 0x7FFFFFFF) == hashcode) && + KeyEquals(b.key, key)) + { + _isWriterInProgress = true; + // Clear hash_coll field, then key, then value + _buckets[bn].hash_coll &= unchecked((int)0x80000000); + if (_buckets[bn].hash_coll != 0) + { + _buckets[bn].key = _buckets; + } + else + { + _buckets[bn].key = null; + } + _buckets[bn].val = null; // Free object references sooner & simplify ContainsValue. + _count--; + UpdateVersion(); + _isWriterInProgress = false; + return; + } + bn = (int)(((long)bn + incr) % (uint)_buckets.Length); + } while (b.hash_coll < 0 && ++ntry < _buckets.Length); + } + + // Returns the object to synchronize on for this hash table. + public virtual object SyncRoot + { + get + { + if (_syncRoot == null) + { + System.Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); + } + return _syncRoot; + } + } + + // Returns the number of associations in this hashtable. + // + public virtual int Count + { + get { return _count; } + } + + // Returns a thread-safe wrapper for a Hashtable. + // + public static Hashtable Synchronized(Hashtable table) + { + if (table == null) + throw new ArgumentNullException(nameof(table)); + return new SyncHashtable(table); + } + + public virtual void GetObjectData(SerializationInfo info, StreamingContext context) + { + if (info == null) + { + throw new ArgumentNullException(nameof(info)); + } + + // This is imperfect - it only works well if all other writes are + // also using our synchronized wrapper. But it's still a good idea. + lock (SyncRoot) + { + // This method hasn't been fully tweaked to be safe for a concurrent writer. + int oldVersion = _version; + info.AddValue(LoadFactorName, _loadFactor); + info.AddValue(VersionName, _version); + + // + // We need to maintain serialization compatibility with Everett and RTM. + // If the comparer is null or a compatible comparer, serialize Hashtable + // in a format that can be deserialized on Everett and RTM. + // + // Also, if the Hashtable is using randomized hashing, serialize the old + // view of the _keycomparer so perevious frameworks don't see the new types +#pragma warning disable 618 + IEqualityComparer keyComparerForSerilization = _keycomparer; + + if (keyComparerForSerilization == null) + { + info.AddValue(ComparerName, null, typeof(IComparer)); + info.AddValue(HashCodeProviderName, null, typeof(IHashCodeProvider)); + } + else if (keyComparerForSerilization is CompatibleComparer) + { + CompatibleComparer c = keyComparerForSerilization as CompatibleComparer; + info.AddValue(ComparerName, c.Comparer, typeof(IComparer)); + info.AddValue(HashCodeProviderName, c.HashCodeProvider, typeof(IHashCodeProvider)); + } + else + { + info.AddValue(KeyComparerName, keyComparerForSerilization, typeof(IEqualityComparer)); + } +#pragma warning restore 618 + + info.AddValue(HashSizeName, _buckets.Length); //This is the length of the bucket array. + object[] serKeys = new object[_count]; + object[] serValues = new object[_count]; + CopyKeys(serKeys, 0); + CopyValues(serValues, 0); + info.AddValue(KeysName, serKeys, typeof(object[])); + info.AddValue(ValuesName, serValues, typeof(object[])); + + // Explicitly check to see if anyone changed the Hashtable while we + // were serializing it. That's a race in their code. + if (_version != oldVersion) + { + throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); + } + } + } + + // + // DeserializationEvent Listener + // + public virtual void OnDeserialization(object sender) + { + if (_buckets != null) + { + // Somebody had a dependency on this hashtable and fixed us up before the ObjectManager got to it. + return; + } + + SerializationInfo siInfo; + HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo); + + if (siInfo == null) + { + throw new SerializationException(SR.Serialization_InvalidOnDeser); + } + + int hashsize = 0; + IComparer c = null; + +#pragma warning disable 618 + IHashCodeProvider hcp = null; +#pragma warning restore 618 + + object[] serKeys = null; + object[] serValues = null; + + SerializationInfoEnumerator enumerator = siInfo.GetEnumerator(); + + while (enumerator.MoveNext()) + { + switch (enumerator.Name) + { + case LoadFactorName: + _loadFactor = siInfo.GetSingle(LoadFactorName); + break; + case HashSizeName: + hashsize = siInfo.GetInt32(HashSizeName); + break; + case KeyComparerName: + _keycomparer = (IEqualityComparer)siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer)); + break; + case ComparerName: + c = (IComparer)siInfo.GetValue(ComparerName, typeof(IComparer)); + break; + case HashCodeProviderName: +#pragma warning disable 618 + hcp = (IHashCodeProvider)siInfo.GetValue(HashCodeProviderName, typeof(IHashCodeProvider)); +#pragma warning restore 618 + break; + case KeysName: + serKeys = (object[])siInfo.GetValue(KeysName, typeof(object[])); + break; + case ValuesName: + serValues = (object[])siInfo.GetValue(ValuesName, typeof(object[])); + break; + } + } + + _loadsize = (int)(_loadFactor * hashsize); + + // V1 object doesn't has _keycomparer field. + if ((_keycomparer == null) && ((c != null) || (hcp != null))) + { + _keycomparer = new CompatibleComparer(hcp, c); + } + + _buckets = new bucket[hashsize]; + + if (serKeys == null) + { + throw new SerializationException(SR.Serialization_MissingKeys); + } + if (serValues == null) + { + throw new SerializationException(SR.Serialization_MissingValues); + } + if (serKeys.Length != serValues.Length) + { + throw new SerializationException(SR.Serialization_KeyValueDifferentSizes); + } + for (int i = 0; i < serKeys.Length; i++) + { + if (serKeys[i] == null) + { + throw new SerializationException(SR.Serialization_NullKey); + } + Insert(serKeys[i], serValues[i], true); + } + + _version = siInfo.GetInt32(VersionName); + + HashHelpers.SerializationInfoTable.Remove(this); + } + + // Implements a Collection for the keys of a hashtable. An instance of this + // class is created by the GetKeys method of a hashtable. + private class KeyCollection : ICollection + { + private Hashtable _hashtable; + + internal KeyCollection(Hashtable hashtable) + { + _hashtable = hashtable; + } + + public virtual void CopyTo(Array array, int arrayIndex) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + if (array.Rank != 1) + throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); + if (arrayIndex < 0) + throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); + if (array.Length - arrayIndex < _hashtable._count) + throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); + _hashtable.CopyKeys(array, arrayIndex); + } + + public virtual IEnumerator GetEnumerator() + { + return new HashtableEnumerator(_hashtable, HashtableEnumerator.Keys); + } + + public virtual bool IsSynchronized + { + get { return _hashtable.IsSynchronized; } + } + + public virtual object SyncRoot + { + get { return _hashtable.SyncRoot; } + } + + public virtual int Count + { + get { return _hashtable._count; } + } + } + + // Implements a Collection for the values of a hashtable. An instance of + // this class is created by the GetValues method of a hashtable. + private class ValueCollection : ICollection + { + private Hashtable _hashtable; + + internal ValueCollection(Hashtable hashtable) + { + _hashtable = hashtable; + } + + public virtual void CopyTo(Array array, int arrayIndex) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + if (array.Rank != 1) + throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); + if (arrayIndex < 0) + throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); + if (array.Length - arrayIndex < _hashtable._count) + throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); + _hashtable.CopyValues(array, arrayIndex); + } + + public virtual IEnumerator GetEnumerator() + { + return new HashtableEnumerator(_hashtable, HashtableEnumerator.Values); + } + + public virtual bool IsSynchronized + { + get { return _hashtable.IsSynchronized; } + } + + public virtual object SyncRoot + { + get { return _hashtable.SyncRoot; } + } + + public virtual int Count + { + get { return _hashtable._count; } + } + } + + // Synchronized wrapper for hashtable + private class SyncHashtable : Hashtable, IEnumerable + { + protected Hashtable _table; + + internal SyncHashtable(Hashtable table) : base(false) + { + _table = table; + } + + internal SyncHashtable(SerializationInfo info, StreamingContext context) : base(info, context) + { + throw new PlatformNotSupportedException(); + } + + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + throw new PlatformNotSupportedException(); + } + + public override int Count + { + get { return _table.Count; } + } + + public override bool IsReadOnly + { + get { return _table.IsReadOnly; } + } + + public override bool IsFixedSize + { + get { return _table.IsFixedSize; } + } + + public override bool IsSynchronized + { + get { return true; } + } + + public override object this[object key] + { + get + { + return _table[key]; + } + set + { + lock (_table.SyncRoot) + { + _table[key] = value; + } + } + } + + public override object SyncRoot + { + get { return _table.SyncRoot; } + } + + public override void Add(object key, object value) + { + lock (_table.SyncRoot) + { + _table.Add(key, value); + } + } + + public override void Clear() + { + lock (_table.SyncRoot) + { + _table.Clear(); + } + } + + public override bool Contains(object key) + { + return _table.Contains(key); + } + + public override bool ContainsKey(object key) + { + if (key == null) + { + throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); + } + return _table.ContainsKey(key); + } + + public override bool ContainsValue(object key) + { + lock (_table.SyncRoot) + { + return _table.ContainsValue(key); + } + } + + public override void CopyTo(Array array, int arrayIndex) + { + lock (_table.SyncRoot) + { + _table.CopyTo(array, arrayIndex); + } + } + + public override object Clone() + { + lock (_table.SyncRoot) + { + return Hashtable.Synchronized((Hashtable)_table.Clone()); + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return _table.GetEnumerator(); + } + + public override IDictionaryEnumerator GetEnumerator() + { + return _table.GetEnumerator(); + } + + public override ICollection Keys + { + get + { + lock (_table.SyncRoot) + { + return _table.Keys; + } + } + } + + public override ICollection Values + { + get + { + lock (_table.SyncRoot) + { + return _table.Values; + } + } + } + + public override void Remove(object key) + { + lock (_table.SyncRoot) + { + _table.Remove(key); + } + } + + public override void OnDeserialization(object sender) + { + // Does nothing. We have to implement this because our parent HT implements it, + // but it doesn't do anything meaningful. The real work will be done when we + // call OnDeserialization on our parent table. + } + + internal override KeyValuePairs[] ToKeyValuePairsArray() + { + return _table.ToKeyValuePairsArray(); + } + } + + + // Implements an enumerator for a hashtable. The enumerator uses the + // internal version number of the hashtable to ensure that no modifications + // are made to the hashtable while an enumeration is in progress. + private class HashtableEnumerator : IDictionaryEnumerator, ICloneable + { + private Hashtable _hashtable; + private int _bucket; + private int _version; + private bool _current; + private int _getObjectRetType; // What should GetObject return? + private object _currentKey; + private object _currentValue; + + internal const int Keys = 1; + internal const int Values = 2; + internal const int DictEntry = 3; + + internal HashtableEnumerator(Hashtable hashtable, int getObjRetType) + { + _hashtable = hashtable; + _bucket = hashtable._buckets.Length; + _version = hashtable._version; + _current = false; + _getObjectRetType = getObjRetType; + } + + public object Clone() => MemberwiseClone(); + + public virtual object Key + { + get + { + if (_current == false) + throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); + return _currentKey; + } + } + + public virtual bool MoveNext() + { + if (_version != _hashtable._version) + throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); + while (_bucket > 0) + { + _bucket--; + object keyv = _hashtable._buckets[_bucket].key; + if ((keyv != null) && (keyv != _hashtable._buckets)) + { + _currentKey = keyv; + _currentValue = _hashtable._buckets[_bucket].val; + _current = true; + return true; + } + } + _current = false; + return false; + } + + public virtual DictionaryEntry Entry + { + get + { + if (_current == false) + throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); + return new DictionaryEntry(_currentKey, _currentValue); + } + } + + + public virtual object Current + { + get + { + if (_current == false) + throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); + + if (_getObjectRetType == Keys) + return _currentKey; + else if (_getObjectRetType == Values) + return _currentValue; + else + return new DictionaryEntry(_currentKey, _currentValue); + } + } + + public virtual object Value + { + get + { + if (_current == false) + throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); + return _currentValue; + } + } + + public virtual void Reset() + { + if (_version != _hashtable._version) + throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); + _current = false; + _bucket = _hashtable._buckets.Length; + _currentKey = null; + _currentValue = null; + } + } + + // internal debug view class for hashtable + internal class HashtableDebugView + { + private Hashtable _hashtable; + + public HashtableDebugView(Hashtable hashtable) + { + if (hashtable == null) + { + throw new ArgumentNullException(nameof(hashtable)); + } + + _hashtable = hashtable; + } + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public KeyValuePairs[] Items + { + get + { + return _hashtable.ToKeyValuePairsArray(); + } + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/ICollection.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/ICollection.cs index f0149020d2..65e37c7381 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/ICollection.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/ICollection.cs @@ -10,7 +10,7 @@ namespace System.Collections // synchronization methods. public interface ICollection : IEnumerable { - // Interfaces are not serialable + // Interfaces are not serializable // CopyTo copies a collection into an Array, starting at a particular // index into the array. // @@ -49,12 +49,12 @@ namespace System.Collections // or your language's equivalent to the C# lock keyword as mentioned // above. // - // For collections with no publically available underlying store, the + // For collections with no publicly available underlying store, the // expected implementation is to simply return the this pointer. Note // that the this pointer may not be sufficient for collections that // wrap other collections; those should return the underlying // collection's SyncRoot property. - Object SyncRoot + object SyncRoot { get; } // Is this collection synchronized (i.e., thread-safe)? If you want a diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IComparer.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IComparer.cs index cef91c3ffa..38bab78b3c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IComparer.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IComparer.cs @@ -17,6 +17,6 @@ namespace System.Collections // value less than zero if x is less than y, zero if x is equal to y, or a // value greater than zero if x is greater than y. // - int Compare(Object x, Object y); + int Compare(object x, object y); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IDictionary.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IDictionary.cs index b934c2399c..b077c91927 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IDictionary.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IDictionary.cs @@ -15,7 +15,7 @@ namespace System.Collections // Interfaces are not serializable // The Item property provides methods to read and edit entries // in the Dictionary. - Object this[Object key] + object this[object key] { get; set; @@ -35,11 +35,11 @@ namespace System.Collections // Returns whether this dictionary contains a particular key. // - bool Contains(Object key); + bool Contains(object key); // Adds a key-value pair to the dictionary. // - void Add(Object key, Object value); + void Add(object key, object value); // Removes all pairs from the dictionary. void Clear(); @@ -55,6 +55,6 @@ namespace System.Collections // Removes a particular key from the dictionary. // - void Remove(Object key); + void Remove(object key); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IDictionaryEnumerator.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IDictionaryEnumerator.cs index 451cf68976..0cf6aaa154 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IDictionaryEnumerator.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IDictionaryEnumerator.cs @@ -39,7 +39,7 @@ namespace System.Collections // GetKey with no intervening calls to GetNext will return // the same object. // - Object Key + object Key { get; } @@ -50,7 +50,7 @@ namespace System.Collections // to GetValue with no intervening calls to GetNext will // return the same object. // - Object Value + object Value { get; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IEnumerator.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IEnumerator.cs index 2c2c2e4a97..29a6f475bf 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IEnumerator.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IEnumerator.cs @@ -25,7 +25,7 @@ namespace System.Collections // GetCurrent with no intervening calls to MoveNext // will return the same object. // - Object Current + object Current { get; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IEqualityComparer.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IEqualityComparer.cs index 35513f577d..9b5476896c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IEqualityComparer.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IEqualityComparer.cs @@ -10,7 +10,7 @@ namespace System.Collections // that can be consumed by some of the common collections. public interface IEqualityComparer { - bool Equals(Object x, Object y); - int GetHashCode(Object obj); + bool Equals(object x, object y); + int GetHashCode(object obj); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IHashCodeProvider.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IHashCodeProvider.cs new file mode 100644 index 0000000000..7d6c63f9f1 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IHashCodeProvider.cs @@ -0,0 +1,18 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Collections +{ + /// + /// Provides a mechanism for a user to override the default + /// GetHashCode() function on Objects, providing their own hash function. + /// + [Obsolete("Please use IEqualityComparer instead.")] + [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] + public interface IHashCodeProvider + { + /// Returns a hash code for the given object. + int GetHashCode(object obj); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IList.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IList.cs index 0110eca1f5..25d3b19226 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IList.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IList.cs @@ -12,7 +12,7 @@ namespace System.Collections public interface IList : ICollection { // The Item property provides methods to read and edit entries in the List. - Object this[int index] + object this[int index] { get; set; @@ -22,10 +22,10 @@ namespace System.Collections // implementation-dependent, so while ArrayList may always insert // in the last available location, a SortedList most likely would not. // The return value is the position the new element was inserted in. - int Add(Object value); + int Add(object value); // Returns whether the list contains a particular item. - bool Contains(Object value); + bool Contains(object value); // Removes all items from the list. void Clear(); @@ -42,16 +42,16 @@ namespace System.Collections // Returns the index of a particular item, if it is in the list. // Returns -1 if the item isn't in the list. - int IndexOf(Object value); + int IndexOf(object value); // Inserts value into the list at position index. // index must be non-negative and less than or equal to the // number of elements in the list. If index equals the number // of items in the list, then value is appended to the end. - void Insert(int index, Object value); + void Insert(int index, object value); // Removes an item from the list. - void Remove(Object value); + void Remove(object value); // Removes the item at position index. void RemoveAt(int index); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IStructuralComparable.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IStructuralComparable.cs index a5e4834b9b..9041e0d5ff 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IStructuralComparable.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IStructuralComparable.cs @@ -8,6 +8,6 @@ namespace System.Collections { public interface IStructuralComparable { - Int32 CompareTo(Object other, IComparer comparer); + int CompareTo(object other, IComparer comparer); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IStructuralEquatable.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IStructuralEquatable.cs index 4e61d5e75f..1784da58cb 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/IStructuralEquatable.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/IStructuralEquatable.cs @@ -6,7 +6,7 @@ namespace System.Collections { public interface IStructuralEquatable { - Boolean Equals(Object other, IEqualityComparer comparer); + bool Equals(object other, IEqualityComparer comparer); int GetHashCode(IEqualityComparer comparer); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/KeyValuePairs.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/KeyValuePairs.cs new file mode 100644 index 0000000000..9ec6365b92 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/KeyValuePairs.cs @@ -0,0 +1,33 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/*============================================================ +** +** Class: KeyValuePairs +** +** Purpose: Defines key/value pairs for displaying items +** in a collection class under the debugger. +** +===========================================================*/ + +using System.Diagnostics; + +namespace System.Collections +{ + [DebuggerDisplay("{_value}", Name = "[{_key}]")] + internal class KeyValuePairs + { + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly object _key; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly object _value; + + public KeyValuePairs(object key, object value) + { + _value = value; + _key = key; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/ListDictionaryInternal.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/ListDictionaryInternal.cs index a8b7a187d9..6045778abf 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/ListDictionaryInternal.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/ListDictionaryInternal.cs @@ -20,24 +20,20 @@ namespace System.Collections /// This should not be used if performance is important for large numbers of elements. [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] -#if CORERT - public -#else - internal -#endif - class ListDictionaryInternal : IDictionary + // Needs to be public to support binary serialization compatibility + public class ListDictionaryInternal : IDictionary { private DictionaryNode head; // Do not rename (binary serialization) private int version; // Do not rename (binary serialization) private int count; // Do not rename (binary serialization) [NonSerialized] - private Object _syncRoot; + private object _syncRoot; public ListDictionaryInternal() { } - public Object this[Object key] + public object this[object key] { get { @@ -138,13 +134,13 @@ namespace System.Collections } } - public Object SyncRoot + public object SyncRoot { get { if (_syncRoot == null) { - System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); + System.Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); } return _syncRoot; } @@ -158,7 +154,7 @@ namespace System.Collections } } - public void Add(Object key, Object value) + public void Add(object key, object value) { if (key == null) { @@ -205,7 +201,7 @@ namespace System.Collections version++; } - public bool Contains(Object key) + public bool Contains(object key) { if (key == null) { @@ -252,7 +248,7 @@ namespace System.Collections return new NodeEnumerator(this); } - public void Remove(Object key) + public void Remove(object key) { if (key == null) { @@ -300,7 +296,7 @@ namespace System.Collections current = null; } - public Object Current + public object Current { get { @@ -320,7 +316,7 @@ namespace System.Collections } } - public Object Key + public object Key { get { @@ -332,7 +328,7 @@ namespace System.Collections } } - public Object Value + public object Value { get { @@ -426,7 +422,7 @@ namespace System.Collections } } - Object ICollection.SyncRoot + object ICollection.SyncRoot { get { @@ -457,7 +453,7 @@ namespace System.Collections current = null; } - public Object Current + public object Current { get { @@ -505,8 +501,8 @@ namespace System.Collections [Serializable] private class DictionaryNode { - public Object key; - public Object value; + public object key; + public object value; public DictionaryNode next; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs index 1e1b2c7959..53272b386a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs @@ -15,7 +15,7 @@ namespace System.Collections.ObjectModel { private IList items; // Do not rename (binary serialization) [NonSerialized] - private Object _syncRoot; + private object _syncRoot; public Collection() { @@ -195,7 +195,7 @@ namespace System.Collections.ObjectModel } else { - System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); + System.Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); } } return _syncRoot; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs b/external/corert/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs index dbf88d8b8d..3c4eda2048 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs @@ -15,7 +15,7 @@ namespace System.Collections.ObjectModel { private IList list; // Do not rename (binary serialization) [NonSerialized] - private Object _syncRoot; + private object _syncRoot; public ReadOnlyCollection(IList list) { @@ -127,7 +127,7 @@ namespace System.Collections.ObjectModel } else { - System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); + System.Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); } } return _syncRoot; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs b/external/corert/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs index 3cdc907297..5f7108a527 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs @@ -2,11 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.ComponentModel; -using System.Diagnostics; using System.Globalization; -using System.Runtime.InteropServices; +using System.Threading; namespace System.ComponentModel { @@ -23,6 +20,9 @@ namespace System.ComponentModel /// private object _value; + // Delegate ad hoc created 'TypeDescriptor.ConvertFromInvariantString' reflection object cache + static object s_convertFromInvariantString; + /// /// Initializes a new instance of the class, converting the /// specified value to the @@ -36,7 +36,11 @@ namespace System.ComponentModel // load an otherwise normal class. try { - if (type.IsSubclassOf(typeof(Enum))) + if (TryConvertFromInvariantString(type, value, out object convertedValue)) + { + _value = convertedValue; + } + else if (type.IsSubclassOf(typeof(Enum))) { _value = Enum.Parse(type, value, true); } @@ -48,6 +52,28 @@ namespace System.ComponentModel { _value = Convert.ChangeType(value, type, CultureInfo.InvariantCulture); } + + return; + + // Looking for ad hoc created TypeDescriptor.ConvertFromInvariantString(Type, string) + bool TryConvertFromInvariantString(Type typeToConvert, string stringValue, out object conversionResult) + { + conversionResult = null; + + // lazy init reflection objects + if (s_convertFromInvariantString == null) + { + Type typeDescriptorType = Type.GetType("System.ComponentModel.TypeDescriptor, System.ComponentModel.TypeConverter", throwOnError: false); + Volatile.Write(ref s_convertFromInvariantString, typeDescriptorType == null ? new object() : Delegate.CreateDelegate(typeof(Func), typeDescriptorType, "ConvertFromInvariantString", ignoreCase: false)); + } + + if (!(s_convertFromInvariantString is Func convertFromInvariantString)) + return false; + + conversionResult = convertFromInvariantString(typeToConvert, stringValue); + + return true; + } } catch { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Convert.Base64.cs b/external/corert/src/System.Private.CoreLib/shared/System/Convert.Base64.cs new file mode 100644 index 0000000000..7e2aee31b2 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Convert.Base64.cs @@ -0,0 +1,217 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Internal.Runtime.CompilerServices; + +namespace System +{ + public static partial class Convert + { + /// + /// Decode the span of UTF-16 encoded text represented as base 64 into binary data. + /// If the input is not a multiple of 4, or contains illegal characters, it will decode as much as it can, to the largest possible multiple of 4. + /// This invariant allows continuation of the parse with a slower, whitespace-tolerant algorithm. + /// + /// The input span which contains UTF-16 encoded text in base 64 that needs to be decoded. + /// The output span which contains the result of the operation, i.e. the decoded binary data. + /// The number of input bytes consumed during the operation. This can be used to slice the input for subsequent calls, if necessary. + /// The number of bytes written into the output span. This can be used to slice the output for subsequent calls, if necessary. + /// Returns: + /// - true - The entire input span was successfully parsed. + /// - false - Only a part of the input span was successfully parsed. Failure causes may include embedded or trailing whitespace, + /// other illegal Base64 characters, trailing characters after an encoding pad ('='), an input span whose length is not divisible by 4 + /// or a destination span that's too small. and are set so that + /// parsing can continue with a slower whitespace-tolerant algorithm. + /// + /// Note: This is a cut down version of the implementation of Base64.DecodeFromUtf8(), modified the accept UTF16 chars and act as a fast-path + /// helper for the Convert routines when the input string contains no whitespace. + /// + /// + private static bool TryDecodeFromUtf16(ReadOnlySpan utf16, Span bytes, out int consumed, out int written) + { + ref char srcChars = ref MemoryMarshal.GetReference(utf16); + ref byte destBytes = ref MemoryMarshal.GetReference(bytes); + + int srcLength = utf16.Length & ~0x3; // only decode input up to the closest multiple of 4. + int destLength = bytes.Length; + + int sourceIndex = 0; + int destIndex = 0; + + if (utf16.Length == 0) + goto DoneExit; + + ref sbyte decodingMap = ref s_decodingMap[0]; + + // Last bytes could have padding characters, so process them separately and treat them as valid. + const int skipLastChunk = 4; + + int maxSrcLength; + if (destLength >= (srcLength >> 2) * 3) + { + maxSrcLength = srcLength - skipLastChunk; + } + else + { + // This should never overflow since destLength here is less than int.MaxValue / 4 * 3 (i.e. 1610612733) + // Therefore, (destLength / 3) * 4 will always be less than 2147483641 + maxSrcLength = (destLength / 3) * 4; + } + + while (sourceIndex < maxSrcLength) + { + int result = Decode(ref Unsafe.Add(ref srcChars, sourceIndex), ref decodingMap); + if (result < 0) + goto InvalidExit; + WriteThreeLowOrderBytes(ref Unsafe.Add(ref destBytes, destIndex), result); + destIndex += 3; + sourceIndex += 4; + } + + if (maxSrcLength != srcLength - skipLastChunk) + goto InvalidExit; + + // If input is less than 4 bytes, srcLength == sourceIndex == 0 + // If input is not a multiple of 4, sourceIndex == srcLength != 0 + if (sourceIndex == srcLength) + { + goto InvalidExit; + } + + int i0 = Unsafe.Add(ref srcChars, srcLength - 4); + int i1 = Unsafe.Add(ref srcChars, srcLength - 3); + int i2 = Unsafe.Add(ref srcChars, srcLength - 2); + int i3 = Unsafe.Add(ref srcChars, srcLength - 1); + if (((i0 | i1 | i2 | i3) & 0xffffff00) != 0) + goto InvalidExit; + + i0 = Unsafe.Add(ref decodingMap, i0); + i1 = Unsafe.Add(ref decodingMap, i1); + + i0 <<= 18; + i1 <<= 12; + + i0 |= i1; + + if (i3 != EncodingPad) + { + i2 = Unsafe.Add(ref decodingMap, i2); + i3 = Unsafe.Add(ref decodingMap, i3); + + i2 <<= 6; + + i0 |= i3; + i0 |= i2; + + if (i0 < 0) + goto InvalidExit; + if (destIndex > destLength - 3) + goto InvalidExit; + WriteThreeLowOrderBytes(ref Unsafe.Add(ref destBytes, destIndex), i0); + destIndex += 3; + } + else if (i2 != EncodingPad) + { + i2 = Unsafe.Add(ref decodingMap, i2); + + i2 <<= 6; + + i0 |= i2; + + if (i0 < 0) + goto InvalidExit; + if (destIndex > destLength - 2) + goto InvalidExit; + Unsafe.Add(ref destBytes, destIndex) = (byte)(i0 >> 16); + Unsafe.Add(ref destBytes, destIndex + 1) = (byte)(i0 >> 8); + destIndex += 2; + } + else + { + if (i0 < 0) + goto InvalidExit; + if (destIndex > destLength - 1) + goto InvalidExit; + Unsafe.Add(ref destBytes, destIndex) = (byte)(i0 >> 16); + destIndex += 1; + } + + sourceIndex += 4; + + if (srcLength != utf16.Length) + goto InvalidExit; + + DoneExit: + consumed = sourceIndex; + written = destIndex; + return true; + + InvalidExit: + consumed = sourceIndex; + written = destIndex; + Debug.Assert((consumed % 4) == 0); + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int Decode(ref char encodedChars, ref sbyte decodingMap) + { + int i0 = encodedChars; + int i1 = Unsafe.Add(ref encodedChars, 1); + int i2 = Unsafe.Add(ref encodedChars, 2); + int i3 = Unsafe.Add(ref encodedChars, 3); + + if (((i0 | i1 | i2 | i3) & 0xffffff00) != 0) + return -1; // One or more chars falls outside the 00..ff range. This cannot be a valid Base64 character. + + i0 = Unsafe.Add(ref decodingMap, i0); + i1 = Unsafe.Add(ref decodingMap, i1); + i2 = Unsafe.Add(ref decodingMap, i2); + i3 = Unsafe.Add(ref decodingMap, i3); + + i0 <<= 18; + i1 <<= 12; + i2 <<= 6; + + i0 |= i3; + i1 |= i2; + + i0 |= i1; + return i0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void WriteThreeLowOrderBytes(ref byte destination, int value) + { + destination = (byte)(value >> 16); + Unsafe.Add(ref destination, 1) = (byte)(value >> 8); + Unsafe.Add(ref destination, 2) = (byte)value; + } + + // Pre-computing this table using a custom string(s_characters) and GenerateDecodingMapAndVerify (found in tests) + private static readonly sbyte[] s_decodingMap = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, //62 is placed at index 43 (for +), 63 at index 47 (for /) + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, //52-61 are placed at index 48-57 (for 0-9), 64 at index 61 (for =) + -1, 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, -1, -1, -1, -1, -1, //0-25 are placed at index 65-90 (for A-Z) + -1, 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, -1, -1, -1, -1, -1, //26-51 are placed at index 97-122 (for a-z) + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // Bytes over 122 ('z') are invalid and cannot be decoded + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // Hence, padding the map with 255, which indicates invalid input + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + }; + + private const byte EncodingPad = (byte)'='; // '=', for padding + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Convert.cs b/external/corert/src/System.Private.CoreLib/shared/System/Convert.cs new file mode 100644 index 0000000000..1c303d2481 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Convert.cs @@ -0,0 +1,2909 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Globalization; +using System.Threading; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Security; +using System.Diagnostics; + +namespace System +{ + [Flags] + public enum Base64FormattingOptions + { + None = 0, + InsertLineBreaks = 1 + } + + // Returns the type code of this object. An implementation of this method + // must not return TypeCode.Empty (which represents a null reference) or + // TypeCode.Object (which represents an object that doesn't implement the + // IConvertible interface). An implementation of this method should return + // TypeCode.DBNull if the value of this object is a database null. For + // example, a nullable integer type should return TypeCode.DBNull if the + // value of the object is the database null. Otherwise, an implementation + // of this method should return the TypeCode that best describes the + // internal representation of the object. + // The Value class provides conversion and querying methods for values. The + // Value class contains static members only, and it is not possible to create + // instances of the class. + // + // The statically typed conversion methods provided by the Value class are all + // of the form: + // + // public static XXX ToXXX(YYY value) + // + // where XXX is the target type and YYY is the source type. The matrix below + // shows the set of supported conversions. The set of conversions is symmetric + // such that for every ToXXX(YYY) there is also a ToYYY(XXX). + // + // From: To: Bol Chr SBy Byt I16 U16 I32 U32 I64 U64 Sgl Dbl Dec Dat Str + // ---------------------------------------------------------------------- + // Boolean x x x x x x x x x x x x x + // Char x x x x x x x x x x + // SByte x x x x x x x x x x x x x x + // Byte x x x x x x x x x x x x x x + // Int16 x x x x x x x x x x x x x x + // UInt16 x x x x x x x x x x x x x x + // Int32 x x x x x x x x x x x x x x + // UInt32 x x x x x x x x x x x x x x + // Int64 x x x x x x x x x x x x x x + // UInt64 x x x x x x x x x x x x x x + // Single x x x x x x x x x x x x x + // Double x x x x x x x x x x x x x + // Decimal x x x x x x x x x x x x x + // DateTime x x + // String x x x x x x x x x x x x x x x + // ---------------------------------------------------------------------- + // + // For dynamic conversions, the Value class provides a set of methods of the + // form: + // + // public static XXX ToXXX(object value) + // + // where XXX is the target type (Boolean, Char, SByte, Byte, Int16, UInt16, + // Int32, UInt32, Int64, UInt64, Single, Double, Decimal, DateTime, + // or String). The implementations of these methods all take the form: + // + // public static XXX toXXX(object value) { + // return value == null? XXX.Default: ((IConvertible)value).ToXXX(); + // } + // + // The code first checks if the given value is a null reference (which is the + // same as Value.Empty), in which case it returns the default value for type + // XXX. Otherwise, a cast to IConvertible is performed, and the appropriate ToXXX() + // method is invoked on the object. An InvalidCastException is thrown if the + // cast to IConvertible fails, and that exception is simply allowed to propagate out + // of the conversion method. + + // Constant representing the database null value. This value is used in + // database applications to indicate the absence of a known value. Note + // that Value.DBNull is NOT the same as a null object reference, which is + // represented by Value.Empty. + // + // The Equals() method of DBNull always returns false, even when the + // argument is itself DBNull. + // + // When passed Value.DBNull, the Value.GetTypeCode() method returns + // TypeCode.DBNull. + // + // When passed Value.DBNull, the Value.ToXXX() methods all throw an + // InvalidCastException. + + public static partial class Convert + { + //A typeof operation is fairly expensive (does a system call), so we'll cache these here + //statically. These are exactly lined up with the TypeCode, eg. ConvertType[TypeCode.Int16] + //will give you the type of an short. + internal static readonly Type[] ConvertTypes = { + typeof(System.Empty), + typeof(object), + typeof(System.DBNull), + typeof(bool), + typeof(char), + typeof(sbyte), + typeof(byte), + typeof(short), + typeof(ushort), + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(float), + typeof(double), + typeof(decimal), + typeof(DateTime), + typeof(object), //TypeCode is discontinuous so we need a placeholder. + typeof(string) + }; + + // Need to special case Enum because typecode will be underlying type, e.g. Int32 + private static readonly Type EnumType = typeof(Enum); + + internal static readonly char[] base64Table = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', + 'P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d', + 'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s', + 't','u','v','w','x','y','z','0','1','2','3','4','5','6','7', + '8','9','+','/','=' }; + + private const int base64LineBreakPosition = 76; + +#if DEBUG + private static bool TriggerAsserts = DoAsserts(); + private static bool DoAsserts() + { + Debug.Assert(ConvertTypes != null, "[Convert.cctor]ConvertTypes!=null"); + Debug.Assert(ConvertTypes.Length == ((int)TypeCode.String + 1), "[Convert.cctor]ConvertTypes.Length == ((int)TypeCode.String + 1)"); + Debug.Assert(ConvertTypes[(int)TypeCode.Empty] == typeof(System.Empty), + "[Convert.cctor]ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty)"); + Debug.Assert(ConvertTypes[(int)TypeCode.String] == typeof(string), + "[Convert.cctor]ConvertTypes[(int)TypeCode.String]==typeof(System.String)"); + Debug.Assert(ConvertTypes[(int)TypeCode.Int32] == typeof(int), + "[Convert.cctor]ConvertTypes[(int)TypeCode.Int32]==typeof(int)"); + return true; + } +#endif + + public static readonly object DBNull = System.DBNull.Value; + + // Returns the type code for the given object. If the argument is null, + // the result is TypeCode.Empty. If the argument is not a value (i.e. if + // the object does not implement IConvertible), the result is TypeCode.Object. + // Otherwise, the result is the type code of the object, as determined by + // the object's implementation of IConvertible. + public static TypeCode GetTypeCode(object value) + { + if (value == null) return TypeCode.Empty; + IConvertible temp = value as IConvertible; + if (temp != null) + { + return temp.GetTypeCode(); + } + return TypeCode.Object; + } + + // Returns true if the given object is a database null. This operation + // corresponds to "value.GetTypeCode() == TypeCode.DBNull". + public static bool IsDBNull(object value) + { + if (value == System.DBNull.Value) return true; + IConvertible convertible = value as IConvertible; + return convertible != null ? convertible.GetTypeCode() == TypeCode.DBNull : false; + } + + // Converts the given object to the given type. In general, this method is + // equivalent to calling the Value.ToXXX(value) method for the given + // typeCode and boxing the result. + // + // The method first checks if the given object implements IConvertible. If not, + // the only permitted conversion is from a null to TypeCode.Empty, the + // result of which is null. + // + // If the object does implement IConvertible, a check is made to see if the + // object already has the given type code, in which case the object is + // simply returned. Otherwise, the appropriate ToXXX() is invoked on the + // object's implementation of IConvertible. + public static object ChangeType(object value, TypeCode typeCode) + { + return ChangeType(value, typeCode, CultureInfo.CurrentCulture); + } + + public static object ChangeType(object value, TypeCode typeCode, IFormatProvider provider) + { + if (value == null && (typeCode == TypeCode.Empty || typeCode == TypeCode.String || typeCode == TypeCode.Object)) + { + return null; + } + + IConvertible v = value as IConvertible; + if (v == null) + { + throw new InvalidCastException(SR.InvalidCast_IConvertible); + } + + // This line is invalid for things like Enums that return a TypeCode + // of int, but the object can't actually be cast to an int. + // if (v.GetTypeCode() == typeCode) return value; + switch (typeCode) + { + case TypeCode.Boolean: + return v.ToBoolean(provider); + case TypeCode.Char: + return v.ToChar(provider); + case TypeCode.SByte: + return v.ToSByte(provider); + case TypeCode.Byte: + return v.ToByte(provider); + case TypeCode.Int16: + return v.ToInt16(provider); + case TypeCode.UInt16: + return v.ToUInt16(provider); + case TypeCode.Int32: + return v.ToInt32(provider); + case TypeCode.UInt32: + return v.ToUInt32(provider); + case TypeCode.Int64: + return v.ToInt64(provider); + case TypeCode.UInt64: + return v.ToUInt64(provider); + case TypeCode.Single: + return v.ToSingle(provider); + case TypeCode.Double: + return v.ToDouble(provider); + case TypeCode.Decimal: + return v.ToDecimal(provider); + case TypeCode.DateTime: + return v.ToDateTime(provider); + case TypeCode.String: + return v.ToString(provider); + case TypeCode.Object: + return value; + case TypeCode.DBNull: + throw new InvalidCastException(SR.InvalidCast_DBNull); + case TypeCode.Empty: + throw new InvalidCastException(SR.InvalidCast_Empty); + default: + throw new ArgumentException(SR.Arg_UnknownTypeCode); + } + } + + internal static object DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) + { + Debug.Assert(value != null, "[Convert.DefaultToType]value!=null"); + if (targetType == null) + { + throw new ArgumentNullException(nameof(targetType)); + } + + if (ReferenceEquals(value.GetType(), targetType)) + { + return value; + } + + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Boolean])) + return value.ToBoolean(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Char])) + return value.ToChar(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.SByte])) + return value.ToSByte(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Byte])) + return value.ToByte(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Int16])) + return value.ToInt16(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.UInt16])) + return value.ToUInt16(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Int32])) + return value.ToInt32(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.UInt32])) + return value.ToUInt32(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Int64])) + return value.ToInt64(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.UInt64])) + return value.ToUInt64(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Single])) + return value.ToSingle(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Double])) + return value.ToDouble(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Decimal])) + return value.ToDecimal(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.DateTime])) + return value.ToDateTime(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.String])) + return value.ToString(provider); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Object])) + return (object)value; + // Need to special case Enum because typecode will be underlying type, e.g. Int32 + if (ReferenceEquals(targetType, EnumType)) + return (Enum)value; + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.DBNull])) + throw new InvalidCastException(SR.InvalidCast_DBNull); + if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Empty])) + throw new InvalidCastException(SR.InvalidCast_Empty); + + throw new InvalidCastException(string.Format(SR.InvalidCast_FromTo, value.GetType().FullName, targetType.FullName)); + } + + public static object ChangeType(object value, Type conversionType) + { + return ChangeType(value, conversionType, CultureInfo.CurrentCulture); + } + + public static object ChangeType(object value, Type conversionType, IFormatProvider provider) + { + if (conversionType is null) + { + throw new ArgumentNullException(nameof(conversionType)); + } + + if (value == null) + { + if (conversionType.IsValueType) + { + throw new InvalidCastException(SR.InvalidCast_CannotCastNullToValueType); + } + return null; + } + + IConvertible ic = value as IConvertible; + if (ic == null) + { + if (value.GetType() == conversionType) + { + return value; + } + throw new InvalidCastException(SR.InvalidCast_IConvertible); + } + + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Boolean])) + return ic.ToBoolean(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Char])) + return ic.ToChar(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.SByte])) + return ic.ToSByte(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Byte])) + return ic.ToByte(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Int16])) + return ic.ToInt16(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.UInt16])) + return ic.ToUInt16(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Int32])) + return ic.ToInt32(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.UInt32])) + return ic.ToUInt32(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Int64])) + return ic.ToInt64(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.UInt64])) + return ic.ToUInt64(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Single])) + return ic.ToSingle(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Double])) + return ic.ToDouble(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Decimal])) + return ic.ToDecimal(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.DateTime])) + return ic.ToDateTime(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.String])) + return ic.ToString(provider); + if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Object])) + return (object)value; + + return ic.ToType(conversionType, provider); + } + + private static void ThrowCharOverflowException() { throw new OverflowException(SR.Overflow_Char); } + + private static void ThrowByteOverflowException() { throw new OverflowException(SR.Overflow_Byte); } + + private static void ThrowSByteOverflowException() { throw new OverflowException(SR.Overflow_SByte); } + + private static void ThrowInt16OverflowException() { throw new OverflowException(SR.Overflow_Int16); } + + private static void ThrowUInt16OverflowException() { throw new OverflowException(SR.Overflow_UInt16); } + + private static void ThrowInt32OverflowException() { throw new OverflowException(SR.Overflow_Int32); } + + private static void ThrowUInt32OverflowException() { throw new OverflowException(SR.Overflow_UInt32); } + + private static void ThrowInt64OverflowException() { throw new OverflowException(SR.Overflow_Int64); } + + private static void ThrowUInt64OverflowException() { throw new OverflowException(SR.Overflow_UInt64); } + + // Conversions to Boolean + public static bool ToBoolean(object value) + { + return value == null ? false : ((IConvertible)value).ToBoolean(null); + } + + public static bool ToBoolean(object value, IFormatProvider provider) + { + return value == null ? false : ((IConvertible)value).ToBoolean(provider); + } + + + public static bool ToBoolean(bool value) + { + return value; + } + + [CLSCompliant(false)] + public static bool ToBoolean(sbyte value) + { + return value != 0; + } + + // To be consistent with IConvertible in the base data types else we get different semantics + // with widening operations. Without this operator this widen succeeds,with this API the widening throws. + public static bool ToBoolean(char value) + { + return ((IConvertible)value).ToBoolean(null); + } + + public static bool ToBoolean(byte value) + { + return value != 0; + } + + + public static bool ToBoolean(short value) + { + return value != 0; + } + + [CLSCompliant(false)] + public static bool ToBoolean(ushort value) + { + return value != 0; + } + + public static bool ToBoolean(int value) + { + return value != 0; + } + + [CLSCompliant(false)] + public static bool ToBoolean(uint value) + { + return value != 0; + } + + public static bool ToBoolean(long value) + { + return value != 0; + } + + [CLSCompliant(false)] + public static bool ToBoolean(ulong value) + { + return value != 0; + } + + public static bool ToBoolean(string value) + { + if (value == null) + return false; + return bool.Parse(value); + } + + public static bool ToBoolean(string value, IFormatProvider provider) + { + if (value == null) + return false; + return bool.Parse(value); + } + + public static bool ToBoolean(float value) + { + return value != 0; + } + + public static bool ToBoolean(double value) + { + return value != 0; + } + + public static bool ToBoolean(decimal value) + { + return value != 0; + } + + public static bool ToBoolean(DateTime value) + { + return ((IConvertible)value).ToBoolean(null); + } + + // Disallowed conversions to Boolean + // public static bool ToBoolean(TimeSpan value) + + // Conversions to Char + + + public static char ToChar(object value) + { + return value == null ? (char)0 : ((IConvertible)value).ToChar(null); + } + + public static char ToChar(object value, IFormatProvider provider) + { + return value == null ? (char)0 : ((IConvertible)value).ToChar(provider); + } + + public static char ToChar(bool value) + { + return ((IConvertible)value).ToChar(null); + } + + public static char ToChar(char value) + { + return value; + } + + [CLSCompliant(false)] + public static char ToChar(sbyte value) + { + if (value < 0) ThrowCharOverflowException(); + return (char)value; + } + + public static char ToChar(byte value) + { + return (char)value; + } + + public static char ToChar(short value) + { + if (value < 0) ThrowCharOverflowException(); + return (char)value; + } + + [CLSCompliant(false)] + public static char ToChar(ushort value) + { + return (char)value; + } + + public static char ToChar(int value) + { + if (value < 0 || value > char.MaxValue) ThrowCharOverflowException(); + return (char)value; + } + + [CLSCompliant(false)] + public static char ToChar(uint value) + { + if (value > char.MaxValue) ThrowCharOverflowException(); + return (char)value; + } + + public static char ToChar(long value) + { + if (value < 0 || value > char.MaxValue) ThrowCharOverflowException(); + return (char)value; + } + + [CLSCompliant(false)] + public static char ToChar(ulong value) + { + if (value > char.MaxValue) ThrowCharOverflowException(); + return (char)value; + } + + // + // @VariantSwitch + // Remove FormatExceptions; + // + public static char ToChar(string value) + { + return ToChar(value, null); + } + + public static char ToChar(string value, IFormatProvider provider) + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + + if (value.Length != 1) + throw new FormatException(SR.Format_NeedSingleChar); + + return value[0]; + } + + // To be consistent with IConvertible in the base data types else we get different semantics + // with widening operations. Without this operator this widen succeeds,with this API the widening throws. + public static char ToChar(float value) + { + return ((IConvertible)value).ToChar(null); + } + + // To be consistent with IConvertible in the base data types else we get different semantics + // with widening operations. Without this operator this widen succeeds,with this API the widening throws. + public static char ToChar(double value) + { + return ((IConvertible)value).ToChar(null); + } + + // To be consistent with IConvertible in the base data types else we get different semantics + // with widening operations. Without this operator this widen succeeds,with this API the widening throws. + public static char ToChar(decimal value) + { + return ((IConvertible)value).ToChar(null); + } + + public static char ToChar(DateTime value) + { + return ((IConvertible)value).ToChar(null); + } + + + // Disallowed conversions to Char + // public static char ToChar(TimeSpan value) + + // Conversions to SByte + + [CLSCompliant(false)] + public static sbyte ToSByte(object value) + { + return value == null ? (sbyte)0 : ((IConvertible)value).ToSByte(null); + } + + [CLSCompliant(false)] + public static sbyte ToSByte(object value, IFormatProvider provider) + { + return value == null ? (sbyte)0 : ((IConvertible)value).ToSByte(provider); + } + + [CLSCompliant(false)] + public static sbyte ToSByte(bool value) + { + return value ? (sbyte)bool.True : (sbyte)bool.False; + } + + [CLSCompliant(false)] + public static sbyte ToSByte(sbyte value) + { + return value; + } + + [CLSCompliant(false)] + public static sbyte ToSByte(char value) + { + if (value > sbyte.MaxValue) ThrowSByteOverflowException(); + return (sbyte)value; + } + + [CLSCompliant(false)] + public static sbyte ToSByte(byte value) + { + if (value > sbyte.MaxValue) ThrowSByteOverflowException(); + return (sbyte)value; + } + + [CLSCompliant(false)] + public static sbyte ToSByte(short value) + { + if (value < sbyte.MinValue || value > sbyte.MaxValue) ThrowSByteOverflowException(); + return (sbyte)value; + } + + [CLSCompliant(false)] + public static sbyte ToSByte(ushort value) + { + if (value > sbyte.MaxValue) ThrowSByteOverflowException(); + return (sbyte)value; + } + + [CLSCompliant(false)] + public static sbyte ToSByte(int value) + { + if (value < sbyte.MinValue || value > sbyte.MaxValue) ThrowSByteOverflowException(); + return (sbyte)value; + } + + [CLSCompliant(false)] + public static sbyte ToSByte(uint value) + { + if (value > sbyte.MaxValue) ThrowSByteOverflowException(); + return (sbyte)value; + } + + [CLSCompliant(false)] + public static sbyte ToSByte(long value) + { + if (value < sbyte.MinValue || value > sbyte.MaxValue) ThrowSByteOverflowException(); + return (sbyte)value; + } + + [CLSCompliant(false)] + public static sbyte ToSByte(ulong value) + { + if (value > (ulong)sbyte.MaxValue) ThrowSByteOverflowException(); + return (sbyte)value; + } + + [CLSCompliant(false)] + public static sbyte ToSByte(float value) + { + return ToSByte((double)value); + } + + [CLSCompliant(false)] + public static sbyte ToSByte(double value) + { + return ToSByte(ToInt32(value)); + } + + [CLSCompliant(false)] + public static sbyte ToSByte(decimal value) + { + return decimal.ToSByte(decimal.Round(value, 0)); + } + + [CLSCompliant(false)] + public static sbyte ToSByte(string value) + { + if (value == null) + return 0; + return sbyte.Parse(value, CultureInfo.CurrentCulture); + } + + [CLSCompliant(false)] + public static sbyte ToSByte(string value, IFormatProvider provider) + { + return sbyte.Parse(value, NumberStyles.Integer, provider); + } + + [CLSCompliant(false)] + public static sbyte ToSByte(DateTime value) + { + return ((IConvertible)value).ToSByte(null); + } + + // Disallowed conversions to SByte + // public static sbyte ToSByte(TimeSpan value) + + // Conversions to Byte + + public static byte ToByte(object value) + { + return value == null ? (byte)0 : ((IConvertible)value).ToByte(null); + } + + public static byte ToByte(object value, IFormatProvider provider) + { + return value == null ? (byte)0 : ((IConvertible)value).ToByte(provider); + } + + public static byte ToByte(bool value) + { + return value ? (byte)bool.True : (byte)bool.False; + } + + public static byte ToByte(byte value) + { + return value; + } + + public static byte ToByte(char value) + { + if (value > byte.MaxValue) ThrowByteOverflowException(); + return (byte)value; + } + + [CLSCompliant(false)] + public static byte ToByte(sbyte value) + { + if (value < byte.MinValue) ThrowByteOverflowException(); + return (byte)value; + } + + public static byte ToByte(short value) + { + if (value < byte.MinValue || value > byte.MaxValue) ThrowByteOverflowException(); + return (byte)value; + } + + [CLSCompliant(false)] + public static byte ToByte(ushort value) + { + if (value > byte.MaxValue) ThrowByteOverflowException(); + return (byte)value; + } + + public static byte ToByte(int value) + { + if (value < byte.MinValue || value > byte.MaxValue) ThrowByteOverflowException(); + return (byte)value; + } + + [CLSCompliant(false)] + public static byte ToByte(uint value) + { + if (value > byte.MaxValue) ThrowByteOverflowException(); + return (byte)value; + } + + public static byte ToByte(long value) + { + if (value < byte.MinValue || value > byte.MaxValue) ThrowByteOverflowException(); + return (byte)value; + } + + [CLSCompliant(false)] + public static byte ToByte(ulong value) + { + if (value > byte.MaxValue) ThrowByteOverflowException(); + return (byte)value; + } + + public static byte ToByte(float value) + { + return ToByte((double)value); + } + + public static byte ToByte(double value) + { + return ToByte(ToInt32(value)); + } + + public static byte ToByte(decimal value) + { + return decimal.ToByte(decimal.Round(value, 0)); + } + + public static byte ToByte(string value) + { + if (value == null) + return 0; + return byte.Parse(value, CultureInfo.CurrentCulture); + } + + public static byte ToByte(string value, IFormatProvider provider) + { + if (value == null) + return 0; + return byte.Parse(value, NumberStyles.Integer, provider); + } + + public static byte ToByte(DateTime value) + { + return ((IConvertible)value).ToByte(null); + } + + + // Disallowed conversions to Byte + // public static byte ToByte(TimeSpan value) + + // Conversions to Int16 + + public static short ToInt16(object value) + { + return value == null ? (short)0 : ((IConvertible)value).ToInt16(null); + } + + public static short ToInt16(object value, IFormatProvider provider) + { + return value == null ? (short)0 : ((IConvertible)value).ToInt16(provider); + } + + public static short ToInt16(bool value) + { + return value ? (short)bool.True : (short)bool.False; + } + + public static short ToInt16(char value) + { + if (value > short.MaxValue) ThrowInt16OverflowException(); + return (short)value; + } + + [CLSCompliant(false)] + public static short ToInt16(sbyte value) + { + return value; + } + + public static short ToInt16(byte value) + { + return value; + } + + [CLSCompliant(false)] + public static short ToInt16(ushort value) + { + if (value > short.MaxValue) ThrowInt16OverflowException(); + return (short)value; + } + + public static short ToInt16(int value) + { + if (value < short.MinValue || value > short.MaxValue) ThrowInt16OverflowException(); + return (short)value; + } + + [CLSCompliant(false)] + public static short ToInt16(uint value) + { + if (value > short.MaxValue) ThrowInt16OverflowException(); + return (short)value; + } + + public static short ToInt16(short value) + { + return value; + } + + public static short ToInt16(long value) + { + if (value < short.MinValue || value > short.MaxValue) ThrowInt16OverflowException(); + return (short)value; + } + + [CLSCompliant(false)] + public static short ToInt16(ulong value) + { + if (value > (ulong)short.MaxValue) ThrowInt16OverflowException(); + return (short)value; + } + + public static short ToInt16(float value) + { + return ToInt16((double)value); + } + + public static short ToInt16(double value) + { + return ToInt16(ToInt32(value)); + } + + public static short ToInt16(decimal value) + { + return decimal.ToInt16(decimal.Round(value, 0)); + } + + public static short ToInt16(string value) + { + if (value == null) + return 0; + return short.Parse(value, CultureInfo.CurrentCulture); + } + + public static short ToInt16(string value, IFormatProvider provider) + { + if (value == null) + return 0; + return short.Parse(value, NumberStyles.Integer, provider); + } + + public static short ToInt16(DateTime value) + { + return ((IConvertible)value).ToInt16(null); + } + + + // Disallowed conversions to Int16 + // public static short ToInt16(TimeSpan value) + + // Conversions to UInt16 + + [CLSCompliant(false)] + public static ushort ToUInt16(object value) + { + return value == null ? (ushort)0 : ((IConvertible)value).ToUInt16(null); + } + + [CLSCompliant(false)] + public static ushort ToUInt16(object value, IFormatProvider provider) + { + return value == null ? (ushort)0 : ((IConvertible)value).ToUInt16(provider); + } + + + [CLSCompliant(false)] + public static ushort ToUInt16(bool value) + { + return value ? (ushort)bool.True : (ushort)bool.False; + } + + [CLSCompliant(false)] + public static ushort ToUInt16(char value) + { + return value; + } + + [CLSCompliant(false)] + public static ushort ToUInt16(sbyte value) + { + if (value < 0) ThrowUInt16OverflowException(); + return (ushort)value; + } + + [CLSCompliant(false)] + public static ushort ToUInt16(byte value) + { + return value; + } + + [CLSCompliant(false)] + public static ushort ToUInt16(short value) + { + if (value < 0) ThrowUInt16OverflowException(); + return (ushort)value; + } + + [CLSCompliant(false)] + public static ushort ToUInt16(int value) + { + if (value < 0 || value > ushort.MaxValue) ThrowUInt16OverflowException(); + return (ushort)value; + } + + [CLSCompliant(false)] + public static ushort ToUInt16(ushort value) + { + return value; + } + + [CLSCompliant(false)] + public static ushort ToUInt16(uint value) + { + if (value > ushort.MaxValue) ThrowUInt16OverflowException(); + return (ushort)value; + } + + + [CLSCompliant(false)] + public static ushort ToUInt16(long value) + { + if (value < 0 || value > ushort.MaxValue) ThrowUInt16OverflowException(); + return (ushort)value; + } + + [CLSCompliant(false)] + public static ushort ToUInt16(ulong value) + { + if (value > ushort.MaxValue) ThrowUInt16OverflowException(); + return (ushort)value; + } + + [CLSCompliant(false)] + public static ushort ToUInt16(float value) + { + return ToUInt16((double)value); + } + + [CLSCompliant(false)] + public static ushort ToUInt16(double value) + { + return ToUInt16(ToInt32(value)); + } + + [CLSCompliant(false)] + public static ushort ToUInt16(decimal value) + { + return decimal.ToUInt16(decimal.Round(value, 0)); + } + + [CLSCompliant(false)] + public static ushort ToUInt16(string value) + { + if (value == null) + return 0; + return ushort.Parse(value, CultureInfo.CurrentCulture); + } + + [CLSCompliant(false)] + public static ushort ToUInt16(string value, IFormatProvider provider) + { + if (value == null) + return 0; + return ushort.Parse(value, NumberStyles.Integer, provider); + } + + [CLSCompliant(false)] + public static ushort ToUInt16(DateTime value) + { + return ((IConvertible)value).ToUInt16(null); + } + + // Disallowed conversions to UInt16 + // public static ushort ToUInt16(TimeSpan value) + + // Conversions to Int32 + + public static int ToInt32(object value) + { + return value == null ? 0 : ((IConvertible)value).ToInt32(null); + } + + public static int ToInt32(object value, IFormatProvider provider) + { + return value == null ? 0 : ((IConvertible)value).ToInt32(provider); + } + + + public static int ToInt32(bool value) + { + return value ? bool.True : bool.False; + } + + public static int ToInt32(char value) + { + return value; + } + + [CLSCompliant(false)] + public static int ToInt32(sbyte value) + { + return value; + } + + public static int ToInt32(byte value) + { + return value; + } + + public static int ToInt32(short value) + { + return value; + } + + [CLSCompliant(false)] + public static int ToInt32(ushort value) + { + return value; + } + + [CLSCompliant(false)] + public static int ToInt32(uint value) + { + if (value > int.MaxValue) ThrowInt32OverflowException(); + return (int)value; + } + + public static int ToInt32(int value) + { + return value; + } + + public static int ToInt32(long value) + { + if (value < int.MinValue || value > int.MaxValue) ThrowInt32OverflowException(); + return (int)value; + } + + [CLSCompliant(false)] + public static int ToInt32(ulong value) + { + if (value > int.MaxValue) ThrowInt32OverflowException(); + return (int)value; + } + + public static int ToInt32(float value) + { + return ToInt32((double)value); + } + + public static int ToInt32(double value) + { + if (value >= 0) + { + if (value < 2147483647.5) + { + int result = (int)value; + double dif = value - result; + if (dif > 0.5 || dif == 0.5 && (result & 1) != 0) result++; + return result; + } + } + else + { + if (value >= -2147483648.5) + { + int result = (int)value; + double dif = value - result; + if (dif < -0.5 || dif == -0.5 && (result & 1) != 0) result--; + return result; + } + } + throw new OverflowException(SR.Overflow_Int32); + } + + public static int ToInt32(decimal value) + { + return decimal.ToInt32(decimal.Round(value, 0)); + } + + public static int ToInt32(string value) + { + if (value == null) + return 0; + return int.Parse(value, CultureInfo.CurrentCulture); + } + + public static int ToInt32(string value, IFormatProvider provider) + { + if (value == null) + return 0; + return int.Parse(value, NumberStyles.Integer, provider); + } + + public static int ToInt32(DateTime value) + { + return ((IConvertible)value).ToInt32(null); + } + + + // Disallowed conversions to Int32 + // public static int ToInt32(TimeSpan value) + + // Conversions to UInt32 + + [CLSCompliant(false)] + public static uint ToUInt32(object value) + { + return value == null ? 0 : ((IConvertible)value).ToUInt32(null); + } + + [CLSCompliant(false)] + public static uint ToUInt32(object value, IFormatProvider provider) + { + return value == null ? 0 : ((IConvertible)value).ToUInt32(provider); + } + + + [CLSCompliant(false)] + public static uint ToUInt32(bool value) + { + return value ? (uint)bool.True : (uint)bool.False; + } + + [CLSCompliant(false)] + public static uint ToUInt32(char value) + { + return value; + } + + [CLSCompliant(false)] + public static uint ToUInt32(sbyte value) + { + if (value < 0) ThrowUInt32OverflowException(); + return (uint)value; + } + + [CLSCompliant(false)] + public static uint ToUInt32(byte value) + { + return value; + } + + [CLSCompliant(false)] + public static uint ToUInt32(short value) + { + if (value < 0) ThrowUInt32OverflowException(); + return (uint)value; + } + + [CLSCompliant(false)] + public static uint ToUInt32(ushort value) + { + return value; + } + + [CLSCompliant(false)] + public static uint ToUInt32(int value) + { + if (value < 0) ThrowUInt32OverflowException(); + return (uint)value; + } + + [CLSCompliant(false)] + public static uint ToUInt32(uint value) + { + return value; + } + + [CLSCompliant(false)] + public static uint ToUInt32(long value) + { + if (value < 0 || value > uint.MaxValue) ThrowUInt32OverflowException(); + return (uint)value; + } + + [CLSCompliant(false)] + public static uint ToUInt32(ulong value) + { + if (value > uint.MaxValue) ThrowUInt32OverflowException(); + return (uint)value; + } + + [CLSCompliant(false)] + public static uint ToUInt32(float value) + { + return ToUInt32((double)value); + } + + [CLSCompliant(false)] + public static uint ToUInt32(double value) + { + if (value >= -0.5 && value < 4294967295.5) + { + uint result = (uint)value; + double dif = value - result; + if (dif > 0.5 || dif == 0.5 && (result & 1) != 0) result++; + return result; + } + throw new OverflowException(SR.Overflow_UInt32); + } + + [CLSCompliant(false)] + public static uint ToUInt32(decimal value) + { + return decimal.ToUInt32(decimal.Round(value, 0)); + } + + [CLSCompliant(false)] + public static uint ToUInt32(string value) + { + if (value == null) + return 0; + return uint.Parse(value, CultureInfo.CurrentCulture); + } + + [CLSCompliant(false)] + public static uint ToUInt32(string value, IFormatProvider provider) + { + if (value == null) + return 0; + return uint.Parse(value, NumberStyles.Integer, provider); + } + + [CLSCompliant(false)] + public static uint ToUInt32(DateTime value) + { + return ((IConvertible)value).ToUInt32(null); + } + + // Disallowed conversions to UInt32 + // public static uint ToUInt32(TimeSpan value) + + // Conversions to Int64 + + public static long ToInt64(object value) + { + return value == null ? 0 : ((IConvertible)value).ToInt64(null); + } + + public static long ToInt64(object value, IFormatProvider provider) + { + return value == null ? 0 : ((IConvertible)value).ToInt64(provider); + } + + + public static long ToInt64(bool value) + { + return value ? bool.True : bool.False; + } + + public static long ToInt64(char value) + { + return value; + } + + [CLSCompliant(false)] + public static long ToInt64(sbyte value) + { + return value; + } + + public static long ToInt64(byte value) + { + return value; + } + + public static long ToInt64(short value) + { + return value; + } + + [CLSCompliant(false)] + public static long ToInt64(ushort value) + { + return value; + } + + public static long ToInt64(int value) + { + return value; + } + + [CLSCompliant(false)] + public static long ToInt64(uint value) + { + return value; + } + + [CLSCompliant(false)] + public static long ToInt64(ulong value) + { + if (value > long.MaxValue) ThrowInt64OverflowException(); + return (long)value; + } + + public static long ToInt64(long value) + { + return value; + } + + + public static long ToInt64(float value) + { + return ToInt64((double)value); + } + + public static long ToInt64(double value) + { + return checked((long)Math.Round(value)); + } + + public static long ToInt64(decimal value) + { + return decimal.ToInt64(decimal.Round(value, 0)); + } + + public static long ToInt64(string value) + { + if (value == null) + return 0; + return long.Parse(value, CultureInfo.CurrentCulture); + } + + public static long ToInt64(string value, IFormatProvider provider) + { + if (value == null) + return 0; + return long.Parse(value, NumberStyles.Integer, provider); + } + + public static long ToInt64(DateTime value) + { + return ((IConvertible)value).ToInt64(null); + } + + // Disallowed conversions to Int64 + // public static long ToInt64(TimeSpan value) + + // Conversions to UInt64 + + [CLSCompliant(false)] + public static ulong ToUInt64(object value) + { + return value == null ? 0 : ((IConvertible)value).ToUInt64(null); + } + + [CLSCompliant(false)] + public static ulong ToUInt64(object value, IFormatProvider provider) + { + return value == null ? 0 : ((IConvertible)value).ToUInt64(provider); + } + + [CLSCompliant(false)] + public static ulong ToUInt64(bool value) + { + return value ? (ulong)bool.True : (ulong)bool.False; + } + + [CLSCompliant(false)] + public static ulong ToUInt64(char value) + { + return value; + } + + + [CLSCompliant(false)] + public static ulong ToUInt64(sbyte value) + { + if (value < 0) ThrowUInt64OverflowException(); + return (ulong)value; + } + + [CLSCompliant(false)] + public static ulong ToUInt64(byte value) + { + return value; + } + + [CLSCompliant(false)] + public static ulong ToUInt64(short value) + { + if (value < 0) ThrowUInt64OverflowException(); + return (ulong)value; + } + + [CLSCompliant(false)] + public static ulong ToUInt64(ushort value) + { + return value; + } + + [CLSCompliant(false)] + public static ulong ToUInt64(int value) + { + if (value < 0) ThrowUInt64OverflowException(); + return (ulong)value; + } + + [CLSCompliant(false)] + public static ulong ToUInt64(uint value) + { + return value; + } + + [CLSCompliant(false)] + public static ulong ToUInt64(long value) + { + if (value < 0) ThrowUInt64OverflowException(); + return (ulong)value; + } + + [CLSCompliant(false)] + public static ulong ToUInt64(ulong value) + { + return value; + } + + [CLSCompliant(false)] + public static ulong ToUInt64(float value) + { + return ToUInt64((double)value); + } + + [CLSCompliant(false)] + public static ulong ToUInt64(double value) + { + return checked((ulong)Math.Round(value)); + } + + [CLSCompliant(false)] + public static ulong ToUInt64(decimal value) + { + return decimal.ToUInt64(decimal.Round(value, 0)); + } + + [CLSCompliant(false)] + public static ulong ToUInt64(string value) + { + if (value == null) + return 0; + return ulong.Parse(value, CultureInfo.CurrentCulture); + } + + [CLSCompliant(false)] + public static ulong ToUInt64(string value, IFormatProvider provider) + { + if (value == null) + return 0; + return ulong.Parse(value, NumberStyles.Integer, provider); + } + + [CLSCompliant(false)] + public static ulong ToUInt64(DateTime value) + { + return ((IConvertible)value).ToUInt64(null); + } + + // Disallowed conversions to UInt64 + // public static ulong ToUInt64(TimeSpan value) + + // Conversions to Single + + public static float ToSingle(object value) + { + return value == null ? 0 : ((IConvertible)value).ToSingle(null); + } + + public static float ToSingle(object value, IFormatProvider provider) + { + return value == null ? 0 : ((IConvertible)value).ToSingle(provider); + } + + [CLSCompliant(false)] + public static float ToSingle(sbyte value) + { + return value; + } + + public static float ToSingle(byte value) + { + return value; + } + + public static float ToSingle(char value) + { + return ((IConvertible)value).ToSingle(null); + } + + public static float ToSingle(short value) + { + return value; + } + + [CLSCompliant(false)] + public static float ToSingle(ushort value) + { + return value; + } + + public static float ToSingle(int value) + { + return value; + } + + [CLSCompliant(false)] + public static float ToSingle(uint value) + { + return value; + } + + public static float ToSingle(long value) + { + return value; + } + + [CLSCompliant(false)] + public static float ToSingle(ulong value) + { + return value; + } + + public static float ToSingle(float value) + { + return value; + } + + public static float ToSingle(double value) + { + return (float)value; + } + + public static float ToSingle(decimal value) + { + return (float)value; + } + + public static float ToSingle(string value) + { + if (value == null) + return 0; + return float.Parse(value, CultureInfo.CurrentCulture); + } + + public static float ToSingle(string value, IFormatProvider provider) + { + if (value == null) + return 0; + return float.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider); + } + + + public static float ToSingle(bool value) + { + return value ? bool.True : bool.False; + } + + public static float ToSingle(DateTime value) + { + return ((IConvertible)value).ToSingle(null); + } + + // Disallowed conversions to Single + // public static float ToSingle(TimeSpan value) + + // Conversions to Double + + public static double ToDouble(object value) + { + return value == null ? 0 : ((IConvertible)value).ToDouble(null); + } + + public static double ToDouble(object value, IFormatProvider provider) + { + return value == null ? 0 : ((IConvertible)value).ToDouble(provider); + } + + + [CLSCompliant(false)] + public static double ToDouble(sbyte value) + { + return value; + } + + public static double ToDouble(byte value) + { + return value; + } + + public static double ToDouble(short value) + { + return value; + } + + public static double ToDouble(char value) + { + return ((IConvertible)value).ToDouble(null); + } + + [CLSCompliant(false)] + public static double ToDouble(ushort value) + { + return value; + } + + public static double ToDouble(int value) + { + return value; + } + + [CLSCompliant(false)] + public static double ToDouble(uint value) + { + return value; + } + + public static double ToDouble(long value) + { + return value; + } + + [CLSCompliant(false)] + public static double ToDouble(ulong value) + { + return value; + } + + public static double ToDouble(float value) + { + return value; + } + + public static double ToDouble(double value) + { + return value; + } + + public static double ToDouble(decimal value) + { + return (double)value; + } + + public static double ToDouble(string value) + { + if (value == null) + return 0; + return double.Parse(value, CultureInfo.CurrentCulture); + } + + public static double ToDouble(string value, IFormatProvider provider) + { + if (value == null) + return 0; + return double.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider); + } + + public static double ToDouble(bool value) + { + return value ? bool.True : bool.False; + } + + public static double ToDouble(DateTime value) + { + return ((IConvertible)value).ToDouble(null); + } + + // Disallowed conversions to Double + // public static double ToDouble(TimeSpan value) + + // Conversions to Decimal + + public static decimal ToDecimal(object value) + { + return value == null ? 0 : ((IConvertible)value).ToDecimal(null); + } + + public static decimal ToDecimal(object value, IFormatProvider provider) + { + return value == null ? 0 : ((IConvertible)value).ToDecimal(provider); + } + + [CLSCompliant(false)] + public static decimal ToDecimal(sbyte value) + { + return value; + } + + public static decimal ToDecimal(byte value) + { + return value; + } + + public static decimal ToDecimal(char value) + { + return ((IConvertible)value).ToDecimal(null); + } + + public static decimal ToDecimal(short value) + { + return value; + } + + [CLSCompliant(false)] + public static decimal ToDecimal(ushort value) + { + return value; + } + + public static decimal ToDecimal(int value) + { + return value; + } + + [CLSCompliant(false)] + public static decimal ToDecimal(uint value) + { + return value; + } + + public static decimal ToDecimal(long value) + { + return value; + } + + [CLSCompliant(false)] + public static decimal ToDecimal(ulong value) + { + return value; + } + + public static decimal ToDecimal(float value) + { + return (decimal)value; + } + + public static decimal ToDecimal(double value) + { + return (decimal)value; + } + + public static decimal ToDecimal(string value) + { + if (value == null) + return 0m; + return decimal.Parse(value, CultureInfo.CurrentCulture); + } + + public static decimal ToDecimal(string value, IFormatProvider provider) + { + if (value == null) + return 0m; + return decimal.Parse(value, NumberStyles.Number, provider); + } + + public static decimal ToDecimal(decimal value) + { + return value; + } + + public static decimal ToDecimal(bool value) + { + return value ? bool.True : bool.False; + } + + public static decimal ToDecimal(DateTime value) + { + return ((IConvertible)value).ToDecimal(null); + } + + // Disallowed conversions to Decimal + // public static decimal ToDecimal(TimeSpan value) + + // Conversions to DateTime + + public static DateTime ToDateTime(DateTime value) + { + return value; + } + + public static DateTime ToDateTime(object value) + { + return value == null ? DateTime.MinValue : ((IConvertible)value).ToDateTime(null); + } + + public static DateTime ToDateTime(object value, IFormatProvider provider) + { + return value == null ? DateTime.MinValue : ((IConvertible)value).ToDateTime(provider); + } + + public static DateTime ToDateTime(string value) + { + if (value == null) + return new DateTime(0); + return DateTime.Parse(value, CultureInfo.CurrentCulture); + } + + public static DateTime ToDateTime(string value, IFormatProvider provider) + { + if (value == null) + return new DateTime(0); + return DateTime.Parse(value, provider); + } + + [CLSCompliant(false)] + public static DateTime ToDateTime(sbyte value) + { + return ((IConvertible)value).ToDateTime(null); + } + + public static DateTime ToDateTime(byte value) + { + return ((IConvertible)value).ToDateTime(null); + } + + public static DateTime ToDateTime(short value) + { + return ((IConvertible)value).ToDateTime(null); + } + + [CLSCompliant(false)] + public static DateTime ToDateTime(ushort value) + { + return ((IConvertible)value).ToDateTime(null); + } + + public static DateTime ToDateTime(int value) + { + return ((IConvertible)value).ToDateTime(null); + } + + [CLSCompliant(false)] + public static DateTime ToDateTime(uint value) + { + return ((IConvertible)value).ToDateTime(null); + } + + public static DateTime ToDateTime(long value) + { + return ((IConvertible)value).ToDateTime(null); + } + + [CLSCompliant(false)] + public static DateTime ToDateTime(ulong value) + { + return ((IConvertible)value).ToDateTime(null); + } + + public static DateTime ToDateTime(bool value) + { + return ((IConvertible)value).ToDateTime(null); + } + + public static DateTime ToDateTime(char value) + { + return ((IConvertible)value).ToDateTime(null); + } + + public static DateTime ToDateTime(float value) + { + return ((IConvertible)value).ToDateTime(null); + } + + public static DateTime ToDateTime(double value) + { + return ((IConvertible)value).ToDateTime(null); + } + + public static DateTime ToDateTime(decimal value) + { + return ((IConvertible)value).ToDateTime(null); + } + + // Disallowed conversions to DateTime + // public static DateTime ToDateTime(TimeSpan value) + + // Conversions to String + + public static string ToString(object value) + { + return ToString(value, null); + } + + public static string ToString(object value, IFormatProvider provider) + { + IConvertible ic = value as IConvertible; + if (ic != null) + return ic.ToString(provider); + IFormattable formattable = value as IFormattable; + if (formattable != null) + return formattable.ToString(null, provider); + return value == null ? string.Empty : value.ToString(); + } + + public static string ToString(bool value) + { + return value.ToString(); + } + + public static string ToString(bool value, IFormatProvider provider) + { + return value.ToString(); + } + + public static string ToString(char value) + { + return char.ToString(value); + } + + public static string ToString(char value, IFormatProvider provider) + { + return value.ToString(); + } + + [CLSCompliant(false)] + public static string ToString(sbyte value) + { + return value.ToString(CultureInfo.CurrentCulture); + } + + [CLSCompliant(false)] + public static string ToString(sbyte value, IFormatProvider provider) + { + return value.ToString(provider); + } + + public static string ToString(byte value) + { + return value.ToString(CultureInfo.CurrentCulture); + } + + public static string ToString(byte value, IFormatProvider provider) + { + return value.ToString(provider); + } + + public static string ToString(short value) + { + return value.ToString(CultureInfo.CurrentCulture); + } + + public static string ToString(short value, IFormatProvider provider) + { + return value.ToString(provider); + } + + [CLSCompliant(false)] + public static string ToString(ushort value) + { + return value.ToString(CultureInfo.CurrentCulture); + } + + [CLSCompliant(false)] + public static string ToString(ushort value, IFormatProvider provider) + { + return value.ToString(provider); + } + + public static string ToString(int value) + { + return value.ToString(CultureInfo.CurrentCulture); + } + + public static string ToString(int value, IFormatProvider provider) + { + return value.ToString(provider); + } + + [CLSCompliant(false)] + public static string ToString(uint value) + { + return value.ToString(CultureInfo.CurrentCulture); + } + + [CLSCompliant(false)] + public static string ToString(uint value, IFormatProvider provider) + { + return value.ToString(provider); + } + + public static string ToString(long value) + { + return value.ToString(CultureInfo.CurrentCulture); + } + + public static string ToString(long value, IFormatProvider provider) + { + return value.ToString(provider); + } + + [CLSCompliant(false)] + public static string ToString(ulong value) + { + return value.ToString(CultureInfo.CurrentCulture); + } + + [CLSCompliant(false)] + public static string ToString(ulong value, IFormatProvider provider) + { + return value.ToString(provider); + } + + public static string ToString(float value) + { + return value.ToString(CultureInfo.CurrentCulture); + } + + public static string ToString(float value, IFormatProvider provider) + { + return value.ToString(provider); + } + + public static string ToString(double value) + { + return value.ToString(CultureInfo.CurrentCulture); + } + + public static string ToString(double value, IFormatProvider provider) + { + return value.ToString(provider); + } + + public static string ToString(decimal value) + { + return value.ToString(CultureInfo.CurrentCulture); + } + + public static string ToString(decimal value, IFormatProvider provider) + { + return value.ToString(provider); + } + + public static string ToString(DateTime value) + { + return value.ToString(); + } + + public static string ToString(DateTime value, IFormatProvider provider) + { + return value.ToString(provider); + } + + public static string ToString(string value) + { + return value; + } + + public static string ToString(string value, IFormatProvider provider) + { + return value; // avoid the null check + } + + + // + // Conversions which understand Base XXX numbers. + // + // Parses value in base base. base can only + // be 2, 8, 10, or 16. If base is 16, the number may be preceded + // by 0x; any other leading or trailing characters cause an error. + // + public static byte ToByte(string value, int fromBase) + { + if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) + { + throw new ArgumentException(SR.Arg_InvalidBase); + } + + if (value == null) + { + return 0; + } + + int r = ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsUnsigned); + if (r < byte.MinValue || r > byte.MaxValue) + ThrowByteOverflowException(); + return (byte)r; + } + + // Parses value in base fromBase. fromBase can only + // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded + // by 0x; any other leading or trailing characters cause an error. + // + [CLSCompliant(false)] + public static sbyte ToSByte(string value, int fromBase) + { + if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) + { + throw new ArgumentException(SR.Arg_InvalidBase); + } + + if (value == null) + { + return 0; + } + + int r = ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsI1); + if (fromBase != 10 && r <= byte.MaxValue) + return (sbyte)r; + + if (r < sbyte.MinValue || r > sbyte.MaxValue) + ThrowSByteOverflowException(); + return (sbyte)r; + } + + // Parses value in base fromBase. fromBase can only + // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded + // by 0x; any other leading or trailing characters cause an error. + // + public static short ToInt16(string value, int fromBase) + { + if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) + { + throw new ArgumentException(SR.Arg_InvalidBase); + } + + if (value == null) + { + return 0; + } + + int r = ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsI2); + if (fromBase != 10 && r <= ushort.MaxValue) + return (short)r; + + if (r < short.MinValue || r > short.MaxValue) + ThrowInt16OverflowException(); + return (short)r; + } + + // Parses value in base fromBase. fromBase can only + // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded + // by 0x; any other leading or trailing characters cause an error. + // + [CLSCompliant(false)] + public static ushort ToUInt16(string value, int fromBase) + { + if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) + { + throw new ArgumentException(SR.Arg_InvalidBase); + } + + if (value == null) + { + return 0; + } + + int r = ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsUnsigned); + if (r < ushort.MinValue || r > ushort.MaxValue) + ThrowUInt16OverflowException(); + return (ushort)r; + } + + // Parses value in base fromBase. fromBase can only + // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded + // by 0x; any other leading or trailing characters cause an error. + // + public static int ToInt32(string value, int fromBase) + { + if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) + { + throw new ArgumentException(SR.Arg_InvalidBase); + } + return value != null ? + ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.IsTight) : + 0; + } + + // Parses value in base fromBase. fromBase can only + // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded + // by 0x; any other leading or trailing characters cause an error. + // + [CLSCompliant(false)] + public static uint ToUInt32(string value, int fromBase) + { + if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) + { + throw new ArgumentException(SR.Arg_InvalidBase); + } + return value != null ? + (uint)ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.TreatAsUnsigned | ParseNumbers.IsTight) : + 0; + } + + // Parses value in base fromBase. fromBase can only + // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded + // by 0x; any other leading or trailing characters cause an error. + // + public static long ToInt64(string value, int fromBase) + { + if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) + { + throw new ArgumentException(SR.Arg_InvalidBase); + } + return value != null ? + ParseNumbers.StringToLong(value.AsSpan(), fromBase, ParseNumbers.IsTight) : + 0; + } + + // Parses value in base fromBase. fromBase can only + // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded + // by 0x; any other leading or trailing characters cause an error. + // + [CLSCompliant(false)] + public static ulong ToUInt64(string value, int fromBase) + { + if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) + { + throw new ArgumentException(SR.Arg_InvalidBase); + } + return value != null ? + (ulong)ParseNumbers.StringToLong(value.AsSpan(), fromBase, ParseNumbers.TreatAsUnsigned | ParseNumbers.IsTight) : + 0; + } + + // Convert the byte value to a string in base fromBase + public static string ToString(byte value, int toBase) + { + if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) + { + throw new ArgumentException(SR.Arg_InvalidBase); + } + return ParseNumbers.IntToString((int)value, toBase, -1, ' ', ParseNumbers.PrintAsI1); + } + + // Convert the Int16 value to a string in base fromBase + public static string ToString(short value, int toBase) + { + if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) + { + throw new ArgumentException(SR.Arg_InvalidBase); + } + return ParseNumbers.IntToString((int)value, toBase, -1, ' ', ParseNumbers.PrintAsI2); + } + + // Convert the Int32 value to a string in base toBase + public static string ToString(int value, int toBase) + { + if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) + { + throw new ArgumentException(SR.Arg_InvalidBase); + } + return ParseNumbers.IntToString(value, toBase, -1, ' ', 0); + } + + // Convert the Int64 value to a string in base toBase + public static string ToString(long value, int toBase) + { + if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) + { + throw new ArgumentException(SR.Arg_InvalidBase); + } + return ParseNumbers.LongToString(value, toBase, -1, ' ', 0); + } + + public static string ToBase64String(byte[] inArray) + { + if (inArray == null) + { + throw new ArgumentNullException(nameof(inArray)); + } + return ToBase64String(new ReadOnlySpan(inArray), Base64FormattingOptions.None); + } + + public static string ToBase64String(byte[] inArray, Base64FormattingOptions options) + { + if (inArray == null) + { + throw new ArgumentNullException(nameof(inArray)); + } + return ToBase64String(new ReadOnlySpan(inArray), options); + } + + public static string ToBase64String(byte[] inArray, int offset, int length) + { + return ToBase64String(inArray, offset, length, Base64FormattingOptions.None); + } + + public static string ToBase64String(byte[] inArray, int offset, int length, Base64FormattingOptions options) + { + if (inArray == null) + throw new ArgumentNullException(nameof(inArray)); + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index); + if (offset < 0) + throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_GenericPositive); + if (offset > (inArray.Length - length)) + throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_OffsetLength); + + return ToBase64String(new ReadOnlySpan(inArray, offset, length), options); + } + + public static string ToBase64String(ReadOnlySpan bytes, Base64FormattingOptions options = Base64FormattingOptions.None) + { + if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks) + { + throw new ArgumentException(string.Format(SR.Arg_EnumIllegalVal, (int)options), nameof(options)); + } + + if (bytes.Length == 0) + { + return string.Empty; + } + + bool insertLineBreaks = (options == Base64FormattingOptions.InsertLineBreaks); + string result = string.FastAllocateString(ToBase64_CalculateAndValidateOutputLength(bytes.Length, insertLineBreaks)); + + unsafe + { + fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) + fixed (char* charsPtr = result) + { + int charsWritten = ConvertToBase64Array(charsPtr, bytesPtr, 0, bytes.Length, insertLineBreaks); + Debug.Assert(result.Length == charsWritten, $"Expected {result.Length} == {charsWritten}"); + } + } + + return result; + } + + public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut) + { + return ToBase64CharArray(inArray, offsetIn, length, outArray, offsetOut, Base64FormattingOptions.None); + } + + public static unsafe int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options) + { + //Do data verfication + if (inArray == null) + throw new ArgumentNullException(nameof(inArray)); + if (outArray == null) + throw new ArgumentNullException(nameof(outArray)); + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index); + if (offsetIn < 0) + throw new ArgumentOutOfRangeException(nameof(offsetIn), SR.ArgumentOutOfRange_GenericPositive); + if (offsetOut < 0) + throw new ArgumentOutOfRangeException(nameof(offsetOut), SR.ArgumentOutOfRange_GenericPositive); + + if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks) + { + throw new ArgumentException(string.Format(SR.Arg_EnumIllegalVal, (int)options), nameof(options)); + } + + + int retVal; + + int inArrayLength; + int outArrayLength; + int numElementsToCopy; + + inArrayLength = inArray.Length; + + if (offsetIn > (int)(inArrayLength - length)) + throw new ArgumentOutOfRangeException(nameof(offsetIn), SR.ArgumentOutOfRange_OffsetLength); + + if (inArrayLength == 0) + return 0; + + bool insertLineBreaks = (options == Base64FormattingOptions.InsertLineBreaks); + //This is the maximally required length that must be available in the char array + outArrayLength = outArray.Length; + + // Length of the char buffer required + numElementsToCopy = ToBase64_CalculateAndValidateOutputLength(length, insertLineBreaks); + + if (offsetOut > (int)(outArrayLength - numElementsToCopy)) + throw new ArgumentOutOfRangeException(nameof(offsetOut), SR.ArgumentOutOfRange_OffsetOut); + + fixed (char* outChars = &outArray[offsetOut]) + { + fixed (byte* inData = &inArray[0]) + { + retVal = ConvertToBase64Array(outChars, inData, offsetIn, length, insertLineBreaks); + } + } + + return retVal; + } + + public static unsafe bool TryToBase64Chars(ReadOnlySpan bytes, Span chars, out int charsWritten, Base64FormattingOptions options = Base64FormattingOptions.None) + { + if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks) + { + throw new ArgumentException(string.Format(SR.Arg_EnumIllegalVal, (int)options), nameof(options)); + } + + if (bytes.Length == 0) + { + charsWritten = 0; + return true; + } + + bool insertLineBreaks = (options == Base64FormattingOptions.InsertLineBreaks); + + int charLengthRequired = ToBase64_CalculateAndValidateOutputLength(bytes.Length, insertLineBreaks); + if (charLengthRequired > chars.Length) + { + charsWritten = 0; + return false; + } + + fixed (char* outChars = &MemoryMarshal.GetReference(chars)) + fixed (byte* inData = &MemoryMarshal.GetReference(bytes)) + { + charsWritten = ConvertToBase64Array(outChars, inData, 0, bytes.Length, insertLineBreaks); + return true; + } + } + + private static unsafe int ConvertToBase64Array(char* outChars, byte* inData, int offset, int length, bool insertLineBreaks) + { + int lengthmod3 = length % 3; + int calcLength = offset + (length - lengthmod3); + int j = 0; + int charcount = 0; + //Convert three bytes at a time to base64 notation. This will consume 4 chars. + int i; + + // get a pointer to the base64Table to avoid unnecessary range checking + fixed (char* base64 = &base64Table[0]) + { + for (i = offset; i < calcLength; i += 3) + { + if (insertLineBreaks) + { + if (charcount == base64LineBreakPosition) + { + outChars[j++] = '\r'; + outChars[j++] = '\n'; + charcount = 0; + } + charcount += 4; + } + outChars[j] = base64[(inData[i] & 0xfc) >> 2]; + outChars[j + 1] = base64[((inData[i] & 0x03) << 4) | ((inData[i + 1] & 0xf0) >> 4)]; + outChars[j + 2] = base64[((inData[i + 1] & 0x0f) << 2) | ((inData[i + 2] & 0xc0) >> 6)]; + outChars[j + 3] = base64[(inData[i + 2] & 0x3f)]; + j += 4; + } + + //Where we left off before + i = calcLength; + + if (insertLineBreaks && (lengthmod3 != 0) && (charcount == base64LineBreakPosition)) + { + outChars[j++] = '\r'; + outChars[j++] = '\n'; + } + + switch (lengthmod3) + { + case 2: //One character padding needed + outChars[j] = base64[(inData[i] & 0xfc) >> 2]; + outChars[j + 1] = base64[((inData[i] & 0x03) << 4) | ((inData[i + 1] & 0xf0) >> 4)]; + outChars[j + 2] = base64[(inData[i + 1] & 0x0f) << 2]; + outChars[j + 3] = base64[64]; //Pad + j += 4; + break; + case 1: // Two character padding needed + outChars[j] = base64[(inData[i] & 0xfc) >> 2]; + outChars[j + 1] = base64[(inData[i] & 0x03) << 4]; + outChars[j + 2] = base64[64]; //Pad + outChars[j + 3] = base64[64]; //Pad + j += 4; + break; + } + } + + return j; + } + + private static int ToBase64_CalculateAndValidateOutputLength(int inputLength, bool insertLineBreaks) + { + long outlen = ((long)inputLength) / 3 * 4; // the base length - we want integer division here. + outlen += ((inputLength % 3) != 0) ? 4 : 0; // at most 4 more chars for the remainder + + if (outlen == 0) + return 0; + + if (insertLineBreaks) + { + long newLines = outlen / base64LineBreakPosition; + if ((outlen % base64LineBreakPosition) == 0) + { + --newLines; + } + outlen += newLines * 2; // the number of line break chars we'll add, "\r\n" + } + + // If we overflow an int then we cannot allocate enough + // memory to output the value so throw + if (outlen > int.MaxValue) + throw new OutOfMemoryException(); + + return (int)outlen; + } + + + /// + /// Converts the specified string, which encodes binary data as Base64 digits, to the equivalent byte array. + /// + /// The string to convert + /// The array of bytes represented by the specified Base64 string. + public static byte[] FromBase64String(string s) + { + // "s" is an unfortunate parameter name, but we need to keep it for backward compat. + + if (s == null) + throw new ArgumentNullException(nameof(s)); + + + unsafe + { + fixed (char* sPtr = s) + { + return FromBase64CharPtr(sPtr, s.Length); + } + } + } + + public static bool TryFromBase64String(string s, Span bytes, out int bytesWritten) + { + if (s == null) + { + throw new ArgumentNullException(nameof(s)); + } + + return TryFromBase64Chars(s.AsSpan(), bytes, out bytesWritten); + } + + public static bool TryFromBase64Chars(ReadOnlySpan chars, Span bytes, out int bytesWritten) + { + // This is actually local to one of the nested blocks but is being declared at the top as we don't want multiple stackallocs + // for each iteraton of the loop. + Span tempBuffer = stackalloc char[4]; // Note: The tempBuffer size could be made larger than 4 but the size must be a multiple of 4. + + bytesWritten = 0; + + while (chars.Length != 0) + { + // Attempt to decode a segment that doesn't contain whitespace. + bool complete = TryDecodeFromUtf16(chars, bytes, out int consumedInThisIteration, out int bytesWrittenInThisIteration); + bytesWritten += bytesWrittenInThisIteration; + if (complete) + return true; + + chars = chars.Slice(consumedInThisIteration); + bytes = bytes.Slice(bytesWrittenInThisIteration); + + Debug.Assert(chars.Length != 0); // If TryDecodeFromUtf16() consumed the entire buffer, it could not have returned false. + if (chars[0].IsSpace()) + { + // If we got here, the very first character not consumed was a whitespace. We can skip past any consecutive whitespace, then continue decoding. + + int indexOfFirstNonSpace = 1; + for (; ; ) + { + if (indexOfFirstNonSpace == chars.Length) + break; + if (!chars[indexOfFirstNonSpace].IsSpace()) + break; + indexOfFirstNonSpace++; + } + + chars = chars.Slice(indexOfFirstNonSpace); + + if ((bytesWrittenInThisIteration % 3) != 0 && chars.Length != 0) + { + // If we got here, the last successfully decoded block encountered an end-marker, yet we have trailing non-whitespace characters. + // That is not allowed. + bytesWritten = default; + return false; + } + + // We now loop again to decode the next run of non-space characters. + } + else + { + Debug.Assert(chars.Length != 0 && !chars[0].IsSpace()); + + // If we got here, it is possible that there is whitespace that occurred in the middle of a 4-byte chunk. That is, we still have + // up to three Base64 characters that were left undecoded by the fast-path helper because they didn't form a complete 4-byte chunk. + // This is hopefully the rare case (multiline-formatted base64 message with a non-space character width that's not a multiple of 4.) + // We'll filter out whitespace and copy the remaining characters into a temporary buffer. + CopyToTempBufferWithoutWhiteSpace(chars, tempBuffer, out int consumedFromChars, out int charsWritten); + if ((charsWritten & 0x3) != 0) + { + // Even after stripping out whitespace, the number of characters is not divisible by 4. This cannot be a legal Base64 string. + bytesWritten = default; + return false; + } + + tempBuffer = tempBuffer.Slice(0, charsWritten); + if (!TryDecodeFromUtf16(tempBuffer, bytes, out int consumedFromTempBuffer, out int bytesWrittenFromTempBuffer)) + { + bytesWritten = default; + return false; + } + bytesWritten += bytesWrittenFromTempBuffer; + chars = chars.Slice(consumedFromChars); + bytes = bytes.Slice(bytesWrittenFromTempBuffer); + + if ((bytesWrittenFromTempBuffer % 3) != 0) + { + // If we got here, this decode contained one or more padding characters ('='). We can accept trailing whitespace after this + // but nothing else. + for (int i = 0; i < chars.Length; i++) + { + if (!chars[i].IsSpace()) + { + bytesWritten = default; + return false; + } + } + return true; + } + + // We now loop again to decode the next run of non-space characters. + } + } + + return true; + } + + private static void CopyToTempBufferWithoutWhiteSpace(ReadOnlySpan chars, Span tempBuffer, out int consumed, out int charsWritten) + { + Debug.Assert(tempBuffer.Length != 0); // We only bound-check after writing a character to the tempBuffer. + + charsWritten = 0; + for (int i = 0; i < chars.Length; i++) + { + char c = chars[i]; + if (!c.IsSpace()) + { + tempBuffer[charsWritten++] = c; + if (charsWritten == tempBuffer.Length) + { + consumed = i + 1; + return; + } + } + } + consumed = chars.Length; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool IsSpace(this char c) => c == ' ' || c == '\t' || c == '\r' || c == '\n'; + + /// + /// Converts the specified range of a Char array, which encodes binary data as Base64 digits, to the equivalent byte array. + /// + /// Chars representing Base64 encoding characters + /// A position within the input array. + /// Number of element to convert. + /// The array of bytes represented by the specified Base64 encoding characters. + public static byte[] FromBase64CharArray(char[] inArray, int offset, int length) + { + if (inArray == null) + throw new ArgumentNullException(nameof(inArray)); + + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index); + + if (offset < 0) + throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_GenericPositive); + + if (offset > inArray.Length - length) + throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_OffsetLength); + + + if (inArray.Length == 0) + { + return Array.Empty(); + } + + unsafe + { + fixed (char* inArrayPtr = &inArray[0]) + { + return FromBase64CharPtr(inArrayPtr + offset, length); + } + } + } + + /// + /// Convert Base64 encoding characters to bytes: + /// - Compute result length exactly by actually walking the input; + /// - Allocate new result array based on computation; + /// - Decode input into the new array; + /// + /// Pointer to the first input char + /// Number of input chars + /// + private static unsafe byte[] FromBase64CharPtr(char* inputPtr, int inputLength) + { + // The validity of parameters much be checked by callers, thus we are Critical here. + + Debug.Assert(0 <= inputLength); + + // We need to get rid of any trailing white spaces. + // Otherwise we would be rejecting input such as "abc= ": + while (inputLength > 0) + { + int lastChar = inputPtr[inputLength - 1]; + if (lastChar != (int)' ' && lastChar != (int)'\n' && lastChar != (int)'\r' && lastChar != (int)'\t') + break; + inputLength--; + } + + // Compute the output length: + int resultLength = FromBase64_ComputeResultLength(inputPtr, inputLength); + + Debug.Assert(0 <= resultLength); + + // resultLength can be zero. We will still enter FromBase64_Decode and process the input. + // It may either simply write no bytes (e.g. input = " ") or throw (e.g. input = "ab"). + + // Create result byte blob: + byte[] decodedBytes = new byte[resultLength]; + + // Convert Base64 chars into bytes: + if (!TryFromBase64Chars(new ReadOnlySpan(inputPtr, inputLength), decodedBytes, out int _)) + throw new FormatException(SR.Format_BadBase64Char); + + // Note that the number of bytes written can differ from resultLength if the caller is modifying the array + // as it is being converted. Silently ignore the failure. + // Consider throwing exception in an non in-place release. + + // We are done: + return decodedBytes; + } + + /// + /// Compute the number of bytes encoded in the specified Base 64 char array: + /// Walk the entire input counting white spaces and padding chars, then compute result length + /// based on 3 bytes per 4 chars. + /// + private static unsafe int FromBase64_ComputeResultLength(char* inputPtr, int inputLength) + { + const uint intEq = (uint)'='; + const uint intSpace = (uint)' '; + + Debug.Assert(0 <= inputLength); + + char* inputEndPtr = inputPtr + inputLength; + int usefulInputLength = inputLength; + int padding = 0; + + while (inputPtr < inputEndPtr) + { + uint c = (uint)(*inputPtr); + inputPtr++; + + // We want to be as fast as possible and filter out spaces with as few comparisons as possible. + // We end up accepting a number of illegal chars as legal white-space chars. + // This is ok: as soon as we hit them during actual decode we will recognise them as illegal and throw. + if (c <= intSpace) + usefulInputLength--; + + else if (c == intEq) + { + usefulInputLength--; + padding++; + } + } + + Debug.Assert(0 <= usefulInputLength); + + // For legal input, we can assume that 0 <= padding < 3. But it may be more for illegal input. + // We will notice it at decode when we see a '=' at the wrong place. + Debug.Assert(0 <= padding); + + // Perf: reuse the variable that stored the number of '=' to store the number of bytes encoded by the + // last group that contains the '=': + if (padding != 0) + { + if (padding == 1) + padding = 2; + else if (padding == 2) + padding = 1; + else + throw new FormatException(SR.Format_BadBase64Char); + } + + // Done: + return (usefulInputLength / 4) * 3 + padding; + } + } // class Convert +} // namespace + diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Convert.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/shared/System/Convert.cs.REMOVED.git-id deleted file mode 100644 index a7b7b7cce8..0000000000 --- a/external/corert/src/System.Private.CoreLib/shared/System/Convert.cs.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -756bf17fc55349ef4fae1a22d3ed7414f4f1e484 \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs b/external/corert/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs index bab6a92bf5..0112c81abf 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs @@ -17,25 +17,21 @@ ** ============================================================*/ -using System; -using System.Text; using System.Collections; using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.Versioning; namespace System { [Obsolete("System.CurrentSystemTimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo.Local instead.")] - internal partial class CurrentSystemTimeZone : TimeZone + internal class CurrentSystemTimeZone : TimeZone { // Standard offset in ticks to the Universal time if // no daylight saving is in used. // E.g. the offset for PST (Pacific Standard time) should be -8 * 60 * 60 * 1000 * 10000. // (1 millisecond = 10000 ticks) private long m_ticksOffset; - private String m_standardName; - private String m_daylightName; + private string m_standardName; + private string m_daylightName; internal CurrentSystemTimeZone() { @@ -46,7 +42,7 @@ namespace System m_daylightName = local.DaylightName; } - public override String StandardName + public override string StandardName { get { @@ -54,7 +50,7 @@ namespace System } } - public override String DaylightName + public override string DaylightName { get { @@ -62,7 +58,7 @@ namespace System } } - internal long GetUtcOffsetFromUniversalTime(DateTime time, ref Boolean isAmbiguousLocalDst) + internal long GetUtcOffsetFromUniversalTime(DateTime time, ref bool isAmbiguousLocalDst) { // Get the daylight changes for the year of the specified time. TimeSpan offset = new TimeSpan(m_ticksOffset); @@ -93,7 +89,7 @@ namespace System ambiguousEnd = startTime - daylightTime.Delta; } - Boolean isDst = false; + bool isDst = false; if (startTime > endTime) { // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year. @@ -126,8 +122,8 @@ namespace System { return time; } - Boolean isAmbiguousLocalDst = false; - Int64 offset = GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst); + bool isAmbiguousLocalDst = false; + long offset = GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst); long tick = time.Ticks + offset; if (tick > DateTime.MaxTicks) { @@ -193,5 +189,29 @@ namespace System return new TimeSpan(TimeZone.CalculateUtcOffset(time, GetDaylightChanges(time.Year)).Ticks + m_ticksOffset); } } + + private DaylightTime GetCachedDaylightChanges(int year) + { + object objYear = (object)year; + + if (!m_CachedDaylightChanges.Contains(objYear)) + { + DaylightTime currentDaylightChanges = CreateDaylightChanges(year); + lock (m_CachedDaylightChanges) + { + if (!m_CachedDaylightChanges.Contains(objYear)) + { + m_CachedDaylightChanges.Add(objYear, currentDaylightChanges); + } + } + } + + return (DaylightTime)m_CachedDaylightChanges[objYear]; + } + + // The per-year information is cached in in this instance value. As a result it can + // be cleaned up by CultureInfo.ClearCachedData, which will clear the instance of this object + private readonly Hashtable m_CachedDaylightChanges = new Hashtable(); + } // class CurrentSystemTimeZone } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/DataMisalignedException.cs b/external/corert/src/System.Private.CoreLib/shared/System/DataMisalignedException.cs index 2a245b6ef7..940407fc57 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/DataMisalignedException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/DataMisalignedException.cs @@ -23,13 +23,13 @@ namespace System HResult = HResults.COR_E_DATAMISALIGNED; } - public DataMisalignedException(String message) + public DataMisalignedException(string message) : base(message) { HResult = HResults.COR_E_DATAMISALIGNED; } - public DataMisalignedException(String message, Exception innerException) + public DataMisalignedException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_DATAMISALIGNED; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/DateTime.cs b/external/corert/src/System.Private.CoreLib/shared/System/DateTime.cs index b5deefa94a..5b76f60925 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/DateTime.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/DateTime.cs @@ -115,18 +115,18 @@ namespace System public static readonly DateTime MaxValue = new DateTime(MaxTicks, DateTimeKind.Unspecified); public static readonly DateTime UnixEpoch = new DateTime(UnixEpochTicks, DateTimeKind.Utc); - private const UInt64 TicksMask = 0x3FFFFFFFFFFFFFFF; - private const UInt64 FlagsMask = 0xC000000000000000; - private const UInt64 LocalMask = 0x8000000000000000; - private const Int64 TicksCeiling = 0x4000000000000000; - private const UInt64 KindUnspecified = 0x0000000000000000; - private const UInt64 KindUtc = 0x4000000000000000; - private const UInt64 KindLocal = 0x8000000000000000; - private const UInt64 KindLocalAmbiguousDst = 0xC000000000000000; - private const Int32 KindShift = 62; + private const ulong TicksMask = 0x3FFFFFFFFFFFFFFF; + private const ulong FlagsMask = 0xC000000000000000; + private const ulong LocalMask = 0x8000000000000000; + private const long TicksCeiling = 0x4000000000000000; + private const ulong KindUnspecified = 0x0000000000000000; + private const ulong KindUtc = 0x4000000000000000; + private const ulong KindLocal = 0x8000000000000000; + private const ulong KindLocalAmbiguousDst = 0xC000000000000000; + private const int KindShift = 62; - private const String TicksField = "ticks"; // Do not rename (binary serialization) - private const String DateDataField = "dateData"; // Do not rename (binary serialization) + private const string TicksField = "ticks"; // Do not rename (binary serialization) + private const string DateDataField = "dateData"; // Do not rename (binary serialization) // The data is stored as an unsigned 64-bit integer // Bits 01-62: The value of 100-nanosecond ticks where 0 represents 1/1/0001 12:00am, up until the value @@ -136,7 +136,7 @@ namespace System // savings time hour and it is in daylight savings time. This allows distinction of these // otherwise ambiguous local times and prevents data loss when round tripping from Local to // UTC time. - private readonly UInt64 _dateData; + private readonly ulong _dateData; // Constructs a DateTime from a tick count. The ticks // argument specifies the date as the number of 100-nanosecond intervals @@ -146,10 +146,10 @@ namespace System { if (ticks < MinTicks || ticks > MaxTicks) throw new ArgumentOutOfRangeException(nameof(ticks), SR.ArgumentOutOfRange_DateTimeBadTicks); - _dateData = (UInt64)ticks; + _dateData = (ulong)ticks; } - private DateTime(UInt64 dateData) + private DateTime(ulong dateData) { this._dateData = dateData; } @@ -164,17 +164,17 @@ namespace System { throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind)); } - _dateData = ((UInt64)ticks | ((UInt64)kind << KindShift)); + _dateData = ((ulong)ticks | ((ulong)kind << KindShift)); } - internal DateTime(long ticks, DateTimeKind kind, Boolean isAmbiguousDst) + internal DateTime(long ticks, DateTimeKind kind, bool isAmbiguousDst) { if (ticks < MinTicks || ticks > MaxTicks) { throw new ArgumentOutOfRangeException(nameof(ticks), SR.ArgumentOutOfRange_DateTimeBadTicks); } Debug.Assert(kind == DateTimeKind.Local, "Internal Constructor is for local times only"); - _dateData = ((UInt64)ticks | (isAmbiguousDst ? KindLocalAmbiguousDst : KindLocal)); + _dateData = ((ulong)ticks | (isAmbiguousDst ? KindLocalAmbiguousDst : KindLocal)); } // Constructs a DateTime from a given year, month, and day. The @@ -182,7 +182,7 @@ namespace System // public DateTime(int year, int month, int day) { - _dateData = (UInt64)DateToTicks(year, month, day); + _dateData = (ulong)DateToTicks(year, month, day); } // Constructs a DateTime from a given year, month, and day for @@ -199,7 +199,7 @@ namespace System // public DateTime(int year, int month, int day, int hour, int minute, int second) { - _dateData = (UInt64)(DateToTicks(year, month, day) + TimeToTicks(hour, minute, second)); + _dateData = (ulong)(DateToTicks(year, month, day) + TimeToTicks(hour, minute, second)); } public DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind) @@ -208,8 +208,8 @@ namespace System { throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind)); } - Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); - _dateData = ((UInt64)ticks | ((UInt64)kind << KindShift)); + long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); + _dateData = ((ulong)ticks | ((ulong)kind << KindShift)); } // Constructs a DateTime from a given year, month, day, hour, @@ -219,7 +219,7 @@ namespace System { if (calendar == null) throw new ArgumentNullException(nameof(calendar)); - _dateData = (UInt64)calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; + _dateData = (ulong)calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; } // Constructs a DateTime from a given year, month, day, hour, @@ -231,11 +231,11 @@ namespace System { throw new ArgumentOutOfRangeException(nameof(millisecond), SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)); } - Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); + long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); ticks += millisecond * TicksPerMillisecond; if (ticks < MinTicks || ticks > MaxTicks) throw new ArgumentException(SR.Arg_DateTimeRange); - _dateData = (UInt64)ticks; + _dateData = (ulong)ticks; } public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind) @@ -248,11 +248,11 @@ namespace System { throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind)); } - Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); + long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); ticks += millisecond * TicksPerMillisecond; if (ticks < MinTicks || ticks > MaxTicks) throw new ArgumentException(SR.Arg_DateTimeRange); - _dateData = ((UInt64)ticks | ((UInt64)kind << KindShift)); + _dateData = ((ulong)ticks | ((ulong)kind << KindShift)); } // Constructs a DateTime from a given year, month, day, hour, @@ -266,11 +266,11 @@ namespace System { throw new ArgumentOutOfRangeException(nameof(millisecond), SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)); } - Int64 ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; + long ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; ticks += millisecond * TicksPerMillisecond; if (ticks < MinTicks || ticks > MaxTicks) throw new ArgumentException(SR.Arg_DateTimeRange); - _dateData = (UInt64)ticks; + _dateData = (ulong)ticks; } public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind) @@ -285,11 +285,11 @@ namespace System { throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind)); } - Int64 ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; + long ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; ticks += millisecond * TicksPerMillisecond; if (ticks < MinTicks || ticks > MaxTicks) throw new ArgumentException(SR.Arg_DateTimeRange); - _dateData = ((UInt64)ticks | ((UInt64)kind << KindShift)); + _dateData = ((ulong)ticks | ((ulong)kind << KindShift)); } private DateTime(SerializationInfo info, StreamingContext context) @@ -297,10 +297,10 @@ namespace System if (info == null) throw new ArgumentNullException(nameof(info)); - Boolean foundTicks = false; - Boolean foundDateData = false; - Int64 serializedTicks = 0; - UInt64 serializedDateData = 0; + bool foundTicks = false; + bool foundDateData = false; + long serializedTicks = 0; + ulong serializedDateData = 0; // Get the data @@ -328,13 +328,13 @@ namespace System } else if (foundTicks) { - _dateData = (UInt64)serializedTicks; + _dateData = (ulong)serializedTicks; } else { throw new SerializationException(SR.Serialization_MissingDateTimeData); } - Int64 ticks = InternalTicks; + long ticks = InternalTicks; if (ticks < MinTicks || ticks > MaxTicks) { throw new SerializationException(SR.Serialization_DateTimeTicksOutOfRange); @@ -343,15 +343,15 @@ namespace System - internal Int64 InternalTicks + internal long InternalTicks { get { - return (Int64)(_dateData & TicksMask); + return (long)(_dateData & TicksMask); } } - private UInt64 InternalKind + private ulong InternalKind { get { @@ -459,7 +459,7 @@ namespace System } int days = DaysInMonth(y, m); if (d > days) d = days; - return new DateTime((UInt64)(DateToTicks(y, m, d) + InternalTicks % TicksPerDay) | InternalKind); + return new DateTime((ulong)(DateToTicks(y, m, d) + InternalTicks % TicksPerDay) | InternalKind); } // Returns the DateTime resulting from adding a fractional number of @@ -484,7 +484,7 @@ namespace System { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_DateArithmetic); } - return new DateTime((UInt64)(ticks + value) | InternalKind); + return new DateTime((ulong)(ticks + value) | InternalKind); } // Returns the DateTime resulting from adding the given number of @@ -511,8 +511,8 @@ namespace System // public static int Compare(DateTime t1, DateTime t2) { - Int64 ticks1 = t1.InternalTicks; - Int64 ticks2 = t2.InternalTicks; + long ticks1 = t1.InternalTicks; + long ticks2 = t2.InternalTicks; if (ticks1 > ticks2) return 1; if (ticks1 < ticks2) return -1; return 0; @@ -524,7 +524,7 @@ namespace System // occurs. Null is considered less than any instance. // // Returns a value less than zero if this object - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) return 1; if (!(value is DateTime)) @@ -610,7 +610,7 @@ namespace System // is equal to the value of this DateTime. Returns false // otherwise. // - public override bool Equals(Object value) + public override bool Equals(object value) { if (value is DateTime) { @@ -633,15 +633,15 @@ namespace System return t1.InternalTicks == t2.InternalTicks; } - public static DateTime FromBinary(Int64 dateData) + public static DateTime FromBinary(long dateData) { - if ((dateData & (unchecked((Int64)LocalMask))) != 0) + if ((dateData & (unchecked((long)LocalMask))) != 0) { // Local times need to be adjusted as you move from one time zone to another, // just as they are when serializing in text. As such the format for local times // changes to store the ticks of the UTC time, but with flags that look like a // local date. - Int64 ticks = dateData & (unchecked((Int64)TicksMask)); + long ticks = dateData & (unchecked((long)TicksMask)); // Negative ticks are stored in the top part of the range and should be converted back into a negative number if (ticks > TicksCeiling - TicksPerDay) { @@ -649,8 +649,8 @@ namespace System } // Convert the ticks back to local. If the UTC ticks are out of range, we need to default to // the UTC offset from MinValue and MaxValue to be consistent with Parse. - Boolean isAmbiguousLocalDst = false; - Int64 offsetTicks; + bool isAmbiguousLocalDst = false; + long offsetTicks; if (ticks < MinTicks) { offsetTicks = TimeZoneInfo.GetLocalUtcOffset(DateTime.MinValue, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks; @@ -664,7 +664,7 @@ namespace System // Because the ticks conversion between UTC and local is lossy, we need to capture whether the // time is in a repeated hour so that it can be passed to the DateTime constructor. DateTime utcDt = new DateTime(ticks, DateTimeKind.Utc); - Boolean isDaylightSavings = false; + bool isDaylightSavings = false; offsetTicks = TimeZoneInfo.GetUtcOffsetFromUtc(utcDt, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst).Ticks; } ticks += offsetTicks; @@ -688,12 +688,12 @@ namespace System // A version of ToBinary that uses the real representation and does not adjust local times. This is needed for // scenarios where the serialized data must maintain compatibility - internal static DateTime FromBinaryRaw(Int64 dateData) + internal static DateTime FromBinaryRaw(long dateData) { - Int64 ticks = dateData & (Int64)TicksMask; + long ticks = dateData & (long)TicksMask; if (ticks < MinTicks || ticks > MaxTicks) throw new ArgumentException(SR.Argument_DateTimeBadBinaryData, nameof(dateData)); - return new DateTime((UInt64)dateData); + return new DateTime((ulong)dateData); } // Creates a DateTime from a Windows filetime. A Windows filetime is @@ -736,7 +736,7 @@ namespace System info.AddValue(DateDataField, _dateData); } - public Boolean IsDaylightSavingTime() + public bool IsDaylightSavingTime() { if (Kind == DateTimeKind.Utc) { @@ -750,7 +750,7 @@ namespace System return new DateTime(value.InternalTicks, kind); } - public Int64 ToBinary() + public long ToBinary() { if (Kind == DateTimeKind.Local) { @@ -765,17 +765,17 @@ namespace System // end of the maximum range, and values just below minimum value are stored // at the end of the ticks area, just below 2^62. TimeSpan offset = TimeZoneInfo.GetLocalUtcOffset(this, TimeZoneInfoOptions.NoThrowOnInvalidTime); - Int64 ticks = Ticks; - Int64 storedTicks = ticks - offset.Ticks; + long ticks = Ticks; + long storedTicks = ticks - offset.Ticks; if (storedTicks < 0) { storedTicks = TicksCeiling + storedTicks; } - return storedTicks | (unchecked((Int64)LocalMask)); + return storedTicks | (unchecked((long)LocalMask)); } else { - return (Int64)_dateData; + return (long)_dateData; } } @@ -787,8 +787,8 @@ namespace System { get { - Int64 ticks = InternalTicks; - return new DateTime((UInt64)(ticks - ticks % TicksPerDay) | InternalKind); + long ticks = InternalTicks; + return new DateTime((ulong)(ticks - ticks % TicksPerDay) | InternalKind); } } @@ -796,7 +796,7 @@ namespace System // to compute the year, day-of-year, month, or day part. private int GetDatePart(int part) { - Int64 ticks = InternalTicks; + long ticks = InternalTicks; // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 @@ -846,7 +846,7 @@ namespace System // are needed rather than redoing the computations for each. internal void GetDatePart(out int year, out int month, out int day) { - Int64 ticks = InternalTicks; + long ticks = InternalTicks; // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 @@ -925,7 +925,7 @@ namespace System // public override int GetHashCode() { - Int64 ticks = InternalTicks; + long ticks = InternalTicks; return unchecked((int)ticks) ^ (int)(ticks >> 32); } @@ -940,7 +940,7 @@ namespace System } } - internal Boolean IsAmbiguousDaylightSavingTime() + internal bool IsAmbiguousDaylightSavingTime() { return (InternalKind == KindLocalAmbiguousDst); } @@ -1001,8 +1001,8 @@ namespace System get { DateTime utc = UtcNow; - Boolean isAmbiguousLocalDst = false; - Int64 offset = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utc, out isAmbiguousLocalDst).Ticks; + bool isAmbiguousLocalDst = false; + long offset = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utc, out isAmbiguousLocalDst).Ticks; long tick = utc.Ticks + offset; if (tick > DateTime.MaxTicks) { @@ -1089,7 +1089,7 @@ namespace System // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // - public static DateTime Parse(String s) + public static DateTime Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return (DateTimeParse.Parse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None)); @@ -1099,13 +1099,13 @@ namespace System // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // - public static DateTime Parse(String s, IFormatProvider provider) + public static DateTime Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return (DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), DateTimeStyles.None)); } - public static DateTime Parse(String s, IFormatProvider provider, DateTimeStyles styles) + public static DateTime Parse(string s, IFormatProvider provider, DateTimeStyles styles) { DateTimeFormatInfo.ValidateStyles(styles, nameof(styles)); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -1122,7 +1122,7 @@ namespace System // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // - public static DateTime ParseExact(String s, String format, IFormatProvider provider) + public static DateTime ParseExact(string s, string format, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); @@ -1133,7 +1133,7 @@ namespace System // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // - public static DateTime ParseExact(String s, String format, IFormatProvider provider, DateTimeStyles style) + public static DateTime ParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -1141,20 +1141,13 @@ namespace System return (DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style)); } - // TODO https://github.com/dotnet/corefx/issues/25337: Remove this overload once corefx is updated to target the new signatures - public static DateTime ParseExact(ReadOnlySpan s, string format, IFormatProvider provider, DateTimeStyles style) - { - if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); - return ParseExact(s, (ReadOnlySpan)format, provider, style); - } - public static DateTime ParseExact(ReadOnlySpan s, ReadOnlySpan format, IFormatProvider provider, DateTimeStyles style = DateTimeStyles.None) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); return DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style); } - public static DateTime ParseExact(String s, String[] formats, IFormatProvider provider, DateTimeStyles style) + public static DateTime ParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -1180,7 +1173,7 @@ namespace System { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_DateArithmetic); } - return new DateTime((UInt64)(ticks - valueTicks) | InternalKind); + return new DateTime((ulong)(ticks - valueTicks) | InternalKind); } // This function is duplicated in COMDateTime.cpp @@ -1239,9 +1232,9 @@ namespace System { return this; } - Boolean isDaylightSavings = false; - Boolean isAmbiguousLocalDst = false; - Int64 offset = TimeZoneInfo.GetUtcOffsetFromUtc(this, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst).Ticks; + bool isDaylightSavings = false; + bool isAmbiguousLocalDst = false; + long offset = TimeZoneInfo.GetUtcOffsetFromUtc(this, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst).Ticks; long tick = Ticks + offset; if (tick > DateTime.MaxTicks) { @@ -1260,59 +1253,55 @@ namespace System return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst); } - public String ToLongDateString() + public string ToLongDateString() { - return DateTimeFormat.Format(this, "D", DateTimeFormatInfo.CurrentInfo); + return DateTimeFormat.Format(this, "D", null); } - public String ToLongTimeString() + public string ToLongTimeString() { - return DateTimeFormat.Format(this, "T", DateTimeFormatInfo.CurrentInfo); + return DateTimeFormat.Format(this, "T", null); } - public String ToShortDateString() + public string ToShortDateString() { - return DateTimeFormat.Format(this, "d", DateTimeFormatInfo.CurrentInfo); + return DateTimeFormat.Format(this, "d", null); } - public String ToShortTimeString() + public string ToShortTimeString() { - return DateTimeFormat.Format(this, "t", DateTimeFormatInfo.CurrentInfo); + return DateTimeFormat.Format(this, "t", null); } - public override String ToString() + public override string ToString() { - return DateTimeFormat.Format(this, null, DateTimeFormatInfo.CurrentInfo); + return DateTimeFormat.Format(this, null, null); } - public String ToString(String format) + public string ToString(string format) { - return DateTimeFormat.Format(this, format, DateTimeFormatInfo.CurrentInfo); + return DateTimeFormat.Format(this, format, null); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { - return DateTimeFormat.Format(this, null, DateTimeFormatInfo.GetInstance(provider)); + return DateTimeFormat.Format(this, null, provider); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { - return DateTimeFormat.Format(this, format, DateTimeFormatInfo.GetInstance(provider)); + return DateTimeFormat.Format(this, format, provider); } - // TODO https://github.com/dotnet/corefx/issues/25337: Remove this overload once corefx is updated to target the new signatures - public bool TryFormat(Span destination, out int charsWritten, string format, IFormatProvider provider) => - TryFormat(destination, out charsWritten, (ReadOnlySpan)format, provider); - public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default, IFormatProvider provider = null) => - DateTimeFormat.TryFormat(this, destination, out charsWritten, format, DateTimeFormatInfo.GetInstance(provider)); + DateTimeFormat.TryFormat(this, destination, out charsWritten, format, provider); public DateTime ToUniversalTime() { return TimeZoneInfo.ConvertTimeToUtc(this, TimeZoneInfoOptions.NoThrowOnInvalidTime); } - public static Boolean TryParse(String s, out DateTime result) + public static bool TryParse(string s, out DateTime result) { if (s == null) { @@ -1327,7 +1316,7 @@ namespace System return DateTimeParse.TryParse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out result); } - public static Boolean TryParse(String s, IFormatProvider provider, DateTimeStyles styles, out DateTime result) + public static bool TryParse(string s, IFormatProvider provider, DateTimeStyles styles, out DateTime result) { DateTimeFormatInfo.ValidateStyles(styles, nameof(styles)); @@ -1346,7 +1335,7 @@ namespace System return DateTimeParse.TryParse(s, DateTimeFormatInfo.GetInstance(provider), styles, out result); } - public static Boolean TryParseExact(String s, String format, IFormatProvider provider, DateTimeStyles style, out DateTime result) + public static bool TryParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); @@ -1359,25 +1348,13 @@ namespace System return DateTimeParse.TryParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style, out result); } - // TODO https://github.com/dotnet/corefx/issues/25337: Remove this overload once corefx is updated to target the new signatures - public static bool TryParseExact(ReadOnlySpan s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result) - { - if (format == null) - { - result = default; - return false; - } - - return TryParseExact(s, (ReadOnlySpan)format, provider, style, out result); - } - public static bool TryParseExact(ReadOnlySpan s, ReadOnlySpan format, IFormatProvider provider, DateTimeStyles style, out DateTime result) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); return DateTimeParse.TryParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style, out result); } - public static Boolean TryParseExact(String s, String[] formats, IFormatProvider provider, DateTimeStyles style, out DateTime result) + public static bool TryParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style, out DateTime result) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); @@ -1404,7 +1381,7 @@ namespace System { throw new ArgumentOutOfRangeException(nameof(t), SR.ArgumentOutOfRange_DateArithmetic); } - return new DateTime((UInt64)(ticks + valueTicks) | d.InternalKind); + return new DateTime((ulong)(ticks + valueTicks) | d.InternalKind); } public static DateTime operator -(DateTime d, TimeSpan t) @@ -1415,7 +1392,7 @@ namespace System { throw new ArgumentOutOfRangeException(nameof(t), SR.ArgumentOutOfRange_DateArithmetic); } - return new DateTime((UInt64)(ticks - valueTicks) | d.InternalKind); + return new DateTime((ulong)(ticks - valueTicks) | d.InternalKind); } public static TimeSpan operator -(DateTime d1, DateTime d2) @@ -1457,7 +1434,7 @@ namespace System // Returns a string array containing all of the known date and time options for the // current culture. The strings returned are properly formatted date and // time strings for the current instance of DateTime. - public String[] GetDateTimeFormats() + public string[] GetDateTimeFormats() { return (GetDateTimeFormats(CultureInfo.CurrentCulture)); } @@ -1465,7 +1442,7 @@ namespace System // Returns a string array containing all of the known date and time options for the // using the information provided by IFormatProvider. The strings returned are properly formatted date and // time strings for the current instance of DateTime. - public String[] GetDateTimeFormats(IFormatProvider provider) + public string[] GetDateTimeFormats(IFormatProvider provider) { return (DateTimeFormat.GetAllDateTimes(this, DateTimeFormatInfo.GetInstance(provider))); } @@ -1474,7 +1451,7 @@ namespace System // Returns a string array containing all of the date and time options for the // given format format and current culture. The strings returned are properly formatted date and // time strings for the current instance of DateTime. - public String[] GetDateTimeFormats(char format) + public string[] GetDateTimeFormats(char format) { return (GetDateTimeFormats(format, CultureInfo.CurrentCulture)); } @@ -1482,7 +1459,7 @@ namespace System // Returns a string array containing all of the date and time options for the // given format format and given culture. The strings returned are properly formatted date and // time strings for the current instance of DateTime. - public String[] GetDateTimeFormats(char format, IFormatProvider provider) + public string[] GetDateTimeFormats(char format, IFormatProvider provider) { return (DateTimeFormat.GetAllDateTimes(this, format, DateTimeFormatInfo.GetInstance(provider))); } @@ -1557,7 +1534,7 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "Double")); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "Decimal")); } @@ -1567,7 +1544,7 @@ namespace System return this; } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } @@ -1575,7 +1552,7 @@ namespace System // Tries to construct a DateTime from a given year, month, day, hour, // minute, second and millisecond. // - internal static Boolean TryCreate(int year, int month, int day, int hour, int minute, int second, int millisecond, out DateTime result) + internal static bool TryCreate(int year, int month, int day, int hour, int minute, int second, int millisecond, out DateTime result) { result = DateTime.MinValue; if (year < 1 || year > 9999 || month < 1 || month > 12) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs b/external/corert/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs index bb2196348c..e89cbc6caf 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs @@ -31,11 +31,11 @@ namespace System [StructLayout(LayoutKind.Auto)] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct DateTimeOffset : IComparable, IFormattable, IComparable, IEquatable, ISerializable, IDeserializationCallback, ISpanFormattable + public readonly struct DateTimeOffset : IComparable, IFormattable, IComparable, IEquatable, ISerializable, IDeserializationCallback, ISpanFormattable { // Constants - internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14; - internal const Int64 MinOffset = -MaxOffset; + internal const long MaxOffset = TimeSpan.TicksPerHour * 14; + internal const long MinOffset = -MaxOffset; private const long UnixEpochSeconds = DateTime.UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800 private const long UnixEpochMilliseconds = DateTime.UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000 @@ -49,8 +49,8 @@ namespace System public static readonly DateTimeOffset UnixEpoch = new DateTimeOffset(DateTime.UnixEpochTicks, TimeSpan.Zero); // Instance Fields - private DateTime _dateTime; - private Int16 _offsetMinutes; + private readonly DateTime _dateTime; + private readonly short _offsetMinutes; // Constructors @@ -447,7 +447,7 @@ namespace System // argument must be another DateTimeOffset, or otherwise an exception // occurs. Null is considered less than any instance. // - int IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { if (obj == null) return 1; if (!(obj is DateTimeOffset)) @@ -477,7 +477,7 @@ namespace System // is equal to the value of this DateTimeOffset. Returns false // otherwise. // - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (obj is DateTimeOffset) { @@ -549,12 +549,12 @@ namespace System // ----- SECTION: private serialization instance methods ----------------* - void IDeserializationCallback.OnDeserialization(Object sender) + void IDeserializationCallback.OnDeserialization(object sender) { try { - _offsetMinutes = ValidateOffset(Offset); - _dateTime = ValidateDate(ClockDateTime, Offset); + ValidateOffset(Offset); + ValidateDate(ClockDateTime, Offset); } catch (ArgumentException e) { @@ -583,7 +583,7 @@ namespace System } _dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime)); // Do not rename (binary serialization) - _offsetMinutes = (Int16)info.GetValue("OffsetMinutes", typeof(Int16)); // Do not rename (binary serialization) + _offsetMinutes = (short)info.GetValue("OffsetMinutes", typeof(short)); // Do not rename (binary serialization) } // Returns the hash code for this DateTimeOffset. @@ -597,7 +597,7 @@ namespace System // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // - public static DateTimeOffset Parse(String input) + public static DateTimeOffset Parse(string input) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); @@ -613,13 +613,13 @@ namespace System // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // - public static DateTimeOffset Parse(String input, IFormatProvider formatProvider) + public static DateTimeOffset Parse(string input, IFormatProvider formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return Parse(input, formatProvider, DateTimeStyles.None); } - public static DateTimeOffset Parse(String input, IFormatProvider formatProvider, DateTimeStyles styles) + public static DateTimeOffset Parse(string input, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); @@ -643,7 +643,7 @@ namespace System // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // - public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider) + public static DateTimeOffset ParseExact(string input, string format, IFormatProvider formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); @@ -654,7 +654,7 @@ namespace System // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // - public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles) + public static DateTimeOffset ParseExact(string input, string format, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); @@ -669,13 +669,6 @@ namespace System return new DateTimeOffset(dateResult.Ticks, offset); } - // TODO https://github.com/dotnet/corefx/issues/25337: Remove this overload once corefx is updated to target the new signatures - public static DateTimeOffset ParseExact(ReadOnlySpan input, string format, IFormatProvider formatProvider, DateTimeStyles styles) - { - if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); - return ParseExact(input, (ReadOnlySpan)format, formatProvider, styles); - } - public static DateTimeOffset ParseExact(ReadOnlySpan input, ReadOnlySpan format, IFormatProvider formatProvider, DateTimeStyles styles = DateTimeStyles.None) { styles = ValidateStyles(styles, nameof(styles)); @@ -683,7 +676,7 @@ namespace System return new DateTimeOffset(dateResult.Ticks, offset); } - public static DateTimeOffset ParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles) + public static DateTimeOffset ParseExact(string input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); @@ -760,43 +753,39 @@ namespace System return new DateTimeOffset(UtcDateTime.ToLocalTime(throwOnOverflow)); } - public override String ToString() + public override string ToString() { - return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.CurrentInfo, Offset); + return DateTimeFormat.Format(ClockDateTime, null, null, Offset); } - public String ToString(String format) + public string ToString(string format) { - return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, Offset); + return DateTimeFormat.Format(ClockDateTime, format, null, Offset); } - public String ToString(IFormatProvider formatProvider) + public string ToString(IFormatProvider formatProvider) { - return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.GetInstance(formatProvider), Offset); + return DateTimeFormat.Format(ClockDateTime, null, formatProvider, Offset); } - public String ToString(String format, IFormatProvider formatProvider) + public string ToString(string format, IFormatProvider formatProvider) { - return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset); + return DateTimeFormat.Format(ClockDateTime, format, formatProvider, Offset); } - // TODO https://github.com/dotnet/corefx/issues/25337: Remove this overload once corefx is updated to target the new signatures - public bool TryFormat(Span destination, out int charsWritten, string format, IFormatProvider provider) => - TryFormat(destination, out charsWritten, (ReadOnlySpan)format, provider); - public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default, IFormatProvider formatProvider = null) => - DateTimeFormat.TryFormat(ClockDateTime, destination, out charsWritten, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset); + DateTimeFormat.TryFormat(ClockDateTime, destination, out charsWritten, format, formatProvider, Offset); public DateTimeOffset ToUniversalTime() { return new DateTimeOffset(UtcDateTime); } - public static Boolean TryParse(String input, out DateTimeOffset result) + public static bool TryParse(string input, out DateTimeOffset result) { TimeSpan offset; DateTime dateResult; - Boolean parsed = DateTimeParse.TryParse(input, + bool parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out dateResult, @@ -812,18 +801,18 @@ namespace System return parsed; } - public static Boolean TryParse(String input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) + public static bool TryParse(string input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) { - result = default(DateTimeOffset); + result = default; return false; } TimeSpan offset; DateTime dateResult; - Boolean parsed = DateTimeParse.TryParse(input, + bool parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, @@ -840,19 +829,19 @@ namespace System return parsed; } - public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles, + public static bool TryParseExact(string input, string format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); if (input == null || format == null) { - result = default(DateTimeOffset); + result = default; return false; } TimeSpan offset; DateTime dateResult; - Boolean parsed = DateTimeParse.TryParseExact(input, + bool parsed = DateTimeParse.TryParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, @@ -862,18 +851,6 @@ namespace System return parsed; } - // TODO https://github.com/dotnet/corefx/issues/25337: Remove this overload once corefx is updated to target the new signatures - public static bool TryParseExact(ReadOnlySpan input, string format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) - { - if (format == null) - { - result = default; - return false; - } - - return TryParseExact(input, (ReadOnlySpan)format, formatProvider, styles, out result); - } - public static bool TryParseExact( ReadOnlySpan input, ReadOnlySpan format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { @@ -883,19 +860,19 @@ namespace System return parsed; } - public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles, + public static bool TryParseExact(string input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) { - result = default(DateTimeOffset); + result = default; return false; } TimeSpan offset; DateTime dateResult; - Boolean parsed = DateTimeParse.TryParseExactMultiple(input, + bool parsed = DateTimeParse.TryParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, @@ -915,9 +892,9 @@ namespace System } // Ensures the TimeSpan is valid to go in a DateTimeOffset. - private static Int16 ValidateOffset(TimeSpan offset) + private static short ValidateOffset(TimeSpan offset) { - Int64 ticks = offset.Ticks; + long ticks = offset.Ticks; if (ticks % TimeSpan.TicksPerMinute != 0) { throw new ArgumentException(SR.Argument_OffsetPrecision, nameof(offset)); @@ -926,7 +903,7 @@ namespace System { throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_OffsetOutOfRange); } - return (Int16)(offset.Ticks / TimeSpan.TicksPerMinute); + return (short)(offset.Ticks / TimeSpan.TicksPerMinute); } // Ensures that the time and offset are in range. @@ -937,8 +914,8 @@ namespace System Debug.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated."); // This operation cannot overflow because offset should have already been validated to be within - // 14 hours and the DateTime instance is more than that distance from the boundaries of Int64. - Int64 utcTicks = dateTime.Ticks - offset.Ticks; + // 14 hours and the DateTime instance is more than that distance from the boundaries of long. + long utcTicks = dateTime.Ticks - offset.Ticks; if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) { throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_UTCOutOfRange); @@ -948,7 +925,7 @@ namespace System return new DateTime(utcTicks, DateTimeKind.Unspecified); } - private static DateTimeStyles ValidateStyles(DateTimeStyles style, String parameterName) + private static DateTimeStyles ValidateStyles(DateTimeStyles style, string parameterName) { if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0) { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Decimal.DecCalc.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/shared/System/Decimal.DecCalc.cs.REMOVED.git-id new file mode 100644 index 0000000000..98c79ece53 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Decimal.DecCalc.cs.REMOVED.git-id @@ -0,0 +1 @@ +22574c106689d5289f6430bb1805a6fdcd14a018 \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/src/System/Decimal.cs b/external/corert/src/System.Private.CoreLib/shared/System/Decimal.cs similarity index 66% rename from external/corert/src/System.Private.CoreLib/src/System/Decimal.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Decimal.cs index a6bd055529..7e472b70c2 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Decimal.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Decimal.cs @@ -52,12 +52,13 @@ namespace System // throw an exception. A conversion from float or double to // Decimal throws an OverflowException if the value is not within // the range of the Decimal type. + [StructLayout(LayoutKind.Sequential)] [Serializable] - [StructLayout(LayoutKind.Explicit)] + [System.Runtime.Versioning.NonVersionable] // This only applies to field layout #if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] #endif - public partial struct Decimal : IFormattable, IComparable, IConvertible, IComparable, IEquatable, IDeserializationCallback, ISpanFormattable + public readonly partial struct Decimal : IFormattable, IComparable, IConvertible, IComparable, IEquatable, IDeserializationCallback, ISpanFormattable { // Sign mask for the flags field. A value of zero in this bit indicates a // positive Decimal value, and a value of one in this bit indicates a @@ -65,34 +66,32 @@ namespace System // // Look at OleAut's DECIMAL_NEG constant to check for negative values // in native code. - private const uint SignMask = 0x80000000; + private const int SignMask = unchecked((int)0x80000000); // Scale mask for the flags field. This byte in the flags field contains // the power of 10 to divide the Decimal value by. The scale byte must // contain a value between 0 and 28 inclusive. - private const uint ScaleMask = 0x00FF0000; + private const int ScaleMask = 0x00FF0000; // Number of bits scale is shifted by. private const int ScaleShift = 16; // Constant representing the Decimal value 0. - public const Decimal Zero = 0m; + public const decimal Zero = 0m; // Constant representing the Decimal value 1. - public const Decimal One = 1m; + public const decimal One = 1m; // Constant representing the Decimal value -1. - public const Decimal MinusOne = -1m; + public const decimal MinusOne = -1m; // Constant representing the largest possible Decimal value. The value of // this constant is 79,228,162,514,264,337,593,543,950,335. - public const Decimal MaxValue = 79228162514264337593543950335m; + public const decimal MaxValue = 79228162514264337593543950335m; // Constant representing the smallest possible Decimal value. The value of // this constant is -79,228,162,514,264,337,593,543,950,335. - public const Decimal MinValue = -79228162514264337593543950335m; - - private const int CurrencyScale = 4; // Divide the "Int64" representation by 1E4 to get the "true" value of the Currency. + public const decimal MinValue = -79228162514264337593543950335m; // The lo, mid, hi, and flags fields contain the representation of the // Decimal value. The lo, mid, and hi fields contain the 96-bit integer @@ -103,51 +102,28 @@ namespace System // and finally bit 31 indicates the sign of the Decimal value, 0 meaning // positive and 1 meaning negative. // - // NOTE: Do not change the offsets of these fields. This structure maps to the OleAut DECIMAL structure - // and can be passed as such in P/Invokes. - [FieldOffset(0)] - private int flags; // Do not rename (binary serialization) - [FieldOffset(4)] - private int hi; // Do not rename (binary serialization) - [FieldOffset(8)] - private int lo; // Do not rename (binary serialization) - [FieldOffset(12)] - private int mid; // Do not rename (binary serialization) - - // NOTE: This set of fields overlay the ones exposed to serialization (which have to be signed ints for serialization compat.) - // The code inside Decimal was ported from C++ and expect unsigned values. - [FieldOffset(0), NonSerialized] - private uint uflags; - [FieldOffset(4), NonSerialized] - private uint uhi; - [FieldOffset(8), NonSerialized] - private uint ulo; - [FieldOffset(12), NonSerialized] - private uint umid; - - /// - /// The low and mid fields combined in little-endian order - /// - [FieldOffset(8), NonSerialized] - private ulong ulomidLE; + // NOTE: Do not change the order in which these fields are declared. The + // native methods in this class rely on this particular order. + // Do not rename (binary serialization). + private readonly int flags; + private readonly int hi; + private readonly int lo; + private readonly int mid; // Constructs a Decimal from an integer value. // public Decimal(int value) { - // JIT today can't inline methods that contains "starg" opcode. - // For more details, see DevDiv Bugs 81184: x86 JIT CQ: Removing the inline striction of "starg". - int value_copy = value; - if (value_copy >= 0) + if (value >= 0) { - uflags = 0; + flags = 0; } else { - uflags = SignMask; - value_copy = -value_copy; + flags = SignMask; + value = -value; } - lo = value_copy; + lo = value; mid = 0; hi = 0; } @@ -157,30 +133,28 @@ namespace System [CLSCompliant(false)] public Decimal(uint value) { - uflags = 0; - ulo = value; - umid = 0; - uhi = 0; + flags = 0; + lo = (int)value; + mid = 0; + hi = 0; } // Constructs a Decimal from a long value. // public Decimal(long value) { - // JIT today can't inline methods that contains "starg" opcode. - // For more details, see DevDiv Bugs 81184: x86 JIT CQ: Removing the inline striction of "starg". - long value_copy = value; - if (value_copy >= 0) + if (value >= 0) { - uflags = 0; + flags = 0; } else { - uflags = SignMask; - value_copy = -value_copy; + flags = SignMask; + value = -value; } - Low64 = (ulong)value_copy; - uhi = 0; + lo = (int)value; + mid = (int)(value >> 32); + hi = 0; } // Constructs a Decimal from an unsigned long value. @@ -188,23 +162,24 @@ namespace System [CLSCompliant(false)] public Decimal(ulong value) { - uflags = 0; - Low64 = value; - uhi = 0; + flags = 0; + lo = (int)value; + mid = (int)(value >> 32); + hi = 0; } // Constructs a Decimal from a float value. // public Decimal(float value) { - DecCalc.VarDecFromR4(value, out this); + DecCalc.VarDecFromR4(value, out AsMutable(ref this)); } // Constructs a Decimal from a double value. // public Decimal(double value) { - DecCalc.VarDecFromR8(value, out this); + DecCalc.VarDecFromR8(value, out AsMutable(ref this)); } // @@ -213,15 +188,13 @@ namespace System // A Currency represents a positive or negative decimal value with 4 digits past the decimal point. The actual Int64 representation used by these methods // is the currency value multiplied by 10,000. For example, a currency value of $12.99 would be represented by the Int64 value 129,900. // - - public static Decimal FromOACurrency(long cy) + public static decimal FromOACurrency(long cy) { - Decimal d = default(Decimal); - ulong absoluteCy; // has to be ulong to accommodate the case where cy == long.MinValue. + bool isNegative = false; if (cy < 0) { - d.IsNegative = true; + isNegative = true; absoluteCy = (ulong)(-cy); } else @@ -232,7 +205,7 @@ namespace System // In most cases, FromOACurrency() produces a Decimal with Scale set to 4. Unless, that is, some of the trailing digits past the decimal point are zero, // in which case, for compatibility with .Net, we reduce the Scale by the number of zeros. While the result is still numerically equivalent, the scale does // affect the ToString() value. In particular, it prevents a converted currency value of $12.95 from printing uglily as "12.9500". - int scale = CurrencyScale; + int scale = 4; if (absoluteCy != 0) // For compatibility, a currency of 0 emits the Decimal "0.0000" (scale set to 4). { while (scale != 0 && ((absoluteCy % 10) == 0)) @@ -242,18 +215,15 @@ namespace System } } - // No need to set d.Hi32 - a currency will never go high enough for it to be anything other than zero. - d.Low64 = absoluteCy; - d.Scale = scale; - return d; + return new decimal((int)absoluteCy, (int)(absoluteCy >> 32), 0, isNegative, (byte)scale); } - public static long ToOACurrency(Decimal value) + public static long ToOACurrency(decimal value) { - return DecCalc.VarCyFromDec(ref value); + return DecCalc.VarCyFromDec(ref AsMutable(ref value)); } - private static bool IsValid(uint flags) => (flags & ~(SignMask | ScaleMask)) == 0 && ((flags & ScaleMask) <= (28 << 16)); + private static bool IsValid(int flags) => (flags & ~(SignMask | ScaleMask)) == 0 && ((uint)(flags & ScaleMask) <= (28 << ScaleShift)); // Constructs a Decimal from an integer array containing a binary // representation. The bits argument must be a non-null integer @@ -280,13 +250,13 @@ namespace System throw new ArgumentNullException(nameof(bits)); if (bits.Length == 4) { - uint f = (uint)bits[3]; + int f = bits[3]; if (IsValid(f)) { lo = bits[0]; mid = bits[1]; hi = bits[2]; - uflags = f; + flags = f; return; } } @@ -302,62 +272,73 @@ namespace System this.lo = lo; this.mid = mid; this.hi = hi; - uflags = ((uint)scale) << 16; + flags = ((int)scale) << 16; if (isNegative) - uflags |= SignMask; + flags |= SignMask; } - void IDeserializationCallback.OnDeserialization(Object sender) + void IDeserializationCallback.OnDeserialization(object sender) { // OnDeserialization is called after each instance of this class is deserialized. // This callback method performs decimal validation after being deserialized. - if (!IsValid(uflags)) + if (!IsValid(flags)) throw new SerializationException(SR.Overflow_Decimal); } // Constructs a Decimal from its constituent parts. - private Decimal(ulong ulomidLE, uint hi, uint flags) + private Decimal(int lo, int mid, int hi, int flags) { - this.ulomidLE = ulomidLE; - this.uhi = hi; - this.uflags = flags; + if (IsValid(flags)) + { + this.lo = lo; + this.mid = mid; + this.hi = hi; + this.flags = flags; + return; + } + throw new ArgumentException(SR.Arg_DecBitCtor); + } + + private Decimal(in decimal d, int flags) + { + this = d; + this.flags = flags; } // Returns the absolute value of the given Decimal. If d is // positive, the result is d. If d is negative, the result // is -d. // - internal static Decimal Abs(ref Decimal d) + internal static decimal Abs(ref decimal d) { - return new Decimal(d.ulomidLE, d.uhi, d.uflags & ~SignMask); + return new decimal(in d, d.flags & ~SignMask); } - // Adds two Decimal values. // - public static Decimal Add(Decimal d1, Decimal d2) + public static decimal Add(decimal d1, decimal d2) { - DecCalc.VarDecAdd(ref d1, ref d2); + DecCalc.DecAddSub(ref AsMutable(ref d1), ref AsMutable(ref d2), false); return d1; } // Rounds a Decimal to an integer value. The Decimal argument is rounded // towards positive infinity. - public static Decimal Ceiling(Decimal d) + public static decimal Ceiling(decimal d) { - uint flags = d.uflags; + int flags = d.flags; if ((flags & ScaleMask) != 0) - DecCalc.InternalRound(ref d, (byte)(flags >> ScaleShift), DecCalc.RoundingMode.Ceiling); + DecCalc.InternalRound(ref AsMutable(ref d), (byte)(flags >> ScaleShift), DecCalc.RoundingMode.Ceiling); return d; } // Compares two Decimal values, returning an integer that indicates their // relationship. // - public static int Compare(Decimal d1, Decimal d2) + public static int Compare(decimal d1, decimal d2) { - return DecCalc.VarDecCmp(ref d1, ref d2); + return DecCalc.VarDecCmp(in d1, in d2); } // Compares this object to another object, returning an integer that @@ -366,27 +347,27 @@ namespace System // null is considered to be less than any instance. // If object is not of type Decimal, this method throws an ArgumentException. // - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) return 1; - if (!(value is Decimal)) + if (!(value is decimal)) throw new ArgumentException(SR.Arg_MustBeDecimal); - Decimal other = (Decimal)value; - return DecCalc.VarDecCmp(ref this, ref other); + decimal other = (decimal)value; + return DecCalc.VarDecCmp(in this, in other); } - public int CompareTo(Decimal value) + public int CompareTo(decimal value) { - return DecCalc.VarDecCmp(ref this, ref value); + return DecCalc.VarDecCmp(in this, in value); } // Divides two Decimal values. // - public static Decimal Divide(Decimal d1, Decimal d2) + public static decimal Divide(decimal d1, decimal d2) { - DecCalc.VarDecDiv(ref d1, ref d2); + DecCalc.VarDecDiv(ref AsMutable(ref d1), ref AsMutable(ref d2)); return d1; } @@ -394,59 +375,41 @@ namespace System // if the given object is a boxed Decimal and its value is equal to the // value of this Decimal. Returns false otherwise. // - public override bool Equals(Object value) + public override bool Equals(object value) { - if (value is Decimal) + if (value is decimal) { - Decimal other = (Decimal)value; - return DecCalc.VarDecCmp(ref this, ref other) == 0; + decimal other = (decimal)value; + return DecCalc.VarDecCmp(in this, in other) == 0; } return false; } - public bool Equals(Decimal value) + public bool Equals(decimal value) { - return DecCalc.VarDecCmp(ref this, ref value) == 0; + return DecCalc.VarDecCmp(in this, in value) == 0; } // Returns the hash code for this Decimal. // - public unsafe override int GetHashCode() - { - double dbl = DecCalc.VarR8FromDec(ref this); - if (dbl == 0.0) - // Ensure 0 and -0 have the same hash code - return 0; - - // conversion to double is lossy and produces rounding errors so we mask off the lowest 4 bits - // - // For example these two numerically equal decimals with different internal representations produce - // slightly different results when converted to double: - // - // decimal a = new decimal(new int[] { 0x76969696, 0x2fdd49fa, 0x409783ff, 0x00160000 }); - // => (decimal)1999021.176470588235294117647000000000 => (double)1999021.176470588 - // decimal b = new decimal(new int[] { 0x3f0f0f0f, 0x1e62edcc, 0x06758d33, 0x00150000 }); - // => (decimal)1999021.176470588235294117647000000000 => (double)1999021.1764705882 - // - return (int)(((((uint*)&dbl)[0]) & 0xFFFFFFF0) ^ ((uint*)&dbl)[1]); - } + public override int GetHashCode() => DecCalc.GetHashCode(in this); // Compares two Decimal values for equality. Returns true if the two // Decimal values are equal, or false if they are not equal. // - public static bool Equals(Decimal d1, Decimal d2) + public static bool Equals(decimal d1, decimal d2) { - return DecCalc.VarDecCmp(ref d1, ref d2) == 0; + return DecCalc.VarDecCmp(in d1, in d2) == 0; } // Rounds a Decimal to an integer value. The Decimal argument is rounded // towards negative infinity. // - public static Decimal Floor(Decimal d) + public static decimal Floor(decimal d) { - uint flags = d.uflags; + int flags = d.flags; if ((flags & ScaleMask) != 0) - DecCalc.InternalRound(ref d, (byte)(flags >> ScaleShift), DecCalc.RoundingMode.Floor); + DecCalc.InternalRound(ref AsMutable(ref d), (byte)(flags >> ScaleShift), DecCalc.RoundingMode.Floor); return d; } @@ -455,22 +418,22 @@ namespace System // optionally followed by a decimal point (".") and another sequence of // digits. // - public override String ToString() + public override string ToString() { return Number.FormatDecimal(this, null, NumberFormatInfo.CurrentInfo); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatDecimal(this, format, NumberFormatInfo.CurrentInfo); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatDecimal(this, null, NumberFormatInfo.GetInstance(provider)); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatDecimal(this, format, NumberFormatInfo.GetInstance(provider)); } @@ -480,7 +443,6 @@ namespace System return Number.TryFormatDecimal(this, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten); } - // Converts a string to a Decimal. The string must consist of an optional // minus sign ("-") followed by a sequence of digits ("0" - "9"). The // sequence of digits may optionally contain a single decimal point (".") @@ -488,58 +450,39 @@ namespace System // Parse also allows a currency symbol, a trailing negative sign, and // parentheses in the number. // - public static Decimal Parse(String s) + public static decimal Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo); } - internal const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite - | NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign - | NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint - | NumberStyles.AllowThousands | NumberStyles.AllowExponent - | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier); - - internal static void ValidateParseStyleFloatingPoint(NumberStyles style) + public static decimal Parse(string s, NumberStyles style) { - // Check for undefined flags - if ((style & InvalidNumberStyles) != 0) - { - throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style)); - } - if ((style & NumberStyles.AllowHexSpecifier) != 0) - { // Check for hex number - throw new ArgumentException(SR.Arg_HexStyleNotSupported); - } - } - - public static Decimal Parse(String s, NumberStyles style) - { - ValidateParseStyleFloatingPoint(style); + NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDecimal(s, style, NumberFormatInfo.CurrentInfo); } - public static Decimal Parse(String s, IFormatProvider provider) + public static decimal Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.GetInstance(provider)); } - public static Decimal Parse(String s, NumberStyles style, IFormatProvider provider) + public static decimal Parse(string s, NumberStyles style, IFormatProvider provider) { - ValidateParseStyleFloatingPoint(style); + NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDecimal(s, style, NumberFormatInfo.GetInstance(provider)); } - public static Decimal Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) + public static decimal Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Number, IFormatProvider provider = null) { - ValidateParseStyleFloatingPoint(style); + NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.ParseDecimal(s, style, NumberFormatInfo.GetInstance(provider)); } - public static Boolean TryParse(String s, out Decimal result) + public static bool TryParse(string s, out decimal result) { if (s == null) { @@ -555,20 +498,22 @@ namespace System return Number.TryParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out result); } - public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Decimal result) + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out decimal result) { - ValidateParseStyleFloatingPoint(style); + NumberFormatInfo.ValidateParseStyleFloatingPoint(style); + if (s == null) { result = 0; return false; } + return Number.TryParseDecimal(s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out decimal result) { - ValidateParseStyleFloatingPoint(style); + NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.TryParseDecimal(s, style, NumberFormatInfo.GetInstance(provider), out result); } @@ -582,12 +527,12 @@ namespace System // indicates the sign of the Decimal value, 0 meaning positive and 1 // meaning negative. // - public static int[] GetBits(Decimal d) + public static int[] GetBits(decimal d) { return new int[] { d.lo, d.mid, d.hi, d.flags }; } - internal static void GetBytes(Decimal d, byte[] buffer) + internal static void GetBytes(decimal d, byte[] buffer) { Debug.Assert((buffer != null && buffer.Length >= 16), "[GetBytes]buffer != null && buffer.Length >= 16"); buffer[0] = (byte)d.lo; @@ -611,40 +556,50 @@ namespace System buffer[15] = (byte)(d.flags >> 24); } + internal static decimal ToDecimal(byte[] buffer) + { + Debug.Assert((buffer != null && buffer.Length >= 16), "[ToDecimal]buffer != null && buffer.Length >= 16"); + int lo = ((int)buffer[0]) | ((int)buffer[1] << 8) | ((int)buffer[2] << 16) | ((int)buffer[3] << 24); + int mid = ((int)buffer[4]) | ((int)buffer[5] << 8) | ((int)buffer[6] << 16) | ((int)buffer[7] << 24); + int hi = ((int)buffer[8]) | ((int)buffer[9] << 8) | ((int)buffer[10] << 16) | ((int)buffer[11] << 24); + int flags = ((int)buffer[12]) | ((int)buffer[13] << 8) | ((int)buffer[14] << 16) | ((int)buffer[15] << 24); + return new decimal(lo, mid, hi, flags); + } + // Returns the larger of two Decimal values. // - internal static ref Decimal Max(ref Decimal d1, ref Decimal d2) + internal static ref decimal Max(ref decimal d1, ref decimal d2) { - return ref DecCalc.VarDecCmp(ref d1, ref d2) >= 0 ? ref d1 : ref d2; + return ref DecCalc.VarDecCmp(in d1, in d2) >= 0 ? ref d1 : ref d2; } // Returns the smaller of two Decimal values. // - internal static ref Decimal Min(ref Decimal d1, ref Decimal d2) + internal static ref decimal Min(ref decimal d1, ref decimal d2) { - return ref DecCalc.VarDecCmp(ref d1, ref d2) < 0 ? ref d1 : ref d2; + return ref DecCalc.VarDecCmp(in d1, in d2) < 0 ? ref d1 : ref d2; } - - public static Decimal Remainder(Decimal d1, Decimal d2) + public static decimal Remainder(decimal d1, decimal d2) { - return DecCalc.VarDecMod(ref d1, ref d2); + DecCalc.VarDecMod(ref AsMutable(ref d1), ref AsMutable(ref d2)); + return d1; } // Multiplies two Decimal values. // - public static Decimal Multiply(Decimal d1, Decimal d2) + public static decimal Multiply(decimal d1, decimal d2) { - DecCalc.VarDecMul(ref d1, ref d2); + DecCalc.VarDecMul(ref AsMutable(ref d1), ref AsMutable(ref d2)); return d1; } // Returns the negated value of the given Decimal. If d is non-zero, // the result is -d. If d is zero, the result is zero. // - public static Decimal Negate(Decimal d) + public static decimal Negate(decimal d) { - return new Decimal(d.ulomidLE, d.uhi, d.uflags ^ SignMask); + return new decimal(in d, d.flags ^ SignMask); } // Rounds a Decimal value to a given number of decimal places. The value @@ -655,12 +610,12 @@ namespace System // By default a mid-point value is rounded to the nearest even number. If the mode is // passed in, it can also round away from zero. - public static Decimal Round(Decimal d) => Round(ref d, 0, MidpointRounding.ToEven); - public static Decimal Round(Decimal d, int decimals) => Round(ref d, decimals, MidpointRounding.ToEven); - public static Decimal Round(Decimal d, MidpointRounding mode) => Round(ref d, 0, mode); - public static Decimal Round(Decimal d, int decimals, MidpointRounding mode) => Round(ref d, decimals, mode); + public static decimal Round(decimal d) => Round(ref d, 0, MidpointRounding.ToEven); + public static decimal Round(decimal d, int decimals) => Round(ref d, decimals, MidpointRounding.ToEven); + public static decimal Round(decimal d, MidpointRounding mode) => Round(ref d, 0, mode); + public static decimal Round(decimal d, int decimals, MidpointRounding mode) => Round(ref d, decimals, mode); - private static Decimal Round(ref Decimal d, int decimals, MidpointRounding mode) + private static decimal Round(ref decimal d, int decimals, MidpointRounding mode) { if ((uint)decimals > 28) throw new ArgumentOutOfRangeException(nameof(decimals), SR.ArgumentOutOfRange_DecimalRound); @@ -669,7 +624,7 @@ namespace System int scale = d.Scale - decimals; if (scale > 0) - DecCalc.InternalRound(ref d, (uint)scale, (DecCalc.RoundingMode)mode); + DecCalc.InternalRound(ref AsMutable(ref d), (uint)scale, (DecCalc.RoundingMode)mode); return d; } @@ -677,9 +632,9 @@ namespace System // Subtracts two Decimal values. // - public static Decimal Subtract(Decimal d1, Decimal d2) + public static decimal Subtract(decimal d1, decimal d2) { - DecCalc.VarDecSub(ref d1, ref d2); + DecCalc.DecAddSub(ref AsMutable(ref d1), ref AsMutable(ref d2), true); return d1; } @@ -687,7 +642,7 @@ namespace System // towards zero to the nearest integer value, and the result of this // operation is returned as a byte. // - public static byte ToByte(Decimal value) + public static byte ToByte(decimal value) { uint temp; try @@ -707,7 +662,7 @@ namespace System // operation is returned as a byte. // [CLSCompliant(false)] - public static sbyte ToSByte(Decimal value) + public static sbyte ToSByte(decimal value) { int temp; try @@ -726,7 +681,7 @@ namespace System // rounded towards zero to the nearest integer value, and the result of // this operation is returned as a short. // - public static short ToInt16(Decimal value) + public static short ToInt16(decimal value) { int temp; try @@ -744,7 +699,7 @@ namespace System // Converts a Decimal to a double. Since a double has fewer significant // digits than a Decimal, this operation may produce round-off errors. // - public static double ToDouble(Decimal d) + public static double ToDouble(decimal d) { return DecCalc.VarR8FromDec(ref d); } @@ -753,7 +708,7 @@ namespace System // zero to the nearest integer value, and the result of this operation is // returned as an integer. // - public static int ToInt32(Decimal d) + public static int ToInt32(decimal d) { Truncate(ref d); if ((d.hi | d.mid) == 0) @@ -776,10 +731,10 @@ namespace System // to the nearest integer value, and the result of this operation is // returned as a long. // - public static long ToInt64(Decimal d) + public static long ToInt64(decimal d) { Truncate(ref d); - if (d.uhi == 0) + if (d.hi == 0) { long l = (long)d.Low64; if (!d.IsNegative) @@ -800,7 +755,7 @@ namespace System // result of this operation is returned as an ushort. // [CLSCompliant(false)] - public static ushort ToUInt16(Decimal value) + public static ushort ToUInt16(decimal value) { uint temp; try @@ -820,12 +775,12 @@ namespace System // result of this operation is returned as an unsigned integer. // [CLSCompliant(false)] - public static uint ToUInt32(Decimal d) + public static uint ToUInt32(decimal d) { Truncate(ref d); - if ((d.uhi | d.umid) == 0) + if ((d.hi | d.mid) == 0) { - uint i = d.ulo; + uint i = d.Low; if (!d.IsNegative || i == 0) return i; } @@ -837,10 +792,10 @@ namespace System // result of this operation is returned as a long. // [CLSCompliant(false)] - public static ulong ToUInt64(Decimal d) + public static ulong ToUInt64(decimal d) { Truncate(ref d); - if (d.uhi == 0) + if (d.hi == 0) { ulong l = d.Low64; if (!d.IsNegative || l == 0) @@ -852,7 +807,7 @@ namespace System // Converts a Decimal to a float. Since a float has fewer significant // digits than a Decimal, this operation may produce round-off errors. // - public static float ToSingle(Decimal d) + public static float ToSingle(decimal d) { return DecCalc.VarR4FromDec(ref d); } @@ -861,94 +816,94 @@ namespace System // towards zero to the nearest integer value, corresponding to removing all // digits after the decimal point. // - public static Decimal Truncate(Decimal d) + public static decimal Truncate(decimal d) { Truncate(ref d); return d; } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void Truncate(ref Decimal d) + private static void Truncate(ref decimal d) { - uint flags = d.uflags; + int flags = d.flags; if ((flags & ScaleMask) != 0) - DecCalc.InternalRound(ref d, (byte)(flags >> ScaleShift), DecCalc.RoundingMode.Truncate); + DecCalc.InternalRound(ref AsMutable(ref d), (byte)(flags >> ScaleShift), DecCalc.RoundingMode.Truncate); } - public static implicit operator Decimal(byte value) + public static implicit operator decimal(byte value) { - return new Decimal(value); + return new decimal(value); } [CLSCompliant(false)] - public static implicit operator Decimal(sbyte value) + public static implicit operator decimal(sbyte value) { - return new Decimal(value); + return new decimal(value); } - public static implicit operator Decimal(short value) + public static implicit operator decimal(short value) { - return new Decimal(value); + return new decimal(value); } [CLSCompliant(false)] - public static implicit operator Decimal(ushort value) + public static implicit operator decimal(ushort value) { - return new Decimal(value); + return new decimal(value); } - public static implicit operator Decimal(char value) + public static implicit operator decimal(char value) { - return new Decimal(value); + return new decimal(value); } - public static implicit operator Decimal(int value) + public static implicit operator decimal(int value) { - return new Decimal(value); + return new decimal(value); } [CLSCompliant(false)] - public static implicit operator Decimal(uint value) + public static implicit operator decimal(uint value) { - return new Decimal(value); + return new decimal(value); } - public static implicit operator Decimal(long value) + public static implicit operator decimal(long value) { - return new Decimal(value); + return new decimal(value); } [CLSCompliant(false)] - public static implicit operator Decimal(ulong value) + public static implicit operator decimal(ulong value) { - return new Decimal(value); + return new decimal(value); } - public static explicit operator Decimal(float value) + public static explicit operator decimal(float value) { - return new Decimal(value); + return new decimal(value); } - public static explicit operator Decimal(double value) + public static explicit operator decimal(double value) { - return new Decimal(value); + return new decimal(value); } - public static explicit operator byte(Decimal value) + public static explicit operator byte(decimal value) { return ToByte(value); } [CLSCompliant(false)] - public static explicit operator sbyte(Decimal value) + public static explicit operator sbyte(decimal value) { return ToSByte(value); } - public static explicit operator char(Decimal value) + public static explicit operator char(decimal value) { - UInt16 temp; + ushort temp; try { temp = ToUInt16(value); @@ -960,122 +915,122 @@ namespace System return (char)temp; } - public static explicit operator short(Decimal value) + public static explicit operator short(decimal value) { return ToInt16(value); } [CLSCompliant(false)] - public static explicit operator ushort(Decimal value) + public static explicit operator ushort(decimal value) { return ToUInt16(value); } - public static explicit operator int(Decimal value) + public static explicit operator int(decimal value) { return ToInt32(value); } [CLSCompliant(false)] - public static explicit operator uint(Decimal value) + public static explicit operator uint(decimal value) { return ToUInt32(value); } - public static explicit operator long(Decimal value) + public static explicit operator long(decimal value) { return ToInt64(value); } [CLSCompliant(false)] - public static explicit operator ulong(Decimal value) + public static explicit operator ulong(decimal value) { return ToUInt64(value); } - public static explicit operator float(Decimal value) + public static explicit operator float(decimal value) { return ToSingle(value); } - public static explicit operator double(Decimal value) + public static explicit operator double(decimal value) { return ToDouble(value); } - public static Decimal operator +(Decimal d) + public static decimal operator +(decimal d) { return d; } - public static Decimal operator -(Decimal d) + public static decimal operator -(decimal d) { return Negate(d); } - public static Decimal operator ++(Decimal d) + public static decimal operator ++(decimal d) { return Add(d, One); } - public static Decimal operator --(Decimal d) + public static decimal operator --(decimal d) { return Subtract(d, One); } - public static Decimal operator +(Decimal d1, Decimal d2) + public static decimal operator +(decimal d1, decimal d2) { return Add(d1, d2); } - public static Decimal operator -(Decimal d1, Decimal d2) + public static decimal operator -(decimal d1, decimal d2) { return Subtract(d1, d2); } - public static Decimal operator *(Decimal d1, Decimal d2) + public static decimal operator *(decimal d1, decimal d2) { return Multiply(d1, d2); } - public static Decimal operator /(Decimal d1, Decimal d2) + public static decimal operator /(decimal d1, decimal d2) { return Divide(d1, d2); } - public static Decimal operator %(Decimal d1, Decimal d2) + public static decimal operator %(decimal d1, decimal d2) { return Remainder(d1, d2); } - public static bool operator ==(Decimal d1, Decimal d2) + public static bool operator ==(decimal d1, decimal d2) { - return DecCalc.VarDecCmp(ref d1, ref d2) == 0; + return DecCalc.VarDecCmp(in d1, in d2) == 0; } - public static bool operator !=(Decimal d1, Decimal d2) + public static bool operator !=(decimal d1, decimal d2) { - return DecCalc.VarDecCmp(ref d1, ref d2) != 0; + return DecCalc.VarDecCmp(in d1, in d2) != 0; } - public static bool operator <(Decimal d1, Decimal d2) + public static bool operator <(decimal d1, decimal d2) { - return DecCalc.VarDecCmp(ref d1, ref d2) < 0; + return DecCalc.VarDecCmp(in d1, in d2) < 0; } - public static bool operator <=(Decimal d1, Decimal d2) + public static bool operator <=(decimal d1, decimal d2) { - return DecCalc.VarDecCmp(ref d1, ref d2) <= 0; + return DecCalc.VarDecCmp(in d1, in d2) <= 0; } - public static bool operator >(Decimal d1, Decimal d2) + public static bool operator >(decimal d1, decimal d2) { - return DecCalc.VarDecCmp(ref d1, ref d2) > 0; + return DecCalc.VarDecCmp(in d1, in d2) > 0; } - public static bool operator >=(Decimal d1, Decimal d2) + public static bool operator >=(decimal d1, decimal d2) { - return DecCalc.VarDecCmp(ref d1, ref d2) >= 0; + return DecCalc.VarDecCmp(in d1, in d2) >= 0; } // @@ -1095,7 +1050,7 @@ namespace System char IConvertible.ToChar(IFormatProvider provider) { - throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Decimal", "Char")); + throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Decimal", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) @@ -1148,17 +1103,17 @@ namespace System return Convert.ToDouble(this); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return this; } DateTime IConvertible.ToDateTime(IFormatProvider provider) { - throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Decimal", "DateTime")); + throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Decimal", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Debug.Unix.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Debug.Unix.cs index 627ea4ab7e..86b095e47b 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Debug.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Debug.Unix.cs @@ -22,11 +22,11 @@ namespace System.Diagnostics // Fail in order to avoid anyone catching an exception and masking // an assert failure. DebugAssertException ex; - if (message == String.Empty) + if (message == string.Empty) { ex = new DebugAssertException(stackTrace); } - else if (detailMessage == String.Empty) + else if (detailMessage == string.Empty) { ex = new DebugAssertException(message, stackTrace); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/StackFrame.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/StackFrame.cs similarity index 96% rename from external/corert/src/System.Private.CoreLib/src/System/Diagnostics/StackFrame.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/StackFrame.cs index fe06d85f2c..22c9b83995 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/StackFrame.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/StackFrame.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - using System.Text; using System; using System.IO; @@ -35,7 +34,7 @@ namespace System.Diagnostics /// /// Source file name representing the current code location if available, null otherwise. /// - private String _fileName; + private string _fileName; /// /// Line number representing the current code location if available, 0 otherwise. @@ -52,7 +51,7 @@ namespace System.Diagnostics /// private bool _isLastFrameFromForeignExceptionStackTrace; - internal void InitMembers() + private void InitMembers() { _method = null; _nativeOffset = OFFSET_UNKNOWN; @@ -104,7 +103,7 @@ namespace System.Diagnostics /// name and line number. Use when you don't want to use the /// debugger's line mapping logic. /// - public StackFrame(String fileName, int lineNumber) + public StackFrame(string fileName, int lineNumber) { InitMembers(); BuildStackFrame(StackTrace.METHODS_TO_SKIP, false); @@ -118,7 +117,7 @@ namespace System.Diagnostics /// name, line number and column number. Use when you don't want to /// use the debugger's line mapping logic. /// - public StackFrame(String fileName, int lineNumber, int colNumber) + public StackFrame(string fileName, int lineNumber, int colNumber) { InitMembers(); BuildStackFrame(StackTrace.METHODS_TO_SKIP, false); @@ -147,7 +146,7 @@ namespace System.Diagnostics _ilOffset = iOffset; } - internal virtual void SetFileName(String strFName) + internal virtual void SetFileName(string strFName) { _fileName = strFName; } @@ -205,7 +204,7 @@ namespace System.Diagnostics /// information is normally extracted from the debugging symbols /// for the executable. /// - public virtual String GetFileName() + public virtual string GetFileName() { return _fileName; } @@ -233,7 +232,7 @@ namespace System.Diagnostics /// /// Builds a readable representation of the stack frame /// - public override String ToString() + public override string ToString() { StringBuilder sb = new StringBuilder(255); bool includeFileInfoIfAvailable; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/ActivityTracker.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/ActivityTracker.cs index 9ac32c3bd6..d9f9f081cb 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/ActivityTracker.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/ActivityTracker.cs @@ -247,11 +247,6 @@ namespace System.Diagnostics.Tracing #region private - /// - /// The current activity ID. Use this to log normal events. - /// - private Guid CurrentActivityId { get { return m_current.Value.ActivityId; } } - /// /// Searched for a active (nonstopped) activity with the given name. Returns null if not found. /// diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventDescriptor.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventDescriptor.cs index b036b28b4b..0fed7b5c00 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventDescriptor.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventDescriptor.cs @@ -168,6 +168,14 @@ namespace System.Diagnostics.Tracing } } + internal int TraceLoggingId + { + get + { + return m_traceloggingId; + } + } + public override bool Equals(object obj) { if (!(obj is EventDescriptor)) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventProvider.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventProvider.cs index fafdd7c6da..36b363fa39 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventProvider.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventProvider.cs @@ -30,6 +30,13 @@ namespace Microsoft.Diagnostics.Tracing namespace System.Diagnostics.Tracing #endif { + internal enum EventProviderType + { + None = 0, + ETW, + EventPipe + }; + // New in CLR4.0 internal enum ControllerCommand { @@ -120,15 +127,28 @@ namespace System.Diagnostics.Tracing // it registers a callback from native code you MUST dispose it BEFORE shutdown, otherwise // you may get native callbacks during shutdown when we have destroyed the delegate. // EventSource has special logic to do this, no one else should be calling EventProvider. - internal EventProvider() + internal EventProvider(EventProviderType providerType) { + switch (providerType) + { + case EventProviderType.ETW: #if PLATFORM_WINDOWS - m_eventProvider = new EtwEventProvider(); -#elif FEATURE_PERFTRACING - m_eventProvider = new EventPipeEventProvider(); + m_eventProvider = new EtwEventProvider(); #else - m_eventProvider = new NoOpEventProvider(); + m_eventProvider = new NoOpEventProvider(); #endif + break; + case EventProviderType.EventPipe: +#if FEATURE_PERFTRACING + m_eventProvider = new EventPipeEventProvider(); +#else + m_eventProvider = new NoOpEventProvider(); +#endif + break; + default: + m_eventProvider = new NoOpEventProvider(); + break; + }; } /// @@ -331,7 +351,7 @@ namespace System.Diagnostics.Tracing protected EventKeywords MatchAnyKeyword { get { return (EventKeywords)m_anyKeywordMask; } set { m_anyKeywordMask = unchecked((long)value); } } protected EventKeywords MatchAllKeyword { get { return (EventKeywords)m_allKeywordMask; } set { m_allKeywordMask = unchecked((long)value); } } - static private int FindNull(byte[] buffer, int idx) + private static int FindNull(byte[] buffer, int idx) { while (idx < buffer.Length && buffer[idx] != 0) idx++; @@ -475,7 +495,7 @@ namespace System.Diagnostics.Tracing var structBase = (byte*)providerInstance; providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset]; } -#else +#else #if !ES_BUILD_PCL && PLATFORM_WINDOWS // TODO command arguments don't work on PCL builds... // This code is only used in the Nuget Package Version of EventSource. because // the code above is using APIs baned from UWP apps. @@ -761,10 +781,10 @@ namespace System.Diagnostics.Tracing *uintptr = (uint)data; dataDescriptor->Ptr = (ulong)uintptr; } - else if (data is UInt64) + else if (data is ulong) { dataDescriptor->Size = (uint)sizeof(ulong); - UInt64* ulongptr = (ulong*)dataBuffer; + ulong* ulongptr = (ulong*)dataBuffer; *ulongptr = (ulong)data; dataDescriptor->Ptr = (ulong)ulongptr; } @@ -863,25 +883,18 @@ namespace System.Diagnostics.Tracing { if (data is System.Enum) { - Type underlyingType = Enum.GetUnderlyingType(data.GetType()); - if (underlyingType == typeof(int)) + try { -#if !ES_BUILD_PCL - data = ((IConvertible)data).ToInt32(null); -#else - data = (int)data; -#endif - goto Again; - } - else if (underlyingType == typeof(long)) - { -#if !ES_BUILD_PCL - data = ((IConvertible)data).ToInt64(null); -#else - data = (long)data; -#endif + Type underlyingType = Enum.GetUnderlyingType(data.GetType()); + if (underlyingType == typeof(ulong)) + data = (ulong)data; + else if (underlyingType == typeof(long)) + data = (long)data; + else + data = (int)Convert.ToInt64(data); // This handles all int/uint or below (we treat them like 32 bit ints) goto Again; } + catch { } // On wierd cases (e.g. enums of type double), give up and for compat simply tostring. } // To our eyes, everything else is a just a string @@ -959,7 +972,7 @@ namespace System.Diagnostics.Tracing List dataRefObj = new List(s_etwAPIMaxRefObjCount); EventData* userData = stackalloc EventData[2 * argCount]; for (int i = 0; i < 2 * argCount; i++) - userData[i] = default(EventData); + userData[i] = default; EventData* userDataPtr = (EventData*)userData; byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * 2 * argCount]; // Assume 16 chars for non-string argument byte* currentBuffer = dataBuffer; @@ -1133,7 +1146,7 @@ namespace System.Diagnostics.Tracing // // [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, IntPtr eventHandle, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data) + internal protected unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, IntPtr eventHandle, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data) { if (childActivityID != null) { @@ -1157,6 +1170,7 @@ namespace System.Diagnostics.Tracing [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] internal unsafe bool WriteEventRaw( ref EventDescriptor eventDescriptor, + IntPtr eventHandle, Guid* activityID, Guid* relatedActivityID, int dataCount, @@ -1167,7 +1181,7 @@ namespace System.Diagnostics.Tracing status = m_eventProvider.EventWriteTransferWrapper( m_regHandle, ref eventDescriptor, - IntPtr.Zero, + eventHandle, activityID, relatedActivityID, dataCount, @@ -1269,14 +1283,13 @@ namespace System.Diagnostics.Tracing } // Define an EventPipeEvent handle. - unsafe IntPtr IEventProvider.DefineEventHandle(uint eventID, string eventName, Int64 keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength) + unsafe IntPtr IEventProvider.DefineEventHandle(uint eventID, string eventName, long keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength) { throw new System.NotSupportedException(); } } -#elif !FEATURE_PERFTRACING - +#endif internal sealed class NoOpEventProvider : IEventProvider { unsafe uint IEventProvider.EventRegister( @@ -1311,12 +1324,10 @@ namespace System.Diagnostics.Tracing } // Define an EventPipeEvent handle. - unsafe IntPtr IEventProvider.DefineEventHandle(uint eventID, string eventName, Int64 keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength) + unsafe IntPtr IEventProvider.DefineEventHandle(uint eventID, string eventName, long keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength) { - throw new System.NotSupportedException(); + return IntPtr.Zero; } } - -#endif } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs.REMOVED.git-id index 73a2b101ef..8167779991 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs.REMOVED.git-id +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs.REMOVED.git-id @@ -1 +1 @@ -40d39ced76cfdabda2badc2e397fd02dab3e243d \ No newline at end of file +b309eb5aab02bb48dfeb4262789558e30bbc2c6f \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/IEventProvider.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/IEventProvider.cs index d34f80eb51..9bbebc79ed 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/IEventProvider.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/IEventProvider.cs @@ -38,6 +38,6 @@ namespace System.Diagnostics.Tracing int EventActivityIdControl(UnsafeNativeMethods.ManifestEtw.ActivityControl ControlCode, ref Guid ActivityId); // Define an EventPipeEvent handle. - unsafe IntPtr DefineEventHandle(uint eventID, string eventName, Int64 keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength); + unsafe IntPtr DefineEventHandle(uint eventID, string eventName, long keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs index 1b3ca8004c..6f2eb9ba21 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs @@ -30,10 +30,10 @@ namespace System.Diagnostics.Tracing.Internal if (fmt != null) return string.Format(fmt, args); - string sargs = String.Empty; + string sargs = string.Empty; foreach(var arg in args) { - if (sargs != String.Empty) + if (sargs != string.Empty) sargs += ", "; sargs += arg.ToString(); } @@ -301,7 +301,7 @@ namespace Microsoft.Reflection else if (type == typeof(float)) return TypeCode.Single; else if (type == typeof(double)) return TypeCode.Double; else if (type == typeof(DateTime)) return TypeCode.DateTime; - else if (type == (typeof(Decimal))) return TypeCode.Decimal; + else if (type == (typeof(decimal))) return TypeCode.Decimal; else return TypeCode.Object; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs index 1444c267cb..11c18a260f 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs @@ -143,6 +143,45 @@ namespace System.Diagnostics.Tracing } } + internal unsafe void AddNullTerminatedString(string value) + { + // Treat null strings as empty strings. + if (value == null) + { + value = string.Empty; + } + + // Calculate the size of the string including the trailing NULL char. + // Don't use value.Length here because string allows for embedded NULL characters. + int nullCharIndex = value.IndexOf((char)0); + if (nullCharIndex < 0) + { + nullCharIndex = value.Length; + } + int size = (nullCharIndex + 1) * 2; + + if (this.bufferNesting != 0) + { + this.EnsureBuffer(size); + } + + if (this.bufferNesting == 0) + { + this.ScalarsEnd(); + this.PinArray(value, size); + } + else + { + var oldPos = this.bufferPos; + this.bufferPos = checked(this.bufferPos + size); + this.EnsureBuffer(); + fixed (void* p = value) + { + Marshal.Copy((IntPtr)p, buffer, oldPos, size); + } + } + } + internal void AddBinary(Array value, int size) { this.AddArray(value, size, 1); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs index 30a941195f..3febe6ff96 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs @@ -144,7 +144,7 @@ namespace System.Diagnostics.Tracing position++; } - value = default(object); + value = default; return false; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs index 865082f767..2d71550803 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs @@ -314,7 +314,7 @@ namespace System.Diagnostics.Tracing private State state; private string eventName; - static internal Guid s_empty; + internal static Guid s_empty; #endregion } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs index 9c7c6369ec..f153734752 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs @@ -135,13 +135,11 @@ namespace System.Diagnostics.Tracing { throw new NotSupportedException(SR.EventSource_NotSupportedArrayOfBinary); } -#if !BROKEN_UNTIL_M3 if (coreType == (int)TraceLoggingDataType.Utf16String || coreType == (int)TraceLoggingDataType.MbcsString) { throw new NotSupportedException(SR.EventSource_NotSupportedArrayOfNullTerminatedString); } -#endif } if (((int)this.tags & 0xfffffff) != 0) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/InvokeTypeInfo.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/InvokeTypeInfo.cs index 3e5997bc9b..2a7113e5d7 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/InvokeTypeInfo.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/InvokeTypeInfo.cs @@ -21,7 +21,7 @@ namespace System.Diagnostics.Tracing /// internal sealed class InvokeTypeInfo : TraceLoggingTypeInfo { - private readonly PropertyAnalysis[] properties; + internal readonly PropertyAnalysis[] properties; public InvokeTypeInfo( Type type, diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/NameInfo.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/NameInfo.cs index 668043ae68..a7daf5e757 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/NameInfo.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/NameInfo.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using System.Collections.Concurrent; using Interlocked = System.Threading.Interlocked; #if ES_BUILD_STANDALONE @@ -75,5 +76,50 @@ namespace System.Diagnostics.Tracing } return result; } + +#if FEATURE_PERFTRACING + public IntPtr GetOrCreateEventHandle(EventProvider provider, TraceLoggingEventHandleTable eventHandleTable, EventDescriptor descriptor, TraceLoggingEventTypes eventTypes) + { + IntPtr eventHandle; + if ((eventHandle = eventHandleTable[descriptor.EventId]) == IntPtr.Zero) + { + lock (eventHandleTable) + { + if ((eventHandle = eventHandleTable[descriptor.EventId]) == IntPtr.Zero) + { + byte[] metadataBlob = EventPipeMetadataGenerator.Instance.GenerateEventMetadata( + descriptor.EventId, + name, + (EventKeywords)descriptor.Keywords, + (EventLevel)descriptor.Level, + descriptor.Version, + eventTypes); + uint metadataLength = (metadataBlob != null) ? (uint)metadataBlob.Length : 0; + + unsafe + { + fixed (byte* pMetadataBlob = metadataBlob) + { + // Define the event. + eventHandle = provider.m_eventProvider.DefineEventHandle( + (uint)descriptor.EventId, + name, + descriptor.Keywords, + descriptor.Version, + descriptor.Level, + pMetadataBlob, + metadataLength); + } + } + + // Cache the event handle. + eventHandleTable.SetEventHandle(descriptor.EventId, eventHandle); + } + } + } + + return eventHandle; + } +#endif } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs index ae60888493..daa6d9736a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs @@ -40,33 +40,33 @@ namespace System.Diagnostics.Tracing public struct Scalar { [FieldOffset(0)] - public Boolean AsBoolean; + public bool AsBoolean; [FieldOffset(0)] - public Byte AsByte; + public byte AsByte; [FieldOffset(0)] - public SByte AsSByte; + public sbyte AsSByte; [FieldOffset(0)] - public Char AsChar; + public char AsChar; [FieldOffset(0)] - public Int16 AsInt16; + public short AsInt16; [FieldOffset(0)] - public UInt16 AsUInt16; + public ushort AsUInt16; [FieldOffset(0)] - public Int32 AsInt32; + public int AsInt32; [FieldOffset(0)] - public UInt32 AsUInt32; + public uint AsUInt32; [FieldOffset(0)] - public Int64 AsInt64; + public long AsInt64; [FieldOffset(0)] - public UInt64 AsUInt64; + public ulong AsUInt64; [FieldOffset(0)] public IntPtr AsIntPtr; [FieldOffset(0)] public UIntPtr AsUIntPtr; [FieldOffset(0)] - public Single AsSingle; + public float AsSingle; [FieldOffset(0)] - public Double AsDouble; + public double AsDouble; [FieldOffset(0)] public Guid AsGuid; [FieldOffset(0)] @@ -76,7 +76,7 @@ namespace System.Diagnostics.Tracing [FieldOffset(0)] public TimeSpan AsTimeSpan; [FieldOffset(0)] - public Decimal AsDecimal; + public decimal AsDecimal; } // Anything not covered by the Scalar union gets stored in this reference. @@ -87,7 +87,7 @@ namespace System.Diagnostics.Tracing private PropertyValue(object value) { _reference = value; - _scalar = default(Scalar); + _scalar = default; _scalarLength = 0; } @@ -98,47 +98,47 @@ namespace System.Diagnostics.Tracing _scalarLength = scalarLength; } - private PropertyValue(Boolean value) : this(new Scalar() { AsBoolean = value }, sizeof(Boolean)) { } - private PropertyValue(Byte value) : this(new Scalar() { AsByte = value }, sizeof(Byte)) { } - private PropertyValue(SByte value) : this(new Scalar() { AsSByte = value }, sizeof(SByte)) { } - private PropertyValue(Char value) : this(new Scalar() { AsChar = value }, sizeof(Char)) { } - private PropertyValue(Int16 value) : this(new Scalar() { AsInt16 = value }, sizeof(Int16)) { } - private PropertyValue(UInt16 value) : this(new Scalar() { AsUInt16 = value }, sizeof(UInt16)) { } - private PropertyValue(Int32 value) : this(new Scalar() { AsInt32 = value }, sizeof(Int32)) { } - private PropertyValue(UInt32 value) : this(new Scalar() { AsUInt32 = value }, sizeof(UInt32)) { } - private PropertyValue(Int64 value) : this(new Scalar() { AsInt64 = value }, sizeof(Int64)) { } - private PropertyValue(UInt64 value) : this(new Scalar() { AsUInt64 = value }, sizeof(UInt64)) { } + private PropertyValue(bool value) : this(new Scalar() { AsBoolean = value }, sizeof(bool)) { } + private PropertyValue(byte value) : this(new Scalar() { AsByte = value }, sizeof(byte)) { } + private PropertyValue(sbyte value) : this(new Scalar() { AsSByte = value }, sizeof(sbyte)) { } + private PropertyValue(char value) : this(new Scalar() { AsChar = value }, sizeof(char)) { } + private PropertyValue(short value) : this(new Scalar() { AsInt16 = value }, sizeof(short)) { } + private PropertyValue(ushort value) : this(new Scalar() { AsUInt16 = value }, sizeof(ushort)) { } + private PropertyValue(int value) : this(new Scalar() { AsInt32 = value }, sizeof(int)) { } + private PropertyValue(uint value) : this(new Scalar() { AsUInt32 = value }, sizeof(uint)) { } + private PropertyValue(long value) : this(new Scalar() { AsInt64 = value }, sizeof(long)) { } + private PropertyValue(ulong value) : this(new Scalar() { AsUInt64 = value }, sizeof(ulong)) { } private PropertyValue(IntPtr value) : this(new Scalar() { AsIntPtr = value }, sizeof(IntPtr)) { } private PropertyValue(UIntPtr value) : this(new Scalar() { AsUIntPtr = value }, sizeof(UIntPtr)) { } - private PropertyValue(Single value) : this(new Scalar() { AsSingle = value }, sizeof(Single)) { } - private PropertyValue(Double value) : this(new Scalar() { AsDouble = value }, sizeof(Double)) { } + private PropertyValue(float value) : this(new Scalar() { AsSingle = value }, sizeof(float)) { } + private PropertyValue(double value) : this(new Scalar() { AsDouble = value }, sizeof(double)) { } private PropertyValue(Guid value) : this(new Scalar() { AsGuid = value }, sizeof(Guid)) { } private PropertyValue(DateTime value) : this(new Scalar() { AsDateTime = value }, sizeof(DateTime)) { } private PropertyValue(DateTimeOffset value) : this(new Scalar() { AsDateTimeOffset = value }, sizeof(DateTimeOffset)) { } private PropertyValue(TimeSpan value) : this(new Scalar() { AsTimeSpan = value }, sizeof(TimeSpan)) { } - private PropertyValue(Decimal value) : this(new Scalar() { AsDecimal = value }, sizeof(Decimal)) { } + private PropertyValue(decimal value) : this(new Scalar() { AsDecimal = value }, sizeof(decimal)) { } public static Func GetFactory(Type type) { - if (type == typeof(Boolean)) return value => new PropertyValue((Boolean)value); - if (type == typeof(Byte)) return value => new PropertyValue((Byte)value); - if (type == typeof(SByte)) return value => new PropertyValue((SByte)value); - if (type == typeof(Char)) return value => new PropertyValue((Char)value); - if (type == typeof(Int16)) return value => new PropertyValue((Int16)value); - if (type == typeof(UInt16)) return value => new PropertyValue((UInt16)value); - if (type == typeof(Int32)) return value => new PropertyValue((Int32)value); - if (type == typeof(UInt32)) return value => new PropertyValue((UInt32)value); - if (type == typeof(Int64)) return value => new PropertyValue((Int64)value); - if (type == typeof(UInt64)) return value => new PropertyValue((UInt64)value); + if (type == typeof(bool)) return value => new PropertyValue((bool)value); + if (type == typeof(byte)) return value => new PropertyValue((byte)value); + if (type == typeof(sbyte)) return value => new PropertyValue((sbyte)value); + if (type == typeof(char)) return value => new PropertyValue((char)value); + if (type == typeof(short)) return value => new PropertyValue((short)value); + if (type == typeof(ushort)) return value => new PropertyValue((ushort)value); + if (type == typeof(int)) return value => new PropertyValue((int)value); + if (type == typeof(uint)) return value => new PropertyValue((uint)value); + if (type == typeof(long)) return value => new PropertyValue((long)value); + if (type == typeof(ulong)) return value => new PropertyValue((ulong)value); if (type == typeof(IntPtr)) return value => new PropertyValue((IntPtr)value); if (type == typeof(UIntPtr)) return value => new PropertyValue((UIntPtr)value); - if (type == typeof(Single)) return value => new PropertyValue((Single)value); - if (type == typeof(Double)) return value => new PropertyValue((Double)value); + if (type == typeof(float)) return value => new PropertyValue((float)value); + if (type == typeof(double)) return value => new PropertyValue((double)value); if (type == typeof(Guid)) return value => new PropertyValue((Guid)value); if (type == typeof(DateTime)) return value => new PropertyValue((DateTime)value); if (type == typeof(DateTimeOffset)) return value => new PropertyValue((DateTimeOffset)value); if (type == typeof(TimeSpan)) return value => new PropertyValue((TimeSpan)value); - if (type == typeof(Decimal)) return value => new PropertyValue((Decimal)value); + if (type == typeof(decimal)) return value => new PropertyValue((decimal)value); return value => new PropertyValue(value); } @@ -249,25 +249,25 @@ namespace System.Diagnostics.Tracing if (type.GetTypeInfo().IsEnum) type = Enum.GetUnderlyingType(type); - if (type == typeof(Boolean)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Byte)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(SByte)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Char)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Int16)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(UInt16)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Int32)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(UInt32)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Int64)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(UInt64)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(bool)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(byte)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(sbyte)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(char)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(short)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(ushort)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(int)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(uint)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(long)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(ulong)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(IntPtr)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(UIntPtr)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Single)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Double)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(float)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(double)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(Guid)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(DateTime)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(DateTimeOffset)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(TimeSpan)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Decimal)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(decimal)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } return container => new PropertyValue(property.GetValue(container.ReferenceValue)); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs index 9b58d82519..e0a9374790 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs @@ -73,20 +73,20 @@ namespace System.Diagnostics.Tracing collector.AddScalar(value); } - public static TraceLoggingTypeInfo Boolean() { return new ScalarTypeInfo(typeof(Boolean), Statics.Format8, TraceLoggingDataType.Boolean8); } - public static TraceLoggingTypeInfo Byte() { return new ScalarTypeInfo(typeof(Byte), Statics.Format8, TraceLoggingDataType.UInt8); } - public static TraceLoggingTypeInfo SByte() { return new ScalarTypeInfo(typeof(SByte), Statics.Format8, TraceLoggingDataType.Int8); } - public static TraceLoggingTypeInfo Char() { return new ScalarTypeInfo(typeof(Char), Statics.Format16, TraceLoggingDataType.Char16); } - public static TraceLoggingTypeInfo Int16() { return new ScalarTypeInfo(typeof(Int16), Statics.Format16, TraceLoggingDataType.Int16); } - public static TraceLoggingTypeInfo UInt16() { return new ScalarTypeInfo(typeof(UInt16), Statics.Format16, TraceLoggingDataType.UInt16); } - public static TraceLoggingTypeInfo Int32() { return new ScalarTypeInfo(typeof(Int32), Statics.Format32, TraceLoggingDataType.Int32); } - public static TraceLoggingTypeInfo UInt32() { return new ScalarTypeInfo(typeof(UInt32), Statics.Format32, TraceLoggingDataType.UInt32); } - public static TraceLoggingTypeInfo Int64() { return new ScalarTypeInfo(typeof(Int64), Statics.Format64, TraceLoggingDataType.Int64); } - public static TraceLoggingTypeInfo UInt64() { return new ScalarTypeInfo(typeof(UInt64), Statics.Format64, TraceLoggingDataType.UInt64); } + public static TraceLoggingTypeInfo Boolean() { return new ScalarTypeInfo(typeof(bool), Statics.Format8, TraceLoggingDataType.Boolean8); } + public static TraceLoggingTypeInfo Byte() { return new ScalarTypeInfo(typeof(byte), Statics.Format8, TraceLoggingDataType.UInt8); } + public static TraceLoggingTypeInfo SByte() { return new ScalarTypeInfo(typeof(sbyte), Statics.Format8, TraceLoggingDataType.Int8); } + public static TraceLoggingTypeInfo Char() { return new ScalarTypeInfo(typeof(char), Statics.Format16, TraceLoggingDataType.Char16); } + public static TraceLoggingTypeInfo Int16() { return new ScalarTypeInfo(typeof(short), Statics.Format16, TraceLoggingDataType.Int16); } + public static TraceLoggingTypeInfo UInt16() { return new ScalarTypeInfo(typeof(ushort), Statics.Format16, TraceLoggingDataType.UInt16); } + public static TraceLoggingTypeInfo Int32() { return new ScalarTypeInfo(typeof(int), Statics.Format32, TraceLoggingDataType.Int32); } + public static TraceLoggingTypeInfo UInt32() { return new ScalarTypeInfo(typeof(uint), Statics.Format32, TraceLoggingDataType.UInt32); } + public static TraceLoggingTypeInfo Int64() { return new ScalarTypeInfo(typeof(long), Statics.Format64, TraceLoggingDataType.Int64); } + public static TraceLoggingTypeInfo UInt64() { return new ScalarTypeInfo(typeof(ulong), Statics.Format64, TraceLoggingDataType.UInt64); } public static TraceLoggingTypeInfo IntPtr() { return new ScalarTypeInfo(typeof(IntPtr), Statics.FormatPtr, Statics.IntPtrType); } public static TraceLoggingTypeInfo UIntPtr() { return new ScalarTypeInfo(typeof(UIntPtr), Statics.FormatPtr, Statics.UIntPtrType); } - public static TraceLoggingTypeInfo Single() { return new ScalarTypeInfo(typeof(Single), Statics.Format32, TraceLoggingDataType.Float); } - public static TraceLoggingTypeInfo Double() { return new ScalarTypeInfo(typeof(Double), Statics.Format64, TraceLoggingDataType.Double); } + public static TraceLoggingTypeInfo Single() { return new ScalarTypeInfo(typeof(float), Statics.Format32, TraceLoggingDataType.Float); } + public static TraceLoggingTypeInfo Double() { return new ScalarTypeInfo(typeof(double), Statics.Format64, TraceLoggingDataType.Double); } public static TraceLoggingTypeInfo Guid() { return new ScalarTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid); } } @@ -122,21 +122,21 @@ namespace System.Diagnostics.Tracing collector.AddArray(value, elementSize); } - public static TraceLoggingTypeInfo Boolean() { return new ScalarArrayTypeInfo(typeof(Boolean[]), Statics.Format8, TraceLoggingDataType.Boolean8, sizeof(Boolean)); } - public static TraceLoggingTypeInfo Byte() { return new ScalarArrayTypeInfo(typeof(Byte[]), Statics.Format8, TraceLoggingDataType.UInt8, sizeof(Byte)); } - public static TraceLoggingTypeInfo SByte() { return new ScalarArrayTypeInfo(typeof(SByte[]), Statics.Format8, TraceLoggingDataType.Int8, sizeof(SByte)); } - public static TraceLoggingTypeInfo Char() { return new ScalarArrayTypeInfo(typeof(Char[]), Statics.Format16, TraceLoggingDataType.Char16, sizeof(Char)); } - public static TraceLoggingTypeInfo Int16() { return new ScalarArrayTypeInfo(typeof(Int16[]), Statics.Format16, TraceLoggingDataType.Int16, sizeof(Int16)); } - public static TraceLoggingTypeInfo UInt16() { return new ScalarArrayTypeInfo(typeof(UInt16[]), Statics.Format16, TraceLoggingDataType.UInt16, sizeof(UInt16)); } - public static TraceLoggingTypeInfo Int32() { return new ScalarArrayTypeInfo(typeof(Int32[]), Statics.Format32, TraceLoggingDataType.Int32, sizeof(Int32)); } - public static TraceLoggingTypeInfo UInt32() { return new ScalarArrayTypeInfo(typeof(UInt32[]), Statics.Format32, TraceLoggingDataType.UInt32, sizeof(UInt32)); } - public static TraceLoggingTypeInfo Int64() { return new ScalarArrayTypeInfo(typeof(Int64[]), Statics.Format64, TraceLoggingDataType.Int64, sizeof(Int64)); } - public static TraceLoggingTypeInfo UInt64() { return new ScalarArrayTypeInfo(typeof(UInt64[]), Statics.Format64, TraceLoggingDataType.UInt64, sizeof(UInt64)); } + public static TraceLoggingTypeInfo Boolean() { return new ScalarArrayTypeInfo(typeof(bool[]), Statics.Format8, TraceLoggingDataType.Boolean8, sizeof(bool)); } + public static TraceLoggingTypeInfo Byte() { return new ScalarArrayTypeInfo(typeof(byte[]), Statics.Format8, TraceLoggingDataType.UInt8, sizeof(byte)); } + public static TraceLoggingTypeInfo SByte() { return new ScalarArrayTypeInfo(typeof(sbyte[]), Statics.Format8, TraceLoggingDataType.Int8, sizeof(sbyte)); } + public static TraceLoggingTypeInfo Char() { return new ScalarArrayTypeInfo(typeof(char[]), Statics.Format16, TraceLoggingDataType.Char16, sizeof(char)); } + public static TraceLoggingTypeInfo Int16() { return new ScalarArrayTypeInfo(typeof(short[]), Statics.Format16, TraceLoggingDataType.Int16, sizeof(short)); } + public static TraceLoggingTypeInfo UInt16() { return new ScalarArrayTypeInfo(typeof(ushort[]), Statics.Format16, TraceLoggingDataType.UInt16, sizeof(ushort)); } + public static TraceLoggingTypeInfo Int32() { return new ScalarArrayTypeInfo(typeof(int[]), Statics.Format32, TraceLoggingDataType.Int32, sizeof(int)); } + public static TraceLoggingTypeInfo UInt32() { return new ScalarArrayTypeInfo(typeof(uint[]), Statics.Format32, TraceLoggingDataType.UInt32, sizeof(uint)); } + public static TraceLoggingTypeInfo Int64() { return new ScalarArrayTypeInfo(typeof(long[]), Statics.Format64, TraceLoggingDataType.Int64, sizeof(long)); } + public static TraceLoggingTypeInfo UInt64() { return new ScalarArrayTypeInfo(typeof(ulong[]), Statics.Format64, TraceLoggingDataType.UInt64, sizeof(ulong)); } public static TraceLoggingTypeInfo IntPtr() { return new ScalarArrayTypeInfo(typeof(IntPtr[]), Statics.FormatPtr, Statics.IntPtrType, System.IntPtr.Size); } public static TraceLoggingTypeInfo UIntPtr() { return new ScalarArrayTypeInfo(typeof(UIntPtr[]), Statics.FormatPtr, Statics.UIntPtrType, System.IntPtr.Size); } - public static TraceLoggingTypeInfo Single() { return new ScalarArrayTypeInfo(typeof(Single[]), Statics.Format32, TraceLoggingDataType.Float, sizeof(Single)); } - public static TraceLoggingTypeInfo Double() { return new ScalarArrayTypeInfo(typeof(Double[]), Statics.Format64, TraceLoggingDataType.Double, sizeof(Double)); } - public unsafe static TraceLoggingTypeInfo Guid() { return new ScalarArrayTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid, sizeof(Guid)); } + public static TraceLoggingTypeInfo Single() { return new ScalarArrayTypeInfo(typeof(float[]), Statics.Format32, TraceLoggingDataType.Float, sizeof(float)); } + public static TraceLoggingTypeInfo Double() { return new ScalarArrayTypeInfo(typeof(double[]), Statics.Format64, TraceLoggingDataType.Double, sizeof(double)); } + public static unsafe TraceLoggingTypeInfo Guid() { return new ScalarArrayTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid, sizeof(Guid)); } } /// @@ -151,12 +151,12 @@ namespace System.Diagnostics.Tracing string name, EventFieldFormat format) { - collector.AddBinary(name, Statics.MakeDataType(TraceLoggingDataType.CountedUtf16String, format)); + collector.AddNullTerminatedString(name, Statics.MakeDataType(TraceLoggingDataType.Utf16String, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { - collector.AddBinary((string)value.ReferenceValue); + collector.AddNullTerminatedString((string)value.ReferenceValue); } public override object GetData(object value) @@ -243,11 +243,11 @@ namespace System.Diagnostics.Tracing } /// - /// TraceLogging: Type handler for Decimal. (Note: not full-fidelity, exposed as Double.) + /// TraceLogging: Type handler for decimal. (Note: not full-fidelity, exposed as Double.) /// internal sealed class DecimalTypeInfo : TraceLoggingTypeInfo { - public DecimalTypeInfo() : base(typeof(Decimal)) { } + public DecimalTypeInfo() : base(typeof(decimal)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs index 05539ab4fd..0c21672131 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs @@ -548,51 +548,51 @@ namespace System.Diagnostics.Tracing else if (dataType.IsArray) { var elementType = dataType.GetElementType(); - if (elementType == typeof(Boolean)) + if (elementType == typeof(bool)) { result = ScalarArrayTypeInfo.Boolean(); } - else if (elementType == typeof(Byte)) + else if (elementType == typeof(byte)) { result = ScalarArrayTypeInfo.Byte(); } - else if (elementType == typeof(SByte)) + else if (elementType == typeof(sbyte)) { result = ScalarArrayTypeInfo.SByte(); } - else if (elementType == typeof(Int16)) + else if (elementType == typeof(short)) { result = ScalarArrayTypeInfo.Int16(); } - else if (elementType == typeof(UInt16)) + else if (elementType == typeof(ushort)) { result = ScalarArrayTypeInfo.UInt16(); } - else if (elementType == typeof(Int32)) + else if (elementType == typeof(int)) { result = ScalarArrayTypeInfo.Int32(); } - else if (elementType == typeof(UInt32)) + else if (elementType == typeof(uint)) { result = ScalarArrayTypeInfo.UInt32(); } - else if (elementType == typeof(Int64)) + else if (elementType == typeof(long)) { result = ScalarArrayTypeInfo.Int64(); } - else if (elementType == typeof(UInt64)) + else if (elementType == typeof(ulong)) { result = ScalarArrayTypeInfo.UInt64(); } - else if (elementType == typeof(Char)) + else if (elementType == typeof(char)) { result = ScalarArrayTypeInfo.Char(); } - else if (elementType == typeof(Double)) + else if (elementType == typeof(double)) { result = ScalarArrayTypeInfo.Double(); } - else if (elementType == typeof(Single)) + else if (elementType == typeof(float)) { result = ScalarArrayTypeInfo.Single(); } @@ -618,55 +618,55 @@ namespace System.Diagnostics.Tracing if (Statics.IsEnum(dataType)) dataType = Enum.GetUnderlyingType(dataType); - if (dataType == typeof(String)) + if (dataType == typeof(string)) { result = new StringTypeInfo(); } - else if (dataType == typeof(Boolean)) + else if (dataType == typeof(bool)) { result = ScalarTypeInfo.Boolean(); } - else if (dataType == typeof(Byte)) + else if (dataType == typeof(byte)) { result = ScalarTypeInfo.Byte(); } - else if (dataType == typeof(SByte)) + else if (dataType == typeof(sbyte)) { result = ScalarTypeInfo.SByte(); } - else if (dataType == typeof(Int16)) + else if (dataType == typeof(short)) { result = ScalarTypeInfo.Int16(); } - else if (dataType == typeof(UInt16)) + else if (dataType == typeof(ushort)) { result = ScalarTypeInfo.UInt16(); } - else if (dataType == typeof(Int32)) + else if (dataType == typeof(int)) { result = ScalarTypeInfo.Int32(); } - else if (dataType == typeof(UInt32)) + else if (dataType == typeof(uint)) { result = ScalarTypeInfo.UInt32(); } - else if (dataType == typeof(Int64)) + else if (dataType == typeof(long)) { result = ScalarTypeInfo.Int64(); } - else if (dataType == typeof(UInt64)) + else if (dataType == typeof(ulong)) { result = ScalarTypeInfo.UInt64(); } - else if (dataType == typeof(Char)) + else if (dataType == typeof(char)) { result = ScalarTypeInfo.Char(); } - else if (dataType == typeof(Double)) + else if (dataType == typeof(double)) { result = ScalarTypeInfo.Double(); } - else if (dataType == typeof(Single)) + else if (dataType == typeof(float)) { result = ScalarTypeInfo.Single(); } @@ -674,7 +674,7 @@ namespace System.Diagnostics.Tracing { result = new DateTimeTypeInfo(); } - else if (dataType == typeof(Decimal)) + else if (dataType == typeof(decimal)) { result = new DecimalTypeInfo(); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataCollector.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataCollector.cs index 04a047fb35..f6d0a59aa6 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataCollector.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataCollector.cs @@ -84,6 +84,17 @@ namespace System.Diagnostics.Tracing DataCollector.ThreadInstance.AddScalar(&value, sizeof(double)); } + /// + /// Adds a null-terminated String value to the event payload. + /// + /// + /// Value to be added. A null value is treated as a zero-length string. + /// + public void AddNullTerminatedString(string value) + { + DataCollector.ThreadInstance.AddNullTerminatedString(value); + } + /// /// Adds a counted String value to the event payload. /// diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs index 4348df7d64..0553f98999 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs @@ -47,6 +47,10 @@ namespace System.Diagnostics.Tracing private byte[] providerMetadata; #endif +#if FEATURE_PERFTRACING + private readonly TraceLoggingEventHandleTable m_eventHandleTable = new TraceLoggingEventHandleTable(); +#endif + /// /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API). /// @@ -431,15 +435,22 @@ namespace System.Diagnostics.Tracing identity = nameInfo.identity; EventDescriptor descriptor = new EventDescriptor(identity, level, opcode, (long)keywords); +#if FEATURE_PERFTRACING + IntPtr eventHandle = nameInfo.GetOrCreateEventHandle(m_eventPipeProvider, m_eventHandleTable, descriptor, eventTypes); + Debug.Assert(eventHandle != IntPtr.Zero); +#else + IntPtr eventHandle = IntPtr.Zero; +#endif + var pinCount = eventTypes.pinCount; var scratch = stackalloc byte[eventTypes.scratchSize]; var descriptors = stackalloc EventData[eventTypes.dataCount + 3]; for(int i = 0; i < eventTypes.dataCount + 3; i++) - descriptors[i] = default(EventData); + descriptors[i] = default; var pins = stackalloc GCHandle[pinCount]; for (int i = 0; i < pinCount; i++) - pins[i] = default(GCHandle); + pins[i] = default; fixed (byte* pMetadata0 = this.providerMetadata, @@ -472,6 +483,7 @@ namespace System.Diagnostics.Tracing this.WriteEventRaw( eventName, ref descriptor, + eventHandle, activityID, childActivityID, (int)(DataCollector.ThreadInstance.Finish() - descriptors), @@ -538,12 +550,19 @@ namespace System.Diagnostics.Tracing return; } +#if FEATURE_PERFTRACING + IntPtr eventHandle = nameInfo.GetOrCreateEventHandle(m_eventPipeProvider, m_eventHandleTable, descriptor, eventTypes); + Debug.Assert(eventHandle != IntPtr.Zero); +#else + IntPtr eventHandle = IntPtr.Zero; +#endif + // We make a descriptor for each EventData, and because we morph strings to counted strings // we may have 2 for each arg, so we allocate enough for this. var descriptorsLength = eventTypes.dataCount + eventTypes.typeInfos.Length * 2 + 3; var descriptors = stackalloc EventData[descriptorsLength]; for(int i = 0; i < descriptorsLength; i++) - descriptors[i] = default(EventData); + descriptors[i] = default; fixed (byte* pMetadata0 = this.providerMetadata, @@ -557,35 +576,20 @@ namespace System.Diagnostics.Tracing for (int i = 0; i < eventTypes.typeInfos.Length; i++) { - // Until M3, we need to morph strings to a counted representation - // When TDH supports null terminated strings, we can remove this. - if (eventTypes.typeInfos[i].DataType == typeof(string)) - { - // Write out the size of the string - descriptors[numDescrs].DataPointer = (IntPtr) (&descriptors[numDescrs + 1].m_Size); - descriptors[numDescrs].m_Size = 2; - numDescrs++; + descriptors[numDescrs].m_Ptr = data[i].m_Ptr; + descriptors[numDescrs].m_Size = data[i].m_Size; - descriptors[numDescrs].m_Ptr = data[i].m_Ptr; - descriptors[numDescrs].m_Size = data[i].m_Size - 2; // Remove the null terminator - numDescrs++; - } - else - { - descriptors[numDescrs].m_Ptr = data[i].m_Ptr; - descriptors[numDescrs].m_Size = data[i].m_Size; + // old conventions for bool is 4 bytes, but meta-data assumes 1. + if (data[i].m_Size == 4 && eventTypes.typeInfos[i].DataType == typeof(bool)) + descriptors[numDescrs].m_Size = 1; - // old conventions for bool is 4 bytes, but meta-data assumes 1. - if (data[i].m_Size == 4 && eventTypes.typeInfos[i].DataType == typeof(bool)) - descriptors[numDescrs].m_Size = 1; - - numDescrs++; - } + numDescrs++; } this.WriteEventRaw( eventName, ref descriptor, + eventHandle, activityID, childActivityID, numDescrs, @@ -615,16 +619,23 @@ namespace System.Diagnostics.Tracing return; } +#if FEATURE_PERFTRACING + IntPtr eventHandle = nameInfo.GetOrCreateEventHandle(m_eventPipeProvider, m_eventHandleTable, descriptor, eventTypes); + Debug.Assert(eventHandle != IntPtr.Zero); +#else + IntPtr eventHandle = IntPtr.Zero; +#endif + #if FEATURE_MANAGED_ETW var pinCount = eventTypes.pinCount; var scratch = stackalloc byte[eventTypes.scratchSize]; var descriptors = stackalloc EventData[eventTypes.dataCount + 3]; for(int i=0; i + /// Adds a null-terminated string field to an event. + /// Compatible with core types: Utf16String, MbcsString. + /// Compatible with dataCollector method: AddNullTerminatedString(string). + /// + /// + /// The name to use for the added field. This value must not be null. + /// + /// + /// The type code for the added field. This must be a null-terminated string type. + /// + public void AddNullTerminatedString(string name, TraceLoggingDataType type) + { + switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask)) + { + case TraceLoggingDataType.Utf16String: + break; + default: + throw new ArgumentOutOfRangeException(nameof(type)); + } + + this.impl.AddNonscalar(); + this.AddField(new FieldMetadata(name, type, this.Tags, this.BeginningBufferedArray)); + } + /// /// Adds an array field to an event. /// @@ -198,16 +223,12 @@ namespace System.Diagnostics.Tracing /// The name to use for the added field. This value must not be null. /// /// - /// The type code for the added field. This must be a fixed-size type - /// or a string type. In the case of a string type, this adds an array - /// of characters, not an array of strings. + /// The type code for the added field. This must be a fixed-size type. /// public void AddArray(string name, TraceLoggingDataType type) { switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask)) { - case TraceLoggingDataType.Utf16String: - case TraceLoggingDataType.MbcsString: case TraceLoggingDataType.Int8: case TraceLoggingDataType.UInt8: case TraceLoggingDataType.Int16: diff --git a/external/corert/src/System.Private.CoreLib/shared/System/DivideByZeroException.cs b/external/corert/src/System.Private.CoreLib/shared/System/DivideByZeroException.cs index b309695ff3..27f57414ff 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/DivideByZeroException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/DivideByZeroException.cs @@ -25,13 +25,13 @@ namespace System HResult = HResults.COR_E_DIVIDEBYZERO; } - public DivideByZeroException(String message) + public DivideByZeroException(string message) : base(message) { HResult = HResults.COR_E_DIVIDEBYZERO; } - public DivideByZeroException(String message, Exception innerException) + public DivideByZeroException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_DIVIDEBYZERO; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/DllNotFoundException.cs b/external/corert/src/System.Private.CoreLib/shared/System/DllNotFoundException.cs index 14fb50d9c5..bd29b8b13a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/DllNotFoundException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/DllNotFoundException.cs @@ -26,13 +26,13 @@ namespace System HResult = HResults.COR_E_DLLNOTFOUND; } - public DllNotFoundException(String message) + public DllNotFoundException(string message) : base(message) { HResult = HResults.COR_E_DLLNOTFOUND; } - public DllNotFoundException(String message, Exception inner) + public DllNotFoundException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_DLLNOTFOUND; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Double.cs b/external/corert/src/System.Private.CoreLib/shared/System/Double.cs index 146ee46005..d85b4bca99 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Double.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Double.cs @@ -24,9 +24,9 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Double : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct Double : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private double m_value; // Do not rename (binary serialization) + private readonly double m_value; // Do not rename (binary serialization) // // Public Constants @@ -47,7 +47,7 @@ namespace System /// Determines whether the specified value is finite (zero, subnormal, or normal). [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static bool IsFinite(double d) + public static unsafe bool IsFinite(double d) { var bits = BitConverter.DoubleToInt64Bits(d); return (bits & 0x7FFFFFFFFFFFFFFF) < 0x7FF0000000000000; @@ -56,7 +56,7 @@ namespace System /// Determines whether the specified value is infinite. [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static bool IsInfinity(double d) + public static unsafe bool IsInfinity(double d) { var bits = BitConverter.DoubleToInt64Bits(d); return (bits & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000; @@ -65,7 +65,7 @@ namespace System /// Determines whether the specified value is NaN. [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static bool IsNaN(double d) + public static unsafe bool IsNaN(double d) { var bits = BitConverter.DoubleToInt64Bits(d); return (bits & 0x7FFFFFFFFFFFFFFF) > 0x7FF0000000000000; @@ -74,10 +74,9 @@ namespace System /// Determines whether the specified value is negative. [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static bool IsNegative(double d) + public static unsafe bool IsNegative(double d) { - var bits = unchecked((ulong)BitConverter.DoubleToInt64Bits(d)); - return (bits & 0x8000000000000000) == 0x8000000000000000; + return BitConverter.DoubleToInt64Bits(d) < 0; } /// Determines whether the specified value is negative infinity. @@ -91,7 +90,7 @@ namespace System /// Determines whether the specified value is normal. [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called - public unsafe static bool IsNormal(double d) + public static unsafe bool IsNormal(double d) { var bits = BitConverter.DoubleToInt64Bits(d); bits &= 0x7FFFFFFFFFFFFFFF; @@ -109,7 +108,7 @@ namespace System /// Determines whether the specified value is subnormal. [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called - public unsafe static bool IsSubnormal(double d) + public static unsafe bool IsSubnormal(double d) { var bits = BitConverter.DoubleToInt64Bits(d); bits &= 0x7FFFFFFFFFFFFFFF; @@ -123,13 +122,13 @@ namespace System // // Returns a value less than zero if this object // - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) { return 1; } - if (value is Double) + if (value is double) { double d = (double)value; if (m_value < d) return -1; @@ -145,7 +144,7 @@ namespace System throw new ArgumentException(SR.Arg_MustBeDouble); } - public int CompareTo(Double value) + public int CompareTo(double value) { if (m_value < value) return -1; if (m_value > value) return 1; @@ -160,13 +159,13 @@ namespace System // True if obj is another Double with the same value as the current instance. This is // a method of object equality, that only returns true if obj is also a double. - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is Double)) + if (!(obj is double)) { return false; } - double temp = ((Double)obj).m_value; + double temp = ((double)obj).m_value; // This code below is written this way for performance reasons i.e the != and == check is intentional. if (temp == m_value) { @@ -176,42 +175,42 @@ namespace System } [NonVersionable] - public static bool operator ==(Double left, Double right) + public static bool operator ==(double left, double right) { return left == right; } [NonVersionable] - public static bool operator !=(Double left, Double right) + public static bool operator !=(double left, double right) { return left != right; } [NonVersionable] - public static bool operator <(Double left, Double right) + public static bool operator <(double left, double right) { return left < right; } [NonVersionable] - public static bool operator >(Double left, Double right) + public static bool operator >(double left, double right) { return left > right; } [NonVersionable] - public static bool operator <=(Double left, Double right) + public static bool operator <=(double left, double right) { return left <= right; } [NonVersionable] - public static bool operator >=(Double left, Double right) + public static bool operator >=(double left, double right) { return left >= right; } - public bool Equals(Double obj) + public bool Equals(double obj) { if (obj == m_value) { @@ -226,7 +225,7 @@ namespace System [MethodImpl(MethodImplOptions.AggressiveInlining)] // 64-bit constants make the IL unusually large that makes the inliner to reject the method public override int GetHashCode() { - var bits = Unsafe.As(ref m_value); + var bits = Unsafe.As(ref Unsafe.AsRef(in m_value)); // Optimized check for IsNan() || IsZero() if (((bits - 1) & 0x7FFFFFFFFFFFFFFF) >= 0x7FF0000000000000) @@ -238,22 +237,22 @@ namespace System return unchecked((int)bits) ^ ((int)(bits >> 32)); } - public override String ToString() + public override string ToString() { return Number.FormatDouble(m_value, null, NumberFormatInfo.CurrentInfo); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatDouble(m_value, null, NumberFormatInfo.GetInstance(provider)); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider)); } @@ -263,26 +262,26 @@ namespace System return Number.TryFormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten); } - public static double Parse(String s) + public static double Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDouble(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } - public static double Parse(String s, NumberStyles style) + public static double Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDouble(s, style, NumberFormatInfo.CurrentInfo); } - public static double Parse(String s, IFormatProvider provider) + public static double Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDouble(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } - public static double Parse(String s, NumberStyles style, IFormatProvider provider) + public static double Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -297,7 +296,7 @@ namespace System // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. - public static double Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) + public static double Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Float | NumberStyles.AllowThousands, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.ParseDouble(s, style, NumberFormatInfo.GetInstance(provider)); @@ -305,7 +304,7 @@ namespace System - public static bool TryParse(String s, out double result) + public static bool TryParse(string s, out double result) { if (s == null) { @@ -321,7 +320,7 @@ namespace System return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } - public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out double result) + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out double result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); @@ -346,15 +345,15 @@ namespace System if (!success) { ReadOnlySpan sTrim = s.Trim(); - if (StringSpanHelpers.Equals(sTrim, info.PositiveInfinitySymbol)) + if (sTrim.EqualsOrdinal(info.PositiveInfinitySymbol)) { result = PositiveInfinity; } - else if (StringSpanHelpers.Equals(sTrim, info.NegativeInfinitySymbol)) + else if (sTrim.EqualsOrdinal(info.NegativeInfinitySymbol)) { result = NegativeInfinity; } - else if (StringSpanHelpers.Equals(sTrim, info.NaNSymbol)) + else if (sTrim.EqualsOrdinal(info.NaNSymbol)) { result = NaN; } @@ -435,7 +434,7 @@ namespace System return m_value; } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -445,7 +444,7 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Double", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/DuplicateWaitObjectException.cs b/external/corert/src/System.Private.CoreLib/shared/System/DuplicateWaitObjectException.cs index 77303846a3..f48e4be174 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/DuplicateWaitObjectException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/DuplicateWaitObjectException.cs @@ -21,9 +21,9 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class DuplicateWaitObjectException : ArgumentException { - private static volatile String s_duplicateWaitObjectMessage = null; + private static volatile string s_duplicateWaitObjectMessage = null; - private static String DuplicateWaitObjectMessage + private static string DuplicateWaitObjectMessage { get { @@ -41,19 +41,19 @@ namespace System HResult = HResults.COR_E_DUPLICATEWAITOBJECT; } - public DuplicateWaitObjectException(String parameterName) + public DuplicateWaitObjectException(string parameterName) : base(DuplicateWaitObjectMessage, parameterName) { HResult = HResults.COR_E_DUPLICATEWAITOBJECT; } - public DuplicateWaitObjectException(String parameterName, String message) + public DuplicateWaitObjectException(string parameterName, string message) : base(message, parameterName) { HResult = HResults.COR_E_DUPLICATEWAITOBJECT; } - public DuplicateWaitObjectException(String message, Exception innerException) + public DuplicateWaitObjectException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_DUPLICATEWAITOBJECT; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/EntryPointNotFoundException.cs b/external/corert/src/System.Private.CoreLib/shared/System/EntryPointNotFoundException.cs index dac1cdb971..606743aa1e 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/EntryPointNotFoundException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/EntryPointNotFoundException.cs @@ -26,13 +26,13 @@ namespace System HResult = HResults.COR_E_ENTRYPOINTNOTFOUND; } - public EntryPointNotFoundException(String message) + public EntryPointNotFoundException(string message) : base(message) { HResult = HResults.COR_E_ENTRYPOINTNOTFOUND; } - public EntryPointNotFoundException(String message, Exception inner) + public EntryPointNotFoundException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_ENTRYPOINTNOTFOUND; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/EventHandler.cs b/external/corert/src/System.Private.CoreLib/shared/System/EventHandler.cs index 3d1cbfef26..c38e17ce6f 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/EventHandler.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/EventHandler.cs @@ -6,7 +6,7 @@ using System; namespace System { - public delegate void EventHandler(Object sender, EventArgs e); + public delegate void EventHandler(object sender, EventArgs e); - public delegate void EventHandler(Object sender, TEventArgs e); // Removed TEventArgs constraint post-.NET 4 + public delegate void EventHandler(object sender, TEventArgs e); // Removed TEventArgs constraint post-.NET 4 } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ExecutionEngineException.cs b/external/corert/src/System.Private.CoreLib/shared/System/ExecutionEngineException.cs index 5edd5cf19f..5649cc082b 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ExecutionEngineException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ExecutionEngineException.cs @@ -31,13 +31,13 @@ namespace System HResult = HResults.COR_E_EXECUTIONENGINE; } - public ExecutionEngineException(String message) + public ExecutionEngineException(string message) : base(message) { HResult = HResults.COR_E_EXECUTIONENGINE; } - public ExecutionEngineException(String message, Exception innerException) + public ExecutionEngineException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_EXECUTIONENGINE; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/FieldAccessException.cs b/external/corert/src/System.Private.CoreLib/shared/System/FieldAccessException.cs index cb28264d61..b23984133c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/FieldAccessException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/FieldAccessException.cs @@ -23,13 +23,13 @@ namespace System HResult = HResults.COR_E_FIELDACCESS; } - public FieldAccessException(String message) + public FieldAccessException(string message) : base(message) { HResult = HResults.COR_E_FIELDACCESS; } - public FieldAccessException(String message, Exception inner) + public FieldAccessException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_FIELDACCESS; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/FormatException.cs b/external/corert/src/System.Private.CoreLib/shared/System/FormatException.cs index b0e273369c..97d5001f3f 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/FormatException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/FormatException.cs @@ -25,13 +25,13 @@ namespace System HResult = HResults.COR_E_FORMAT; } - public FormatException(String message) + public FormatException(string message) : base(message) { HResult = HResults.COR_E_FORMAT; } - public FormatException(String message, Exception innerException) + public FormatException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_FORMAT; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/FormattableString.cs b/external/corert/src/System.Private.CoreLib/shared/System/FormattableString.cs index 6369363b5d..51863d6e7c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/FormattableString.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/FormattableString.cs @@ -73,6 +73,29 @@ namespace System return formattable.ToString(Globalization.CultureInfo.InvariantCulture); } + /// + /// Format the given object in the current culture. This static method may be + /// imported in C# by + /// + /// using static System.FormattableString; + /// . + /// Within the scope + /// of that import directive an interpolated string may be formatted in the + /// current culture by writing, for example, + /// + /// CurrentCulture($"{{ lat = {latitude}; lon = {longitude} }}") + /// + /// + public static string CurrentCulture(FormattableString formattable) + { + if (formattable == null) + { + throw new ArgumentNullException(nameof(formattable)); + } + + return formattable.ToString(Globalization.CultureInfo.CurrentCulture); + } + public override string ToString() { return ToString(Globalization.CultureInfo.CurrentCulture); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Gen2GcCallback.cs b/external/corert/src/System.Private.CoreLib/shared/System/Gen2GcCallback.cs new file mode 100644 index 0000000000..2252681224 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Gen2GcCallback.cs @@ -0,0 +1,76 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.ConstrainedExecution; +using System.Runtime.InteropServices; + +namespace System +{ + /// + /// Schedules a callback roughly every gen 2 GC (you may see a Gen 0 an Gen 1 but only once) + /// (We can fix this by capturing the Gen 2 count at startup and testing, but I mostly don't care) + /// + internal sealed class Gen2GcCallback : CriticalFinalizerObject + { + private Gen2GcCallback() + : base() + { + } + + /// + /// Schedule 'callback' to be called in the next GC. If the callback returns true it is + /// rescheduled for the next Gen 2 GC. Otherwise the callbacks stop. + /// + /// NOTE: This callback will be kept alive until either the callback function returns false, + /// or the target object dies. + /// + public static void Register(Func callback, object targetObj) + { + // Create a unreachable object that remembers the callback function and target object. + Gen2GcCallback gcCallback = new Gen2GcCallback(); + gcCallback.Setup(callback, targetObj); + } + + private Func _callback; + private GCHandle _weakTargetObj; + + private void Setup(Func callback, object targetObj) + { + _callback = callback; + _weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak); + } + + ~Gen2GcCallback() + { + // Check to see if the target object is still alive. + object targetObj = _weakTargetObj.Target; + if (targetObj == null) + { + // The target object is dead, so this callback object is no longer needed. + _weakTargetObj.Free(); + return; + } + + // Execute the callback method. + try + { + if (!_callback(targetObj)) + { + // If the callback returns false, this callback object is no longer needed. + return; + } + } + catch + { + // Ensure that we still get a chance to resurrect this object, even if the callback throws an exception. + } + + // Resurrect ourselves by re-registering for finalization. + if (!Environment.HasShutdownStarted) + { + GC.ReRegisterForFinalize(this); + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/Calendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/Calendar.cs index 49ad597ceb..66a63694a5 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/Calendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/Calendar.cs @@ -206,7 +206,7 @@ namespace System.Globalization if (ticks < minValue.Ticks || ticks > maxValue.Ticks) { throw new ArgumentException( - String.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange, + string.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange, minValue, maxValue))); } } @@ -736,7 +736,7 @@ namespace System.Globalization public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era); - internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) + internal virtual bool TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { result = DateTime.MinValue; try @@ -818,7 +818,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(millisecond), - String.Format( + string.Format( CultureInfo.InvariantCulture, SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1))); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Unix.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Unix.cs index 17d6ed7a01..c94ac0ae5f 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Unix.cs @@ -32,7 +32,7 @@ namespace System.Globalization internal partial class CalendarData { - private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId) + private bool LoadCalendarDataFromSystem(string localeName, CalendarId calendarId) { bool result = true; result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out this.sNativeName); @@ -134,16 +134,107 @@ namespace System.Globalization { List datePatternsList = callbackContext.Results; - datePatterns = new string[datePatternsList.Count]; for (int i = 0; i < datePatternsList.Count; i++) { - datePatterns[i] = NormalizeDatePattern(datePatternsList[i]); + datePatternsList[i] = NormalizeDatePattern(datePatternsList[i]); } + + if (dataType == CalendarDataType.ShortDates) + FixDefaultShortDatePattern(datePatternsList); + + datePatterns = datePatternsList.ToArray(); } return result; } + // FixDefaultShortDatePattern will convert the default short date pattern from using 'yy' to using 'yyyy' + // And will ensure the original pattern still exist in the list. + // doing that will have the short date pattern format the year as 4-digit number and not just 2-digit number. + // Example: June 5, 2018 will be formatted to something like 6/5/2018 instead of 6/5/18 fro en-US culture. + private static void FixDefaultShortDatePattern(List shortDatePatterns) + { + if (shortDatePatterns.Count == 0) + return; + + string s = shortDatePatterns[0]; + + // We are not expecting any pattern have length more than 100. + // We have to do this check to prevent stack overflow as we allocate the buffer on the stack. + if (s.Length > 100) + return; + + Span modifiedPattern = stackalloc char[s.Length + 2]; + int index = 0; + + while (index < s.Length) + { + if (s[index] == '\'') + { + do + { + modifiedPattern[index] = s[index]; + index++; + } while (index < s.Length && s[index] != '\''); + + if (index >= s.Length) + return; + } + else if (s[index] == 'y') + { + modifiedPattern[index] = 'y'; + break; + } + + modifiedPattern[index] = s[index]; + index++; + } + + if (index >= s.Length - 1 || s[index + 1] != 'y') + { + // not a 'yy' pattern + return; + } + + if (index + 2 < s.Length && s[index + 2] == 'y') + { + // we have 'yyy' then nothing to do + return; + } + + // we are sure now we have 'yy' pattern + + Debug.Assert(index + 3 < modifiedPattern.Length); + + modifiedPattern[index + 1] = 'y'; // second y + modifiedPattern[index + 2] = 'y'; // third y + modifiedPattern[index + 3] = 'y'; // fourth y + + index += 2; + + // Now, copy the rest of the pattern to the destination buffer + while (index < s.Length) + { + modifiedPattern[index + 2] = s[index]; + index++; + } + + shortDatePatterns[0] = modifiedPattern.ToString(); + + for (int i = 1; i < shortDatePatterns.Count; i++) + { + if (shortDatePatterns[i] == shortDatePatterns[0]) + { + // Found match in the list to the new constructed pattern, then replace it with the original modified pattern + shortDatePatterns[i] = s; + return; + } + } + + // if we come here means the newly constructed pattern not found on the list, then add the original pattern + shortDatePatterns.Add(s); + } + /// /// The ICU date format characters are not exactly the same as the .NET date format characters. /// NormalizeDatePattern will take in an ICU date pattern and return the equivalent .NET date pattern. @@ -220,7 +311,7 @@ namespace System.Globalization break; default: const string unsupportedDateFieldSymbols = "YuUrQqwWDFg"; - Debug.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1, + Debug.Assert(!unsupportedDateFieldSymbols.Contains(input[index]), string.Format(CultureInfo.InvariantCulture, "Encountered an unexpected date field symbol '{0}' from ICU which has no known corresponding .NET equivalent.", input[index])); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Windows.cs index 03f9088d62..de50374412 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Windows.cs @@ -13,7 +13,7 @@ namespace System.Globalization { internal partial class CalendarData { - private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId) + private bool LoadCalendarDataFromSystem(string localeName, CalendarId calendarId) { Debug.Assert(!GlobalizationMode.Invariant); @@ -127,7 +127,7 @@ namespace System.Globalization } // Call native side to figure out which calendars are allowed - internal static int GetCalendars(String localeName, bool useUserOverride, CalendarId[] calendars) + internal static int GetCalendars(string localeName, bool useUserOverride, CalendarId[] calendars) { Debug.Assert(!GlobalizationMode.Invariant); @@ -451,7 +451,7 @@ namespace System.Globalization } } - private static unsafe String GetUserDefaultLocaleName() + private static unsafe string GetUserDefaultLocaleName() { Debug.Assert(!GlobalizationMode.Invariant); @@ -463,7 +463,7 @@ namespace System.Globalization char* localeName = stackalloc char[LOCALE_NAME_MAX_LENGTH]; result = CultureData.GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SNAME, localeName, LOCALE_NAME_MAX_LENGTH); - return result <= 0 ? "" : new String(localeName, 0, result - 1); // exclude the null termination + return result <= 0 ? "" : new string(localeName, 0, result - 1); // exclude the null termination } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.cs index ea70a1ce9a..56ddf75791 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.cs @@ -19,26 +19,26 @@ namespace System.Globalization internal const int MAX_CALENDARS = 23; // Identity - internal String sNativeName; // Calendar Name for the locale + internal string sNativeName; // Calendar Name for the locale // Formats - internal String[] saShortDates; // Short Data format, default first - internal String[] saYearMonths; // Year/Month Data format, default first - internal String[] saLongDates; // Long Data format, default first - internal String sMonthDay; // Month/Day format + internal string[] saShortDates; // Short Data format, default first + internal string[] saYearMonths; // Year/Month Data format, default first + internal string[] saLongDates; // Long Data format, default first + internal string sMonthDay; // Month/Day format // Calendar Parts Names - internal String[] saEraNames; // Names of Eras - internal String[] saAbbrevEraNames; // Abbreviated Era Names - internal String[] saAbbrevEnglishEraNames; // Abbreviated Era Names in English - internal String[] saDayNames; // Day Names, null to use locale data, starts on Sunday - internal String[] saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday - internal String[] saSuperShortDayNames; // Super short Day of week names - internal String[] saMonthNames; // Month Names (13) - internal String[] saAbbrevMonthNames; // Abbrev Month Names (13) - internal String[] saMonthGenitiveNames; // Genitive Month Names (13) - internal String[] saAbbrevMonthGenitiveNames; // Genitive Abbrev Month Names (13) - internal String[] saLeapYearMonthNames; // Multiple strings for the month names in a leap year. + internal string[] saEraNames; // Names of Eras + internal string[] saAbbrevEraNames; // Abbreviated Era Names + internal string[] saAbbrevEnglishEraNames; // Abbreviated Era Names in English + internal string[] saDayNames; // Day Names, null to use locale data, starts on Sunday + internal string[] saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday + internal string[] saSuperShortDayNames; // Super short Day of week names + internal string[] saMonthNames; // Month Names (13) + internal string[] saAbbrevMonthNames; // Abbrev Month Names (13) + internal string[] saMonthGenitiveNames; // Genitive Month Names (13) + internal string[] saAbbrevMonthGenitiveNames; // Genitive Abbrev Month Names (13) + internal string[] saLeapYearMonthNames; // Multiple strings for the month names in a leap year. // Integers at end to make marshaller happier internal int iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry) @@ -69,22 +69,22 @@ namespace System.Globalization invariant.iCurrentEra = 1; // Current era # // Formats - invariant.saShortDates = new String[] { "MM/dd/yyyy", "yyyy-MM-dd" }; // short date format - invariant.saLongDates = new String[] { "dddd, dd MMMM yyyy" }; // long date format - invariant.saYearMonths = new String[] { "yyyy MMMM" }; // year month format + invariant.saShortDates = new string[] { "MM/dd/yyyy", "yyyy-MM-dd" }; // short date format + invariant.saLongDates = new string[] { "dddd, dd MMMM yyyy" }; // long date format + invariant.saYearMonths = new string[] { "yyyy MMMM" }; // year month format invariant.sMonthDay = "MMMM dd"; // Month day pattern // Calendar Parts Names - invariant.saEraNames = new String[] { "A.D." }; // Era names - invariant.saAbbrevEraNames = new String[] { "AD" }; // Abbreviated Era names - invariant.saAbbrevEnglishEraNames = new String[] { "AD" }; // Abbreviated era names in English - invariant.saDayNames = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };// day names - invariant.saAbbrevDayNames = new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // abbreviated day names - invariant.saSuperShortDayNames = new String[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; // The super short day names - invariant.saMonthNames = new String[] { "January", "February", "March", "April", "May", "June", - "July", "August", "September", "October", "November", "December", String.Empty}; // month names - invariant.saAbbrevMonthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", String.Empty}; // abbreviated month names + invariant.saEraNames = new string[] { "A.D." }; // Era names + invariant.saAbbrevEraNames = new string[] { "AD" }; // Abbreviated Era names + invariant.saAbbrevEnglishEraNames = new string[] { "AD" }; // Abbreviated era names in English + invariant.saDayNames = new string[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };// day names + invariant.saAbbrevDayNames = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // abbreviated day names + invariant.saSuperShortDayNames = new string[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; // The super short day names + invariant.saMonthNames = new string[] { "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December", string.Empty}; // month names + invariant.saAbbrevMonthNames = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", string.Empty}; // abbreviated month names invariant.saMonthGenitiveNames = invariant.saMonthNames; // Genitive month names (same as month names for invariant) invariant.saAbbrevMonthGenitiveNames = invariant.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant) invariant.saLeapYearMonthNames = invariant.saMonthNames; // leap year month names are unused in Gregorian English (invariant) @@ -97,7 +97,7 @@ namespace System.Globalization // // Get a bunch of data for a calendar // - internal CalendarData(String localeName, CalendarId calendarId, bool bUseUserOverrides) + internal CalendarData(string localeName, CalendarId calendarId, bool bUseUserOverrides) { this.bUseUserOverrides = bUseUserOverrides; @@ -109,7 +109,7 @@ namespace System.Globalization // Something failed, try invariant for missing parts // This is really not good, but we don't want the callers to crash. - if (this.sNativeName == null) this.sNativeName = String.Empty; // Calendar Name for the locale. + if (this.sNativeName == null) this.sNativeName = string.Empty; // Calendar Name for the locale. // Formats if (this.saShortDates == null) this.saShortDates = Invariant.saShortDates; // Short Data format, default first @@ -138,16 +138,16 @@ namespace System.Globalization } else { - this.sNativeName = String.Empty; + this.sNativeName = string.Empty; } } // Check for null genitive names (in case unmanaged side skips it for non-gregorian calendars, etc) - if (this.saMonthGenitiveNames == null || this.saMonthGenitiveNames.Length == 0 || String.IsNullOrEmpty(this.saMonthGenitiveNames[0])) + if (this.saMonthGenitiveNames == null || this.saMonthGenitiveNames.Length == 0 || string.IsNullOrEmpty(this.saMonthGenitiveNames[0])) this.saMonthGenitiveNames = this.saMonthNames; // Genitive month names (same as month names for invariant) - if (this.saAbbrevMonthGenitiveNames == null || this.saAbbrevMonthGenitiveNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0])) + if (this.saAbbrevMonthGenitiveNames == null || this.saAbbrevMonthGenitiveNames.Length == 0 || string.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0])) this.saAbbrevMonthGenitiveNames = this.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant) - if (this.saLeapYearMonthNames == null || this.saLeapYearMonthNames.Length == 0 || String.IsNullOrEmpty(this.saLeapYearMonthNames[0])) + if (this.saLeapYearMonthNames == null || this.saLeapYearMonthNames.Length == 0 || string.IsNullOrEmpty(this.saLeapYearMonthNames[0])) this.saLeapYearMonthNames = this.saMonthNames; InitializeEraNames(localeName, calendarId); @@ -162,7 +162,7 @@ namespace System.Globalization else { // For all others just use the an empty string (doesn't matter we'll never ask for it for other calendars) - this.saAbbrevEnglishEraNames = new String[] { "" }; + this.saAbbrevEnglishEraNames = new string[] { "" }; } // Japanese is the only thing with > 1 era. Its current era # is how many ever @@ -178,60 +178,60 @@ namespace System.Globalization // For Localized Gregorian we really expect the data from the OS. case CalendarId.GREGORIAN: // Fallback for CoreCLR < Win7 or culture.dll missing - if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0])) + if (this.saEraNames == null || this.saEraNames.Length == 0 || string.IsNullOrEmpty(this.saEraNames[0])) { - this.saEraNames = new String[] { "A.D." }; + this.saEraNames = new string[] { "A.D." }; } break; // The rest of the calendars have constant data, so we'll just use that case CalendarId.GREGORIAN_US: case CalendarId.JULIAN: - this.saEraNames = new String[] { "A.D." }; + this.saEraNames = new string[] { "A.D." }; break; case CalendarId.HEBREW: - this.saEraNames = new String[] { "C.E." }; + this.saEraNames = new string[] { "C.E." }; break; case CalendarId.HIJRI: case CalendarId.UMALQURA: if (localeName == "dv-MV") { // Special case for Divehi - this.saEraNames = new String[] { "\x0780\x07a8\x0796\x07b0\x0783\x07a9" }; + this.saEraNames = new string[] { "\x0780\x07a8\x0796\x07b0\x0783\x07a9" }; } else { - this.saEraNames = new String[] { "\x0628\x0639\x062F \x0627\x0644\x0647\x062C\x0631\x0629" }; + this.saEraNames = new string[] { "\x0628\x0639\x062F \x0627\x0644\x0647\x062C\x0631\x0629" }; } break; case CalendarId.GREGORIAN_ARABIC: case CalendarId.GREGORIAN_XLIT_ENGLISH: case CalendarId.GREGORIAN_XLIT_FRENCH: // These are all the same: - this.saEraNames = new String[] { "\x0645" }; + this.saEraNames = new string[] { "\x0645" }; break; case CalendarId.GREGORIAN_ME_FRENCH: - this.saEraNames = new String[] { "ap. J.-C." }; + this.saEraNames = new string[] { "ap. J.-C." }; break; case CalendarId.TAIWAN: if (SystemSupportsTaiwaneseCalendar()) { - this.saEraNames = new String[] { "\x4e2d\x83ef\x6c11\x570b" }; + this.saEraNames = new string[] { "\x4e2d\x83ef\x6c11\x570b" }; } else { - this.saEraNames = new String[] { String.Empty }; + this.saEraNames = new string[] { string.Empty }; } break; case CalendarId.KOREA: - this.saEraNames = new String[] { "\xb2e8\xae30" }; + this.saEraNames = new string[] { "\xb2e8\xae30" }; break; case CalendarId.THAI: - this.saEraNames = new String[] { "\x0e1e\x002e\x0e28\x002e" }; + this.saEraNames = new string[] { "\x0e1e\x002e\x0e28\x002e" }; break; case CalendarId.JAPAN: @@ -240,9 +240,9 @@ namespace System.Globalization break; case CalendarId.PERSIAN: - if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0])) + if (this.saEraNames == null || this.saEraNames.Length == 0 || string.IsNullOrEmpty(this.saEraNames[0])) { - this.saEraNames = new String[] { "\x0647\x002e\x0634" }; + this.saEraNames = new string[] { "\x0647\x002e\x0634" }; } break; @@ -261,16 +261,16 @@ namespace System.Globalization // For Localized Gregorian we really expect the data from the OS. case CalendarId.GREGORIAN: // Fallback for CoreCLR < Win7 or culture.dll missing - if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0])) + if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || string.IsNullOrEmpty(this.saAbbrevEraNames[0])) { - this.saAbbrevEraNames = new String[] { "AD" }; + this.saAbbrevEraNames = new string[] { "AD" }; } break; // The rest of the calendars have constant data, so we'll just use that case CalendarId.GREGORIAN_US: case CalendarId.JULIAN: - this.saAbbrevEraNames = new String[] { "AD" }; + this.saAbbrevEraNames = new string[] { "AD" }; break; case CalendarId.JAPAN: case CalendarId.JAPANESELUNISOLAR: @@ -281,16 +281,16 @@ namespace System.Globalization if (localeName == "dv-MV") { // Special case for Divehi - this.saAbbrevEraNames = new String[] { "\x0780\x002e" }; + this.saAbbrevEraNames = new string[] { "\x0780\x002e" }; } else { - this.saAbbrevEraNames = new String[] { "\x0647\x0640" }; + this.saAbbrevEraNames = new string[] { "\x0647\x0640" }; } break; case CalendarId.TAIWAN: // Get era name and abbreviate it - this.saAbbrevEraNames = new String[1]; + this.saAbbrevEraNames = new string[1]; if (this.saEraNames[0].Length == 4) { this.saAbbrevEraNames[0] = this.saEraNames[0].Substring(2, 2); @@ -302,7 +302,7 @@ namespace System.Globalization break; case CalendarId.PERSIAN: - if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0])) + if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || string.IsNullOrEmpty(this.saAbbrevEraNames[0])) { this.saAbbrevEraNames = this.saEraNames; } @@ -326,13 +326,13 @@ namespace System.Globalization // Get a culture name // TODO: Note that this doesn't handle the new calendars (lunisolar, etc) - String culture = CalendarIdToCultureName(calendarId); + string culture = CalendarIdToCultureName(calendarId); // Return our calendar return CultureInfo.GetCultureInfo(culture)._cultureData.GetCalendar(calendarId); } - private static String CalendarIdToCultureName(CalendarId calendarId) + private static string CalendarIdToCultureName(CalendarId calendarId) { switch (calendarId) { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CharUnicodeInfo.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CharUnicodeInfo.cs index 0cd8429bbc..d8d621cb05 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CharUnicodeInfo.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CharUnicodeInfo.cs @@ -13,6 +13,7 @@ //////////////////////////////////////////////////////////////////////////// using System.Diagnostics; +using System.Text; namespace System.Globalization { @@ -29,6 +30,7 @@ namespace System.Globalization internal const char HIGH_SURROGATE_END = '\udbff'; internal const char LOW_SURROGATE_START = '\udc00'; internal const char LOW_SURROGATE_END = '\udfff'; + internal const int HIGH_SURROGATE_RANGE = 0x3FF; internal const int UNICODE_CATEGORY_OFFSET = 0; internal const int BIDI_CATEGORY_OFFSET = 1; @@ -41,7 +43,7 @@ namespace System.Globalization // // Actions: // Convert the BMP character or surrogate pointed by index to a UTF32 value. - // This is similar to Char.ConvertToUTF32, but the difference is that + // This is similar to char.ConvertToUTF32, but the difference is that // it does not throw exceptions when invalid surrogate characters are passed in. // // WARNING: since it doesn't throw an exception it CAN return a value @@ -49,17 +51,17 @@ namespace System.Globalization // //////////////////////////////////////////////////////////////////////// - internal static int InternalConvertToUtf32(String s, int index) + internal static int InternalConvertToUtf32(string s, int index) { Debug.Assert(s != null, "s != null"); Debug.Assert(index >= 0 && index < s.Length, "index < s.Length"); if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; - if (temp1 >= 0 && temp1 <= 0x3ff) + if (temp1 >= 0 && temp1 <= HIGH_SURROGATE_RANGE) { int temp2 = (int)s[index + 1] - LOW_SURROGATE_START; - if (temp2 >= 0 && temp2 <= 0x3ff) + if (temp2 >= 0 && temp2 <= HIGH_SURROGATE_RANGE) { // Convert the surrogate to UTF32 and get the result. return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); @@ -68,6 +70,29 @@ namespace System.Globalization } return ((int)s[index]); } + + internal static int InternalConvertToUtf32(StringBuilder s, int index) + { + Debug.Assert(s != null, "s != null"); + Debug.Assert(index >= 0 && index < s.Length, "index < s.Length"); + + int c = (int)s[index]; + if (index < s.Length - 1) + { + int temp1 = c - HIGH_SURROGATE_START; + if (temp1 >= 0 && temp1 <= HIGH_SURROGATE_RANGE) + { + int temp2 = (int)s[index + 1] - LOW_SURROGATE_START; + if (temp2 >= 0 && temp2 <= HIGH_SURROGATE_RANGE) + { + // Convert the surrogate to UTF32 and get the result. + return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); + } + } + } + return c; + } + //////////////////////////////////////////////////////////////////////// // // Convert a character or a surrogate pair starting at index of string s @@ -90,7 +115,7 @@ namespace System.Globalization // //////////////////////////////////////////////////////////////////////// - internal static int InternalConvertToUtf32(String s, int index, out int charLength) + internal static int InternalConvertToUtf32(string s, int index, out int charLength) { Debug.Assert(s != null, "s != null"); Debug.Assert(s.Length > 0, "s.Length > 0"); @@ -99,10 +124,10 @@ namespace System.Globalization if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; - if (temp1 >= 0 && temp1 <= 0x3ff) + if (temp1 >= 0 && temp1 <= HIGH_SURROGATE_RANGE) { int temp2 = (int)s[index + 1] - LOW_SURROGATE_START; - if (temp2 >= 0 && temp2 <= 0x3ff) + if (temp2 >= 0 && temp2 <= HIGH_SURROGATE_RANGE) { // Convert the surrogate to UTF32 and get the result. charLength++; @@ -121,7 +146,7 @@ namespace System.Globalization // //////////////////////////////////////////////////////////////////////// - internal static bool IsWhiteSpace(String s, int index) + internal static bool IsWhiteSpace(string s, int index) { Debug.Assert(s != null, "s!=null"); Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); @@ -221,7 +246,7 @@ namespace System.Globalization } - public static double GetNumericValue(String s, int index) + public static double GetNumericValue(string s, int index) { if (s == null) { @@ -239,7 +264,7 @@ namespace System.Globalization return (sbyte)(InternalGetDigitValues(ch) >> 8); } - public static int GetDecimalDigitValue(String s, int index) + public static int GetDecimalDigitValue(string s, int index) { if (s == null) { @@ -259,7 +284,7 @@ namespace System.Globalization return (sbyte)(InternalGetDigitValues(ch) & 0x00FF); } - public static int GetDigitValue(String s, int index) + public static int GetDigitValue(string s, int index) { if (s == null) { @@ -279,7 +304,7 @@ namespace System.Globalization return (GetUnicodeCategory((int)ch)); } - public static UnicodeCategory GetUnicodeCategory(String s, int index) + public static UnicodeCategory GetUnicodeCategory(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -347,7 +372,7 @@ namespace System.Globalization // //////////////////////////////////////////////////////////////////////// - internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index) + internal static UnicodeCategory InternalGetUnicodeCategory(string value, int index) { Debug.Assert(value != null, "value can not be null"); Debug.Assert(index < value.Length, "index < value.Length"); @@ -355,7 +380,7 @@ namespace System.Globalization return (GetUnicodeCategory(InternalConvertToUtf32(value, index))); } - internal static BidiCategory GetBidiCategory(String s, int index) + internal static BidiCategory GetBidiCategory(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -368,6 +393,14 @@ namespace System.Globalization return ((BidiCategory) InternalGetCategoryValue(InternalConvertToUtf32(s, index), BIDI_CATEGORY_OFFSET)); } + internal static BidiCategory GetBidiCategory(StringBuilder s, int index) + { + Debug.Assert(s != null, "s can not be null"); + Debug.Assert(index >= 0 && index < s.Length, "invalid index"); ; + + return ((BidiCategory) InternalGetCategoryValue(InternalConvertToUtf32(s, index), BIDI_CATEGORY_OFFSET)); + } + //////////////////////////////////////////////////////////////////////// // // Get the Unicode category of the character starting at index. If the character is in BMP, charLength will return 1. @@ -375,7 +408,7 @@ namespace System.Globalization // //////////////////////////////////////////////////////////////////////// - internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength) + internal static UnicodeCategory InternalGetUnicodeCategory(string str, int index, out int charLength) { Debug.Assert(str != null, "str can not be null"); Debug.Assert(str.Length > 0, "str.Length > 0"); ; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/ChineseLunisolarCalendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/ChineseLunisolarCalendar.cs index d2b52b97be..39448e183f 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/ChineseLunisolarCalendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/ChineseLunisolarCalendar.cs @@ -8,9 +8,9 @@ namespace System.Globalization /* ** Calendar support range: ** Calendar Minimum Maximum - ** ========== ========== ========== + ** ========== ========== ========== ** Gregorian 1901/02/19 2101/01/28 - ** ChineseLunisolar 1901/01/01 2100/12/29 + ** ChineseLunisolar 1901/01/01 2100/12/29 */ public class ChineseLunisolarCalendar : EastAsianLunisolarCalendar @@ -43,7 +43,6 @@ namespace System.Globalization } } - public override DateTime MaxSupportedDateTime { get @@ -56,218 +55,222 @@ namespace System.Globalization { get { - // 1900: 1-29 2-30 3-29 4-29 5-30 6-29 7-30 8-30 Leap8-29 9-30 10-30 11-29 12-30 from Calendrical Tabulations + // 1900: 1-29 2-30 3-29 4-29 5-30 6-29 7-30 8-30 Leap8-29 9-30 10-30 11-29 12-30 from Calendrical Tabulations [1] + // [1] Reingold, Edward M, and Nachum Dershowitz. Calendrical Tabulations, 1900 - 2200.Cambridge: Cambridge Univ. Press, 2002.Print. return 384; } } - + // Data for years 1901-1905 and 1907-2100 matches output of Calendrical Calculations [2] and published calendar tables [3]. + // For 1906, month 4 of the Chinese year starts on 24 Apr 1906 and has 29 days. This is historially accurate + // but different to the values in [1] and output from [2]. This is due to a change in the astronomical methods used + // by the Chinese to calculate the calendar from 1913 onwards (see warnings in [1]). + // [2] Reingold, Edward M, and Nachum Dershowitz. Calendrical Calculations: The Ultimate Edition. Cambridge [etc.: Cambridge University Press, 2018. Print. + // [3] Wang, Jianmin. Xin Bian Wan Nian Li: (1840-2050) Chong Bian Ben. Beijing: Ke xue pu ji chu ban she, 1990. Print. private static readonly int[,] s_yinfo = { - /*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days - 1901 */ - { 0 , 2 , 19 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354 -1902 */{ 0 , 2 , 8 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 -1903 */{ 5 , 1 , 29 , 21096 },/* 29 30 29 30 29 29 30 29 29 30 30 29 30 383 -1904 */{ 0 , 2 , 16 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354 -1905 */{ 0 , 2 , 4 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355 -1906 */{ 4 , 1 , 25 , 27304 },/* 29 30 30 29 30 29 30 29 30 29 30 29 30 384 -1907 */{ 0 , 2 , 13 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 -1908 */{ 0 , 2 , 2 , 39632 },/* 30 29 29 30 30 29 30 29 30 30 29 30 0 355 -1909 */{ 2 , 1 , 22 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 -1910 */{ 0 , 2 , 10 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354 -1911 */{ 6 , 1 , 30 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384 -1912 */{ 0 , 2 , 18 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 -1913 */{ 0 , 2 , 6 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 -1914 */{ 5 , 1 , 26 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 -1915 */{ 0 , 2 , 14 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 -1916 */{ 0 , 2 , 3 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355 -1917 */{ 2 , 1 , 23 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 -1918 */{ 0 , 2 , 11 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 -1919 */{ 7 , 2 , 1 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384 -1920 */{ 0 , 2 , 20 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 -1921 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 -1922 */{ 5 , 1 , 28 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 -1923 */{ 0 , 2 , 16 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 -1924 */{ 0 , 2 , 5 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 -1925 */{ 4 , 1 , 24 , 44456 },/* 30 29 30 29 30 30 29 30 30 29 30 29 30 385 -1926 */{ 0 , 2 , 13 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 -1927 */{ 0 , 2 , 2 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355 -1928 */{ 2 , 1 , 23 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 -1929 */{ 0 , 2 , 10 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 -1930 */{ 6 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383 -1931 */{ 0 , 2 , 17 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 -1932 */{ 0 , 2 , 6 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 -1933 */{ 5 , 1 , 26 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384 -1934 */{ 0 , 2 , 14 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355 -1935 */{ 0 , 2 , 4 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 -1936 */{ 3 , 1 , 24 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384 -1937 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 -1938 */{ 7 , 1 , 31 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384 -1939 */{ 0 , 2 , 19 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354 -1940 */{ 0 , 2 , 8 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 -1941 */{ 6 , 1 , 27 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384 -1942 */{ 0 , 2 , 15 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 -1943 */{ 0 , 2 , 5 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 -1944 */{ 4 , 1 , 25 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 -1945 */{ 0 , 2 , 13 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 -1946 */{ 0 , 2 , 2 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 -1947 */{ 2 , 1 , 22 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 -1948 */{ 0 , 2 , 10 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 -1949 */{ 7 , 1 , 29 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384 -1950 */{ 0 , 2 , 17 , 27808 },/* 29 30 30 29 30 30 29 29 30 29 30 29 0 354 -1951 */{ 0 , 2 , 6 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 -1952 */{ 5 , 1 , 27 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 -1953 */{ 0 , 2 , 14 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354 -1954 */{ 0 , 2 , 3 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 -1955 */{ 3 , 1 , 24 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 -1956 */{ 0 , 2 , 12 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 -1957 */{ 8 , 1 , 31 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383 -1958 */{ 0 , 2 , 18 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355 -1959 */{ 0 , 2 , 8 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 -1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384 -1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355 -1962 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 -1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 -1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 -1965 */{ 0 , 2 , 2 , 21088 },/* 29 30 29 30 29 29 30 29 29 30 30 29 0 353 -1966 */{ 3 , 1 , 21 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 -1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355 -1968 */{ 7 , 1 , 30 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 -1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 -1970 */{ 0 , 2 , 6 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 -1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 -1972 */{ 0 , 2 , 15 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354 -1973 */{ 0 , 2 , 3 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 -1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 -1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 -1976 */{ 8 , 1 , 31 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 -1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 -1978 */{ 0 , 2 , 7 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355 -1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 -1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 -1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 -1982 */{ 4 , 1 , 25 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 -1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 -1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 -1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 -1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 -1987 */{ 6 , 1 , 29 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 29 384 -1988 */{ 0 , 2 , 17 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355 -1989 */{ 0 , 2 , 6 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355 -1990 */{ 5 , 1 , 27 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 -1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 -1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354 -1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 -1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 -1995 */{ 8 , 1 , 31 , 27432 },/* 29 30 30 29 30 29 30 30 29 29 30 29 30 384 -1996 */{ 0 , 2 , 19 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354 -1997 */{ 0 , 2 , 7 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355 -1998 */{ 5 , 1 , 28 , 37736 },/* 30 29 29 30 29 29 30 30 29 30 30 29 30 384 -1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 -2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354 -2001 */{ 4 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384 -2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 -2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355 -2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 -2005 */{ 0 , 2 , 9 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 -2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 -2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 -2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 -2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 -2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 -2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354 -2012 */{ 4 , 1 , 23 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384 -2013 */{ 0 , 2 , 10 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 -2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 -2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354 -2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 -2017 */{ 6 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 -2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 -2019 */{ 0 , 2 , 5 , 43312 },/* 30 29 30 29 30 29 29 30 29 29 30 30 0 354 -2020 */{ 4 , 1 , 25 , 29864 },/* 29 30 30 30 29 30 29 29 30 29 30 29 30 384 -2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 -2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 -2023 */{ 2 , 1 , 22 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384 -2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 -2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 -2026 */{ 0 , 2 , 17 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354 -2027 */{ 0 , 2 , 6 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354 -2028 */{ 5 , 1 , 26 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 -2029 */{ 0 , 2 , 13 , 54576 },/* 30 30 29 30 29 30 29 30 29 29 30 30 0 355 -2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354 -2031 */{ 3 , 1 , 23 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384 -2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 -2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 -2034 */{ 0 , 2 , 19 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354 -2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 -2036 */{ 6 , 1 , 28 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384 -2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 -2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354 -2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384 -2040 */{ 0 , 2 , 12 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355 -2041 */{ 0 , 2 , 1 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355 -2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384 -2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 -2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 -2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 -2046 */{ 0 , 2 , 6 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354 -2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384 -2048 */{ 0 , 2 , 14 , 27936 },/* 29 30 30 29 30 30 29 30 29 29 30 29 0 354 -2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355 -2050 */{ 3 , 1 , 23 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384 -2051 */{ 0 , 2 , 11 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 0 355 -2052 */{ 8 , 2 , 1 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 -2053 */{ 0 , 2 , 19 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 -2054 */{ 0 , 2 , 8 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354 -2055 */{ 6 , 1 , 28 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 -2056 */{ 0 , 2 , 15 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 -2057 */{ 0 , 2 , 4 , 27424 },/* 29 30 30 29 30 29 30 30 29 29 30 29 0 354 -2058 */{ 4 , 1 , 24 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 29 384 -2059 */{ 0 , 2 , 12 , 43744 },/* 30 29 30 29 30 29 30 29 30 30 30 29 0 355 -2060 */{ 0 , 2 , 2 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 -2061 */{ 3 , 1 , 21 , 51568 },/* 30 30 29 29 30 29 29 30 29 30 30 30 29 384 -2062 */{ 0 , 2 , 9 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354 -2063 */{ 7 , 1 , 29 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384 -2064 */{ 0 , 2 , 17 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 -2065 */{ 0 , 2 , 5 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355 -2066 */{ 5 , 1 , 26 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 -2067 */{ 0 , 2 , 14 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 -2068 */{ 0 , 2 , 3 , 42704 },/* 30 29 30 29 29 30 30 29 30 30 29 30 0 355 -2069 */{ 4 , 1 , 23 , 21224 },/* 29 30 29 30 29 29 30 29 30 30 30 29 30 384 -2070 */{ 0 , 2 , 11 , 21200 },/* 29 30 29 30 29 29 30 29 30 30 29 30 0 354 -2071 */{ 8 , 1 , 31 , 43352 },/* 30 29 30 29 30 29 29 30 29 30 29 30 30 384 -2072 */{ 0 , 2 , 19 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 -2073 */{ 0 , 2 , 7 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354 -2074 */{ 6 , 1 , 27 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384 -2075 */{ 0 , 2 , 15 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 -2076 */{ 0 , 2 , 5 , 21920 },/* 29 30 29 30 29 30 29 30 30 29 30 29 0 354 -2077 */{ 4 , 1 , 24 , 42448 },/* 30 29 30 29 29 30 29 30 30 30 29 30 29 384 -2078 */{ 0 , 2 , 12 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 -2079 */{ 0 , 2 , 2 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 -2080 */{ 3 , 1 , 22 , 43320 },/* 30 29 30 29 30 29 29 30 29 29 30 30 30 384 -2081 */{ 0 , 2 , 9 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 0 354 -2082 */{ 7 , 1 , 29 , 29336 },/* 29 30 30 30 29 29 30 29 30 29 29 30 30 384 -2083 */{ 0 , 2 , 17 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 -2084 */{ 0 , 2 , 6 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 -2085 */{ 5 , 1 , 26 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384 -2086 */{ 0 , 2 , 14 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 -2087 */{ 0 , 2 , 3 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 -2088 */{ 4 , 1 , 24 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 29 383 -2089 */{ 0 , 2 , 10 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354 -2090 */{ 8 , 1 , 30 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 -2091 */{ 0 , 2 , 18 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354 -2092 */{ 0 , 2 , 7 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 0 355 -2093 */{ 6 , 1 , 27 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384 -2094 */{ 0 , 2 , 15 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355 -2095 */{ 0 , 2 , 5 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354 -2096 */{ 4 , 1 , 25 , 42216 },/* 30 29 30 29 29 30 29 29 30 30 30 29 30 384 -2097 */{ 0 , 2 , 12 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 -2098 */{ 0 , 2 , 1 , 53584 },/* 30 30 29 30 29 29 29 30 29 30 29 30 0 354 -2099 */{ 2 , 1 , 21 , 55592 },/* 30 30 29 30 30 29 29 30 29 29 30 29 30 384 -2100 */{ 0 , 2 , 9 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354 - */}; - +/*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days +1901 */ { 00, 02, 19, 0b0100101011100000 }, /* 29 30 29 29 30 29 30 29 30 30 30 29 354 +1902 */ { 00, 02, 08, 0b1010010101110000 }, /* 30 29 30 29 29 30 29 30 29 30 30 30 355 +1903 */ { 05, 01, 29, 0b0101001001101000 }, /* 29 30 29 30 29 29 30 29 29 30 30 29 30 383 +1904 */ { 00, 02, 16, 0b1101001001100000 }, /* 30 30 29 30 29 29 30 29 29 30 30 29 354 +1905 */ { 00, 02, 04, 0b1101100101010000 }, /* 30 30 29 30 30 29 29 30 29 30 29 30 355 +1906 */ { 04, 01, 25, 0b0110101010101000 }, /* 29 30 30 29 30 29 30 29 30 29 30 29 30 384 +1907 */ { 00, 02, 13, 0b0101011010100000 }, /* 29 30 29 30 29 30 30 29 30 29 30 29 354 +1908 */ { 00, 02, 02, 0b1001101011010000 }, /* 30 29 29 30 30 29 30 29 30 30 29 30 355 +1909 */ { 02, 01, 22, 0b0100101011101000 }, /* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 +1910 */ { 00, 02, 10, 0b0100101011100000 }, /* 29 30 29 29 30 29 30 29 30 30 30 29 354 +1911 */ { 06, 01, 30, 0b1010010011011000 }, /* 30 29 30 29 29 30 29 29 30 30 29 30 30 384 +1912 */ { 00, 02, 18, 0b1010010011010000 }, /* 30 29 30 29 29 30 29 29 30 30 29 30 354 +1913 */ { 00, 02, 06, 0b1101001001010000 }, /* 30 30 29 30 29 29 30 29 29 30 29 30 354 +1914 */ { 05, 01, 26, 0b1101010100101000 }, /* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 +1915 */ { 00, 02, 14, 0b1011010101000000 }, /* 30 29 30 30 29 30 29 30 29 30 29 29 354 +1916 */ { 00, 02, 03, 0b1101011010100000 }, /* 30 30 29 30 29 30 30 29 30 29 30 29 355 +1917 */ { 02, 01, 23, 0b1001011011010000 }, /* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 +1918 */ { 00, 02, 11, 0b1001010110110000 }, /* 30 29 29 30 29 30 29 30 30 29 30 30 355 +1919 */ { 07, 02, 01, 0b0100100110111000 }, /* 29 30 29 29 30 29 29 30 30 29 30 30 30 384 +1920 */ { 00, 02, 20, 0b0100100101110000 }, /* 29 30 29 29 30 29 29 30 29 30 30 30 354 +1921 */ { 00, 02, 08, 0b1010010010110000 }, /* 30 29 30 29 29 30 29 29 30 29 30 30 354 +1922 */ { 05, 01, 28, 0b1011001001011000 }, /* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 +1923 */ { 00, 02, 16, 0b0110101001010000 }, /* 29 30 30 29 30 29 30 29 29 30 29 30 354 +1924 */ { 00, 02, 05, 0b0110110101000000 }, /* 29 30 30 29 30 30 29 30 29 30 29 29 354 +1925 */ { 04, 01, 24, 0b1010110110101000 }, /* 30 29 30 29 30 30 29 30 30 29 30 29 30 385 +1926 */ { 00, 02, 13, 0b0010101101100000 }, /* 29 29 30 29 30 29 30 30 29 30 30 29 354 +1927 */ { 00, 02, 02, 0b1001010101110000 }, /* 30 29 29 30 29 30 29 30 29 30 30 30 355 +1928 */ { 02, 01, 23, 0b0100100101111000 }, /* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 +1929 */ { 00, 02, 10, 0b0100100101110000 }, /* 29 30 29 29 30 29 29 30 29 30 30 30 354 +1930 */ { 06, 01, 30, 0b0110010010110000 }, /* 29 30 30 29 29 30 29 29 30 29 30 30 29 383 +1931 */ { 00, 02, 17, 0b1101010010100000 }, /* 30 30 29 30 29 30 29 29 30 29 30 29 354 +1932 */ { 00, 02, 06, 0b1110101001010000 }, /* 30 30 30 29 30 29 30 29 29 30 29 30 355 +1933 */ { 05, 01, 26, 0b0110110101001000 }, /* 29 30 30 29 30 30 29 30 29 30 29 29 30 384 +1934 */ { 00, 02, 14, 0b0101101011010000 }, /* 29 30 29 30 30 29 30 29 30 30 29 30 355 +1935 */ { 00, 02, 04, 0b0010101101100000 }, /* 29 29 30 29 30 29 30 30 29 30 30 29 354 +1936 */ { 03, 01, 24, 0b1001001101110000 }, /* 30 29 29 30 29 29 30 30 29 30 30 30 29 384 +1937 */ { 00, 02, 11, 0b1001001011100000 }, /* 30 29 29 30 29 29 30 29 30 30 30 29 354 +1938 */ { 07, 01, 31, 0b1100100101101000 }, /* 30 30 29 29 30 29 29 30 29 30 30 29 30 384 +1939 */ { 00, 02, 19, 0b1100100101010000 }, /* 30 30 29 29 30 29 29 30 29 30 29 30 354 +1940 */ { 00, 02, 08, 0b1101010010100000 }, /* 30 30 29 30 29 30 29 29 30 29 30 29 354 +1941 */ { 06, 01, 27, 0b1101101001010000 }, /* 30 30 29 30 30 29 30 29 29 30 29 30 29 384 +1942 */ { 00, 02, 15, 0b1011010101010000 }, /* 30 29 30 30 29 30 29 30 29 30 29 30 355 +1943 */ { 00, 02, 05, 0b0101011010100000 }, /* 29 30 29 30 29 30 30 29 30 29 30 29 354 +1944 */ { 04, 01, 25, 0b1010101011011000 }, /* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 +1945 */ { 00, 02, 13, 0b0010010111010000 }, /* 29 29 30 29 29 30 29 30 30 30 29 30 354 +1946 */ { 00, 02, 02, 0b1001001011010000 }, /* 30 29 29 30 29 29 30 29 30 30 29 30 354 +1947 */ { 02, 01, 22, 0b1100100101011000 }, /* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 +1948 */ { 00, 02, 10, 0b1010100101010000 }, /* 30 29 30 29 30 29 29 30 29 30 29 30 354 +1949 */ { 07, 01, 29, 0b1011010010101000 }, /* 30 29 30 30 29 30 29 29 30 29 30 29 30 384 +1950 */ { 00, 02, 17, 0b0110110010100000 }, /* 29 30 30 29 30 30 29 29 30 29 30 29 354 +1951 */ { 00, 02, 06, 0b1011010101010000 }, /* 30 29 30 30 29 30 29 30 29 30 29 30 355 +1952 */ { 05, 01, 27, 0b0101010110101000 }, /* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 +1953 */ { 00, 02, 14, 0b0100110110100000 }, /* 29 30 29 29 30 30 29 30 30 29 30 29 354 +1954 */ { 00, 02, 03, 0b1010010110110000 }, /* 30 29 30 29 29 30 29 30 30 29 30 30 355 +1955 */ { 03, 01, 24, 0b0101001010111000 }, /* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 +1956 */ { 00, 02, 12, 0b0101001010110000 }, /* 29 30 29 30 29 29 30 29 30 29 30 30 354 +1957 */ { 08, 01, 31, 0b1010100101010000 }, /* 30 29 30 29 30 29 29 30 29 30 29 30 29 383 +1958 */ { 00, 02, 18, 0b1110100101010000 }, /* 30 30 30 29 30 29 29 30 29 30 29 30 355 +1959 */ { 00, 02, 08, 0b0110101010100000 }, /* 29 30 30 29 30 29 30 29 30 29 30 29 354 +1960 */ { 06, 01, 28, 0b1010110101010000 }, /* 30 29 30 29 30 30 29 30 29 30 29 30 29 384 +1961 */ { 00, 02, 15, 0b1010101101010000 }, /* 30 29 30 29 30 29 30 30 29 30 29 30 355 +1962 */ { 00, 02, 05, 0b0100101101100000 }, /* 29 30 29 29 30 29 30 30 29 30 30 29 354 +1963 */ { 04, 01, 25, 0b1010010101110000 }, /* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 +1964 */ { 00, 02, 13, 0b1010010101110000 }, /* 30 29 30 29 29 30 29 30 29 30 30 30 355 +1965 */ { 00, 02, 02, 0b0101001001100000 }, /* 29 30 29 30 29 29 30 29 29 30 30 29 353 +1966 */ { 03, 01, 21, 0b1110100100110000 }, /* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 +1967 */ { 00, 02, 09, 0b1101100101010000 }, /* 30 30 29 30 30 29 29 30 29 30 29 30 355 +1968 */ { 07, 01, 30, 0b0101101010101000 }, /* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 +1969 */ { 00, 02, 17, 0b0101011010100000 }, /* 29 30 29 30 29 30 30 29 30 29 30 29 354 +1970 */ { 00, 02, 06, 0b1001011011010000 }, /* 30 29 29 30 29 30 30 29 30 30 29 30 355 +1971 */ { 05, 01, 27, 0b0100101011101000 }, /* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 +1972 */ { 00, 02, 15, 0b0100101011010000 }, /* 29 30 29 29 30 29 30 29 30 30 29 30 354 +1973 */ { 00, 02, 03, 0b1010010011010000 }, /* 30 29 30 29 29 30 29 29 30 30 29 30 354 +1974 */ { 04, 01, 23, 0b1101001001101000 }, /* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 +1975 */ { 00, 02, 11, 0b1101001001010000 }, /* 30 30 29 30 29 29 30 29 29 30 29 30 354 +1976 */ { 08, 01, 31, 0b1101010100101000 }, /* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 +1977 */ { 00, 02, 18, 0b1011010101000000 }, /* 30 29 30 30 29 30 29 30 29 30 29 29 354 +1978 */ { 00, 02, 07, 0b1011011010100000 }, /* 30 29 30 30 29 30 30 29 30 29 30 29 355 +1979 */ { 06, 01, 28, 0b1001011011010000 }, /* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 +1980 */ { 00, 02, 16, 0b1001010110110000 }, /* 30 29 29 30 29 30 29 30 30 29 30 30 355 +1981 */ { 00, 02, 05, 0b0100100110110000 }, /* 29 30 29 29 30 29 29 30 30 29 30 30 354 +1982 */ { 04, 01, 25, 0b1010010010111000 }, /* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 +1983 */ { 00, 02, 13, 0b1010010010110000 }, /* 30 29 30 29 29 30 29 29 30 29 30 30 354 +1984 */ { 10, 02, 02, 0b1011001001011000 }, /* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 +1985 */ { 00, 02, 20, 0b0110101001010000 }, /* 29 30 30 29 30 29 30 29 29 30 29 30 354 +1986 */ { 00, 02, 09, 0b0110110101000000 }, /* 29 30 30 29 30 30 29 30 29 30 29 29 354 +1987 */ { 06, 01, 29, 0b1010110110100000 }, /* 30 29 30 29 30 30 29 30 30 29 30 29 29 384 +1988 */ { 00, 02, 17, 0b1010101101100000 }, /* 30 29 30 29 30 29 30 30 29 30 30 29 355 +1989 */ { 00, 02, 06, 0b1001010101110000 }, /* 30 29 29 30 29 30 29 30 29 30 30 30 355 +1990 */ { 05, 01, 27, 0b0100100101111000 }, /* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 +1991 */ { 00, 02, 15, 0b0100100101110000 }, /* 29 30 29 29 30 29 29 30 29 30 30 30 354 +1992 */ { 00, 02, 04, 0b0110010010110000 }, /* 29 30 30 29 29 30 29 29 30 29 30 30 354 +1993 */ { 03, 01, 23, 0b0110101001010000 }, /* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 +1994 */ { 00, 02, 10, 0b1110101001010000 }, /* 30 30 30 29 30 29 30 29 29 30 29 30 355 +1995 */ { 08, 01, 31, 0b0110101100101000 }, /* 29 30 30 29 30 29 30 30 29 29 30 29 30 384 +1996 */ { 00, 02, 19, 0b0101101011000000 }, /* 29 30 29 30 30 29 30 29 30 30 29 29 354 +1997 */ { 00, 02, 07, 0b1010101101100000 }, /* 30 29 30 29 30 29 30 30 29 30 30 29 355 +1998 */ { 05, 01, 28, 0b1001001101101000 }, /* 30 29 29 30 29 29 30 30 29 30 30 29 30 384 +1999 */ { 00, 02, 16, 0b1001001011100000 }, /* 30 29 29 30 29 29 30 29 30 30 30 29 354 +2000 */ { 00, 02, 05, 0b1100100101100000 }, /* 30 30 29 29 30 29 29 30 29 30 30 29 354 +2001 */ { 04, 01, 24, 0b1101010010101000 }, /* 30 30 29 30 29 30 29 29 30 29 30 29 30 384 +2002 */ { 00, 02, 12, 0b1101010010100000 }, /* 30 30 29 30 29 30 29 29 30 29 30 29 354 +2003 */ { 00, 02, 01, 0b1101101001010000 }, /* 30 30 29 30 30 29 30 29 29 30 29 30 355 +2004 */ { 02, 01, 22, 0b0101101010101000 }, /* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 +2005 */ { 00, 02, 09, 0b0101011010100000 }, /* 29 30 29 30 29 30 30 29 30 29 30 29 354 +2006 */ { 07, 01, 29, 0b1010101011011000 }, /* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 +2007 */ { 00, 02, 18, 0b0010010111010000 }, /* 29 29 30 29 29 30 29 30 30 30 29 30 354 +2008 */ { 00, 02, 07, 0b1001001011010000 }, /* 30 29 29 30 29 29 30 29 30 30 29 30 354 +2009 */ { 05, 01, 26, 0b1100100101011000 }, /* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 +2010 */ { 00, 02, 14, 0b1010100101010000 }, /* 30 29 30 29 30 29 29 30 29 30 29 30 354 +2011 */ { 00, 02, 03, 0b1011010010100000 }, /* 30 29 30 30 29 30 29 29 30 29 30 29 354 +2012 */ { 04, 01, 23, 0b1011010101010000 }, /* 30 29 30 30 29 30 29 30 29 30 29 30 29 384 +2013 */ { 00, 02, 10, 0b1010110101010000 }, /* 30 29 30 29 30 30 29 30 29 30 29 30 355 +2014 */ { 09, 01, 31, 0b0101010110101000 }, /* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 +2015 */ { 00, 02, 19, 0b0100101110100000 }, /* 29 30 29 29 30 29 30 30 30 29 30 29 354 +2016 */ { 00, 02, 08, 0b1010010110110000 }, /* 30 29 30 29 29 30 29 30 30 29 30 30 355 +2017 */ { 06, 01, 28, 0b0101001010111000 }, /* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 +2018 */ { 00, 02, 16, 0b0101001010110000 }, /* 29 30 29 30 29 29 30 29 30 29 30 30 354 +2019 */ { 00, 02, 05, 0b1010100100110000 }, /* 30 29 30 29 30 29 29 30 29 29 30 30 354 +2020 */ { 04, 01, 25, 0b0111010010101000 }, /* 29 30 30 30 29 30 29 29 30 29 30 29 30 384 +2021 */ { 00, 02, 12, 0b0110101010100000 }, /* 29 30 30 29 30 29 30 29 30 29 30 29 354 +2022 */ { 00, 02, 01, 0b1010110101010000 }, /* 30 29 30 29 30 30 29 30 29 30 29 30 355 +2023 */ { 02, 01, 22, 0b0100110110101000 }, /* 29 30 29 29 30 30 29 30 30 29 30 29 30 384 +2024 */ { 00, 02, 10, 0b0100101101100000 }, /* 29 30 29 29 30 29 30 30 29 30 30 29 354 +2025 */ { 06, 01, 29, 0b1010010101110000 }, /* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 +2026 */ { 00, 02, 17, 0b1010010011100000 }, /* 30 29 30 29 29 30 29 29 30 30 30 29 354 +2027 */ { 00, 02, 06, 0b1101001001100000 }, /* 30 30 29 30 29 29 30 29 29 30 30 29 354 +2028 */ { 05, 01, 26, 0b1110100100110000 }, /* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 +2029 */ { 00, 02, 13, 0b1101010100110000 }, /* 30 30 29 30 29 30 29 30 29 29 30 30 355 +2030 */ { 00, 02, 03, 0b0101101010100000 }, /* 29 30 29 30 30 29 30 29 30 29 30 29 354 +2031 */ { 03, 01, 23, 0b0110101101010000 }, /* 29 30 30 29 30 29 30 30 29 30 29 30 29 384 +2032 */ { 00, 02, 11, 0b1001011011010000 }, /* 30 29 29 30 29 30 30 29 30 30 29 30 355 +2033 */ { 11, 01, 31, 0b0100101011101000 }, /* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 +2034 */ { 00, 02, 19, 0b0100101011010000 }, /* 29 30 29 29 30 29 30 29 30 30 29 30 354 +2035 */ { 00, 02, 08, 0b1010010011010000 }, /* 30 29 30 29 29 30 29 29 30 30 29 30 354 +2036 */ { 06, 01, 28, 0b1101001001011000 }, /* 30 30 29 30 29 29 30 29 29 30 29 30 30 384 +2037 */ { 00, 02, 15, 0b1101001001010000 }, /* 30 30 29 30 29 29 30 29 29 30 29 30 354 +2038 */ { 00, 02, 04, 0b1101010100100000 }, /* 30 30 29 30 29 30 29 30 29 29 30 29 354 +2039 */ { 05, 01, 24, 0b1101101010100000 }, /* 30 30 29 30 30 29 30 29 30 29 30 29 29 384 +2040 */ { 00, 02, 12, 0b1011010110100000 }, /* 30 29 30 30 29 30 29 30 30 29 30 29 355 +2041 */ { 00, 02, 01, 0b0101011011010000 }, /* 29 30 29 30 29 30 30 29 30 30 29 30 355 +2042 */ { 02, 01, 22, 0b0100101011011000 }, /* 29 30 29 29 30 29 30 29 30 30 29 30 30 384 +2043 */ { 00, 02, 10, 0b0100100110110000 }, /* 29 30 29 29 30 29 29 30 30 29 30 30 354 +2044 */ { 07, 01, 30, 0b1010010010111000 }, /* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 +2045 */ { 00, 02, 17, 0b1010010010110000 }, /* 30 29 30 29 29 30 29 29 30 29 30 30 354 +2046 */ { 00, 02, 06, 0b1010101001010000 }, /* 30 29 30 29 30 29 30 29 29 30 29 30 354 +2047 */ { 05, 01, 26, 0b1011010100101000 }, /* 30 29 30 30 29 30 29 30 29 29 30 29 30 384 +2048 */ { 00, 02, 14, 0b0110110100100000 }, /* 29 30 30 29 30 30 29 30 29 29 30 29 354 +2049 */ { 00, 02, 02, 0b1010110110100000 }, /* 30 29 30 29 30 30 29 30 30 29 30 29 355 +2050 */ { 03, 01, 23, 0b0101010110110000 }, /* 29 30 29 30 29 30 29 30 30 29 30 30 29 384 +2051 */ { 00, 02, 11, 0b1001001101110000 }, /* 30 29 29 30 29 29 30 30 29 30 30 30 355 +2052 */ { 08, 02, 01, 0b0100100101111000 }, /* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 +2053 */ { 00, 02, 19, 0b0100100101110000 }, /* 29 30 29 29 30 29 29 30 29 30 30 30 354 +2054 */ { 00, 02, 08, 0b0110010010110000 }, /* 29 30 30 29 29 30 29 29 30 29 30 30 354 +2055 */ { 06, 01, 28, 0b0110101001010000 }, /* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 +2056 */ { 00, 02, 15, 0b1110101001010000 }, /* 30 30 30 29 30 29 30 29 29 30 29 30 355 +2057 */ { 00, 02, 04, 0b0110101010100000 }, /* 29 30 30 29 30 29 30 29 30 29 30 29 354 +2058 */ { 04, 01, 24, 0b1010101101100000 }, /* 30 29 30 29 30 29 30 30 29 30 30 29 29 384 +2059 */ { 00, 02, 12, 0b1010101011100000 }, /* 30 29 30 29 30 29 30 29 30 30 30 29 355 +2060 */ { 00, 02, 02, 0b1001001011100000 }, /* 30 29 29 30 29 29 30 29 30 30 30 29 354 +2061 */ { 03, 01, 21, 0b1100100101110000 }, /* 30 30 29 29 30 29 29 30 29 30 30 30 29 384 +2062 */ { 00, 02, 09, 0b1100100101100000 }, /* 30 30 29 29 30 29 29 30 29 30 30 29 354 +2063 */ { 07, 01, 29, 0b1101010010101000 }, /* 30 30 29 30 29 30 29 29 30 29 30 29 30 384 +2064 */ { 00, 02, 17, 0b1101010010100000 }, /* 30 30 29 30 29 30 29 29 30 29 30 29 354 +2065 */ { 00, 02, 05, 0b1101101001010000 }, /* 30 30 29 30 30 29 30 29 29 30 29 30 355 +2066 */ { 05, 01, 26, 0b0101101010101000 }, /* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 +2067 */ { 00, 02, 14, 0b0101011010100000 }, /* 29 30 29 30 29 30 30 29 30 29 30 29 354 +2068 */ { 00, 02, 03, 0b1010011011010000 }, /* 30 29 30 29 29 30 30 29 30 30 29 30 355 +2069 */ { 04, 01, 23, 0b0101001011101000 }, /* 29 30 29 30 29 29 30 29 30 30 30 29 30 384 +2070 */ { 00, 02, 11, 0b0101001011010000 }, /* 29 30 29 30 29 29 30 29 30 30 29 30 354 +2071 */ { 08, 01, 31, 0b1010100101011000 }, /* 30 29 30 29 30 29 29 30 29 30 29 30 30 384 +2072 */ { 00, 02, 19, 0b1010100101010000 }, /* 30 29 30 29 30 29 29 30 29 30 29 30 354 +2073 */ { 00, 02, 07, 0b1011010010100000 }, /* 30 29 30 30 29 30 29 29 30 29 30 29 354 +2074 */ { 06, 01, 27, 0b1011010101010000 }, /* 30 29 30 30 29 30 29 30 29 30 29 30 29 384 +2075 */ { 00, 02, 15, 0b1010110101010000 }, /* 30 29 30 29 30 30 29 30 29 30 29 30 355 +2076 */ { 00, 02, 05, 0b0101010110100000 }, /* 29 30 29 30 29 30 29 30 30 29 30 29 354 +2077 */ { 04, 01, 24, 0b1010010111010000 }, /* 30 29 30 29 29 30 29 30 30 30 29 30 29 384 +2078 */ { 00, 02, 12, 0b1010010110110000 }, /* 30 29 30 29 29 30 29 30 30 29 30 30 355 +2079 */ { 00, 02, 02, 0b0101001010110000 }, /* 29 30 29 30 29 29 30 29 30 29 30 30 354 +2080 */ { 03, 01, 22, 0b1010100100111000 }, /* 30 29 30 29 30 29 29 30 29 29 30 30 30 384 +2081 */ { 00, 02, 09, 0b0110100100110000 }, /* 29 30 30 29 30 29 29 30 29 29 30 30 354 +2082 */ { 07, 01, 29, 0b0111001010011000 }, /* 29 30 30 30 29 29 30 29 30 29 29 30 30 384 +2083 */ { 00, 02, 17, 0b0110101010100000 }, /* 29 30 30 29 30 29 30 29 30 29 30 29 354 +2084 */ { 00, 02, 06, 0b1010110101010000 }, /* 30 29 30 29 30 30 29 30 29 30 29 30 355 +2085 */ { 05, 01, 26, 0b0100110110101000 }, /* 29 30 29 29 30 30 29 30 30 29 30 29 30 384 +2086 */ { 00, 02, 14, 0b0100101101100000 }, /* 29 30 29 29 30 29 30 30 29 30 30 29 354 +2087 */ { 00, 02, 03, 0b1010010101110000 }, /* 30 29 30 29 29 30 29 30 29 30 30 30 355 +2088 */ { 04, 01, 24, 0b0101001001110000 }, /* 29 30 29 30 29 29 30 29 29 30 30 30 29 383 +2089 */ { 00, 02, 10, 0b1101000101100000 }, /* 30 30 29 30 29 29 29 30 29 30 30 29 354 +2090 */ { 08, 01, 30, 0b1110100100110000 }, /* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 +2091 */ { 00, 02, 18, 0b1101010100100000 }, /* 30 30 29 30 29 30 29 30 29 29 30 29 354 +2092 */ { 00, 02, 07, 0b1101101010100000 }, /* 30 30 29 30 30 29 30 29 30 29 30 29 355 +2093 */ { 06, 01, 27, 0b0110101101010000 }, /* 29 30 30 29 30 29 30 30 29 30 29 30 29 384 +2094 */ { 00, 02, 15, 0b0101011011010000 }, /* 29 30 29 30 29 30 30 29 30 30 29 30 355 +2095 */ { 00, 02, 05, 0b0100101011100000 }, /* 29 30 29 29 30 29 30 29 30 30 30 29 354 +2096 */ { 04, 01, 25, 0b1010010011101000 }, /* 30 29 30 29 29 30 29 29 30 30 30 29 30 384 +2097 */ { 00, 02, 12, 0b1010001011010000 }, /* 30 29 30 29 29 29 30 29 30 30 29 30 354 +2098 */ { 00, 02, 01, 0b1101000101010000 }, /* 30 30 29 30 29 29 29 30 29 30 29 30 354 +2099 */ { 02, 01, 21, 0b1101100100101000 }, /* 30 30 29 30 30 29 29 30 29 29 30 29 30 384 +2100 */ { 00, 02, 09, 0b1101010100100000 }, /* 30 30 29 30 29 30 29 30 29 29 30 29 354 + */ }; internal override int MinCalendarYear { @@ -315,7 +318,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "year", - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } @@ -339,7 +342,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } @@ -374,7 +377,6 @@ namespace System.Globalization } } - public override int[] Eras { get diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Invariant.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Invariant.cs index 29e4f53212..16201b8d1f 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Invariant.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Invariant.cs @@ -18,7 +18,7 @@ namespace System.Globalization fixed (char* pSource = source) fixed (char* pValue = value) { char* pSrc = &pSource[startIndex]; - int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, start : true); + int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, fromBeginning : true); if (index >= 0) { return index + startIndex; @@ -27,7 +27,7 @@ namespace System.Globalization } } - internal static unsafe int InvariantIndexOf(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase) + internal static unsafe int InvariantIndexOf(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase, bool fromBeginning = true) { Debug.Assert(source.Length != 0); Debug.Assert(value.Length != 0); @@ -35,7 +35,7 @@ namespace System.Globalization fixed (char* pSource = &MemoryMarshal.GetReference(source)) fixed (char* pValue = &MemoryMarshal.GetReference(value)) { - return InvariantFindString(pSource, source.Length, pValue, value.Length, ignoreCase, start: true); + return InvariantFindString(pSource, source.Length, pValue, value.Length, ignoreCase, fromBeginning); } } @@ -48,7 +48,7 @@ namespace System.Globalization fixed (char* pSource = source) fixed (char* pValue = value) { char* pSrc = &pSource[startIndex - count + 1]; - int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, start : false); + int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, fromBeginning : false); if (index >= 0) { return index + startIndex - count + 1; @@ -57,7 +57,7 @@ namespace System.Globalization } } - private static unsafe int InvariantFindString(char* source, int sourceCount, char* value, int valueCount, bool ignoreCase, bool start) + private static unsafe int InvariantFindString(char* source, int sourceCount, char* value, int valueCount, bool ignoreCase, bool fromBeginning) { int ctrSource = 0; // index value into source int ctrValue = 0; // index value into value @@ -72,7 +72,7 @@ namespace System.Globalization if (valueCount == 0) { - return start ? 0 : sourceCount - 1; + return fromBeginning ? 0 : sourceCount - 1; } if (sourceCount < valueCount) @@ -80,7 +80,7 @@ namespace System.Globalization return -1; } - if (start) + if (fromBeginning) { lastSourceStart = sourceCount - valueCount; if (ignoreCase) diff --git a/external/corert/src/System.Private.CoreLib/src/System/Globalization/CompareInfo.Unix.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs similarity index 83% rename from external/corert/src/System.Private.CoreLib/src/System/Globalization/CompareInfo.Unix.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs index 40f0ab0081..f517540099 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Globalization/CompareInfo.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -87,7 +88,7 @@ namespace System.Globalization return -1; } - internal static unsafe int IndexOfOrdinalCore(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase) + internal static unsafe int IndexOfOrdinalCore(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase, bool fromBeginning) { Debug.Assert(!GlobalizationMode.Invariant); @@ -104,13 +105,29 @@ namespace System.Globalization fixed (char* pSource = &MemoryMarshal.GetReference(source)) fixed (char* pValue = &MemoryMarshal.GetReference(value)) { - int index = Interop.Globalization.IndexOfOrdinalIgnoreCase(pValue, value.Length, pSource, source.Length, findLast: false); - return index; + return Interop.Globalization.IndexOfOrdinalIgnoreCase(pValue, value.Length, pSource, source.Length, findLast: !fromBeginning); } } - int endIndex = source.Length - value.Length; - for (int i = 0; i <= endIndex; i++) + int startIndex, endIndex, jump; + if (fromBeginning) + { + // Left to right, from zero to last possible index in the source string. + // Incrementing by one after each iteration. Stop condition is last possible index plus 1. + startIndex = 0; + endIndex = source.Length - value.Length + 1; + jump = 1; + } + else + { + // Right to left, from first possible index in the source string to zero. + // Decrementing by one after each iteration. Stop condition is last possible index minus 1. + startIndex = source.Length - value.Length; + endIndex = -1; + jump = -1; + } + + for (int i = startIndex; i != endIndex; i += jump) { int valueIndex, sourceIndex; @@ -177,11 +194,15 @@ namespace System.Globalization return -1; } - private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2) + private static unsafe int CompareStringOrdinalIgnoreCase(ref char string1, int count1, ref char string2, int count2) { Debug.Assert(!GlobalizationMode.Invariant); - return Interop.Globalization.CompareStringOrdinalIgnoreCase(string1, count1, string2, count2); + fixed (char* char1 = &string1) + fixed (char* char2 = &string2) + { + return Interop.Globalization.CompareStringOrdinalIgnoreCase(char1, count1, char2, count2); + } } // TODO https://github.com/dotnet/coreclr/issues/13827: @@ -224,7 +245,7 @@ namespace System.Globalization if (target.Length == 0) { - if(matchLengthPtr != null) + if (matchLengthPtr != null) *matchLengthPtr = 0; return startIndex; } @@ -232,35 +253,38 @@ namespace System.Globalization if (options == CompareOptions.Ordinal) { index = IndexOfOrdinal(source, target, startIndex, count, ignoreCase: false); - if(index != -1) + if (index != -1) { - if(matchLengthPtr != null) + if (matchLengthPtr != null) *matchLengthPtr = target.Length; } return index; } + #if CORECLR if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && target.IsFastSort()) { index = IndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options)); - if(index != -1) + if (index != -1) { - if(matchLengthPtr != null) + if (matchLengthPtr != null) *matchLengthPtr = target.Length; } return index; } #endif + fixed (char* pSource = source) + fixed (char* pTarget = target) { - index = Interop.Globalization.IndexOf(_sortHandle, target, target.Length, pSource + startIndex, count, options, matchLengthPtr); + index = Interop.Globalization.IndexOf(_sortHandle, pTarget, target.Length, pSource + startIndex, count, options, matchLengthPtr); return index != -1 ? index + startIndex : -1; } } // For now, this method is only called from Span APIs with either options == CompareOptions.None or CompareOptions.IgnoreCase - internal unsafe int IndexOfCore(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr) + internal unsafe int IndexOfCore(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { Debug.Assert(!_invariantMode); Debug.Assert(source.Length != 0); @@ -269,25 +293,29 @@ namespace System.Globalization if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options)) { if ((options & CompareOptions.IgnoreCase) == CompareOptions.IgnoreCase) - { - return IndexOfOrdinalIgnoreCaseHelper(source, target, options, matchLengthPtr); - } + return IndexOfOrdinalIgnoreCaseHelper(source, target, options, matchLengthPtr, fromBeginning); else - { - return IndexOfOrdinalHelper(source, target, options, matchLengthPtr); - } + return IndexOfOrdinalHelper(source, target, options, matchLengthPtr, fromBeginning); } else { fixed (char* pSource = &MemoryMarshal.GetReference(source)) fixed (char* pTarget = &MemoryMarshal.GetReference(target)) { - return Interop.Globalization.IndexOf(_sortHandle, pTarget, target.Length, pSource, source.Length, options, matchLengthPtr); + if (fromBeginning) + return Interop.Globalization.IndexOf(_sortHandle, pTarget, target.Length, pSource, source.Length, options, matchLengthPtr); + else + return Interop.Globalization.LastIndexOf(_sortHandle, pTarget, target.Length, pSource, source.Length, options); } } } - private unsafe int IndexOfOrdinalIgnoreCaseHelper(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr) + /// + /// Duplicate of IndexOfOrdinalHelper that also handles ignore case. Can't converge both methods + /// as the JIT wouldn't be able to optimize the ignoreCase path away. + /// + /// + private unsafe int IndexOfOrdinalIgnoreCaseHelper(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { Debug.Assert(!_invariantMode); @@ -300,9 +328,8 @@ namespace System.Globalization { char* a = ap; char* b = bp; - int endIndex = source.Length - target.Length; - if (endIndex < 0) + if (target.Length > source.Length) goto InteropCall; for (int j = 0; j < target.Length; j++) @@ -312,20 +339,36 @@ namespace System.Globalization goto InteropCall; } - int i = 0; - for (; i <= endIndex; i++) + int startIndex, endIndex, jump; + if (fromBeginning) + { + // Left to right, from zero to last possible index in the source string. + // Incrementing by one after each iteration. Stop condition is last possible index plus 1. + startIndex = 0; + endIndex = source.Length - target.Length + 1; + jump = 1; + } + else + { + // Right to left, from first possible index in the source string to zero. + // Decrementing by one after each iteration. Stop condition is last possible index minus 1. + startIndex = source.Length - target.Length; + endIndex = -1; + jump = -1; + } + + for (int i = startIndex; i != endIndex; i += jump) { int targetIndex = 0; int sourceIndex = i; - for (; targetIndex < target.Length; targetIndex++) + for (; targetIndex < target.Length; targetIndex++, sourceIndex++) { char valueChar = *(a + sourceIndex); char targetChar = *(b + targetIndex); if (valueChar == targetChar && valueChar < 0x80 && !s_highCharTable[valueChar]) { - sourceIndex++; continue; } @@ -339,7 +382,6 @@ namespace System.Globalization goto InteropCall; else if (valueChar != targetChar) break; - sourceIndex++; } if (targetIndex == target.Length) @@ -349,14 +391,17 @@ namespace System.Globalization return i; } } - if (i > endIndex) - return -1; - InteropCall: - return Interop.Globalization.IndexOf(_sortHandle, b, target.Length, a, source.Length, options, matchLengthPtr); + + return -1; + InteropCall: + if (fromBeginning) + return Interop.Globalization.IndexOf(_sortHandle, b, target.Length, a, source.Length, options, matchLengthPtr); + else + return Interop.Globalization.LastIndexOf(_sortHandle, b, target.Length, a, source.Length, options); } } - private unsafe int IndexOfOrdinalHelper(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr) + private unsafe int IndexOfOrdinalHelper(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { Debug.Assert(!_invariantMode); @@ -369,9 +414,8 @@ namespace System.Globalization { char* a = ap; char* b = bp; - int endIndex = source.Length - target.Length; - if (endIndex < 0) + if (target.Length > source.Length) goto InteropCall; for (int j = 0; j < target.Length; j++) @@ -381,21 +425,38 @@ namespace System.Globalization goto InteropCall; } - int i = 0; - for (; i <= endIndex; i++) + int startIndex, endIndex, jump; + if (fromBeginning) + { + // Left to right, from zero to last possible index in the source string. + // Incrementing by one after each iteration. Stop condition is last possible index plus 1. + startIndex = 0; + endIndex = source.Length - target.Length + 1; + jump = 1; + } + else + { + // Right to left, from first possible index in the source string to zero. + // Decrementing by one after each iteration. Stop condition is last possible index minus 1. + startIndex = source.Length - target.Length; + endIndex = -1; + jump = -1; + } + + for (int i = startIndex; i != endIndex; i += jump) { int targetIndex = 0; int sourceIndex = i; - for (; targetIndex < target.Length; targetIndex++) + for (; targetIndex < target.Length; targetIndex++, sourceIndex++) { char valueChar = *(a + sourceIndex); char targetChar = *(b + targetIndex); + if (valueChar >= 0x80 || s_highCharTable[valueChar]) goto InteropCall; else if (valueChar != targetChar) break; - sourceIndex++; } if (targetIndex == target.Length) @@ -405,10 +466,13 @@ namespace System.Globalization return i; } } - if (i > endIndex) - return -1; + + return -1; InteropCall: - return Interop.Globalization.IndexOf(_sortHandle, b, target.Length, a, source.Length, options, matchLengthPtr); + if (fromBeginning) + return Interop.Globalization.IndexOf(_sortHandle, b, target.Length, a, source.Length, options, matchLengthPtr); + else + return Interop.Globalization.LastIndexOf(_sortHandle, b, target.Length, a, source.Length, options); } } @@ -442,8 +506,9 @@ namespace System.Globalization int leftStartIndex = (startIndex - count + 1); fixed (char* pSource = source) + fixed (char* pTarget = target) { - int lastIndex = Interop.Globalization.LastIndexOf(_sortHandle, target, target.Length, pSource + (startIndex - count + 1), count, options); + int lastIndex = Interop.Globalization.LastIndexOf(_sortHandle, pTarget, target.Length, pSource + (startIndex - count + 1), count, options); return lastIndex != -1 ? lastIndex + leftStartIndex : -1; } @@ -599,7 +664,7 @@ namespace System.Globalization return Interop.Globalization.EndsWith(_sortHandle, suffix, suffix.Length, source, source.Length, options); } - + private unsafe bool EndsWith(ReadOnlySpan source, ReadOnlySpan suffix, CompareOptions options) { Debug.Assert(!_invariantMode); @@ -715,7 +780,7 @@ namespace System.Globalization } } - private unsafe SortKey CreateSortKey(String source, CompareOptions options) + private unsafe SortKey CreateSortKey(string source, CompareOptions options) { Debug.Assert(!_invariantMode); @@ -738,14 +803,17 @@ namespace System.Globalization fixed (byte* pSortKey = keyData) { - Interop.Globalization.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options); + if (Interop.Globalization.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options) != sortKeyLength) + { + throw new ArgumentException(SR.Arg_ExternalException); + } } } return new SortKey(Name, source, options, keyData); } - private unsafe static bool IsSortable(char *text, int length) + private static unsafe bool IsSortable(char *text, int length) { Debug.Assert(!GlobalizationMode.Invariant); @@ -754,12 +822,12 @@ namespace System.Globalization while (index < length) { - if (Char.IsHighSurrogate(text[index])) + if (char.IsHighSurrogate(text[index])) { - if (index == length - 1 || !Char.IsLowSurrogate(text[index+1])) + if (index == length - 1 || !char.IsLowSurrogate(text[index+1])) return false; // unpaired surrogate - uc = CharUnicodeInfo.GetUnicodeCategory(Char.ConvertToUtf32(text[index], text[index+1])); + uc = CharUnicodeInfo.GetUnicodeCategory(char.ConvertToUtf32(text[index], text[index+1])); if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned) return false; @@ -767,7 +835,7 @@ namespace System.Globalization continue; } - if (Char.IsLowSurrogate(text[index])) + if (char.IsLowSurrogate(text[index])) { return false; // unpaired surrogate } @@ -802,45 +870,28 @@ namespace System.Globalization int sortKeyLength = Interop.Globalization.GetSortKey(_sortHandle, source, source.Length, null, 0, options); - // As an optimization, for small sort keys we allocate the buffer on the stack. - if (sortKeyLength <= 256) + byte[] borrowedArr = null; + Span span = sortKeyLength <= 512 ? + stackalloc byte[512] : + (borrowedArr = ArrayPool.Shared.Rent(sortKeyLength)); + + fixed (byte* pSortKey = &MemoryMarshal.GetReference(span)) { - byte* pSortKey = stackalloc byte[sortKeyLength]; - Interop.Globalization.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options); - return InternalHashSortKey(pSortKey, sortKeyLength); + if (Interop.Globalization.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options) != sortKeyLength) + { + throw new ArgumentException(SR.Arg_ExternalException); + } } - byte[] sortKey = new byte[sortKeyLength]; + int hash = Marvin.ComputeHash32(span.Slice(0, sortKeyLength), Marvin.DefaultSeed); - fixed (byte* pSortKey = &sortKey[0]) + // Return the borrowed array if necessary. + if (borrowedArr != null) { - Interop.Globalization.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options); - return InternalHashSortKey(pSortKey, sortKeyLength); - } - } - - private static unsafe int InternalHashSortKey(byte* sortKey, int sortKeyLength) - { - // TODO: Random hashing is yet to be done - // Active Issue: https://github.com/dotnet/corert/issues/2588 - - int hash1 = 5381; - int hash2 = hash1; - if (sortKeyLength == 0) - { - return 0; - } - if (sortKeyLength == 1) - { - return (((hash1 << 5) + hash1) ^ sortKey[0]) + (hash2 * 1566083941); + ArrayPool.Shared.Return(borrowedArr); } - for (int i = 0; i < (sortKeyLength & ~1); i += 2) - { - hash1 = ((hash1 << 5) + hash1) ^ sortKey[i]; - hash2 = ((hash2 << 5) + hash2) ^ sortKey[i+1]; - } - return hash1 + (hash2 * 1566083941); + return hash; } private static CompareOptions GetOrdinalCompareOptions(CompareOptions options) diff --git a/external/corert/src/System.Private.CoreLib/src/System/Globalization/CompareInfo.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Windows.cs similarity index 79% rename from external/corert/src/System.Private.CoreLib/src/System/Globalization/CompareInfo.Windows.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Windows.cs index c0befb2633..d1b12c664f 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Globalization/CompareInfo.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Windows.cs @@ -2,7 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Buffers; using System.Diagnostics; +using System.Security; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Globalization @@ -37,6 +40,8 @@ namespace System.Globalization bool bIgnoreCase) { Debug.Assert(!GlobalizationMode.Invariant); + Debug.Assert(stringSource != null); + Debug.Assert(value != null); fixed (char* pSource = stringSource) fixed (char* pValue = value) @@ -51,7 +56,7 @@ namespace System.Globalization return ret < 0 ? ret : ret + offset; } } - + private static unsafe int FindStringOrdinal( uint dwFindStringOrdinalFlags, ReadOnlySpan source, @@ -59,6 +64,8 @@ namespace System.Globalization bool bIgnoreCase) { Debug.Assert(!GlobalizationMode.Invariant); + Debug.Assert(!source.IsEmpty); + Debug.Assert(!value.IsEmpty); fixed (char* pSource = &MemoryMarshal.GetReference(source)) fixed (char* pValue = &MemoryMarshal.GetReference(value)) @@ -84,14 +91,15 @@ namespace System.Globalization return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase); } - internal static int IndexOfOrdinalCore(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase) + internal static int IndexOfOrdinalCore(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase, bool fromBeginning) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(source.Length != 0); Debug.Assert(value.Length != 0); - return FindStringOrdinal(FIND_FROMSTART, source, value, ignoreCase); + uint positionFlag = fromBeginning ? (uint)FIND_FROMSTART : FIND_FROMEND; + return FindStringOrdinal(positionFlag, source, value, ignoreCase); } internal static int LastIndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase) @@ -116,29 +124,59 @@ namespace System.Globalization return 0; } - int tmpHash = 0; + uint flags = LCMAP_SORTKEY | (uint)GetNativeCompareFlags(options); fixed (char* pSource = source) { - if (Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, - LCMAP_HASH | (uint)GetNativeCompareFlags(options), + int sortKeyLength = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, + flags, pSource, source.Length, - &tmpHash, sizeof(int), - null, null, _sortHandle) == 0) + null, 0, + null, null, _sortHandle); + if (sortKeyLength == 0) { - Environment.FailFast("LCMapStringEx failed!"); + throw new ArgumentException(SR.Arg_ExternalException); } - } - return tmpHash; + byte[] borrowedArr = null; + Span span = sortKeyLength <= 512 ? + stackalloc byte[512] : + (borrowedArr = ArrayPool.Shared.Rent(sortKeyLength)); + + fixed (byte* pSortKey = &MemoryMarshal.GetReference(span)) + { + if (Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, + flags, + pSource, source.Length, + pSortKey, sortKeyLength, + null, null, _sortHandle) != sortKeyLength) + { + throw new ArgumentException(SR.Arg_ExternalException); + } + } + + int hash = Marvin.ComputeHash32(span.Slice(0, sortKeyLength), Marvin.DefaultSeed); + + // Return the borrowed array if necessary. + if (borrowedArr != null) + { + ArrayPool.Shared.Return(borrowedArr); + } + + return hash; + } } - private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2) + private static unsafe int CompareStringOrdinalIgnoreCase(ref char string1, int count1, ref char string2, int count2) { Debug.Assert(!GlobalizationMode.Invariant); - // Use the OS to compare and then convert the result to expected value by subtracting 2 - return Interop.Kernel32.CompareStringOrdinal(string1, count1, string2, count2, true) - 2; + fixed (char* char1 = &string1) + fixed (char* char2 = &string2) + { + // Use the OS to compare and then convert the result to expected value by subtracting 2 + return Interop.Kernel32.CompareStringOrdinal(char1, count1, char2, count2, true) - 2; + } } // TODO https://github.com/dotnet/coreclr/issues/13827: @@ -156,6 +194,7 @@ namespace System.Globalization fixed (char* pString1 = &MemoryMarshal.GetReference(string1)) fixed (char* pString2 = &string2.GetRawStringData()) { + Debug.Assert(pString1 != null); int result = Interop.Kernel32.CompareStringEx( pLocaleName, (uint)GetNativeCompareFlags(options), @@ -169,7 +208,7 @@ namespace System.Globalization if (result == 0) { - Environment.FailFast("CompareStringEx failed"); + throw new ArgumentException(SR.Arg_ExternalException); } // Map CompareStringEx return value to -1, 0, 1. @@ -188,6 +227,8 @@ namespace System.Globalization fixed (char* pString1 = &MemoryMarshal.GetReference(string1)) fixed (char* pString2 = &MemoryMarshal.GetReference(string2)) { + Debug.Assert(pString1 != null); + Debug.Assert(pString2 != null); int result = Interop.Kernel32.CompareStringEx( pLocaleName, (uint)GetNativeCompareFlags(options), @@ -201,7 +242,7 @@ namespace System.Globalization if (result == 0) { - Environment.FailFast("CompareStringEx failed"); + throw new ArgumentException(SR.Arg_ExternalException); } // Map CompareStringEx return value to -1, 0, 1. @@ -210,12 +251,14 @@ namespace System.Globalization } private unsafe int FindString( - uint dwFindNLSStringFlags, - ReadOnlySpan lpStringSource, - ReadOnlySpan lpStringValue, - int* pcchFound) + uint dwFindNLSStringFlags, + ReadOnlySpan lpStringSource, + ReadOnlySpan lpStringValue, + int* pcchFound) { Debug.Assert(!_invariantMode); + Debug.Assert(!lpStringSource.IsEmpty); + Debug.Assert(!lpStringValue.IsEmpty); string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; @@ -236,18 +279,20 @@ namespace System.Globalization _sortHandle); } } - + private unsafe int FindString( - uint dwFindNLSStringFlags, - string lpStringSource, - int startSource, - int cchSource, - string lpStringValue, - int startValue, - int cchValue, - int* pcchFound) + uint dwFindNLSStringFlags, + string lpStringSource, + int startSource, + int cchSource, + string lpStringValue, + int startValue, + int cchValue, + int* pcchFound) { Debug.Assert(!_invariantMode); + Debug.Assert(lpStringSource != null); + Debug.Assert(lpStringValue != null); string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; @@ -274,39 +319,38 @@ namespace System.Globalization internal unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options, int* matchLengthPtr) { - Debug.Assert(!string.IsNullOrEmpty(source)); + Debug.Assert(!_invariantMode); + + Debug.Assert(source != null); Debug.Assert(target != null); Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); - int index; - - // TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for - // and add a precondition that target is not empty. if (target.Length == 0) { - if(matchLengthPtr != null) + if (matchLengthPtr != null) *matchLengthPtr = 0; - return startIndex; // keep Whidbey compatibility + return startIndex; + } + + if (source.Length == 0) + { + return -1; } if ((options & CompareOptions.Ordinal) != 0) { - index = FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: false); - if(index != -1 && matchLengthPtr != null) - *matchLengthPtr = target.Length; - - return index; + int retValue = FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: false); + if (retValue >= 0) + { + if (matchLengthPtr != null) + *matchLengthPtr = target.Length; + } + return retValue; } else { - int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options), - source, - startIndex, - count, - target, - 0, - target.Length, - matchLengthPtr); + int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options), source, startIndex, count, + target, 0, target.Length, matchLengthPtr); if (retValue >= 0) { return retValue + startIndex; @@ -316,7 +360,7 @@ namespace System.Globalization return -1; } - internal unsafe int IndexOfCore(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr) + internal unsafe int IndexOfCore(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { Debug.Assert(!_invariantMode); @@ -324,8 +368,8 @@ namespace System.Globalization Debug.Assert(target.Length != 0); Debug.Assert((options == CompareOptions.None || options == CompareOptions.IgnoreCase)); - int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options), source, target, matchLengthPtr); - return retValue; + uint positionFlag = fromBeginning ? (uint)FIND_FROMSTART : FIND_FROMEND; + return FindString(positionFlag | (uint)GetNativeCompareFlags(options), source, target, matchLengthPtr); } private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) @@ -336,10 +380,8 @@ namespace System.Globalization Debug.Assert(target != null); Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); - // TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for - // and add a precondition that target is not empty. if (target.Length == 0) - return startIndex; // keep Whidbey compatibility + return startIndex; if ((options & CompareOptions.Ordinal) != 0) { @@ -347,14 +389,8 @@ namespace System.Globalization } else { - int retValue = FindString(FIND_FROMEND | (uint)GetNativeCompareFlags(options), - source, - startIndex - count + 1, - count, - target, - 0, - target.Length, - null); + int retValue = FindString(FIND_FROMEND | (uint)GetNativeCompareFlags(options), source, startIndex - count + 1, + count, target, 0, target.Length, null); if (retValue >= 0) { @@ -373,14 +409,8 @@ namespace System.Globalization Debug.Assert(!string.IsNullOrEmpty(prefix)); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); - return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), - source, - 0, - source.Length, - prefix, - 0, - prefix.Length, - null) >= 0; + return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length, + prefix, 0, prefix.Length, null) >= 0; } private unsafe bool StartsWith(ReadOnlySpan source, ReadOnlySpan prefix, CompareOptions options) @@ -402,14 +432,8 @@ namespace System.Globalization Debug.Assert(!string.IsNullOrEmpty(suffix)); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); - return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), - source, - 0, - source.Length, - suffix, - 0, - suffix.Length, - null) >= 0; + return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length, + suffix, 0, suffix.Length, null) >= 0; } private unsafe bool EndsWith(ReadOnlySpan source, ReadOnlySpan suffix, CompareOptions options) @@ -428,7 +452,7 @@ namespace System.Globalization private IntPtr _sortHandle; private const uint LCMAP_SORTKEY = 0x00000400; - private const uint LCMAP_HASH = 0x00040000; + private const uint LCMAP_HASH = 0x00040000; private const int FIND_STARTSWITH = 0x00100000; private const int FIND_ENDSWITH = 0x00200000; @@ -510,7 +534,7 @@ namespace System.Globalization return retValue; } - private unsafe SortKey CreateSortKey(String source, CompareOptions options) + private unsafe SortKey CreateSortKey(string source, CompareOptions options) { Debug.Assert(!_invariantMode); @@ -528,27 +552,32 @@ namespace System.Globalization } else { + uint flags = LCMAP_SORTKEY | (uint)GetNativeCompareFlags(options); + fixed (char *pSource = source) { - int result = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, - LCMAP_SORTKEY | (uint) GetNativeCompareFlags(options), + int sortKeyLength = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, + flags, pSource, source.Length, null, 0, null, null, _sortHandle); - if (result == 0) + if (sortKeyLength == 0) { - throw new ArgumentException(SR.Argument_InvalidFlag, "source"); + throw new ArgumentException(SR.Arg_ExternalException); } - keyData = new byte[result]; + keyData = new byte[sortKeyLength]; fixed (byte* pBytes = keyData) { - result = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, - LCMAP_SORTKEY | (uint) GetNativeCompareFlags(options), + if (Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, + flags, pSource, source.Length, pBytes, keyData.Length, - null, null, _sortHandle); + null, null, _sortHandle) != sortKeyLength) + { + throw new ArgumentException(SR.Arg_ExternalException); + } } } } @@ -559,6 +588,7 @@ namespace System.Globalization private static unsafe bool IsSortable(char* text, int length) { Debug.Assert(!GlobalizationMode.Invariant); + Debug.Assert(text != null); return Interop.Kernel32.IsNLSDefinedString(Interop.Kernel32.COMPARE_STRING, 0, IntPtr.Zero, text, length); } @@ -606,6 +636,7 @@ namespace System.Globalization Debug.Assert(!_invariantMode); Interop.Kernel32.NlsVersionInfoEx nlsVersion = new Interop.Kernel32.NlsVersionInfoEx(); + nlsVersion.dwNLSVersionInfoSize = sizeof(Interop.Kernel32.NlsVersionInfoEx); Interop.Kernel32.GetNLSVersionEx(Interop.Kernel32.COMPARE_STRING, _sortName, &nlsVersion); return new SortVersion( nlsVersion.dwNLSVersion, diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs index c369c816b0..92742c7b9f 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs @@ -16,6 +16,8 @@ using System.Reflection; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Serialization; +using System.Buffers; +using Internal.Runtime.CompilerServices; namespace System.Globalization { @@ -105,7 +107,7 @@ namespace System.Globalization { throw new ArgumentNullException(nameof(assembly)); } - if (assembly != typeof(Object).Module.Assembly) + if (assembly != typeof(object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib); } @@ -132,7 +134,7 @@ namespace System.Globalization throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly)); } - if (assembly != typeof(Object).Module.Assembly) + if (assembly != typeof(object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib); } @@ -302,7 +304,7 @@ namespace System.Globalization { if (options == CompareOptions.OrdinalIgnoreCase) { - return String.Compare(string1, string2, StringComparison.OrdinalIgnoreCase); + return string.Compare(string1, string2, StringComparison.OrdinalIgnoreCase); } // Verify the options before we do any real comparison. @@ -313,7 +315,7 @@ namespace System.Globalization throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options)); } - return String.CompareOrdinal(string1, string2); + return string.CompareOrdinal(string1, string2); } if ((options & ValidCompareMaskOffFlags) != 0) @@ -339,9 +341,9 @@ namespace System.Globalization if (_invariantMode) { if ((options & CompareOptions.IgnoreCase) != 0) - return CompareOrdinalIgnoreCase(string1, 0, string1.Length, string2, 0, string2.Length); + return CompareOrdinalIgnoreCase(string1, string2); - return String.CompareOrdinal(string1, string2); + return string.CompareOrdinal(string1, string2); } return CompareString(string1.AsSpan(), string2.AsSpan(), options); @@ -389,38 +391,26 @@ namespace System.Globalization return CompareString(string1, string2, options); } - // TODO https://github.com/dotnet/corefx/issues/21395: Expose this publicly? - internal virtual int Compare(ReadOnlySpan string1, ReadOnlySpan string2, CompareOptions options) + internal int CompareOptionNone(ReadOnlySpan string1, ReadOnlySpan string2) { - if (options == CompareOptions.OrdinalIgnoreCase) - { - return CompareOrdinalIgnoreCase(string1, string2); - } + // Check for empty span or span from a null string + if (string1.Length == 0 || string2.Length == 0) + return string1.Length - string2.Length; - // Verify the options before we do any real comparison. - if ((options & CompareOptions.Ordinal) != 0) - { - if (options != CompareOptions.Ordinal) - { - throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options)); - } + return _invariantMode ? + string.CompareOrdinal(string1, string2) : + CompareString(string1, string2, CompareOptions.None); + } - return string.CompareOrdinal(string1, string2); - } + internal int CompareOptionIgnoreCase(ReadOnlySpan string1, ReadOnlySpan string2) + { + // Check for empty span or span from a null string + if (string1.Length == 0 || string2.Length == 0) + return string1.Length - string2.Length; - if ((options & ValidCompareMaskOffFlags) != 0) - { - throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); - } - - if (_invariantMode) - { - return (options & CompareOptions.IgnoreCase) != 0 ? - CompareOrdinalIgnoreCase(string1, string2) : - string.CompareOrdinal(string1, string2); - } - - return CompareString(string1, string2, options); + return _invariantMode ? + CompareOrdinalIgnoreCase(string1, string2) : + CompareString(string1, string2, CompareOptions.IgnoreCase); } //////////////////////////////////////////////////////////////////////// @@ -459,7 +449,7 @@ namespace System.Globalization { if (options == CompareOptions.OrdinalIgnoreCase) { - int result = String.Compare(string1, offset1, string2, offset2, length1 < length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase); + int result = string.Compare(string1, offset1, string2, offset2, length1 < length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase); if ((length1 != length2) && result == 0) return (length1 > length2 ? 1 : -1); return (result); @@ -511,35 +501,23 @@ namespace System.Globalization return (1); } + ReadOnlySpan span1 = string1.AsSpan(offset1, length1); + ReadOnlySpan span2 = string2.AsSpan(offset2, length2); + if (options == CompareOptions.Ordinal) { - return CompareOrdinal(string1, offset1, length1, - string2, offset2, length2); + return string.CompareOrdinal(span1, span2); } if (_invariantMode) { if ((options & CompareOptions.IgnoreCase) != 0) - return CompareOrdinalIgnoreCase(string1, offset1, length1, string2, offset2, length2); + return CompareOrdinalIgnoreCase(span1, span2); - return CompareOrdinal(string1, offset1, length1, string2, offset2, length2); + return string.CompareOrdinal(span1, span2); } - return CompareString( - string1.AsSpan().Slice(offset1, length1), - string2.AsSpan().Slice(offset2, length2), - options); - } - - private static int CompareOrdinal(string string1, int offset1, int length1, string string2, int offset2, int length2) - { - int result = String.CompareOrdinal(string1, offset1, string2, offset2, - (length1 < length2 ? length1 : length2)); - if ((length1 != length2) && result == 0) - { - return (length1 > length2 ? 1 : -1); - } - return (result); + return CompareString(span1, span2, options); } // @@ -551,57 +529,103 @@ namespace System.Globalization { Debug.Assert(indexA + lengthA <= strA.Length); Debug.Assert(indexB + lengthB <= strB.Length); - return CompareOrdinalIgnoreCase(strA.AsSpan().Slice(indexA, lengthA), strB.AsSpan().Slice(indexB, lengthB)); + return CompareOrdinalIgnoreCase( + ref Unsafe.Add(ref strA.GetRawStringData(), indexA), + lengthA, + ref Unsafe.Add(ref strB.GetRawStringData(), indexB), + lengthB); } - internal static unsafe int CompareOrdinalIgnoreCase(ReadOnlySpan strA, ReadOnlySpan strB) + internal static int CompareOrdinalIgnoreCase(ReadOnlySpan strA, ReadOnlySpan strB) { - int length = Math.Min(strA.Length, strB.Length); + return CompareOrdinalIgnoreCase(ref MemoryMarshal.GetReference(strA), strA.Length, ref MemoryMarshal.GetReference(strB), strB.Length); + } + + internal static int CompareOrdinalIgnoreCase(string strA, string strB) + { + return CompareOrdinalIgnoreCase(ref strA.GetRawStringData(), strA.Length, ref strB.GetRawStringData(), strB.Length); + } + + internal static int CompareOrdinalIgnoreCase(ref char strA, int lengthA, ref char strB, int lengthB) + { + int length = Math.Min(lengthA, lengthB); int range = length; - fixed (char* ap = &MemoryMarshal.GetReference(strA)) - fixed (char* bp = &MemoryMarshal.GetReference(strB)) + ref char charA = ref strA; + ref char charB = ref strB; + + // in InvariantMode we support all range and not only the ascii characters. + char maxChar = (GlobalizationMode.Invariant ? (char)0xFFFF : (char)0x7F); + + while (length != 0 && charA <= maxChar && charB <= maxChar) { - char* a = ap; - char* b = bp; - - // in InvariantMode we support all range and not only the ascii characters. - char maxChar = (char) (GlobalizationMode.Invariant ? 0xFFFF : 0x7F); - - while (length != 0 && (*a <= maxChar) && (*b <= maxChar)) + // Ordinal equals or lowercase equals if the result ends up in the a-z range + if (charA == charB || + ((charA | 0x20) == (charB | 0x20) && + (uint)((charA | 0x20) - 'a') <= (uint)('z' - 'a'))) { - int charA = *a; - int charB = *b; + length--; + charA = ref Unsafe.Add(ref charA, 1); + charB = ref Unsafe.Add(ref charB, 1); + } + else + { + int currentA = charA; + int currentB = charB; - if (charA == charB) - { - a++; b++; - length--; - continue; - } - - // uppercase both chars - notice that we need just one compare per char - if ((uint)(charA - 'a') <= 'z' - 'a') charA -= 0x20; - if ((uint)(charB - 'a') <= 'z' - 'a') charB -= 0x20; + // Uppercase both chars if needed + if ((uint)(charA - 'a') <= 'z' - 'a') + currentA -= 0x20; + if ((uint)(charB - 'a') <= 'z' - 'a') + currentB -= 0x20; // Return the (case-insensitive) difference between them. - if (charA != charB) - return charA - charB; - - // Next char - a++; b++; - length--; + return currentA - currentB; } - - if (length == 0) - return strA.Length - strB.Length; - - Debug.Assert(!GlobalizationMode.Invariant); - - range -= length; - - return CompareStringOrdinalIgnoreCase(a, strA.Length - range, b, strB.Length - range); } + + if (length == 0) + return lengthA - lengthB; + + Debug.Assert(!GlobalizationMode.Invariant); + + range -= length; + + return CompareStringOrdinalIgnoreCase(ref charA, lengthA - range, ref charB, lengthB - range); + } + + + internal static bool EqualsOrdinalIgnoreCase(ref char strA, ref char strB, int length) + { + ref char charA = ref strA; + ref char charB = ref strB; + + // in InvariantMode we support all range and not only the ascii characters. + char maxChar = (GlobalizationMode.Invariant ? (char)0xFFFF : (char)0x7F); + + while (length != 0 && charA <= maxChar && charB <= maxChar) + { + // Ordinal equals or lowercase equals if the result ends up in the a-z range + if (charA == charB || + ((charA | 0x20) == (charB | 0x20) && + (uint)((charA | 0x20) - 'a') <= (uint)('z' - 'a'))) + { + length--; + charA = ref Unsafe.Add(ref charA, 1); + charB = ref Unsafe.Add(ref charB, 1); + } + else + { + return false; + } + } + + if (length == 0) + return true; + + Debug.Assert(!GlobalizationMode.Invariant); + + return CompareStringOrdinalIgnoreCase(ref charA, length, ref charB, length) == 0; } //////////////////////////////////////////////////////////////////////// @@ -609,7 +633,7 @@ namespace System.Globalization // IsPrefix // // Determines whether prefix is a prefix of string. If prefix equals - // String.Empty, true is returned. + // string.Empty, true is returned. // //////////////////////////////////////////////////////////////////////// public virtual bool IsPrefix(string source, string prefix, CompareOptions options) @@ -674,7 +698,7 @@ namespace System.Globalization // IsSuffix // // Determines whether suffix is a suffix of string. If suffix equals - // String.Empty, true is returned. + // string.Empty, true is returned. // //////////////////////////////////////////////////////////////////////// public virtual bool IsSuffix(string source, string suffix, CompareOptions options) @@ -741,7 +765,7 @@ namespace System.Globalization // // Returns the first index where value is found in string. The // search starts from startIndex and ends at endIndex. Returns -1 if - // the specified value is not found. If value equals String.Empty, + // the specified value is not found. If value equals string.Empty, // startIndex is returned. Throws IndexOutOfRange if startIndex or // endIndex is less than zero or greater than the length of string. // Throws ArgumentException if value is null. @@ -910,16 +934,36 @@ namespace System.Globalization return IndexOfCore(source, value, startIndex, count, options, null); } - internal virtual int IndexOfOrdinal(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase) + internal int IndexOfOrdinal(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase) { Debug.Assert(!_invariantMode); - return IndexOfOrdinalCore(source, value, ignoreCase); + Debug.Assert(!source.IsEmpty); + Debug.Assert(!value.IsEmpty); + return IndexOfOrdinalCore(source, value, ignoreCase, fromBeginning: true); } - internal unsafe virtual int IndexOf(ReadOnlySpan source, ReadOnlySpan value, CompareOptions options) + internal int LastIndexOfOrdinal(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase) { Debug.Assert(!_invariantMode); - return IndexOfCore(source, value, options, null); + Debug.Assert(!source.IsEmpty); + Debug.Assert(!value.IsEmpty); + return IndexOfOrdinalCore(source, value, ignoreCase, fromBeginning: false); + } + + internal unsafe int IndexOf(ReadOnlySpan source, ReadOnlySpan value, CompareOptions options) + { + Debug.Assert(!_invariantMode); + Debug.Assert(!source.IsEmpty); + Debug.Assert(!value.IsEmpty); + return IndexOfCore(source, value, options, null, fromBeginning: true); + } + + internal unsafe int LastIndexOf(ReadOnlySpan source, ReadOnlySpan value, CompareOptions options) + { + Debug.Assert(!_invariantMode); + Debug.Assert(!source.IsEmpty); + Debug.Assert(!value.IsEmpty); + return IndexOfCore(source, value, options, null, fromBeginning: false); } // The following IndexOf overload is mainly used by String.Replace. This overload assumes the parameters are already validated @@ -985,7 +1029,7 @@ namespace System.Globalization // // Returns the last index where value is found in string. The // search starts from startIndex and ends at endIndex. Returns -1 if - // the specified value is not found. If value equals String.Empty, + // the specified value is not found. If value equals string.Empty, // endIndex is returned. Throws IndexOutOfRange if startIndex or // endIndex is less than zero or greater than the length of string. // Throws ArgumentException if value is null. @@ -993,7 +1037,7 @@ namespace System.Globalization //////////////////////////////////////////////////////////////////////// - public virtual int LastIndexOf(String source, char value) + public virtual int LastIndexOf(string source, char value) { if (source == null) throw new ArgumentNullException(nameof(source)); @@ -1208,7 +1252,7 @@ namespace System.Globalization //////////////////////////////////////////////////////////////////////// - public override bool Equals(Object value) + public override bool Equals(object value) { CompareInfo that = value as CompareInfo; @@ -1237,6 +1281,34 @@ namespace System.Globalization return (this.Name.GetHashCode()); } + internal static unsafe int GetIgnoreCaseHash(string source) + { + Debug.Assert(source != null, "source must not be null"); + + // Do not allocate on the stack if string is empty + if (source.Length == 0) + { + return source.GetHashCode(); + } + + char[] borrowedArr = null; + Span span = source.Length <= 255 ? + stackalloc char[255] : + (borrowedArr = ArrayPool.Shared.Rent(source.Length)); + + int charsWritten = source.AsSpan().ToUpperInvariant(span); + + // Slice the array to the size returned by ToUpperInvariant. + int hash = Marvin.ComputeHash32(MemoryMarshal.AsBytes(span.Slice(0, charsWritten)), Marvin.DefaultSeed); + + // Return the borrowed array if necessary. + if (borrowedArr != null) + { + ArrayPool.Shared.Return(borrowedArr); + } + + return hash; + } //////////////////////////////////////////////////////////////////////// // @@ -1277,6 +1349,11 @@ namespace System.Globalization throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } + if (_invariantMode) + { + return ((options & CompareOptions.IgnoreCase) != 0) ? GetIgnoreCaseHash(source) : source.GetHashCode(); + } + return GetHashCodeOfStringCore(source, options); } @@ -1294,7 +1371,7 @@ namespace System.Globalization if (options == CompareOptions.OrdinalIgnoreCase) { - return TextInfo.GetHashCodeOrdinalIgnoreCase(source); + return GetIgnoreCaseHash(source); } // diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Unix.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Unix.cs index 3fce527929..4b21f2e7d3 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Unix.cs @@ -149,7 +149,7 @@ namespace System.Globalization // Failed, just use empty string StringBuilderCache.Release(sb); Debug.Fail("[CultureData.GetLocaleInfo(LocaleStringData)] Failed"); - return String.Empty; + return string.Empty; } return StringBuilderCache.GetStringAndRelease(sb); } @@ -216,7 +216,7 @@ namespace System.Globalization // Failed, just use empty string StringBuilderCache.Release(sb); Debug.Fail("[CultureData.GetTimeFormatString(bool shortFormat)] Failed"); - return String.Empty; + return string.Empty; } return ConvertIcuTimeFormatString(StringBuilderCache.GetStringAndRelease(sb)); @@ -227,19 +227,19 @@ namespace System.Globalization return this.GetLocaleInfo(LocaleNumberData.FirstDayOfWeek); } - private String[] GetTimeFormats() + private string[] GetTimeFormats() { string format = GetTimeFormatString(false); return new string[] { format }; } - private String[] GetShortTimeFormats() + private string[] GetShortTimeFormats() { string format = GetTimeFormatString(true); return new string[] { format }; } - private static CultureData GetCultureDataFromRegionName(String regionName) + private static CultureData GetCultureDataFromRegionName(string regionName) { // no support to lookup by region name, other than the hard-coded list in CultureData return null; @@ -371,7 +371,7 @@ namespace System.Globalization return Array.Empty(); } - Char [] chars = new Char[bufferLength]; + char [] chars = new char[bufferLength]; bufferLength = Interop.Globalization.GetLocales(chars, bufferLength); if (bufferLength <= 0) @@ -394,7 +394,7 @@ namespace System.Globalization int length = (int) chars[index++]; if (index + length <= bufferLength) { - CultureInfo ci = CultureInfo.GetCultureInfo(new String(chars, index, length)); + CultureInfo ci = CultureInfo.GetCultureInfo(new string(chars, index, length)); if ((enumNeutrals && ci.IsNeutralCulture) || (enumSpecificss && !ci.IsNeutralCulture)) { list.Add(ci); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Windows.cs index 393f983bba..75f78620d5 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Windows.cs @@ -517,7 +517,7 @@ namespace System.Globalization // Context for EnumCalendarInfoExEx callback. - private class EnumLocaleData + private struct EnumLocaleData { public string regionName; public string cultureName; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureData.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureData.cs.REMOVED.git-id index 664359dc36..a59e4efbfa 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureData.cs.REMOVED.git-id +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureData.cs.REMOVED.git-id @@ -1 +1 @@ -fda239c5180b4ef8faf34dca61ab7461d2a8366c \ No newline at end of file +5eb9f44f8642023dccd159082c16ebaa7aae2f33 \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureNotFoundException.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureNotFoundException.cs index 10e8b1f836..007aff7b9c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureNotFoundException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/CultureNotFoundException.cs @@ -18,28 +18,28 @@ namespace System.Globalization { } - public CultureNotFoundException(String message) + public CultureNotFoundException(string message) : base(message) { } - public CultureNotFoundException(String paramName, String message) + public CultureNotFoundException(string paramName, string message) : base(message, paramName) { } - public CultureNotFoundException(String message, Exception innerException) + public CultureNotFoundException(string message, Exception innerException) : base(message, innerException) { } - public CultureNotFoundException(String paramName, string invalidCultureName, String message) + public CultureNotFoundException(string paramName, string invalidCultureName, string message) : base(message, paramName) { _invalidCultureName = invalidCultureName; } - public CultureNotFoundException(String message, string invalidCultureName, Exception innerException) + public CultureNotFoundException(string message, string invalidCultureName, Exception innerException) : base(message, innerException) { _invalidCultureName = invalidCultureName; @@ -81,7 +81,7 @@ namespace System.Globalization get { return _invalidCultureName; } } - private static String DefaultMessage + private static string DefaultMessage { get { @@ -89,24 +89,24 @@ namespace System.Globalization } } - private String FormatedInvalidCultureId + private string FormatedInvalidCultureId { get { return InvalidCultureId != null ? - String.Format(CultureInfo.InvariantCulture, "{0} (0x{0:x4})", (int)InvalidCultureId) : + string.Format(CultureInfo.InvariantCulture, "{0} (0x{0:x4})", (int)InvalidCultureId) : InvalidCultureName; } } - public override String Message + public override string Message { get { - String s = base.Message; + string s = base.Message; if (_invalidCultureId != null || _invalidCultureName != null) { - String valueMessage = SR.Format(SR.Argument_CultureInvalidIdentifier, FormatedInvalidCultureId); + string valueMessage = SR.Format(SR.Argument_CultureInvalidIdentifier, FormatedInvalidCultureId); if (s == null) { return valueMessage; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormat.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormat.cs index 595fb56313..73fb0e9b3d 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormat.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormat.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Globalization; using System.Text; using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; namespace System { @@ -133,8 +134,8 @@ namespace System 's', 't', 'T', 'u', 'U', 'y', 'Y', }; - internal const String RoundtripFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"; - internal const String RoundtripDateTimeUnfixed = "yyyy'-'MM'-'ddTHH':'mm':'ss zzz"; + internal const string RoundtripFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"; + internal const string RoundtripDateTimeUnfixed = "yyyy'-'MM'-'ddTHH':'mm':'ss zzz"; private const int DEFAULT_ALL_DATETIMES_SIZE = 132; @@ -143,7 +144,7 @@ namespace System internal static readonly string[] InvariantAbbreviatedDayNames = InvariantFormatInfo.AbbreviatedDayNames; internal const string Gmt = "GMT"; - internal static String[] fixedNumberFormats = new String[] { + internal static string[] fixedNumberFormats = new string[] { "0", "00", "000", @@ -164,7 +165,7 @@ namespace System // If the digits of the value is greater than len, no leading zero is added. // // Notes: - // The function can format to Int32.MaxValue. + // The function can format to int.MaxValue. // //////////////////////////////////////////////////////////////////////////// internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) @@ -173,7 +174,7 @@ namespace System FormatDigits(outputBuffer, value, len, false); } - internal unsafe static void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit) + internal static unsafe void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit) { Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); @@ -222,7 +223,7 @@ namespace System return (index - pos); } - private static String FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi) + private static string FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi) { Debug.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6"); if (repeat == 3) @@ -234,7 +235,7 @@ namespace System return (dtfi.GetDayName((DayOfWeek)dayOfWeek)); } - private static String FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi) + private static string FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi) { Debug.Assert(month >= 1 && month <= 12, "month >=1 && month <= 12"); if (repeatCount == 3) @@ -275,7 +276,7 @@ namespace System Therefore, if we are in a regular year, we have to increment the month name if moth is greater or eqaul to 7. */ - private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi) + private static string FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi) { Debug.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4"); if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) @@ -346,7 +347,7 @@ namespace System { // Here we can't find the matching quote. throw new FormatException( - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.Format_BadQuote, quoteChar)); } @@ -668,7 +669,7 @@ namespace System } else { - String fmtPattern = "D" + tokenLen.ToString(); + string fmtPattern = "D" + tokenLen.ToString(); result.Append(year.ToString(fmtPattern, CultureInfo.InvariantCulture)); } } @@ -764,10 +765,10 @@ namespace System // output the 'z' famliy of formats, which output a the offset from UTC, e.g. "-07:30" - private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, ReadOnlySpan format, Int32 tokenLen, Boolean timeOnly, StringBuilder result) + private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, ReadOnlySpan format, int tokenLen, bool timeOnly, StringBuilder result) { // See if the instance already has an offset - Boolean dateTimeFormat = (offset == NullOffset); + bool dateTimeFormat = (offset == NullOffset); if (dateTimeFormat) { // No offset. The instance is a DateTime and the output should be the local time zone @@ -852,14 +853,20 @@ namespace System offset = offset.Negate(); } - AppendNumber(result, offset.Hours, 2); + Append2DigitNumber(result, offset.Hours); result.Append(':'); - AppendNumber(result, offset.Minutes, 2); + Append2DigitNumber(result, offset.Minutes); } - internal static String GetRealFormat(ReadOnlySpan format, DateTimeFormatInfo dtfi) + private static void Append2DigitNumber(StringBuilder result, int val) { - String realFormat = null; + result.Append((char)('0' + (val / 10))); + result.Append((char)('0' + (val % 10))); + } + + internal static string GetRealFormat(ReadOnlySpan format, DateTimeFormatInfo dtfi) + { + string realFormat = null; switch (format[0]) { @@ -924,7 +931,7 @@ namespace System // This method also convert the dateTime if necessary (e.g. when the format is in Universal time), // and change dtfi if necessary (e.g. when the format should use invariant culture). // - private static String ExpandPredefinedFormat(ReadOnlySpan format, ref DateTime dateTime, ref DateTimeFormatInfo dtfi, ref TimeSpan offset) + private static string ExpandPredefinedFormat(ReadOnlySpan format, ref DateTime dateTime, ref DateTimeFormatInfo dtfi, ref TimeSpan offset) { switch (format[0]) { @@ -981,19 +988,65 @@ namespace System return GetRealFormat(format, dtfi); } - internal static String Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi) + internal static string Format(DateTime dateTime, string format, IFormatProvider provider) { - return Format(dateTime, format, dtfi, NullOffset); + return Format(dateTime, format, provider, NullOffset); } - internal static string Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi, TimeSpan offset) => - StringBuilderCache.GetStringAndRelease(FormatStringBuilder(dateTime, format, dtfi, offset)); - - internal static bool TryFormat(DateTime dateTime, Span destination, out int charsWritten, ReadOnlySpan format, DateTimeFormatInfo dtfi) => - TryFormat(dateTime, destination, out charsWritten, format, dtfi, NullOffset); - - internal static bool TryFormat(DateTime dateTime, Span destination, out int charsWritten, ReadOnlySpan format, DateTimeFormatInfo dtfi, TimeSpan offset) + internal static string Format(DateTime dateTime, string format, IFormatProvider provider, TimeSpan offset) { + if (format != null && format.Length == 1) + { + // Optimize for these standard formats that are not affected by culture. + switch (format[0]) + { + // Round trip format + case 'o': + case 'O': + const int MinFormatOLength = 27, MaxFormatOLength = 33; + Span span = stackalloc char[MaxFormatOLength]; + TryFormatO(dateTime, offset, span, out int ochars); + Debug.Assert(ochars >= MinFormatOLength && ochars <= MaxFormatOLength); + return span.Slice(0, ochars).ToString(); + + // RFC1123 + case 'r': + case 'R': + const int FormatRLength = 29; + string str = string.FastAllocateString(FormatRLength); + TryFormatR(dateTime, offset, new Span(ref str.GetRawStringData(), str.Length), out int rchars); + Debug.Assert(rchars == str.Length); + return str; + } + } + + DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(provider); + return StringBuilderCache.GetStringAndRelease(FormatStringBuilder(dateTime, format, dtfi, offset)); + } + + internal static bool TryFormat(DateTime dateTime, Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider provider) => + TryFormat(dateTime, destination, out charsWritten, format, provider, NullOffset); + + internal static bool TryFormat(DateTime dateTime, Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider provider, TimeSpan offset) + { + if (format.Length == 1) + { + // Optimize for these standard formats that are not affected by culture. + switch (format[0]) + { + // Round trip format + case 'o': + case 'O': + return TryFormatO(dateTime, offset, destination, out charsWritten); + + // RFC1123 + case 'r': + case 'R': + return TryFormatR(dateTime, offset, destination, out charsWritten); + } + } + + DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(provider); StringBuilder sb = FormatStringBuilder(dateTime, format, dtfi, offset); bool success = sb.Length <= destination.Length; @@ -1011,12 +1064,12 @@ namespace System return success; } - internal static StringBuilder FormatStringBuilder(DateTime dateTime, ReadOnlySpan format, DateTimeFormatInfo dtfi, TimeSpan offset) + private static StringBuilder FormatStringBuilder(DateTime dateTime, ReadOnlySpan format, DateTimeFormatInfo dtfi, TimeSpan offset) { Debug.Assert(dtfi != null); if (format.Length == 0) { - Boolean timeOnlySpecialCase = false; + bool timeOnlySpecialCase = false; if (dateTime.Ticks < Calendar.TicksPerDay) { // If the time is less than 1 day, consider it as time of day. @@ -1060,108 +1113,211 @@ namespace System if (format.Length == 1) { - switch (format[0]) - { - case 'O': - case 'o': - return FastFormatRoundtrip(dateTime, offset); - case 'R': - case 'r': - return FastFormatRfc1123(dateTime, offset, dtfi); - } - format = ExpandPredefinedFormat(format, ref dateTime, ref dtfi, ref offset); } return FormatCustomized(dateTime, format, dtfi, offset, result: null); } - internal static StringBuilder FastFormatRfc1123(DateTime dateTime, TimeSpan offset, DateTimeFormatInfo dtfi) + // Roundtrippable format. One of + // 012345678901234567890123456789012 + // --------------------------------- + // 2017-06-12T05:30:45.7680000-07:00 + // 2017-06-12T05:30:45.7680000Z (Z is short for "+00:00" but also distinguishes DateTimeKind.Utc from DateTimeKind.Local) + // 2017-06-12T05:30:45.7680000 (interpreted as local time wrt to current time zone) + private static bool TryFormatO(DateTime dateTime, TimeSpan offset, Span destination, out int charsWritten) { - // ddd, dd MMM yyyy HH:mm:ss GMT - const int Rfc1123FormatLength = 29; - StringBuilder result = StringBuilderCache.Acquire(Rfc1123FormatLength); + const int MinimumBytesNeeded = 27; + + int charsRequired = MinimumBytesNeeded; + DateTimeKind kind = DateTimeKind.Local; + + if (offset == NullOffset) + { + kind = dateTime.Kind; + if (kind == DateTimeKind.Local) + { + offset = TimeZoneInfo.Local.GetUtcOffset(dateTime); + charsRequired += 6; + } + else if (kind == DateTimeKind.Utc) + { + charsRequired += 1; + } + } + else + { + charsRequired += 6; + } + + if (destination.Length < charsRequired) + { + charsWritten = 0; + return false; + } + charsWritten = charsRequired; + + // Hoist most of the bounds checks on destination. + { var unused = destination[MinimumBytesNeeded - 1]; } + + WriteFourDecimalDigits((uint)dateTime.Year, destination, 0); + destination[4] = '-'; + WriteTwoDecimalDigits((uint)dateTime.Month, destination, 5); + destination[7] = '-'; + WriteTwoDecimalDigits((uint)dateTime.Day, destination, 8); + destination[10] = 'T'; + WriteTwoDecimalDigits((uint)dateTime.Hour, destination, 11); + destination[13] = ':'; + WriteTwoDecimalDigits((uint)dateTime.Minute, destination, 14); + destination[16] = ':'; + WriteTwoDecimalDigits((uint)dateTime.Second, destination, 17); + destination[19] = '.'; + WriteDigits((uint)((ulong)dateTime.Ticks % (ulong)TimeSpan.TicksPerSecond), destination.Slice(20, 7)); + + if (kind == DateTimeKind.Local) + { + char sign; + if (offset < default(TimeSpan) /* a "const" version of TimeSpan.Zero */) + { + sign = '-'; + offset = TimeSpan.FromTicks(-offset.Ticks); + } + else + { + sign = '+'; + } + + // Writing the value backward allows the JIT to optimize by + // performing a single bounds check against buffer. + WriteTwoDecimalDigits((uint)offset.Minutes, destination, 31); + destination[30] = ':'; + WriteTwoDecimalDigits((uint)offset.Hours, destination, 28); + destination[27] = sign; + } + else if (kind == DateTimeKind.Utc) + { + destination[27] = 'Z'; + } + + return true; + } + + // Rfc1123 + // 01234567890123456789012345678 + // ----------------------------- + // Tue, 03 Jan 2017 08:08:05 GMT + private static bool TryFormatR(DateTime dateTime, TimeSpan offset, Span destination, out int charsWritten) + { + // Writing the check in this fashion elides all bounds checks on 'destination' + // for the remainder of the method. + if (28 >= (uint)destination.Length) + { + charsWritten = 0; + return false; + } if (offset != NullOffset) { - // Convert to UTC invariants + // Convert to UTC invariants. dateTime = dateTime - offset; } dateTime.GetDatePart(out int year, out int month, out int day); - result.Append(InvariantAbbreviatedDayNames[(int)dateTime.DayOfWeek]); - result.Append(','); - result.Append(' '); - AppendNumber(result, day, 2); - result.Append(' '); - result.Append(InvariantAbbreviatedMonthNames[month - 1]); - result.Append(' '); - AppendNumber(result, year, 4); - result.Append(' '); - AppendHHmmssTimeOfDay(result, dateTime); - result.Append(' '); - result.Append(Gmt); - return result; + string dayAbbrev = InvariantAbbreviatedDayNames[(int)dateTime.DayOfWeek]; + Debug.Assert(dayAbbrev.Length == 3); + + string monthAbbrev = InvariantAbbreviatedMonthNames[month - 1]; + Debug.Assert(monthAbbrev.Length == 3); + + destination[0] = dayAbbrev[0]; + destination[1] = dayAbbrev[1]; + destination[2] = dayAbbrev[2]; + destination[3] = ','; + destination[4] = ' '; + WriteTwoDecimalDigits((uint)day, destination, 5); + destination[7] = ' '; + destination[8] = monthAbbrev[0]; + destination[9] = monthAbbrev[1]; + destination[10] = monthAbbrev[2]; + destination[11] = ' '; + WriteFourDecimalDigits((uint)year, destination, 12); + destination[16] = ' '; + WriteTwoDecimalDigits((uint)dateTime.Hour, destination, 17); + destination[19] = ':'; + WriteTwoDecimalDigits((uint)dateTime.Minute, destination, 20); + destination[22] = ':'; + WriteTwoDecimalDigits((uint)dateTime.Second, destination, 23); + destination[25] = ' '; + destination[26] = 'G'; + destination[27] = 'M'; + destination[28] = 'T'; + + charsWritten = 29; + return true; } - internal static StringBuilder FastFormatRoundtrip(DateTime dateTime, TimeSpan offset) + /// + /// Writes a value [ 00 .. 99 ] to the buffer starting at the specified offset. + /// This method performs best when the starting index is a constant literal. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void WriteTwoDecimalDigits(uint value, Span destination, int offset) { - // yyyy-MM-ddTHH:mm:ss.fffffffK - const int roundTripFormatLength = 28; - StringBuilder result = StringBuilderCache.Acquire(roundTripFormatLength); + Debug.Assert(0 <= value && value <= 99); - dateTime.GetDatePart(out int year, out int month, out int day); - AppendNumber(result, year, 4); - result.Append('-'); - AppendNumber(result, month, 2); - result.Append('-'); - AppendNumber(result, day, 2); - result.Append('T'); - AppendHHmmssTimeOfDay(result, dateTime); - result.Append('.'); - - long fraction = dateTime.Ticks % TimeSpan.TicksPerSecond; - AppendNumber(result, fraction, 7); - - FormatCustomizedRoundripTimeZone(dateTime, offset, result); - - return result; + uint temp = '0' + value; + value /= 10; + destination[offset + 1] = (char)(temp - (value * 10)); + destination[offset] = (char)('0' + value); } - private static void AppendHHmmssTimeOfDay(StringBuilder result, DateTime dateTime) + /// + /// Writes a value [ 0000 .. 9999 ] to the buffer starting at the specified offset. + /// This method performs best when the starting index is a constant literal. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void WriteFourDecimalDigits(uint value, Span buffer, int startingIndex = 0) { - // HH:mm:ss - AppendNumber(result, dateTime.Hour, 2); - result.Append(':'); - AppendNumber(result, dateTime.Minute, 2); - result.Append(':'); - AppendNumber(result, dateTime.Second, 2); + Debug.Assert(0 <= value && value <= 9999); + + uint temp = '0' + value; + value /= 10; + buffer[startingIndex + 3] = (char)(temp - (value * 10)); + + temp = '0' + value; + value /= 10; + buffer[startingIndex + 2] = (char)(temp - (value * 10)); + + temp = '0' + value; + value /= 10; + buffer[startingIndex + 1] = (char)(temp - (value * 10)); + + buffer[startingIndex] = (char)('0' + value); } - internal static void AppendNumber(StringBuilder builder, long val, int digits) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void WriteDigits(ulong value, Span buffer) { - for (int i = 0; i < digits; i++) + // We can mutate the 'value' parameter since it's a copy-by-value local. + // It'll be used to represent the value left over after each division by 10. + + for (int i = buffer.Length - 1; i >= 1; i--) { - builder.Append('0'); + ulong temp = '0' + value; + value /= 10; + buffer[i] = (char)(temp - (value * 10)); } - int index = 1; - while (val > 0 && index <= digits) - { - builder[builder.Length - index] = (char)('0' + (val % 10)); - val = val / 10; - index++; - } - - Debug.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val"); + Debug.Assert(value < 10); + buffer[0] = (char)('0' + value); } - internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi) + internal static string[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi) { Debug.Assert(dtfi != null); - String[] allFormats = null; - String[] results = null; + string[] allFormats = null; + string[] results = null; switch (format) { @@ -1178,7 +1334,7 @@ namespace System case 'y': case 'Y': allFormats = dtfi.GetAllDateTimePatterns(format); - results = new String[allFormats.Length]; + results = new string[allFormats.Length]; for (int i = 0; i < allFormats.Length; i++) { results[i] = Format(dateTime, allFormats[i], dtfi); @@ -1187,7 +1343,7 @@ namespace System case 'U': DateTime universalTime = dateTime.ToUniversalTime(); allFormats = dtfi.GetAllDateTimePatterns(format); - results = new String[allFormats.Length]; + results = new string[allFormats.Length]; for (int i = 0; i < allFormats.Length; i++) { results[i] = Format(universalTime, allFormats[i], dtfi); @@ -1203,7 +1359,7 @@ namespace System case 'O': case 's': case 'u': - results = new String[] { Format(dateTime, new String(format, 1), dtfi) }; + results = new string[] { Format(dateTime, new string(format, 1), dtfi) }; break; default: throw new FormatException(SR.Format_InvalidString); @@ -1211,19 +1367,19 @@ namespace System return (results); } - internal static String[] GetAllDateTimes(DateTime dateTime, DateTimeFormatInfo dtfi) + internal static string[] GetAllDateTimes(DateTime dateTime, DateTimeFormatInfo dtfi) { - List results = new List(DEFAULT_ALL_DATETIMES_SIZE); + List results = new List(DEFAULT_ALL_DATETIMES_SIZE); for (int i = 0; i < allStandardFormats.Length; i++) { - String[] strings = GetAllDateTimes(dateTime, allStandardFormats[i], dtfi); + string[] strings = GetAllDateTimes(dateTime, allStandardFormats[i], dtfi); for (int j = 0; j < strings.Length; j++) { results.Add(strings[j]); } } - String[] value = new String[results.Count]; + string[] value = new string[results.Count]; results.CopyTo(0, value, 0, results.Count); return (value); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs.REMOVED.git-id index 4fa6f09a2e..201af6814e 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs.REMOVED.git-id +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs.REMOVED.git-id @@ -1 +1 @@ -faa0deac3d757d164a1195fb50966eb92a8af93b \ No newline at end of file +8fc6f7bebc1afe0d44283be1171613ae973daaef \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfoScanner.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfoScanner.cs index d3c3aac84e..de43c2da3e 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfoScanner.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfoScanner.cs @@ -94,23 +94,23 @@ namespace System.Globalization internal const char IgnorableSymbolChar = '\xe001'; // Known CJK suffix - internal const String CJKYearSuff = "\u5e74"; - internal const String CJKMonthSuff = "\u6708"; - internal const String CJKDaySuff = "\u65e5"; + internal const string CJKYearSuff = "\u5e74"; + internal const string CJKMonthSuff = "\u6708"; + internal const string CJKDaySuff = "\u65e5"; - internal const String KoreanYearSuff = "\ub144"; - internal const String KoreanMonthSuff = "\uc6d4"; - internal const String KoreanDaySuff = "\uc77c"; + internal const string KoreanYearSuff = "\ub144"; + internal const string KoreanMonthSuff = "\uc6d4"; + internal const string KoreanDaySuff = "\uc77c"; - internal const String KoreanHourSuff = "\uc2dc"; - internal const String KoreanMinuteSuff = "\ubd84"; - internal const String KoreanSecondSuff = "\ucd08"; + internal const string KoreanHourSuff = "\uc2dc"; + internal const string KoreanMinuteSuff = "\ubd84"; + internal const string KoreanSecondSuff = "\ucd08"; - internal const String CJKHourSuff = "\u6642"; - internal const String ChineseHourSuff = "\u65f6"; + internal const string CJKHourSuff = "\u6642"; + internal const string ChineseHourSuff = "\u65f6"; - internal const String CJKMinuteSuff = "\u5206"; - internal const String CJKSecondSuff = "\u79d2"; + internal const string CJKMinuteSuff = "\u5206"; + internal const string CJKSecondSuff = "\u79d2"; // The collection fo date words & postfix. internal List m_dateWords = new List(); @@ -127,23 +127,23 @@ namespace System.Globalization // Add known words into the hash table. // Skip these special symbols. - temp.Add("/", String.Empty); - temp.Add("-", String.Empty); - temp.Add(".", String.Empty); + temp.Add("/", string.Empty); + temp.Add("-", string.Empty); + temp.Add(".", string.Empty); // Skip known CJK suffixes. - temp.Add(CJKYearSuff, String.Empty); - temp.Add(CJKMonthSuff, String.Empty); - temp.Add(CJKDaySuff, String.Empty); - temp.Add(KoreanYearSuff, String.Empty); - temp.Add(KoreanMonthSuff, String.Empty); - temp.Add(KoreanDaySuff, String.Empty); - temp.Add(KoreanHourSuff, String.Empty); - temp.Add(KoreanMinuteSuff, String.Empty); - temp.Add(KoreanSecondSuff, String.Empty); - temp.Add(CJKHourSuff, String.Empty); - temp.Add(ChineseHourSuff, String.Empty); - temp.Add(CJKMinuteSuff, String.Empty); - temp.Add(CJKSecondSuff, String.Empty); + temp.Add(CJKYearSuff, string.Empty); + temp.Add(CJKMonthSuff, string.Empty); + temp.Add(CJKDaySuff, string.Empty); + temp.Add(KoreanYearSuff, string.Empty); + temp.Add(KoreanMonthSuff, string.Empty); + temp.Add(KoreanDaySuff, string.Empty); + temp.Add(KoreanHourSuff, string.Empty); + temp.Add(KoreanMinuteSuff, string.Empty); + temp.Add(KoreanSecondSuff, string.Empty); + temp.Add(CJKHourSuff, string.Empty); + temp.Add(ChineseHourSuff, string.Empty); + temp.Add(CJKMinuteSuff, string.Empty); + temp.Add(CJKSecondSuff, string.Empty); s_knownWords = temp; } @@ -163,7 +163,7 @@ namespace System.Globalization // Note that the index can be pattern.Length if we reach the end of the string. // //////////////////////////////////////////////////////////////////////////// - internal static int SkipWhiteSpacesAndNonLetter(String pattern, int currentIndex) + internal static int SkipWhiteSpacesAndNonLetter(string pattern, int currentIndex) { while (currentIndex < pattern.Length) { @@ -189,7 +189,7 @@ namespace System.Globalization break; } } - if (Char.IsLetter(ch) || ch == '\'' || ch == '.') + if (char.IsLetter(ch) || ch == '\'' || ch == '.') { break; } @@ -211,7 +211,7 @@ namespace System.Globalization // word: The date word or postfix to be added. // //////////////////////////////////////////////////////////////////////////// - internal void AddDateWordOrPostfix(String formatPostfix, String str) + internal void AddDateWordOrPostfix(string formatPostfix, string str) { if (str.Length > 0) { @@ -221,7 +221,7 @@ namespace System.Globalization AddIgnorableSymbols("."); return; } - String words; + string words; if (KnownWords.TryGetValue(str, out words) == false) { if (m_dateWords == null) @@ -231,7 +231,7 @@ namespace System.Globalization if (formatPostfix == "MMMM") { // Add the word into the ArrayList as "\xfffe" + real month postfix. - String temp = MonthPostfixChar + str; + string temp = MonthPostfixChar + str; if (!m_dateWords.Contains(temp)) { m_dateWords.Add(temp); @@ -246,7 +246,7 @@ namespace System.Globalization if (str[str.Length - 1] == '.') { // Old version ignore the trialing dot in the date words. Support this as well. - String strWithoutDot = str.Substring(0, str.Length - 1); + string strWithoutDot = str.Substring(0, str.Length - 1); if (!m_dateWords.Contains(strWithoutDot)) { m_dateWords.Add(strWithoutDot); @@ -272,7 +272,7 @@ namespace System.Globalization // // //////////////////////////////////////////////////////////////////////////// - internal int AddDateWords(String pattern, int index, String formatPostfix) + internal int AddDateWords(string pattern, int index, string formatPostfix) { // Skip any whitespaces so we will start from a letter. int newIndex = SkipWhiteSpacesAndNonLetter(pattern, index); @@ -314,7 +314,7 @@ namespace System.Globalization index++; } } - else if (Char.IsWhiteSpace(ch)) + else if (char.IsWhiteSpace(ch)) { // Found a whitespace. We have to add the current date word/postfix. AddDateWordOrPostfix(formatPostfix, dateWord.ToString()); @@ -341,7 +341,7 @@ namespace System.Globalization // A simple helper to find the repeat count for a specified char. // //////////////////////////////////////////////////////////////////////////// - internal static int ScanRepeatChar(String pattern, char ch, int index, out int count) + internal static int ScanRepeatChar(string pattern, char ch, int index, out int count) { count = 1; while (++index < pattern.Length && pattern[index] == ch) @@ -367,7 +367,7 @@ namespace System.Globalization // //////////////////////////////////////////////////////////////////////////// - internal void AddIgnorableSymbols(String text) + internal void AddIgnorableSymbols(string text) { if (m_dateWords == null) { @@ -375,7 +375,7 @@ namespace System.Globalization m_dateWords = new List(); } // Add the ignorable symbol into the ArrayList. - String temp = IgnorableSymbolChar + text; + string temp = IgnorableSymbolChar + text; if (!m_dateWords.Contains(temp)) { m_dateWords.Add(temp); @@ -421,7 +421,7 @@ namespace System.Globalization // Windows style pattern uses '' for single quote, while .NET uses \' // //////////////////////////////////////////////////////////////////////////// - internal void ScanDateWord(String pattern) + internal void ScanDateWord(string pattern) { // Check if we have found all of the year/month/day pattern. _ymdFlags = FoundDatePattern.None; @@ -479,7 +479,7 @@ namespace System.Globalization i++; break; default: - if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag && !Char.IsWhiteSpace(ch)) + if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag && !char.IsWhiteSpace(ch)) { // We are not seeing "." after YMD. Clear the flag. _ymdFlags = FoundDatePattern.None; @@ -497,10 +497,10 @@ namespace System.Globalization // //////////////////////////////////////////////////////////////////////////// - internal String[] GetDateWordsOfDTFI(DateTimeFormatInfo dtfi) + internal string[] GetDateWordsOfDTFI(DateTimeFormatInfo dtfi) { // Enumarate all LongDatePatterns, and get the DateWords and scan for month postfix. - String[] datePatterns = dtfi.GetAllDateTimePatterns('D'); + string[] datePatterns = dtfi.GetAllDateTimePatterns('D'); int i; // Scan the long date patterns @@ -539,10 +539,10 @@ namespace System.Globalization ScanDateWord(datePatterns[i]); } - String[] result = null; + string[] result = null; if (m_dateWords != null && m_dateWords.Count > 0) { - result = new String[m_dateWords.Count]; + result = new string[m_dateWords.Count]; for (i = 0; i < m_dateWords.Count; i++) { result[i] = m_dateWords[i]; @@ -558,7 +558,7 @@ namespace System.Globalization // the format flag. // //////////////////////////////////////////////////////////////////////////// - internal static FORMATFLAGS GetFormatFlagGenitiveMonth(String[] monthNames, String[] genitveMonthNames, String[] abbrevMonthNames, String[] genetiveAbbrevMonthNames) + internal static FORMATFLAGS GetFormatFlagGenitiveMonth(string[] monthNames, string[] genitveMonthNames, string[] abbrevMonthNames, string[] genetiveAbbrevMonthNames) { // If we have different names in regular and genitive month names, use genitive month flag. return ((!EqualStringArrays(monthNames, genitveMonthNames) || !EqualStringArrays(abbrevMonthNames, genetiveAbbrevMonthNames)) @@ -570,7 +570,7 @@ namespace System.Globalization // Scan the month names to see if spaces are used or start with a digit, and return the format flag // //////////////////////////////////////////////////////////////////////////// - internal static FORMATFLAGS GetFormatFlagUseSpaceInMonthNames(String[] monthNames, String[] genitveMonthNames, String[] abbrevMonthNames, String[] genetiveAbbrevMonthNames) + internal static FORMATFLAGS GetFormatFlagUseSpaceInMonthNames(string[] monthNames, string[] genitveMonthNames, string[] abbrevMonthNames, string[] genetiveAbbrevMonthNames) { FORMATFLAGS formatFlags = 0; formatFlags |= (ArrayElementsBeginWithDigit(monthNames) || @@ -592,7 +592,7 @@ namespace System.Globalization // Scan the day names and set the correct format flag. // //////////////////////////////////////////////////////////////////////////// - internal static FORMATFLAGS GetFormatFlagUseSpaceInDayNames(String[] dayNames, String[] abbrevDayNames) + internal static FORMATFLAGS GetFormatFlagUseSpaceInDayNames(string[] dayNames, string[] abbrevDayNames) { return ((ArrayElementsHaveSpace(dayNames) || ArrayElementsHaveSpace(abbrevDayNames)) @@ -659,7 +659,7 @@ namespace System.Globalization // so we don't have to go to native code side. for (int j = 0; j < array[i].Length; j++) { - if (Char.IsWhiteSpace(array[i][j])) + if (char.IsWhiteSpace(array[i][j])) { return true; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs.REMOVED.git-id index 22ef7ed746..5beca263cb 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs.REMOVED.git-id +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs.REMOVED.git-id @@ -1 +1 @@ -5b285eb5df11142cbb449db54de9d03ef59ffd04 \ No newline at end of file +8d703ea98945c3fe1ca7664492b46315997d7ca9 \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DaylightTime.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DaylightTime.cs index e6920b3666..72a572c97d 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DaylightTime.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/DaylightTime.cs @@ -11,10 +11,6 @@ namespace System.Globalization private readonly DateTime _end; private readonly TimeSpan _delta; - private DaylightTime() - { - } - public DaylightTime(DateTime start, DateTime end, TimeSpan delta) { _start = start; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/EastAsianLunisolarCalendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/EastAsianLunisolarCalendar.cs index 358f4df182..a29f8a1ee5 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/EastAsianLunisolarCalendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/EastAsianLunisolarCalendar.cs @@ -162,7 +162,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "time", - String.Format(CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, + string.Format(CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, MinSupportedDateTime, MaxSupportedDateTime)); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/GregorianCalendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/GregorianCalendar.cs index 16023209ea..6b08ee5405 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/GregorianCalendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/GregorianCalendar.cs @@ -20,8 +20,14 @@ namespace System.Globalization public const int ADEra = 1; // - // This is the max Gregorian year can be represented by DateTime class. The limitation - // is derived from DateTime class. + // This is the min Gregorian year can be represented by the DateTime class. + // The limitation is derived from the DateTime class. + // + internal const int MinYear = 1; + + // + // This is the max Gregorian year can be represented by the DateTime class. + // The limitation is derived from the DateTime class. // internal const int MaxYear = 9999; @@ -206,7 +212,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(months), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, @@ -317,7 +323,7 @@ namespace System.Globalization } throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, @@ -364,7 +370,7 @@ namespace System.Globalization } throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, @@ -451,7 +457,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } @@ -473,7 +479,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } @@ -501,7 +507,7 @@ namespace System.Globalization throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } @@ -520,25 +526,11 @@ namespace System.Globalization throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } - internal override Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) + internal override bool TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { if (era == CurrentEra || era == ADEra) { - try - { - result = new DateTime(year, month, day, hour, minute, second, millisecond); - return true; - } - catch (ArgumentOutOfRangeException) - { - result = DateTime.Now; - return false; - } - catch (ArgumentException) - { - result = DateTime.Now; - return false; - } + return DateTime.TryCreate(year, month, day, hour, minute, second, millisecond, out result); } result = DateTime.MinValue; return false; @@ -565,7 +557,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "year", - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, @@ -588,7 +580,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/GregorianCalendarHelper.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/GregorianCalendarHelper.cs index 2842bd3a16..34206b3805 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/GregorianCalendarHelper.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/GregorianCalendarHelper.cs @@ -19,9 +19,9 @@ namespace System.Globalization // be affected by the DateTime.MinValue; internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1) - internal String eraName; // The era name - internal String abbrevEraName; // Abbreviated Era Name - internal String englishEraName; // English era name + internal string eraName; // The era name + internal string abbrevEraName; // Abbreviated Era Name + internal string englishEraName; // English era name internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear) { @@ -33,7 +33,7 @@ namespace System.Globalization } internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear, - String eraName, String abbrevEraName, String englishEraName) + string eraName, string abbrevEraName, string englishEraName) { this.era = era; this.yearOffset = yearOffset; @@ -47,8 +47,8 @@ namespace System.Globalization } // This calendar recognizes two era values: - // 0 CurrentEra (AD) - // 1 BeforeCurrentEra (BC) + // 0 CurrentEra (AD) + // 1 BeforeCurrentEra (BC) internal class GregorianCalendarHelper { // 1 tick = 100ns = 10E-7 second @@ -87,7 +87,7 @@ namespace System.Globalization // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. - // + // internal int MaxYear { get @@ -123,6 +123,83 @@ namespace System.Globalization m_minYear = m_EraInfo[0].minEraYear; ; } + // EraInfo.yearOffset: The offset to Gregorian year when the era starts. Gregorian Year = Era Year + yearOffset + // Era Year = Gregorian Year - yearOffset + // EraInfo.minEraYear: Min year value in this era. Generally, this value is 1, but this may be affected by the DateTime.MinValue; + // EraInfo.maxEraYear: Max year value in this era. (== the year length of the era + 1) + private int GetYearOffset(int year, int era, bool throwOnError) + { + if (year < 0) + { + if (throwOnError) + { + throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); + } + return -1; + } + + if (era == Calendar.CurrentEra) + { + era = m_Cal.CurrentEraValue; + } + + for (int i = 0; i < m_EraInfo.Length; i++) + { + if (era == m_EraInfo[i].era) + { + if (year >= m_EraInfo[i].minEraYear) + { + if (year <= m_EraInfo[i].maxEraYear) + { + return m_EraInfo[i].yearOffset; + } + else if (!AppContextSwitches.EnforceJapaneseEraYearRanges) + { + // If we got the year number exceeding the era max year number, this still possible be valid as the date can be created before + // introducing new eras after the era we are checking. we'll loop on the eras after the era we have and ensure the year + // can exist in one of these eras. otherwise, we'll throw. + // Note, we always return the offset associated with the requested era. + // + // Here is some example: + // if we are getting the era number 4 (Heisei) and getting the year number 32. if the era 4 has year range from 1 to 31 + // then year 32 exceeded the range of era 4 and we'll try to find out if the years difference (32 - 31 = 1) would lay in + // the subsequent eras (e.g era 5 and up) + + int remainingYears = year - m_EraInfo[i].maxEraYear; + + for (int j = i - 1; j >= 0; j--) + { + if (remainingYears <= m_EraInfo[j].maxEraYear) + { + return m_EraInfo[i].yearOffset; + } + remainingYears -= m_EraInfo[j].maxEraYear; + } + } + } + + if (throwOnError) + { + throw new ArgumentOutOfRangeException( + nameof(year), + string.Format( + CultureInfo.CurrentCulture, + SR.ArgumentOutOfRange_Range, + m_EraInfo[i].minEraYear, + m_EraInfo[i].maxEraYear)); + } + + break; // no need to iterate more on eras. + } + } + + if (throwOnError) + { + throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); + } + return -1; + } + /*=================================GetGregorianYear========================== **Action: Get the Gregorian year value for the specified year in an era. **Returns: The Gregorian year value. @@ -135,64 +212,14 @@ namespace System.Globalization internal int GetGregorianYear(int year, int era) { - if (year < 0) - { - throw new ArgumentOutOfRangeException(nameof(year), - SR.ArgumentOutOfRange_NeedNonNegNum); - } - - if (era == Calendar.CurrentEra) - { - era = m_Cal.CurrentEraValue; - } - - for (int i = 0; i < m_EraInfo.Length; i++) - { - if (era == m_EraInfo[i].era) - { - if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) - { - throw new ArgumentOutOfRangeException( - nameof(year), - String.Format( - CultureInfo.CurrentCulture, - SR.ArgumentOutOfRange_Range, - m_EraInfo[i].minEraYear, - m_EraInfo[i].maxEraYear)); - } - return (m_EraInfo[i].yearOffset + year); - } - } - throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); + return GetYearOffset(year, era, throwOnError: true) + year; } internal bool IsValidYear(int year, int era) { - if (year < 0) - { - return false; - } - - if (era == Calendar.CurrentEra) - { - era = m_Cal.CurrentEraValue; - } - - for (int i = 0; i < m_EraInfo.Length; i++) - { - if (era == m_EraInfo[i].era) - { - if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) - { - return false; - } - return true; - } - } - return false; + return GetYearOffset(year, era, throwOnError: false) >= 0; } - // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart(long ticks, int part) @@ -297,7 +324,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(millisecond), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, @@ -315,7 +342,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "time", - String.Format( + string.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, m_Cal.MinSupportedDateTime, @@ -346,7 +373,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(months), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, @@ -544,7 +571,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(day), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, @@ -583,7 +610,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(month), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, @@ -638,7 +665,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, m_minYear, m_maxYear)); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HebrewCalendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HebrewCalendar.cs index 533d3831bf..06807811e2 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HebrewCalendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HebrewCalendar.cs @@ -100,7 +100,7 @@ namespace System.Globalization A 99 means the year is not supported for translation. for convenience the table was defined for 750 year, but only 640 years are supported. (from 1583 to 2239) - the years before 1582 (starting of Georgian calander) + the years before 1582 (starting of Georgian calendar) and after 2239, are filled with 99. Greogrian January 1st falls usually in Tevet (4th month). Tevet has always 29 days. @@ -344,14 +344,14 @@ namespace System.Globalization ** We use a table for the Hebrew calendar calculation, so the year supported is limited. ============================================================================*/ - private static void CheckHebrewYearValue(int y, int era, String varName) + private static void CheckHebrewYearValue(int y, int era, string varName) { CheckEraRange(era); if (y > MaxHebrewYear || y < MinHebrewYear) { throw new ArgumentOutOfRangeException( varName, - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MinHebrewYear, @@ -376,7 +376,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(month), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, @@ -402,7 +402,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(day), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, @@ -425,7 +425,7 @@ namespace System.Globalization throw new ArgumentOutOfRangeException( "time", // Print out the date in Gregorian using InvariantCulture since the DateTime is based on GreograinCalendar. - String.Format( + string.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, calendarMinValue, @@ -708,7 +708,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(months), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_AddValue)); } @@ -1104,7 +1104,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MinHebrewYear, diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HebrewNumber.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HebrewNumber.cs index 1e8fff2bcb..4413cd9fa0 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HebrewNumber.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HebrewNumber.cs @@ -87,7 +87,7 @@ namespace System.Globalization // //////////////////////////////////////////////////////////////////////////// - internal static String ToString(int Number) + internal static string ToString(int Number) { char cTens = '\x0'; char cUnits; // tens and units chars diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.Win32.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.Win32.cs index 365942ccec..7333f87d5e 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.Win32.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.Win32.cs @@ -10,7 +10,7 @@ namespace System.Globalization { private int GetHijriDateAdjustment() { - if (_hijriAdvance == Int32.MinValue) + if (_hijriAdvance == int.MinValue) { // Never been set before. Use the system value from registry. _hijriAdvance = GetAdvanceHijriDate(); @@ -18,8 +18,8 @@ namespace System.Globalization return (_hijriAdvance); } - private const String InternationalRegKey = "Control Panel\\International"; - private const String HijriAdvanceRegKeyEntry = "AddHijriDate"; + private const string InternationalRegKey = "Control Panel\\International"; + private const string HijriAdvanceRegKeyEntry = "AddHijriDate"; /*=================================GetAdvanceHijriDate========================== **Action: Gets the AddHijriDate value from the registry. @@ -45,7 +45,7 @@ namespace System.Globalization try { // Open in read-only mode. - key = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_USER).OpenSubKey(InternationalRegKey, false); + key = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser).OpenSubKey(InternationalRegKey, false); } //If this fails for any reason, we'll just return 0. catch (ObjectDisposedException) { return 0; } @@ -55,13 +55,13 @@ namespace System.Globalization { try { - Object value = key.InternalGetValue(HijriAdvanceRegKeyEntry, null, false, false); + object value = key.InternalGetValue(HijriAdvanceRegKeyEntry, null, false, false); if (value == null) { return (0); } - String str = value.ToString(); - if (String.Compare(str, 0, HijriAdvanceRegKeyEntry, 0, HijriAdvanceRegKeyEntry.Length, StringComparison.OrdinalIgnoreCase) == 0) + string str = value.ToString(); + if (string.Compare(str, 0, HijriAdvanceRegKeyEntry, 0, HijriAdvanceRegKeyEntry.Length, StringComparison.OrdinalIgnoreCase) == 0) { if (str.Length == HijriAdvanceRegKeyEntry.Length) hijriAdvance = -1; @@ -69,7 +69,7 @@ namespace System.Globalization { try { - int advance = Int32.Parse(str.AsSpan().Slice(HijriAdvanceRegKeyEntry.Length), provider:CultureInfo.InvariantCulture); + int advance = int.Parse(str.AsSpan(HijriAdvanceRegKeyEntry.Length), provider:CultureInfo.InvariantCulture); if ((advance >= MinAdvancedHijri) && (advance <= MaxAdvancedHijri)) { hijriAdvance = advance; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.cs index 6755844620..3eaf3d2539 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.cs @@ -55,7 +55,7 @@ namespace System.Globalization internal static readonly int[] HijriMonthDays = { 0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355 }; - private int _hijriAdvance = Int32.MinValue; + private int _hijriAdvance = int.MinValue; // DateTime.MaxValue = Hijri calendar (year:9666, month: 4, day: 3). internal const int MaxCalendarYear = 9666; @@ -176,7 +176,7 @@ namespace System.Globalization { get { - if (_hijriAdvance == Int32.MinValue) + if (_hijriAdvance == int.MinValue) { // Never been set before. Use the system value from registry. _hijriAdvance = GetHijriDateAdjustment(); @@ -191,7 +191,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "HijriAdjustment", - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Bounds_Lower_Upper, MinAdvancedHijri, @@ -209,7 +209,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "time", - String.Format( + string.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, calendarMinValue, @@ -232,7 +232,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, @@ -249,7 +249,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(month), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, @@ -387,7 +387,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(months), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, @@ -541,7 +541,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(day), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Day, daysInMonth, @@ -591,7 +591,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(day), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Day, daysInMonth, @@ -631,7 +631,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(value), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, @@ -659,7 +659,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/ISOWeek.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/ISOWeek.cs new file mode 100644 index 0000000000..3b3ba15ec8 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/ISOWeek.cs @@ -0,0 +1,162 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using static System.Globalization.GregorianCalendar; + +namespace System.Globalization +{ + public static class ISOWeek + { + private const int WeeksInLongYear = 53; + private const int WeeksInShortYear = 52; + + private const int MinWeek = 1; + private const int MaxWeek = WeeksInLongYear; + + public static int GetWeekOfYear(DateTime date) + { + int week = GetWeekNumber(date); + + if (week < MinWeek) + { + // If the week number obtained equals 0, it means that the + // given date belongs to the preceding (week-based) year. + return GetWeeksInYear(date.Year - 1); + } + + if (week > GetWeeksInYear(date.Year)) + { + // If a week number of 53 is obtained, one must check that + // the date is not actually in week 1 of the following year. + return MinWeek; + } + + return week; + } + + public static int GetYear(DateTime date) + { + int week = GetWeekNumber(date); + + if (week < MinWeek) + { + // If the week number obtained equals 0, it means that the + // given date belongs to the preceding (week-based) year. + return date.Year - 1; + } + + if (week > GetWeeksInYear(date.Year)) + { + // If a week number of 53 is obtained, one must check that + // the date is not actually in week 1 of the following year. + return date.Year + 1; + } + + return date.Year; + } + + // The year parameter represents an ISO week-numbering year (also called ISO year informally). + // Each week's year is the Gregorian year in which the Thursday falls. + // The first week of the year, hence, always contains 4 January. + // ISO week year numbering therefore slightly deviates from the Gregorian for some days close to 1 January. + public static DateTime GetYearStart(int year) + { + return ToDateTime(year, MinWeek, DayOfWeek.Monday); + } + + // The year parameter represents an ISO week-numbering year (also called ISO year informally). + // Each week's year is the Gregorian year in which the Thursday falls. + // The first week of the year, hence, always contains 4 January. + // ISO week year numbering therefore slightly deviates from the Gregorian for some days close to 1 January. + public static DateTime GetYearEnd(int year) + { + return ToDateTime(year, GetWeeksInYear(year), DayOfWeek.Sunday); + } + + // From https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year: + // + // The long years, with 53 weeks in them, can be described by any of the following equivalent definitions: + // + // - Any year starting on Thursday and any leap year starting on Wednesday. + // - Any year ending on Thursday and any leap year ending on Friday. + // - Years in which 1 January and 31 December (in common years) or either (in leap years) are Thursdays. + // + // All other week-numbering years are short years and have 52 weeks. + public static int GetWeeksInYear(int year) + { + if (year < MinYear || year > MaxYear) + { + throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_Year); + } + + int P(int y) => (y + (y / 4) - (y / 100) + (y / 400)) % 7; + + if (P(year) == 4 || P(year - 1) == 3) + { + return WeeksInLongYear; + } + + return WeeksInShortYear; + } + + // From https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year,_week_number_and_weekday: + // + // This method requires that one know the weekday of 4 January of the year in question. + // Add 3 to the number of this weekday, giving a correction to be used for dates within this year. + // + // Multiply the week number by 7, then add the weekday. From this sum subtract the correction for the year. + // The result is the ordinal date, which can be converted into a calendar date. + // + // If the ordinal date thus obtained is zero or negative, the date belongs to the previous calendar year. + // If greater than the number of days in the year, to the following year. + public static DateTime ToDateTime(int year, int week, DayOfWeek dayOfWeek) + { + if (year < MinYear || year > MaxYear) + { + throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_Year); + } + + if (week < MinWeek || week > MaxWeek) + { + throw new ArgumentOutOfRangeException(nameof(week), SR.ArgumentOutOfRange_Week_ISO); + } + + // We allow 7 for convenience in cases where a user already has a valid ISO + // day of week value for Sunday. This means that both 0 and 7 will map to Sunday. + // The GetWeekday method will normalize this into the 1-7 range required by ISO. + if ((int)dayOfWeek < 0 || (int)dayOfWeek > 7) + { + throw new ArgumentOutOfRangeException(nameof(dayOfWeek), SR.ArgumentOutOfRange_DayOfWeek); + } + + var jan4 = new DateTime(year, month: 1, day: 4); + + int correction = GetWeekday(jan4.DayOfWeek) + 3; + + int ordinal = (week * 7) + GetWeekday(dayOfWeek) - correction; + + return new DateTime(year, month: 1, day: 1).AddDays(ordinal - 1); + } + + // From https://en.wikipedia.org/wiki/ISO_week_date#Calculating_the_week_number_of_a_given_date: + // + // Using ISO weekday numbers (running from 1 for Monday to 7 for Sunday), + // subtract the weekday from the ordinal date, then add 10. Divide the result by 7. + // Ignore the remainder; the quotient equals the week number. + // + // If the week number thus obtained equals 0, it means that the given date belongs to the preceding (week-based) year. + // If a week number of 53 is obtained, one must check that the date is not actually in week 1 of the following year. + private static int GetWeekNumber(DateTime date) + { + return (date.DayOfYear - GetWeekday(date.DayOfWeek) + 10) / 7; + } + + // Day of week in ISO is represented by an integer from 1 through 7, beginning with Monday and ending with Sunday. + // This matches the underlying values of the DayOfWeek enum, except for Sunday, which needs to be converted. + private static int GetWeekday(DayOfWeek dayOfWeek) + { + return dayOfWeek == DayOfWeek.Sunday ? 7 : (int) dayOfWeek; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.Unix.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.Unix.cs index 5320936a73..20f753e986 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.Unix.cs @@ -8,9 +8,10 @@ namespace System.Globalization { sealed partial class IdnMapping { - private unsafe string GetAsciiCore(char* unicode, int count) + private unsafe string GetAsciiCore(string unicodeString, char* unicode, int count) { Debug.Assert(!GlobalizationMode.Invariant); + Debug.Assert(unicodeString != null && unicodeString.Length >= count); uint flags = Flags; CheckInvalidIdnCharacters(unicode, count, flags, nameof(unicode)); @@ -26,7 +27,7 @@ namespace System.Globalization actualLength = Interop.Globalization.ToAscii(flags, unicode, count, outputStack, estimatedLength); if (actualLength > 0 && actualLength <= estimatedLength) { - return new string(outputStack, 0, actualLength); + return GetStringForOutput(unicodeString, unicode, count, outputStack, actualLength); } } else @@ -46,13 +47,14 @@ namespace System.Globalization { throw new ArgumentException(SR.Argument_IdnIllegalName, nameof(unicode)); } - return new string(pOutputHeap, 0, actualLength); + return GetStringForOutput(unicodeString, unicode, count, pOutputHeap, actualLength); } } - private unsafe string GetUnicodeCore(char* ascii, int count) + private unsafe string GetUnicodeCore(string asciiString, char* ascii, int count) { Debug.Assert(!GlobalizationMode.Invariant); + Debug.Assert(asciiString != null && asciiString.Length >= count); uint flags = Flags; CheckInvalidIdnCharacters(ascii, count, flags, nameof(ascii)); @@ -61,21 +63,22 @@ namespace System.Globalization if (count < StackAllocThreshold) { char* output = stackalloc char[count]; - return GetUnicodeCore(ascii, count, flags, output, count, reattempt: true); + return GetUnicodeCore(asciiString, ascii, count, flags, output, count, reattempt: true); } else { char[] output = new char[count]; fixed (char* pOutput = &output[0]) { - return GetUnicodeCore(ascii, count, flags, pOutput, count, reattempt: true); + return GetUnicodeCore(asciiString, ascii, count, flags, pOutput, count, reattempt: true); } } } - private unsafe string GetUnicodeCore(char* ascii, int count, uint flags, char* output, int outputLength, bool reattempt) + private unsafe string GetUnicodeCore(string asciiString, char* ascii, int count, uint flags, char* output, int outputLength, bool reattempt) { Debug.Assert(!GlobalizationMode.Invariant); + Debug.Assert(asciiString != null && asciiString.Length >= count); int realLen = Interop.Globalization.ToUnicode(flags, ascii, count, output, outputLength); @@ -85,14 +88,14 @@ namespace System.Globalization } else if (realLen <= outputLength) { - return new string(output, 0, realLen); + return GetStringForOutput(asciiString, ascii, count, output, realLen); } else if (reattempt) { char[] newOutput = new char[realLen]; fixed (char* pNewOutput = newOutput) { - return GetUnicodeCore(ascii, count, flags, pNewOutput, realLen, reattempt: false); + return GetUnicodeCore(asciiString, ascii, count, flags, pNewOutput, realLen, reattempt: false); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.Windows.cs index 35da7343e7..9d491dfbb8 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.Windows.cs @@ -9,9 +9,10 @@ namespace System.Globalization { public sealed partial class IdnMapping { - private unsafe string GetAsciiCore(char* unicode, int count) + private unsafe string GetAsciiCore(string unicodeString, char* unicode, int count) { Debug.Assert(!GlobalizationMode.Invariant); + Debug.Assert(unicodeString != null && unicodeString.Length >= count); uint flags = Flags; @@ -27,21 +28,22 @@ namespace System.Globalization if (length < StackAllocThreshold) { char* output = stackalloc char[length]; - return GetAsciiCore(unicode, count, flags, output, length); + return GetAsciiCore(unicodeString, unicode, count, flags, output, length); } else { char[] output = new char[length]; fixed (char* pOutput = &output[0]) { - return GetAsciiCore(unicode, count, flags, pOutput, length); + return GetAsciiCore(unicodeString, unicode, count, flags, pOutput, length); } } } - private unsafe string GetAsciiCore(char* unicode, int count, uint flags, char* output, int outputLength) + private unsafe string GetAsciiCore(string unicodeString, char* unicode, int count, uint flags, char* output, int outputLength) { Debug.Assert(!GlobalizationMode.Invariant); + Debug.Assert(unicodeString != null && unicodeString.Length >= count); int length = Interop.Normaliz.IdnToAscii(flags, unicode, count, output, outputLength); if (length == 0) @@ -49,12 +51,13 @@ namespace System.Globalization ThrowForZeroLength(unicode: true); } Debug.Assert(length == outputLength); - return new string(output, 0, length); + return GetStringForOutput(unicodeString, unicode, count, output, length); } - private unsafe string GetUnicodeCore(char* ascii, int count) + private unsafe string GetUnicodeCore(string asciiString, char* ascii, int count) { Debug.Assert(!GlobalizationMode.Invariant); + Debug.Assert(asciiString != null && asciiString.Length >= count); uint flags = Flags; @@ -70,21 +73,22 @@ namespace System.Globalization if (length < StackAllocThreshold) { char* output = stackalloc char[length]; - return GetUnicodeCore(ascii, count, flags, output, length); + return GetUnicodeCore(asciiString, ascii, count, flags, output, length); } else { char[] output = new char[length]; fixed (char* pOutput = &output[0]) { - return GetUnicodeCore(ascii, count, flags, pOutput, length); + return GetUnicodeCore(asciiString, ascii, count, flags, pOutput, length); } } } - private unsafe string GetUnicodeCore(char* ascii, int count, uint flags, char* output, int outputLength) + private unsafe string GetUnicodeCore(string asciiString, char* ascii, int count, uint flags, char* output, int outputLength) { Debug.Assert(!GlobalizationMode.Invariant); + Debug.Assert(asciiString != null && asciiString.Length >= count); int length = Interop.Normaliz.IdnToUnicode(flags, ascii, count, output, outputLength); if (length == 0) @@ -92,7 +96,7 @@ namespace System.Globalization ThrowForZeroLength(unicode: false); } Debug.Assert(length == outputLength); - return new string(output, 0, length); + return GetStringForOutput(asciiString, ascii, count, output, length); } // ----------------------------- diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs index 176e5feed5..164e46dc8a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs @@ -25,6 +25,7 @@ // RFC 3492 - Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA) using System.Diagnostics; +using System.Runtime.CompilerServices; using System.Text; namespace System.Globalization @@ -93,7 +94,7 @@ namespace System.Globalization { fixed (char* pUnicode = unicode) { - return GetAsciiCore(pUnicode + index, count); + return GetAsciiCore(unicode, pUnicode + index, count); } } } @@ -137,7 +138,7 @@ namespace System.Globalization { fixed (char* pAscii = ascii) { - return GetUnicodeCore(pAscii + index, count); + return GetUnicodeCore(ascii, pAscii + index, count); } } } @@ -156,6 +157,14 @@ namespace System.Globalization return (_allowUnassigned ? 100 : 200) + (_useStd3AsciiRules ? 1000 : 2000); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static unsafe string GetStringForOutput(string originalString, char* input, int inputLength, char* output, int outputLength) + { + return originalString.Length == inputLength && new ReadOnlySpan(input, inputLength).SequenceEqual(new ReadOnlySpan(output, outputLength)) ? + originalString : + new string(output, 0, outputLength); + } + // // Invariant implementation // @@ -272,7 +281,7 @@ namespace System.Globalization // Need to validate entire string length, 1 shorter if last char wasn't a dot if (unicode.Length > c_defaultNameLimit - (IsDot(unicode[unicode.Length - 1]) ? 0 : 1)) - throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, + throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, c_defaultNameLimit - (IsDot(unicode[unicode.Length - 1]) ? 0 : 1)), nameof(unicode)); // If last char wasn't a dot we need to check for trailing - @@ -352,7 +361,7 @@ namespace System.Globalization // Check last char int iTest = iNextDot - 1; - if (Char.IsLowSurrogate(unicode, iTest)) + if (char.IsLowSurrogate(unicode, iTest)) { iTest--; } @@ -371,7 +380,7 @@ namespace System.Globalization for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++) { // Can't be lonely surrogate because it would've thrown in normalization - Debug.Assert(Char.IsLowSurrogate(unicode, basicCount) == false, "[IdnMapping.punycode_encode]Unexpected low surrogate"); + Debug.Assert(char.IsLowSurrogate(unicode, basicCount) == false, "[IdnMapping.punycode_encode]Unexpected low surrogate"); // Double check our bidi rules BidiCategory testBidi = CharUnicodeInfo.GetBidiCategory(unicode, basicCount); @@ -397,7 +406,7 @@ namespace System.Globalization numProcessed++; } // If its a surrogate, skip the next since our bidi category tester doesn't handle it. - else if (Char.IsSurrogatePair(unicode, basicCount)) + else if (char.IsSurrogatePair(unicode, basicCount)) basicCount++; } @@ -443,7 +452,7 @@ namespace System.Globalization j < iNextDot; j += IsSupplementary(test) ? 2 : 1) { - test = Char.ConvertToUtf32(unicode, j); + test = char.ConvertToUtf32(unicode, j); if (test >= n && test < m) m = test; } @@ -456,7 +465,7 @@ namespace System.Globalization for (j = iAfterLastDot; j < iNextDot; j+= IsSupplementary(test) ? 2 : 1) { // Make sure we're aware of surrogates - test = Char.ConvertToUtf32(unicode, j); + test = char.ConvertToUtf32(unicode, j); // Adjust for character position (only the chars in our string already, some // haven't been processed. @@ -512,7 +521,7 @@ namespace System.Globalization // Throw if we're too long if (output.Length > c_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)) - throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, + throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, c_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)), nameof(unicode)); // Return our output string return output.ToString(); @@ -594,7 +603,7 @@ namespace System.Globalization // Throw if we're too long if (ascii.Length > c_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)) - throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, + throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, c_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)), nameof(ascii)); // output stringbuilder @@ -628,11 +637,11 @@ namespace System.Globalization throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii)); // See if this section's ASCII or ACE - if (ascii.Length < c_strAcePrefix.Length + iAfterLastDot || - !ascii.Substring(iAfterLastDot,c_strAcePrefix.Length).Equals(c_strAcePrefix, StringComparison.OrdinalIgnoreCase)) + if (ascii.Length < c_strAcePrefix.Length + iAfterLastDot || + string.Compare(ascii, iAfterLastDot, c_strAcePrefix, 0, c_strAcePrefix.Length, StringComparison.OrdinalIgnoreCase) != 0) { // Its ASCII, copy it - output.Append(ascii.Substring(iAfterLastDot, iNextDot - iAfterLastDot)); + output.Append(ascii, iAfterLastDot, iNextDot - iAfterLastDot); } else { @@ -706,7 +715,7 @@ namespace System.Globalization i += (int)(digit * w); int t = k <= bias ? c_tmin : k >= bias + c_tmax ? c_tmax : k - bias; - if (digit < t) + if (digit < t) break; Debug.Assert(c_punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != c_punycodeBase (36)"); if (w > c_maxint / (c_punycodeBase - t)) @@ -731,7 +740,7 @@ namespace System.Globalization // insert n at position i of the output: Really tricky if we have surrogates int iUseInsertLocation; - String strTemp = Char.ConvertFromUtf32(n); + string strTemp = char.ConvertFromUtf32(n); // If we have supplimentary characters if (numSurrogatePairs > 0) @@ -743,7 +752,7 @@ namespace System.Globalization // If its a surrogate, we have to go one more if (iUseInsertLocation >= output.Length) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); - if (Char.IsSurrogate(output[iUseInsertLocation])) + if (char.IsSurrogate(output[iUseInsertLocation])) iUseInsertLocation++; } } @@ -768,7 +777,7 @@ namespace System.Globalization bool bRightToLeft = false; // Check for RTL. If right-to-left, then 1st & last chars must be RTL - BidiCategory eBidi = CharUnicodeInfo.GetBidiCategory(output.ToString(), iOutputAfterLastDot); + BidiCategory eBidi = CharUnicodeInfo.GetBidiCategory(output, iOutputAfterLastDot); if (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic) { // It has to be right to left. @@ -779,11 +788,11 @@ namespace System.Globalization for (int iTest = iOutputAfterLastDot; iTest < output.Length; iTest++) { // This might happen if we run into a pair - if (Char.IsLowSurrogate(output.ToString(), iTest)) + if (char.IsLowSurrogate(output[iTest])) continue; // Check to see if its LTR - eBidi = CharUnicodeInfo.GetBidiCategory(output.ToString(), iTest); + eBidi = CharUnicodeInfo.GetBidiCategory(output, iTest); if ((bRightToLeft && eBidi == BidiCategory.LeftToRight) || (!bRightToLeft && (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic))) throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(ascii)); @@ -888,6 +897,5 @@ namespace System.Globalization // 0-25 map to a-z or A-Z return (char)(d + 'a'); } - } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/InternalGlobalizationHelper.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/InternalGlobalizationHelper.cs index 60abcecf61..6dc2b19515 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/InternalGlobalizationHelper.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/InternalGlobalizationHelper.cs @@ -25,8 +25,8 @@ namespace System.Globalization internal const long TicksPerMillisecond = 10000; internal const long TicksPerTenthSecond = TicksPerMillisecond * 100; internal const long TicksPerSecond = TicksPerMillisecond * 1000; // 10,000,000 - internal const long MaxSeconds = Int64.MaxValue / TicksPerSecond; - internal const long MinSeconds = Int64.MinValue / TicksPerSecond; + internal const long MaxSeconds = long.MaxValue / TicksPerSecond; + internal const long MinSeconds = long.MinValue / TicksPerSecond; private const int DaysPerYear = 365; private const int DaysPer4Years = DaysPerYear * 4 + 1; // 1461 private const int DaysPer100Years = DaysPer4Years * 25 - 1; // 36524 @@ -37,12 +37,12 @@ namespace System.Globalization private const long TicksPerDay = TicksPerHour * 24; internal const long MaxTicks = DaysTo10000 * TicksPerDay - 1; internal const long MinTicks = 0; - internal const long MaxMilliSeconds = Int64.MaxValue / TicksPerMillisecond; - internal const long MinMilliSeconds = Int64.MinValue / TicksPerMillisecond; + internal const long MaxMilliSeconds = long.MaxValue / TicksPerMillisecond; + internal const long MinMilliSeconds = long.MinValue / TicksPerMillisecond; internal const int StringBuilderDefaultCapacity = 16; - internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14; - internal const Int64 MinOffset = -MaxOffset; + internal const long MaxOffset = TimeSpan.TicksPerHour * 14; + internal const long MinOffset = -MaxOffset; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.Win32.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.Win32.cs index 1d0180b00e..2356afe35a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.Win32.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.Win32.cs @@ -37,13 +37,13 @@ namespace System.Globalization try { // Need to access registry - RegistryKey key = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE).OpenSubKey(c_japaneseErasHive, false); + RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine).OpenSubKey(c_japaneseErasHive, false); // Abort if we didn't find anything if (key == null) return null; // Look up the values in our reg key - String[] valueNames = key.GetValueNames(); + string[] valueNames = key.GetValueNames(); if (valueNames != null && valueNames.Length > 0) { registryEraRanges = new EraInfo[valueNames.Length]; @@ -143,7 +143,7 @@ namespace System.Globalization // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. - private static EraInfo GetEraFromValue(String value, String data) + private static EraInfo GetEraFromValue(string value, string data) { // Need inputs if (value == null || data == null) return null; @@ -160,9 +160,9 @@ namespace System.Globalization int day; ReadOnlySpan valueSpan = value.AsSpan(); - if (!Int32.TryParse(valueSpan.Slice(0, 4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) || - !Int32.TryParse(valueSpan.Slice(5, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) || - !Int32.TryParse(valueSpan.Slice(8, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day)) + if (!int.TryParse(valueSpan.Slice(0, 4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) || + !int.TryParse(valueSpan.Slice(5, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) || + !int.TryParse(valueSpan.Slice(8, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day)) { // Couldn't convert integer, fail return null; @@ -172,7 +172,7 @@ namespace System.Globalization // Get Strings // // Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups) - String[] names = data.Split('_'); + string[] names = data.Split('_'); // Should have exactly 4 parts // 0 - Era Name @@ -199,7 +199,7 @@ namespace System.Globalization // PAL Layer ends here - private static string[] s_japaneseErasEnglishNames = new String[] { "M", "T", "S", "H" }; + private static string[] s_japaneseErasEnglishNames = new string[] { "M", "T", "S", "H" }; private static string GetJapaneseEnglishEraName(int era) { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.WinRT.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.WinRT.cs index 6a9df97200..818cb5b427 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.WinRT.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.WinRT.cs @@ -46,7 +46,7 @@ namespace System.Globalization // PAL Layer ends here - private static string[] JapaneseErasEnglishNames = new String[] { "M", "T", "S", "H" }; + private static string[] JapaneseErasEnglishNames = new string[] { "M", "T", "S", "H" }; private static string GetJapaneseEnglishEraName(int era) { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.cs index 50195d7f1c..fdf2dc670a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.cs @@ -303,7 +303,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, @@ -325,10 +325,10 @@ namespace System.Globalization // Return the various era strings // Note: The arrays are backwards of the eras // - internal static String[] EraNames() + internal static string[] EraNames() { EraInfo[] eras = GetEraInfo(); - String[] eraNames = new String[eras.Length]; + string[] eraNames = new string[eras.Length]; for (int i = 0; i < eras.Length; i++) { @@ -339,10 +339,10 @@ namespace System.Globalization return eraNames; } - internal static String[] AbbrevEraNames() + internal static string[] AbbrevEraNames() { EraInfo[] eras = GetEraInfo(); - String[] erasAbbrev = new String[eras.Length]; + string[] erasAbbrev = new string[eras.Length]; for (int i = 0; i < eras.Length; i++) { @@ -353,10 +353,10 @@ namespace System.Globalization return erasAbbrev; } - internal static String[] EnglishEraNames() + internal static string[] EnglishEraNames() { EraInfo[] eras = GetEraInfo(); - String[] erasEnglish = new String[eras.Length]; + string[] erasEnglish = new string[eras.Length]; for (int i = 0; i < eras.Length; i++) { @@ -392,7 +392,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "year", - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseLunisolarCalendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseLunisolarCalendar.cs index e8a2dcd637..64aa79d875 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseLunisolarCalendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JapaneseLunisolarCalendar.cs @@ -62,101 +62,103 @@ namespace System.Globalization } } + // Data for years 1960-2049 matches output of Calendrical Calculations [1] and published calendar tables [2]. + // [1] Reingold, Edward M, and Nachum Dershowitz. Calendrical Calculations: The Ultimate Edition. Cambridge [etc.: Cambridge University Press, 2018. Print. + // [2] Nishizawa, Yūsō. Rekijitsu Taikan: Meiji Kaireki 1873-Nen-2100-Nen Shinkyūreki, Kanshi Kyūsei Rokuyō Taishō. Tōkyō: Shin Jinbutsu Ōraisha, 1994. Print. private static readonly int[,] s_yinfo = { - /*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days - 1960 */ - { 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384 -1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355 -1962 */{ 0 , 2 , 5 , 19808 },/* 29 30 29 29 30 30 29 30 29 30 30 29 0 354 -1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 -1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 -1965 */{ 0 , 2 , 2 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354 -1966 */{ 3 , 1 , 22 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383 -1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355 -1968 */{ 7 , 1 , 30 , 27304 },/* 29 30 30 29 30 29 30 29 30 29 30 29 30 384 -1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 -1970 */{ 0 , 2 , 6 , 39632 },/* 30 29 29 30 30 29 30 29 30 30 29 30 0 355 -1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 -1972 */{ 0 , 2 , 15 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354 -1973 */{ 0 , 2 , 3 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354 -1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 -1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 -1976 */{ 8 , 1 , 31 , 54600 },/* 30 30 29 30 29 30 29 30 29 30 29 29 30 384 -1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 -1978 */{ 0 , 2 , 7 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355 -1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 -1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 -1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 -1982 */{ 4 , 1 , 25 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384 -1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 -1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 -1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 -1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 -1987 */{ 6 , 1 , 29 , 46504 },/* 30 29 30 30 29 30 29 30 30 29 30 29 30 385 -1988 */{ 0 , 2 , 18 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 -1989 */{ 0 , 2 , 6 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 -1990 */{ 5 , 1 , 27 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384 -1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 -1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354 -1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 -1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 -1995 */{ 8 , 1 , 31 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384 -1996 */{ 0 , 2 , 19 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355 -1997 */{ 0 , 2 , 8 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 -1998 */{ 5 , 1 , 28 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384 -1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 -2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354 -2001 */{ 4 , 1 , 24 , 58536 },/* 30 30 30 29 29 30 29 29 30 29 30 29 30 384 -2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 -2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355 -2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 -2005 */{ 0 , 2 , 9 , 22208 },/* 29 30 29 30 29 30 30 29 30 30 29 29 0 354 -2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 -2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 -2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 -2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 -2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 -2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354 -2012 */{ 3 , 1 , 23 , 47696 },/* 30 29 30 30 30 29 30 29 29 30 29 30 29 384 -2013 */{ 0 , 2 , 10 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 -2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 -2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354 -2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 -2017 */{ 5 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 -2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 -2019 */{ 0 , 2 , 5 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 -2020 */{ 4 , 1 , 25 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384 -2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 -2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 -2023 */{ 2 , 1 , 22 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 -2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 -2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 -2026 */{ 0 , 2 , 17 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 -2027 */{ 0 , 2 , 7 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354 -2028 */{ 5 , 1 , 27 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383 -2029 */{ 0 , 2 , 13 , 55600 },/* 30 30 29 30 30 29 29 30 29 29 30 30 0 355 -2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354 -2031 */{ 3 , 1 , 23 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 29 384 -2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 -2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 -2034 */{ 0 , 2 , 19 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354 -2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 -2036 */{ 6 , 1 , 28 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 -2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 -2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354 -2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384 -2040 */{ 0 , 2 , 12 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355 -2041 */{ 0 , 2 , 1 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 -2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384 -2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 -2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 -2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 -2046 */{ 0 , 2 , 6 , 45648 },/* 30 29 30 30 29 29 30 29 29 30 29 30 0 354 -2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384 -2048 */{ 0 , 2 , 14 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 -2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355 - */ }; +/*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days +1960 */ { 06, 01, 28, 0b1010110101010000 }, /* 30 29 30 29 30 30 29 30 29 30 29 30 29 384 +1961 */ { 00, 02, 15, 0b1010101101010000 }, /* 30 29 30 29 30 29 30 30 29 30 29 30 355 +1962 */ { 00, 02, 05, 0b0100101101100000 }, /* 29 30 29 29 30 29 30 30 29 30 30 29 354 +1963 */ { 04, 01, 25, 0b1010010101110000 }, /* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 +1964 */ { 00, 02, 13, 0b1010010101110000 }, /* 30 29 30 29 29 30 29 30 29 30 30 30 355 +1965 */ { 00, 02, 02, 0b0101001001110000 }, /* 29 30 29 30 29 29 30 29 29 30 30 30 354 +1966 */ { 03, 01, 22, 0b0110100100110000 }, /* 29 30 30 29 30 29 29 30 29 29 30 30 29 383 +1967 */ { 00, 02, 09, 0b1101100101010000 }, /* 30 30 29 30 30 29 29 30 29 30 29 30 355 +1968 */ { 07, 01, 30, 0b0110101010101000 }, /* 29 30 30 29 30 29 30 29 30 29 30 29 30 384 +1969 */ { 00, 02, 17, 0b0101011010100000 }, /* 29 30 29 30 29 30 30 29 30 29 30 29 354 +1970 */ { 00, 02, 06, 0b1001101011010000 }, /* 30 29 29 30 30 29 30 29 30 30 29 30 355 +1971 */ { 05, 01, 27, 0b0100101011101000 }, /* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 +1972 */ { 00, 02, 15, 0b0100101011100000 }, /* 29 30 29 29 30 29 30 29 30 30 30 29 354 +1973 */ { 00, 02, 03, 0b1010010011100000 }, /* 30 29 30 29 29 30 29 29 30 30 30 29 354 +1974 */ { 04, 01, 23, 0b1101001001101000 }, /* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 +1975 */ { 00, 02, 11, 0b1101001001010000 }, /* 30 30 29 30 29 29 30 29 29 30 29 30 354 +1976 */ { 08, 01, 31, 0b1101010101001000 }, /* 30 30 29 30 29 30 29 30 29 30 29 29 30 384 +1977 */ { 00, 02, 18, 0b1011010101000000 }, /* 30 29 30 30 29 30 29 30 29 30 29 29 354 +1978 */ { 00, 02, 07, 0b1101011010100000 }, /* 30 30 29 30 29 30 30 29 30 29 30 29 355 +1979 */ { 06, 01, 28, 0b1001011011010000 }, /* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 +1980 */ { 00, 02, 16, 0b1001010110110000 }, /* 30 29 29 30 29 30 29 30 30 29 30 30 355 +1981 */ { 00, 02, 05, 0b0100100110110000 }, /* 29 30 29 29 30 29 29 30 30 29 30 30 354 +1982 */ { 04, 01, 25, 0b1010010011011000 }, /* 30 29 30 29 29 30 29 29 30 30 29 30 30 384 +1983 */ { 00, 02, 13, 0b1010010010110000 }, /* 30 29 30 29 29 30 29 29 30 29 30 30 354 +1984 */ { 10, 02, 02, 0b1011001001011000 }, /* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 +1985 */ { 00, 02, 20, 0b0110101001010000 }, /* 29 30 30 29 30 29 30 29 29 30 29 30 354 +1986 */ { 00, 02, 09, 0b0110110101000000 }, /* 29 30 30 29 30 30 29 30 29 30 29 29 354 +1987 */ { 06, 01, 29, 0b1011010110101000 }, /* 30 29 30 30 29 30 29 30 30 29 30 29 30 385 +1988 */ { 00, 02, 18, 0b0010101101100000 }, /* 29 29 30 29 30 29 30 30 29 30 30 29 354 +1989 */ { 00, 02, 06, 0b1001010110110000 }, /* 30 29 29 30 29 30 29 30 30 29 30 30 355 +1990 */ { 05, 01, 27, 0b0100100110111000 }, /* 29 30 29 29 30 29 29 30 30 29 30 30 30 384 +1991 */ { 00, 02, 15, 0b0100100101110000 }, /* 29 30 29 29 30 29 29 30 29 30 30 30 354 +1992 */ { 00, 02, 04, 0b0110010010110000 }, /* 29 30 30 29 29 30 29 29 30 29 30 30 354 +1993 */ { 03, 01, 23, 0b0110101001010000 }, /* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 +1994 */ { 00, 02, 10, 0b1110101001010000 }, /* 30 30 30 29 30 29 30 29 29 30 29 30 355 +1995 */ { 08, 01, 31, 0b0110110101001000 }, /* 29 30 30 29 30 30 29 30 29 30 29 29 30 384 +1996 */ { 00, 02, 19, 0b0101101011010000 }, /* 29 30 29 30 30 29 30 29 30 30 29 30 355 +1997 */ { 00, 02, 08, 0b0010101101100000 }, /* 29 29 30 29 30 29 30 30 29 30 30 29 354 +1998 */ { 05, 01, 28, 0b1001001101110000 }, /* 30 29 29 30 29 29 30 30 29 30 30 30 29 384 +1999 */ { 00, 02, 16, 0b1001001011100000 }, /* 30 29 29 30 29 29 30 29 30 30 30 29 354 +2000 */ { 00, 02, 05, 0b1100100101100000 }, /* 30 30 29 29 30 29 29 30 29 30 30 29 354 +2001 */ { 04, 01, 24, 0b1110010010101000 }, /* 30 30 30 29 29 30 29 29 30 29 30 29 30 384 +2002 */ { 00, 02, 12, 0b1101010010100000 }, /* 30 30 29 30 29 30 29 29 30 29 30 29 354 +2003 */ { 00, 02, 01, 0b1101101001010000 }, /* 30 30 29 30 30 29 30 29 29 30 29 30 355 +2004 */ { 02, 01, 22, 0b0101101010101000 }, /* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 +2005 */ { 00, 02, 09, 0b0101011011000000 }, /* 29 30 29 30 29 30 30 29 30 30 29 29 354 +2006 */ { 07, 01, 29, 0b1010101011011000 }, /* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 +2007 */ { 00, 02, 18, 0b0010010111010000 }, /* 29 29 30 29 29 30 29 30 30 30 29 30 354 +2008 */ { 00, 02, 07, 0b1001001011010000 }, /* 30 29 29 30 29 29 30 29 30 30 29 30 354 +2009 */ { 05, 01, 26, 0b1100100101011000 }, /* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 +2010 */ { 00, 02, 14, 0b1010100101010000 }, /* 30 29 30 29 30 29 29 30 29 30 29 30 354 +2011 */ { 00, 02, 03, 0b1011010010100000 }, /* 30 29 30 30 29 30 29 29 30 29 30 29 354 +2012 */ { 03, 01, 23, 0b1011101001010000 }, /* 30 29 30 30 30 29 30 29 29 30 29 30 29 384 +2013 */ { 00, 02, 10, 0b1011010101010000 }, /* 30 29 30 30 29 30 29 30 29 30 29 30 355 +2014 */ { 09, 01, 31, 0b0101010110101000 }, /* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 +2015 */ { 00, 02, 19, 0b0100101110100000 }, /* 29 30 29 29 30 29 30 30 30 29 30 29 354 +2016 */ { 00, 02, 08, 0b1010010110110000 }, /* 30 29 30 29 29 30 29 30 30 29 30 30 355 +2017 */ { 05, 01, 28, 0b0101001010111000 }, /* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 +2018 */ { 00, 02, 16, 0b0101001010110000 }, /* 29 30 29 30 29 29 30 29 30 29 30 30 354 +2019 */ { 00, 02, 05, 0b1010100101010000 }, /* 30 29 30 29 30 29 29 30 29 30 29 30 354 +2020 */ { 04, 01, 25, 0b1011010010101000 }, /* 30 29 30 30 29 30 29 29 30 29 30 29 30 384 +2021 */ { 00, 02, 12, 0b0110101010100000 }, /* 29 30 30 29 30 29 30 29 30 29 30 29 354 +2022 */ { 00, 02, 01, 0b1010110101010000 }, /* 30 29 30 29 30 30 29 30 29 30 29 30 355 +2023 */ { 02, 01, 22, 0b0101010110101000 }, /* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 +2024 */ { 00, 02, 10, 0b0100101101100000 }, /* 29 30 29 29 30 29 30 30 29 30 30 29 354 +2025 */ { 06, 01, 29, 0b1010010101110000 }, /* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 +2026 */ { 00, 02, 17, 0b1010010101110000 }, /* 30 29 30 29 29 30 29 30 29 30 30 30 355 +2027 */ { 00, 02, 07, 0b0101001001110000 }, /* 29 30 29 30 29 29 30 29 29 30 30 30 354 +2028 */ { 05, 01, 27, 0b0110100100110000 }, /* 29 30 30 29 30 29 29 30 29 29 30 30 29 383 +2029 */ { 00, 02, 13, 0b1101100100110000 }, /* 30 30 29 30 30 29 29 30 29 29 30 30 355 +2030 */ { 00, 02, 03, 0b0101101010100000 }, /* 29 30 29 30 30 29 30 29 30 29 30 29 354 +2031 */ { 03, 01, 23, 0b1010101101010000 }, /* 30 29 30 29 30 29 30 30 29 30 29 30 29 384 +2032 */ { 00, 02, 11, 0b1001011011010000 }, /* 30 29 29 30 29 30 30 29 30 30 29 30 355 +2033 */ { 11, 01, 31, 0b0100101011101000 }, /* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 +2034 */ { 00, 02, 19, 0b0100101011100000 }, /* 29 30 29 29 30 29 30 29 30 30 30 29 354 +2035 */ { 00, 02, 08, 0b1010010011010000 }, /* 30 29 30 29 29 30 29 29 30 30 29 30 354 +2036 */ { 06, 01, 28, 0b1101001001101000 }, /* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 +2037 */ { 00, 02, 15, 0b1101001001010000 }, /* 30 30 29 30 29 29 30 29 29 30 29 30 354 +2038 */ { 00, 02, 04, 0b1101010100100000 }, /* 30 30 29 30 29 30 29 30 29 29 30 29 354 +2039 */ { 05, 01, 24, 0b1101101010100000 }, /* 30 30 29 30 30 29 30 29 30 29 30 29 29 384 +2040 */ { 00, 02, 12, 0b1011011010100000 }, /* 30 29 30 30 29 30 30 29 30 29 30 29 355 +2041 */ { 00, 02, 01, 0b1001011011010000 }, /* 30 29 29 30 29 30 30 29 30 30 29 30 355 +2042 */ { 02, 01, 22, 0b0100101011011000 }, /* 29 30 29 29 30 29 30 29 30 30 29 30 30 384 +2043 */ { 00, 02, 10, 0b0100100110110000 }, /* 29 30 29 29 30 29 29 30 30 29 30 30 354 +2044 */ { 07, 01, 30, 0b1010010010111000 }, /* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 +2045 */ { 00, 02, 17, 0b1010010010110000 }, /* 30 29 30 29 29 30 29 29 30 29 30 30 354 +2046 */ { 00, 02, 06, 0b1011001001010000 }, /* 30 29 30 30 29 29 30 29 29 30 29 30 354 +2047 */ { 05, 01, 26, 0b1011010100101000 }, /* 30 29 30 30 29 30 29 30 29 29 30 29 30 384 +2048 */ { 00, 02, 14, 0b0110110101000000 }, /* 29 30 30 29 30 30 29 30 29 30 29 29 354 +2049 */ { 00, 02, 02, 0b1010110110100000 }, /* 30 29 30 29 30 30 29 30 30 29 30 29 355 + */ }; internal override int MinCalendarYear { @@ -204,7 +206,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "year", - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, @@ -261,14 +263,12 @@ namespace System.Globalization return newEras; } - // Construct an instance of JapaneseLunisolar calendar. public JapaneseLunisolarCalendar() { helper = new GregorianCalendarHelper(this, TrimEras(JapaneseCalendar.GetEraInfo())); } - public override int GetEra(DateTime time) { return (helper.GetEra(time)); @@ -290,7 +290,6 @@ namespace System.Globalization } } - public override int[] Eras { get diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JulianCalendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JulianCalendar.cs index 82e4d589d3..a1ffbeb488 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JulianCalendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/JulianCalendar.cs @@ -98,7 +98,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, @@ -142,7 +142,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(day), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, @@ -214,7 +214,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(months), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, @@ -372,7 +372,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(millisecond), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, @@ -404,7 +404,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "year", - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, @@ -427,7 +427,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/KoreanCalendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/KoreanCalendar.cs index 9168b664e0..3f265f69e8 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/KoreanCalendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/KoreanCalendar.cs @@ -237,7 +237,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "year", - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/KoreanLunisolarCalendar.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/KoreanLunisolarCalendar.cs.REMOVED.git-id index 184ae46bbb..95775726d4 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/KoreanLunisolarCalendar.cs.REMOVED.git-id +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/KoreanLunisolarCalendar.cs.REMOVED.git-id @@ -1 +1 @@ -8cdade866c50ba78d20e7913ee0c9d88b0d1e0ed \ No newline at end of file +63636f5e3f4bc579c54e4456fb79ea32a655a115 \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/NumberFormatInfo.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/NumberFormatInfo.cs index a98023dc96..7afe094748 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/NumberFormatInfo.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/NumberFormatInfo.cs @@ -52,23 +52,23 @@ namespace System.Globalization internal int[] numberGroupSizes = new int[] { 3 }; internal int[] currencyGroupSizes = new int[] { 3 }; internal int[] percentGroupSizes = new int[] { 3 }; - internal String positiveSign = "+"; - internal String negativeSign = "-"; - internal String numberDecimalSeparator = "."; - internal String numberGroupSeparator = ","; - internal String currencyGroupSeparator = ","; - internal String currencyDecimalSeparator = "."; - internal String currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund. - internal String nanSymbol = "NaN"; - internal String positiveInfinitySymbol = "Infinity"; - internal String negativeInfinitySymbol = "-Infinity"; - internal String percentDecimalSeparator = "."; - internal String percentGroupSeparator = ","; - internal String percentSymbol = "%"; - internal String perMilleSymbol = "\u2030"; + internal string positiveSign = "+"; + internal string negativeSign = "-"; + internal string numberDecimalSeparator = "."; + internal string numberGroupSeparator = ","; + internal string currencyGroupSeparator = ","; + internal string currencyDecimalSeparator = "."; + internal string currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund. + internal string nanSymbol = "NaN"; + internal string positiveInfinitySymbol = "Infinity"; + internal string negativeInfinitySymbol = "-Infinity"; + internal string percentDecimalSeparator = "."; + internal string percentGroupSeparator = ","; + internal string percentSymbol = "%"; + internal string perMilleSymbol = "\u2030"; - internal String[] nativeDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; + internal string[] nativeDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; internal int numberDecimalDigits = 2; internal int currencyDecimalDigits = 2; @@ -90,7 +90,7 @@ namespace System.Globalization { } - private static void VerifyDecimalSeparator(String decSep, String propertyName) + private static void VerifyDecimalSeparator(string decSep, string propertyName) { if (decSep == null) { @@ -104,7 +104,7 @@ namespace System.Globalization } } - private static void VerifyGroupSeparator(String groupSep, String propertyName) + private static void VerifyGroupSeparator(string groupSep, string propertyName) { if (groupSep == null) { @@ -237,7 +237,7 @@ namespace System.Globalization } } - public Object Clone() + public object Clone() { NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone(); n.isReadOnly = false; @@ -254,7 +254,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(CurrencyDecimalDigits), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, @@ -266,7 +266,7 @@ namespace System.Globalization } - public String CurrencyDecimalSeparator + public string CurrencyDecimalSeparator { get { return currencyDecimalSeparator; } set @@ -292,7 +292,7 @@ namespace System.Globalization // Every element in the groupSize array should be between 1 and 9 // excpet the last element could be zero. // - internal static void CheckGroupSize(String propName, int[] groupSize) + internal static void CheckGroupSize(string propName, int[] groupSize) { for (int i = 0; i < groupSize.Length; i++) { @@ -325,7 +325,7 @@ namespace System.Globalization } VerifyWritable(); - Int32[] inputSizes = (Int32[])value.Clone(); + int[] inputSizes = (int[])value.Clone(); CheckGroupSize(nameof(CurrencyGroupSizes), inputSizes); currencyGroupSizes = inputSizes; } @@ -348,7 +348,7 @@ namespace System.Globalization } VerifyWritable(); - Int32[] inputSizes = (Int32[])value.Clone(); + int[] inputSizes = (int[])value.Clone(); CheckGroupSize(nameof(NumberGroupSizes), inputSizes); numberGroupSizes = inputSizes; } @@ -369,14 +369,14 @@ namespace System.Globalization SR.ArgumentNull_Obj); } VerifyWritable(); - Int32[] inputSizes = (Int32[])value.Clone(); + int[] inputSizes = (int[])value.Clone(); CheckGroupSize(nameof(PercentGroupSizes), inputSizes); percentGroupSizes = inputSizes; } } - public String CurrencyGroupSeparator + public string CurrencyGroupSeparator { get { return currencyGroupSeparator; } set @@ -388,7 +388,7 @@ namespace System.Globalization } - public String CurrencySymbol + public string CurrencySymbol { get { return currencySymbol; } set @@ -424,7 +424,7 @@ namespace System.Globalization } - public String NaNSymbol + public string NaNSymbol { get { @@ -453,7 +453,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(CurrencyNegativePattern), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, @@ -477,7 +477,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(NumberNegativePattern), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, @@ -501,7 +501,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(PercentPositivePattern), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, @@ -525,7 +525,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(PercentNegativePattern), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, @@ -537,7 +537,7 @@ namespace System.Globalization } - public String NegativeInfinitySymbol + public string NegativeInfinitySymbol { get { @@ -556,7 +556,7 @@ namespace System.Globalization } - public String NegativeSign + public string NegativeSign { get { return negativeSign; } set @@ -581,7 +581,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(NumberDecimalDigits), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, @@ -593,7 +593,7 @@ namespace System.Globalization } - public String NumberDecimalSeparator + public string NumberDecimalSeparator { get { return numberDecimalSeparator; } set @@ -605,7 +605,7 @@ namespace System.Globalization } - public String NumberGroupSeparator + public string NumberGroupSeparator { get { return numberGroupSeparator; } set @@ -626,7 +626,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(CurrencyPositivePattern), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, @@ -638,7 +638,7 @@ namespace System.Globalization } - public String PositiveInfinitySymbol + public string PositiveInfinitySymbol { get { @@ -657,7 +657,7 @@ namespace System.Globalization } - public String PositiveSign + public string PositiveSign { get { return positiveSign; } set @@ -682,7 +682,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(PercentDecimalDigits), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, @@ -694,7 +694,7 @@ namespace System.Globalization } - public String PercentDecimalSeparator + public string PercentDecimalSeparator { get { return percentDecimalSeparator; } set @@ -706,7 +706,7 @@ namespace System.Globalization } - public String PercentGroupSeparator + public string PercentGroupSeparator { get { return percentGroupSeparator; } set @@ -718,7 +718,7 @@ namespace System.Globalization } - public String PercentSymbol + public string PercentSymbol { get { @@ -737,7 +737,7 @@ namespace System.Globalization } - public String PerMilleSymbol + public string PerMilleSymbol { get { return perMilleSymbol; } set @@ -754,7 +754,7 @@ namespace System.Globalization public string[] NativeDigits { - get { return (String[])nativeDigits.Clone(); } + get { return (string[])nativeDigits.Clone(); } set { VerifyWritable(); @@ -774,7 +774,7 @@ namespace System.Globalization } } - public Object GetFormat(Type formatType) + public object GetFormat(Type formatType) { return formatType == typeof(NumberFormatInfo) ? this : null; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/PersianCalendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/PersianCalendar.cs index 10912f85b1..a6f964d342 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/PersianCalendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/PersianCalendar.cs @@ -117,7 +117,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "time", - String.Format( + string.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, minDate, @@ -140,7 +140,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, @@ -157,7 +157,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(month), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, @@ -282,7 +282,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(months), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, @@ -462,7 +462,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(day), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Day, daysInMonth, @@ -521,7 +521,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(day), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Day, daysInMonth, @@ -560,7 +560,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(value), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, @@ -589,7 +589,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/RegionInfo.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/RegionInfo.cs index 2cad7bb31c..8416257d91 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/RegionInfo.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/RegionInfo.cs @@ -31,7 +31,7 @@ namespace System.Globalization // // Name of this region (ie: es-US): serialized, the field used for deserialization // - internal String _name; + internal string _name; // // The CultureData instance that we are going to read data from. @@ -54,7 +54,7 @@ namespace System.Globalization // In Silverlight we enforce that RegionInfos must be created with a full culture name // //////////////////////////////////////////////////////////////////////// - public RegionInfo(String name) + public RegionInfo(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); @@ -71,7 +71,7 @@ namespace System.Globalization _cultureData = CultureData.GetCultureDataForRegion(name, true); if (_cultureData == null) throw new ArgumentException( - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.Argument_InvalidCultureName, name), nameof(name)); @@ -157,7 +157,7 @@ namespace System.Globalization // Returns the name of the region (ie: en-US) // //////////////////////////////////////////////////////////////////////// - public virtual String Name + public virtual string Name { get { @@ -173,7 +173,7 @@ namespace System.Globalization // Returns the name of the region in English. (ie: United States) // //////////////////////////////////////////////////////////////////////// - public virtual String EnglishName + public virtual string EnglishName { get { @@ -190,7 +190,7 @@ namespace System.Globalization // if the current UI language is en-US) // //////////////////////////////////////////////////////////////////////// - public virtual String DisplayName + public virtual string DisplayName { get { @@ -207,7 +207,7 @@ namespace System.Globalization // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// - public virtual String NativeName + public virtual string NativeName { get { @@ -222,7 +222,7 @@ namespace System.Globalization // Returns the two letter ISO region name (ie: US) // //////////////////////////////////////////////////////////////////////// - public virtual String TwoLetterISORegionName + public virtual string TwoLetterISORegionName { get { @@ -237,7 +237,7 @@ namespace System.Globalization // Returns the three letter ISO region name (ie: USA) // //////////////////////////////////////////////////////////////////////// - public virtual String ThreeLetterISORegionName + public virtual string ThreeLetterISORegionName { get { @@ -252,7 +252,7 @@ namespace System.Globalization // Returns the three letter windows region name (ie: USA) // //////////////////////////////////////////////////////////////////////// - public virtual String ThreeLetterWindowsRegionName + public virtual string ThreeLetterWindowsRegionName { get { @@ -324,7 +324,7 @@ namespace System.Globalization // Currency Symbol for this locale, ie: Fr. or $ // //////////////////////////////////////////////////////////////////////// - public virtual String CurrencySymbol + public virtual string CurrencySymbol { get { @@ -339,7 +339,7 @@ namespace System.Globalization // ISO Currency Symbol for this locale, ie: CHF // //////////////////////////////////////////////////////////////////////// - public virtual String ISOCurrencySymbol + public virtual string ISOCurrencySymbol { get { @@ -358,7 +358,7 @@ namespace System.Globalization // (ie: en-US) // //////////////////////////////////////////////////////////////////////// - public override bool Equals(Object value) + public override bool Equals(object value) { RegionInfo that = value as RegionInfo; if (that != null) @@ -391,7 +391,7 @@ namespace System.Globalization // Implements Object.ToString(). Returns the name of the Region, ie: es-US // //////////////////////////////////////////////////////////////////////// - public override String ToString() + public override string ToString() { return (Name); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/SortKey.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/SortKey.cs index 647db75b63..9624946257 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/SortKey.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/SortKey.cs @@ -33,7 +33,7 @@ namespace System.Globalization // The following constructor is designed to be called from CompareInfo to get the // the sort key of specific string for synthetic culture // - internal SortKey(String localeName, String str, CompareOptions options, byte[] keyData) + internal SortKey(string localeName, string str, CompareOptions options, byte[] keyData) { _keyData = keyData; _localeName = localeName; @@ -49,7 +49,7 @@ namespace System.Globalization // of SortKey. // //////////////////////////////////////////////////////////////////////// - public virtual String OriginalString + public virtual string OriginalString { get { @@ -133,7 +133,7 @@ namespace System.Globalization // or not object refers to the same SortKey as the current instance. // //////////////////////////////////////////////////////////////////////// - public override bool Equals(Object value) + public override bool Equals(object value) { SortKey that = value as SortKey; @@ -167,7 +167,7 @@ namespace System.Globalization // SortKey. // //////////////////////////////////////////////////////////////////////// - public override String ToString() + public override string ToString() { return ("SortKey - " + _localeName + ", " + _options + ", " + _string); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/StringInfo.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/StringInfo.cs index aa62b2c474..f7be252bfe 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/StringInfo.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/StringInfo.cs @@ -32,7 +32,7 @@ namespace System.Globalization this.String = value; } - public override bool Equals(Object value) + public override bool Equals(object value) { StringInfo that = value as StringInfo; if (that != null) @@ -266,7 +266,7 @@ namespace System.Globalization { if (index == len) { - return (String.Empty); + return (string.Empty); } throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TaiwanCalendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TaiwanCalendar.cs index c5161138de..e2455cd5e3 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TaiwanCalendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TaiwanCalendar.cs @@ -243,7 +243,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "year", - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, @@ -268,7 +268,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TaiwanLunisolarCalendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TaiwanLunisolarCalendar.cs index 60e84f7f33..451fc30747 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TaiwanLunisolarCalendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TaiwanLunisolarCalendar.cs @@ -263,7 +263,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "year", - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextElementEnumerator.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextElementEnumerator.cs index 8b0f102a77..7d8ff64a38 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextElementEnumerator.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextElementEnumerator.cs @@ -21,7 +21,7 @@ namespace System.Globalization public class TextElementEnumerator : IEnumerator { - private String _str; + private string _str; private int _index; private int _startIndex; @@ -33,7 +33,7 @@ namespace System.Globalization private int _charLen; // The next abstract char to look at after MoveNext() is called. It could be 1 or 2, depending on if it is a surrogate or not. - internal TextElementEnumerator(String str, int startIndex, int strLen) + internal TextElementEnumerator(string str, int startIndex, int strLen) { Debug.Assert(str != null, "TextElementEnumerator(): str != null"); Debug.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0"); @@ -61,7 +61,7 @@ namespace System.Globalization // Get the current text element. // - public Object Current + public object Current { get { @@ -73,7 +73,7 @@ namespace System.Globalization // Get the current text element. // - public String GetTextElement() + public string GetTextElement() { if (_index == _startIndex) { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.Unix.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.Unix.cs index d13d3e8cee..c431e462b5 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.Unix.cs @@ -13,116 +13,7 @@ namespace System.Globalization { private Tristate _needsTurkishCasing = Tristate.NotInitialized; - private void FinishInitialization() - { - } - - private unsafe string ChangeCase(string s, bool toUpper) - { - Debug.Assert(!_invariantMode); - - Debug.Assert(s != null); - - if (s.Length == 0) - { - return string.Empty; - } - - string result = string.FastAllocateString(s.Length); - - fixed (char* pSource = s) - { - fixed (char* pResult = result) - { -#if CORECLR - if (IsAsciiCasingSameAsInvariant && s.IsAscii()) - { - int length = s.Length; - char* a = pSource, b = pResult; - if (toUpper) - { - while (length-- != 0) - { - *b++ = ToUpperAsciiInvariant(*a++); - } - } - else - { - while (length-- != 0) - { - *b++ = ToLowerAsciiInvariant(*a++); - } - } - } - else -#endif - { - ChangeCase(pSource, s.Length, pResult, result.Length, toUpper); - } - } - } - - return result; - } - - internal unsafe void ChangeCase(ReadOnlySpan source, Span destination, bool toUpper) - { - Debug.Assert(!_invariantMode); - Debug.Assert(destination.Length >= source.Length); - - if (source.IsEmpty) - { - return; - } - - fixed (char* pSource = &MemoryMarshal.GetReference(source)) - { - fixed (char* pResult = &MemoryMarshal.GetReference(destination)) - { - if (IsAsciiCasingSameAsInvariant) - { - int length = 0; - char* a = pSource, b = pResult; - if (toUpper) - { - while (length < source.Length && *a < 0x80) - { - *b++ = ToUpperAsciiInvariant(*a++); - length++; - } - } - else - { - while (length < source.Length && *a < 0x80) - { - *b++ = ToLowerAsciiInvariant(*a++); - length++; - } - } - - if (length != source.Length) - { - ChangeCase(a, source.Length - length, b, destination.Length - length, toUpper); - } - } - else - { - ChangeCase(pSource, source.Length, pResult, destination.Length, toUpper); - } - } - } - } - - private unsafe char ChangeCase(char c, bool toUpper) - { - Debug.Assert(!_invariantMode); - - char dst = default(char); - - ChangeCase(&c, 1, &dst, 1, toUpper); - - return dst; - } + private void FinishInitialization() { } // ----------------------------- // ---- PAL layer ends here ---- diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.Windows.cs index 015b37fcc4..6e5e321002 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.Windows.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Runtime.InteropServices; namespace System.Globalization { @@ -24,115 +23,33 @@ namespace System.Globalization _sortHandle = ret > 0 ? handle : IntPtr.Zero; } - private unsafe string ChangeCase(string s, bool toUpper) + private unsafe void ChangeCase(char* pSource, int pSourceLen, char* pResult, int pResultLen, bool toUpper) { Debug.Assert(!_invariantMode); - - Debug.Assert(s != null); - - // - // Get the length of the string. - // - int nLengthInput = s.Length; - - // - // Check if we have the empty string. - // - if (nLengthInput == 0) - { - return s; - } - - int ret; + Debug.Assert(pSource != null); + Debug.Assert(pResult != null); + Debug.Assert(pSourceLen >= 0); + Debug.Assert(pResultLen >= 0); + Debug.Assert(pSourceLen <= pResultLen); // Check for Invariant to avoid A/V in LCMapStringEx uint linguisticCasing = IsInvariantLocale(_textInfoName) ? 0 : LCMAP_LINGUISTIC_CASING; - // - // Create the result string. - // - string result = string.FastAllocateString(nLengthInput); - - fixed (char* pSource = s) - fixed (char* pResult = result) - { - ret = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _textInfoName, - linguisticCasing | (toUpper ? LCMAP_UPPERCASE : LCMAP_LOWERCASE), - pSource, - nLengthInput, - pResult, - nLengthInput, - null, - null, - _sortHandle); - } - + int ret = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _textInfoName, + linguisticCasing | (toUpper ? LCMAP_UPPERCASE : LCMAP_LOWERCASE), + pSource, + pSourceLen, + pResult, + pSourceLen, + null, + null, + _sortHandle); if (ret == 0) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - Debug.Assert(ret == nLengthInput, "Expected getting the same length of the original string"); - return result; - } - - internal unsafe void ChangeCase(ReadOnlySpan source, Span destination, bool toUpper) - { - Debug.Assert(!_invariantMode); - Debug.Assert(destination.Length >= source.Length); - - if (source.IsEmpty) - { - return; - } - - int ret; - - // Check for Invariant to avoid A/V in LCMapStringEx - uint linguisticCasing = IsInvariantLocale(_textInfoName) ? 0 : LCMAP_LINGUISTIC_CASING; - - fixed (char* pSource = &MemoryMarshal.GetReference(source)) - fixed (char* pResult = &MemoryMarshal.GetReference(destination)) - { - ret = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _textInfoName, - linguisticCasing | (toUpper ? LCMAP_UPPERCASE : LCMAP_LOWERCASE), - pSource, - source.Length, - pResult, - source.Length, - null, - null, - _sortHandle); - } - - if (ret == 0) - { - throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); - } - - Debug.Assert(ret == source.Length, "Expected getting the same length of the original span"); - } - - private unsafe char ChangeCase(char c, bool toUpper) - { - Debug.Assert(!_invariantMode); - - char retVal = '\0'; - - // Check for Invariant to avoid A/V in LCMapStringEx - uint linguisticCasing = IsInvariantLocale(_textInfoName) ? 0 : LCMAP_LINGUISTIC_CASING; - - Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _textInfoName, - toUpper ? LCMAP_UPPERCASE | linguisticCasing : LCMAP_LOWERCASE | linguisticCasing, - &c, - 1, - &retVal, - 1, - null, - null, - _sortHandle); - - return retVal; + Debug.Assert(ret == pSourceLen, "Expected getting the same length of the original string"); } // PAL Ends here @@ -143,9 +60,6 @@ namespace System.Globalization private const uint LCMAP_LOWERCASE = 0x00000100; private const uint LCMAP_UPPERCASE = 0x00000200; - private static bool IsInvariantLocale(string localeName) - { - return localeName == ""; - } + private static bool IsInvariantLocale(string localeName) => localeName == ""; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs index 631c8c0f19..8073b4b56b 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs @@ -13,6 +13,7 @@ //////////////////////////////////////////////////////////////////////////// using System.Diagnostics; +using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Text; @@ -75,22 +76,11 @@ namespace System.Globalization FinishInitialization(); } - void IDeserializationCallback.OnDeserialization(Object sender) + void IDeserializationCallback.OnDeserialization(object sender) { throw new PlatformNotSupportedException(); } - // - // Internal ordinal comparison functions - // - - internal static int GetHashCodeOrdinalIgnoreCase(string s) - { - // This is the same as an case insensitive hash for Invariant - // (not necessarily true for sorting, but OK for casing & then we apply normal hash code rules) - return Invariant.GetCaseInsensitiveHashCode(s); - } - public virtual int ANSICodePage => _cultureData.IDEFAULTANSICODEPAGE; public virtual int OEMCodePage => _cultureData.IDEFAULTOEMCODEPAGE; @@ -212,7 +202,224 @@ namespace System.Globalization return ChangeCase(str, toUpper: false); } - private unsafe string ToLowerAsciiInvariant(string s) + private unsafe char ChangeCase(char c, bool toUpper) + { + Debug.Assert(!_invariantMode); + + char dst = default; + ChangeCase(&c, 1, &dst, 1, toUpper); + return dst; + } + + private unsafe string ChangeCase(string source, bool toUpper) + { + Debug.Assert(!_invariantMode); + Debug.Assert(source != null); + + // If the string is empty, we're done. + if (source.Length == 0) + { + return string.Empty; + } + + int sourcePos = 0; + string result = null; + + // If this culture's casing for ASCII is the same as invariant, try to take + // a fast path that'll work in managed code and ASCII rather than calling out + // to the OS for culture-aware casing. + if (IsAsciiCasingSameAsInvariant) + { + if (toUpper) + { + // Loop through each character. + for (sourcePos = 0; sourcePos < source.Length; sourcePos++) + { + // If the character is lower-case, we're going to need to allocate a string. + char c = source[sourcePos]; + if ((uint)(c - 'a') <= 'z' - 'a') + { + // Allocate the result string. + result = string.FastAllocateString(source.Length); + fixed (char* pResult = result) + { + // Store all of characters examined thus far. + if (sourcePos > 0) + { + source.AsSpan(0, sourcePos).CopyTo(new Span(pResult, sourcePos)); + } + + // And store the current character, upper-cased. + char* d = pResult + sourcePos; + *d++ = (char)(c & ~0x20); + sourcePos++; + + // Then continue looping through the remainder of the characters. If we hit + // a non-ASCII character, bail to fall back to culture-aware casing. + for (; sourcePos < source.Length; sourcePos++) + { + c = source[sourcePos]; + if ((uint)(c - 'a') <= 'z' - 'a') + { + *d++ = (char)(c & ~0x20); + } + else if (!IsAscii(c)) + { + break; + } + else + { + *d++ = c; + } + } + } + + break; + } + else if (!IsAscii(c)) + { + // The character isn't ASCII; bail to fall back to a culture-aware casing. + break; + } + } + } + else // toUpper == false + { + // Loop through each character. + for (sourcePos = 0; sourcePos < source.Length; sourcePos++) + { + // If the character is upper-case, we're going to need to allocate a string. + char c = source[sourcePos]; + if ((uint)(c - 'A') <= 'Z' - 'A') + { + // Allocate the result string. + result = string.FastAllocateString(source.Length); + fixed (char* pResult = result) + { + // Store all of characters examined thus far. + if (sourcePos > 0) + { + source.AsSpan(0, sourcePos).CopyTo(new Span(pResult, sourcePos)); + } + + // And store the current character, lower-cased. + char* d = pResult + sourcePos; + *d++ = (char)(c | 0x20); + sourcePos++; + + // Then continue looping through the remainder of the characters. If we hit + // a non-ASCII character, bail to fall back to culture-aware casing. + for (; sourcePos < source.Length; sourcePos++) + { + c = source[sourcePos]; + if ((uint)(c - 'A') <= 'Z' - 'A') + { + *d++ = (char)(c | 0x20); + } + else if (!IsAscii(c)) + { + break; + } + else + { + *d++ = c; + } + } + } + + break; + } + else if (!IsAscii(c)) + { + // The character isn't ASCII; bail to fall back to a culture-aware casing. + break; + } + } + } + + // If we successfully iterated through all of the characters, we didn't need to fall back + // to culture-aware casing. In that case, if we allocated a result string, use it, otherwise + // just return the original string, as no modifications were necessary. + if (sourcePos == source.Length) + { + return result ?? source; + } + } + + // Falling back to culture-aware casing. Make sure we have a result string to write into. + // If we need to allocate the result string, we'll also need to copy over to it any + // characters already examined. + if (result == null) + { + result = string.FastAllocateString(source.Length); + if (sourcePos > 0) + { + fixed (char* pResult = result) + { + source.AsSpan(0, sourcePos).CopyTo(new Span(pResult, sourcePos)); + } + } + } + + // Do the casing operation on everything after what we already processed. + fixed (char* pSource = source) + { + fixed (char* pResult = result) + { + ChangeCase(pSource + sourcePos, source.Length - sourcePos, pResult + sourcePos, result.Length - sourcePos, toUpper); + } + } + + return result; + } + + internal unsafe void ChangeCase(ReadOnlySpan source, Span destination, bool toUpper) + { + Debug.Assert(!_invariantMode); + Debug.Assert(destination.Length >= source.Length); + + if (source.IsEmpty) + { + return; + } + + fixed (char* pSource = &MemoryMarshal.GetReference(source)) + fixed (char* pResult = &MemoryMarshal.GetReference(destination)) + { + if (IsAsciiCasingSameAsInvariant) + { + int length = 0; + char* a = pSource, b = pResult; + if (toUpper) + { + while (length < source.Length && *a < 0x80) + { + *b++ = ToUpperAsciiInvariant(*a++); + length++; + } + } + else + { + while (length < source.Length && *a < 0x80) + { + *b++ = ToLowerAsciiInvariant(*a++); + length++; + } + } + + if (length != source.Length) + { + ChangeCase(a, source.Length - length, b, destination.Length - length, toUpper); + } + } + else + { + ChangeCase(pSource, source.Length, pResult, destination.Length, toUpper); + } + } + } + + private static unsafe string ToLowerAsciiInvariant(string s) { if (s.Length == 0) { @@ -258,7 +465,7 @@ namespace System.Globalization } } - internal void ToLowerAsciiInvariant(ReadOnlySpan source, Span destination) + internal static void ToLowerAsciiInvariant(ReadOnlySpan source, Span destination) { Debug.Assert(destination.Length >= source.Length); @@ -268,7 +475,7 @@ namespace System.Globalization } } - private unsafe string ToUpperAsciiInvariant(string s) + private static unsafe string ToUpperAsciiInvariant(string s) { if (s.Length == 0) { @@ -314,7 +521,7 @@ namespace System.Globalization } } - internal void ToUpperAsciiInvariant(ReadOnlySpan source, Span destination) + internal static void ToUpperAsciiInvariant(ReadOnlySpan source, Span destination) { Debug.Assert(destination.Length >= source.Length); @@ -405,7 +612,7 @@ namespace System.Globalization // or not object refers to the same CultureInfo as the current instance. // //////////////////////////////////////////////////////////////////////// - public override bool Equals(Object obj) + public override bool Equals(object obj) { TextInfo that = obj as TextInfo; @@ -602,11 +809,20 @@ namespace System.Globalization { Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); - // for surrogate pairs do a simple ToUpper operation on the substring if (charLen == 2) { - // Surrogate pair - result.Append(ToUpper(input.Substring(inputIndex, charLen))); + // for surrogate pairs do a ToUpper operation on the substring + ReadOnlySpan src = input.AsSpan(inputIndex, 2); + if (_invariantMode) + { + result.Append(src); // surrogate pair in invariant mode, so changing case is a nop + } + else + { + Span dst = stackalloc char[2]; + ChangeCase(src, dst, toUpper: true); + result.Append(dst); + } inputIndex++; } else @@ -693,64 +909,5 @@ namespace System.Globalization || uc == UnicodeCategory.ModifierLetter || uc == UnicodeCategory.OtherLetter); } - - // - // Get case-insensitive hash code for the specified string. - // - internal unsafe int GetCaseInsensitiveHashCode(string str) - { - // Validate inputs - if (str == null) - { - throw new ArgumentNullException(nameof(str)); - } - - // This code assumes that ASCII casing is safe for whatever context is passed in. - // this is true today, because we only ever call these methods on Invariant. It would be ideal to refactor - // these methods so they were correct by construction and we could only ever use Invariant. - - uint hash = 5381; - uint c; - - // Note: We assume that str contains only ASCII characters until - // we hit a non-ASCII character to optimize the common case. - for (int i = 0; i < str.Length; i++) - { - c = str[i]; - if (c >= 0x80) - { - return GetCaseInsensitiveHashCodeSlow(str); - } - - // If we have a lowercase character, ANDing off 0x20 - // will make it an uppercase character. - if ((c - 'a') <= ('z' - 'a')) - { - c = (uint)((int)c & ~0x20); - } - - hash = ((hash << 5) + hash) ^ c; - } - - return (int)hash; - } - - private unsafe int GetCaseInsensitiveHashCodeSlow(string str) - { - Debug.Assert(str != null); - - string upper = ToUpper(str); - - uint hash = 5381; - uint c; - - for (int i = 0; i < upper.Length; i++) - { - c = upper[i]; - hash = ((hash << 5) + hash) ^ c; - } - - return (int)hash; - } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/ThaiBuddhistCalendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/ThaiBuddhistCalendar.cs index 4f8fd8f019..1175185dd6 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/ThaiBuddhistCalendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/ThaiBuddhistCalendar.cs @@ -206,7 +206,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "year", - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanFormat.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanFormat.cs index a66e4600aa..5e553d56b4 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanFormat.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanFormat.cs @@ -2,9 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Text; +using System.Buffers.Text; using System.Diagnostics; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Text; namespace System.Globalization { @@ -35,159 +37,300 @@ namespace System.Globalization internal static readonly FormatLiterals PositiveInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(isNegative: false); internal static readonly FormatLiterals NegativeInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(isNegative: true); - internal enum Pattern - { - None = 0, - Minimum = 1, - Full = 2, - } /// Main method called from TimeSpan.ToString. - internal static string Format(TimeSpan value, string format, IFormatProvider formatProvider) => - StringBuilderCache.GetStringAndRelease(FormatToBuilder(value, format, formatProvider)); + internal static string Format(TimeSpan value, string format, IFormatProvider formatProvider) + { + if (string.IsNullOrEmpty(format)) + { + return FormatC(value); // formatProvider ignored, as "c" is invariant + } + + if (format.Length == 1) + { + char c = format[0]; + + if (c == 'c' || (c | 0x20) == 't') // special-case to optimize the default TimeSpan format + { + return FormatC(value); // formatProvider ignored, as "c" is invariant + } + + if ((c | 0x20) == 'g') // special-case to optimize the remaining 'g'/'G' standard formats + { + return FormatG(value, DateTimeFormatInfo.GetInstance(formatProvider), c == 'G' ? StandardFormat.G : StandardFormat.g); + } + + throw new FormatException(SR.Format_InvalidString); + } + + return StringBuilderCache.GetStringAndRelease(FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider), result: null)); + } /// Main method called from TimeSpan.TryFormat. internal static bool TryFormat(TimeSpan value, Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider formatProvider) { - StringBuilder sb = FormatToBuilder(value, format, formatProvider); + if (format.Length == 0) + { + return TryFormatStandard(value, StandardFormat.C, null, destination, out charsWritten); + } + + if (format.Length == 1) + { + char c = format[0]; + if (c == 'c' || ((c | 0x20) == 't')) + { + return TryFormatStandard(value, StandardFormat.C, null, destination, out charsWritten); + } + else + { + StandardFormat sf = + c == 'g' ? StandardFormat.g : + c == 'G' ? StandardFormat.G : + throw new FormatException(SR.Format_InvalidString); + return TryFormatStandard(value, sf, DateTimeFormatInfo.GetInstance(formatProvider).DecimalSeparator, destination, out charsWritten); + } + } + + StringBuilder sb = FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider), result: null); + if (sb.Length <= destination.Length) { - charsWritten = sb.Length; sb.CopyTo(0, destination, sb.Length); + charsWritten = sb.Length; StringBuilderCache.Release(sb); return true; } - else + + charsWritten = 0; + StringBuilderCache.Release(sb); + return false; + } + + internal static string FormatC(TimeSpan value) + { + Span destination = stackalloc char[26]; // large enough for any "c" TimeSpan + TryFormatStandard(value, StandardFormat.C, null, destination, out int charsWritten); + return new string(destination.Slice(0, charsWritten)); + } + + private static string FormatG(TimeSpan value, DateTimeFormatInfo dtfi, StandardFormat format) + { + string decimalSeparator = dtfi.DecimalSeparator; + int maxLength = 25 + decimalSeparator.Length; // large enough for any "g"/"G" TimeSpan + Span destination = maxLength < 128 ? + stackalloc char[maxLength] : + new char[maxLength]; // the chances of needing this case are almost 0, as DecimalSeparator.Length will basically always == 1 + TryFormatStandard(value, format, decimalSeparator, destination, out int charsWritten); + return new string(destination.Slice(0, charsWritten)); + } + + private enum StandardFormat { C, G, g } + + private static bool TryFormatStandard(TimeSpan value, StandardFormat format, string decimalSeparator, Span destination, out int charsWritten) + { + Debug.Assert(format == StandardFormat.C || format == StandardFormat.G || format == StandardFormat.g); + + // First, calculate how large an output buffer is needed to hold the entire output. + int requiredOutputLength = 8; // start with "hh:mm:ss" and adjust as necessary + + uint fraction; + ulong totalSecondsRemaining; + { + // Turn this into a non-negative TimeSpan if possible. + long ticks = value.Ticks; + if (ticks < 0) + { + requiredOutputLength = 9; // requiredOutputLength + 1 for the leading '-' sign + ticks = -ticks; + if (ticks < 0) + { + Debug.Assert(ticks == long.MinValue /* -9223372036854775808 */); + + // We computed these ahead of time; they're straight from the decimal representation of Int64.MinValue. + fraction = 4775808; + totalSecondsRemaining = 922337203685; + goto AfterComputeFraction; + } + } + + totalSecondsRemaining = Math.DivRem((ulong)ticks, TimeSpan.TicksPerSecond, out ulong fraction64); + fraction = (uint)fraction64; + } + + AfterComputeFraction: + // Only write out the fraction if it's non-zero, and in that + // case write out the entire fraction (all digits). + Debug.Assert(fraction < 10_000_000); + int fractionDigits = 0; + switch (format) + { + case StandardFormat.C: + // "c": Write out a fraction only if it's non-zero, and write out all 7 digits of it. + if (fraction != 0) + { + fractionDigits = DateTimeFormat.MaxSecondsFractionDigits; + requiredOutputLength += fractionDigits + 1; // digits plus leading decimal separator + } + break; + + case StandardFormat.G: + // "G": Write out a fraction regardless of whether it's 0, and write out all 7 digits of it. + fractionDigits = DateTimeFormat.MaxSecondsFractionDigits; + requiredOutputLength += fractionDigits + 1; // digits plus leading decimal separator + break; + + default: + // "g": Write out a fraction only if it's non-zero, and write out only the most significant digits. + Debug.Assert(format == StandardFormat.g); + if (fraction != 0) + { + fractionDigits = DateTimeFormat.MaxSecondsFractionDigits - FormattingHelpers.CountDecimalTrailingZeros(fraction, out fraction); + requiredOutputLength += fractionDigits + 1; // digits plus leading decimal separator + } + break; + } + + ulong totalMinutesRemaining = 0, seconds = 0; + if (totalSecondsRemaining > 0) + { + // Only compute minutes if the TimeSpan has an absolute value of >= 1 minute. + totalMinutesRemaining = Math.DivRem(totalSecondsRemaining, 60 /* seconds per minute */, out seconds); + Debug.Assert(seconds < 60); + } + + ulong totalHoursRemaining = 0, minutes = 0; + if (totalMinutesRemaining > 0) + { + // Only compute hours if the TimeSpan has an absolute value of >= 1 hour. + totalHoursRemaining = Math.DivRem(totalMinutesRemaining, 60 /* minutes per hour */, out minutes); + Debug.Assert(minutes < 60); + } + + // At this point, we can switch over to 32-bit DivRem since the data has shrunk far enough. + Debug.Assert(totalHoursRemaining <= uint.MaxValue); + + uint days = 0, hours = 0; + if (totalHoursRemaining > 0) + { + // Only compute days if the TimeSpan has an absolute value of >= 1 day. + days = Math.DivRem((uint)totalHoursRemaining, 24 /* hours per day */, out hours); + Debug.Assert(hours < 24); + } + + int hourDigits = 2; + if (format == StandardFormat.g && hours < 10) + { + // "g": Only writing a one-digit hour, rather than expected two-digit hour + hourDigits = 1; + requiredOutputLength--; + } + + int dayDigits = 0; + if (days > 0) + { + dayDigits = FormattingHelpers.CountDigits(days); + Debug.Assert(dayDigits <= 8); + requiredOutputLength += dayDigits + 1; // for the leading "d." + } + else if (format == StandardFormat.G) + { + // "G": has a leading "0:" if days is 0 + requiredOutputLength += 2; + dayDigits = 1; + } + + if (destination.Length < requiredOutputLength) { - StringBuilderCache.Release(sb); charsWritten = 0; return false; } - } - - private static StringBuilder FormatToBuilder(TimeSpan value, ReadOnlySpan format, IFormatProvider formatProvider) - { - if (format.Length == 0) - { - format = "c"; - } - - // Standard formats - if (format.Length == 1) - { - char f = format[0]; - switch (f) - { - case 'c': - case 't': - case 'T': - return FormatStandard( - value, - isInvariant: true, - format: format, - pattern: Pattern.Minimum); - - case 'g': - case 'G': - DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(formatProvider); - return FormatStandard( - value, - isInvariant: false, - format: value.Ticks < 0 ? dtfi.FullTimeSpanNegativePattern : dtfi.FullTimeSpanPositivePattern, - pattern: f == 'g' ? Pattern.Minimum : Pattern.Full); - - default: - throw new FormatException(SR.Format_InvalidString); - } - } - - // Custom formats - return FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider), result: null); - } - - /// Format the TimeSpan instance using the specified format. - private static StringBuilder FormatStandard(TimeSpan value, bool isInvariant, ReadOnlySpan format, Pattern pattern) - { - StringBuilder sb = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity); - int day = (int)(value.Ticks / TimeSpan.TicksPerDay); - long time = value.Ticks % TimeSpan.TicksPerDay; + // Write leading '-' if necessary + int idx = 0; if (value.Ticks < 0) { - day = -day; - time = -time; + destination[idx++] = '-'; } - int hours = (int)(time / TimeSpan.TicksPerHour % 24); - int minutes = (int)(time / TimeSpan.TicksPerMinute % 60); - int seconds = (int)(time / TimeSpan.TicksPerSecond % 60); - int fraction = (int)(time % TimeSpan.TicksPerSecond); - FormatLiterals literal; - if (isInvariant) + // Write day and separator, if necessary + if (dayDigits != 0) { - literal = value.Ticks < 0 ? - NegativeInvariantFormatLiterals : - PositiveInvariantFormatLiterals; + WriteDigits(days, destination.Slice(idx, dayDigits)); + idx += dayDigits; + destination[idx++] = format == StandardFormat.C ? '.' : ':'; + } + + // Write "[h]h:mm:ss + Debug.Assert(hourDigits == 1 || hourDigits == 2); + if (hourDigits == 2) + { + WriteTwoDigits(hours, destination.Slice(idx)); + idx += 2; } else { - literal = new FormatLiterals(); - literal.Init(format, pattern == Pattern.Full); + destination[idx++] = (char)('0' + hours); } + destination[idx++] = ':'; + WriteTwoDigits((uint)minutes, destination.Slice(idx)); + idx += 2; + destination[idx++] = ':'; + WriteTwoDigits((uint)seconds, destination.Slice(idx)); + idx += 2; - if (fraction != 0) + // Write fraction and separator, if necessary + if (fractionDigits != 0) { - // truncate the partial second to the specified length - fraction = (int)(fraction / TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - literal.ff)); - } - - // Pattern.Full: [-]dd.hh:mm:ss.fffffff - // Pattern.Minimum: [-][d.]hh:mm:ss[.fffffff] - - sb.Append(literal.Start); // [-] - if (pattern == Pattern.Full || day != 0) - { - sb.Append(day); // [dd] - sb.Append(literal.DayHourSep); // [.] - } // - AppendNonNegativeInt32(sb, hours, literal.hh); // hh - sb.Append(literal.HourMinuteSep); // : - AppendNonNegativeInt32(sb, minutes, literal.mm); // mm - sb.Append(literal.MinuteSecondSep); // : - AppendNonNegativeInt32(sb, seconds, literal.ss); // ss - if (!isInvariant && pattern == Pattern.Minimum) - { - int effectiveDigits = literal.ff; - while (effectiveDigits > 0) + if (format == StandardFormat.C) { - if (fraction % 10 == 0) - { - fraction = fraction / 10; - effectiveDigits--; - } - else - { - break; - } + destination[idx++] = '.'; } - if (effectiveDigits > 0) + else if (decimalSeparator.Length == 1) { - sb.Append(literal.SecondFractionSep); // [.FFFFFFF] - sb.Append((fraction).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture)); + destination[idx++] = decimalSeparator[0]; } + else + { + decimalSeparator.AsSpan().CopyTo(destination); + idx += decimalSeparator.Length; + } + WriteDigits(fraction, destination.Slice(idx, fractionDigits)); + idx += fractionDigits; } - else if (pattern == Pattern.Full || fraction != 0) - { - sb.Append(literal.SecondFractionSep); // [.] - AppendNonNegativeInt32(sb, fraction, literal.ff); // [fffffff] - } - sb.Append(literal.End); - return sb; + Debug.Assert(idx == requiredOutputLength); + charsWritten = requiredOutputLength; + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void WriteTwoDigits(uint value, Span buffer) + { + Debug.Assert(buffer.Length >= 2); + uint temp = '0' + value; + value /= 10; + buffer[1] = (char)(temp - (value * 10)); + buffer[0] = (char)('0' + value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void WriteDigits(uint value, Span buffer) + { + Debug.Assert(buffer.Length > 0); + + for (int i = buffer.Length - 1; i >= 1; i--) + { + uint temp = '0' + value; + value /= 10; + buffer[i] = (char)(temp - (value * 10)); + } + + Debug.Assert(value < 10); + buffer[0] = (char)('0' + value); } /// Format the TimeSpan instance using the specified format. - private static StringBuilder FormatCustomized(TimeSpan value, ReadOnlySpan format, DateTimeFormatInfo dtfi, StringBuilder result) + private static StringBuilder FormatCustomized(TimeSpan value, ReadOnlySpan format, DateTimeFormatInfo dtfi, StringBuilder result = null) { Debug.Assert(dtfi != null); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs index ae77957cec..1bf81742a0 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs @@ -62,15 +62,6 @@ namespace System.Globalization private const int MaxSeconds = 59; private const int MaxFraction = 9999999; - private enum ParseFailureKind : byte - { - None = 0, - ArgumentNull = 1, - Format = 2, - FormatWithParameter = 3, - Overflow = 4, - } - [Flags] private enum TimeSpanStandardStyles : byte { @@ -99,11 +90,11 @@ namespace System.Globalization internal int _zeroes; // Store the number of leading zeroes (if any) internal ReadOnlySpan _sep; // Store the literal that we are parsing (if any) - public TimeSpanToken(TTT type) : this(type, 0, 0, default(ReadOnlySpan)) { } + public TimeSpanToken(TTT type) : this(type, 0, 0, default) { } - public TimeSpanToken(int number) : this(TTT.Num, number, 0, default(ReadOnlySpan)) { } + public TimeSpanToken(int number) : this(TTT.Num, number, 0, default) { } - public TimeSpanToken(int number, int leadingZeroes) : this(TTT.Num, number, leadingZeroes, default(ReadOnlySpan)) { } + public TimeSpanToken(int number, int leadingZeroes) : this(TTT.Num, number, leadingZeroes, default) { } public TimeSpanToken(TTT type, int number, int leadingZeroes, ReadOnlySpan separator) { @@ -169,7 +160,7 @@ namespace System.Globalization int digit; if (++_pos >= _value.Length || (uint)(digit = _value[_pos] - '0') > 9) { - return new TimeSpanToken(TTT.Num, 0, zeroes, default(ReadOnlySpan)); + return new TimeSpanToken(TTT.Num, 0, zeroes, default); } if (digit == 0) @@ -199,7 +190,7 @@ namespace System.Globalization } } - return new TimeSpanToken(TTT.Num, num, zeroes, default(ReadOnlySpan)); + return new TimeSpanToken(TTT.Num, num, zeroes, default); } // Otherwise, we're processing a separator, and we've already processed the first @@ -274,83 +265,83 @@ namespace System.Globalization internal bool FullAppCompatMatch(TimeSpanFormat.FormatLiterals pattern) => _sepCount == 5 && _numCount == 4 - && StringSpanHelpers.Equals(_literals0, pattern.Start) - && StringSpanHelpers.Equals(_literals1, pattern.DayHourSep) - && StringSpanHelpers.Equals(_literals2, pattern.HourMinuteSep) - && StringSpanHelpers.Equals(_literals3, pattern.AppCompatLiteral) - && StringSpanHelpers.Equals(_literals4, pattern.End); + && _literals0.EqualsOrdinal(pattern.Start) + && _literals1.EqualsOrdinal(pattern.DayHourSep) + && _literals2.EqualsOrdinal(pattern.HourMinuteSep) + && _literals3.EqualsOrdinal(pattern.AppCompatLiteral) + && _literals4.EqualsOrdinal(pattern.End); internal bool PartialAppCompatMatch(TimeSpanFormat.FormatLiterals pattern) => _sepCount == 4 && _numCount == 3 - && StringSpanHelpers.Equals(_literals0, pattern.Start) - && StringSpanHelpers.Equals(_literals1, pattern.HourMinuteSep) - && StringSpanHelpers.Equals(_literals2, pattern.AppCompatLiteral) - && StringSpanHelpers.Equals(_literals3, pattern.End); + && _literals0.EqualsOrdinal(pattern.Start) + && _literals1.EqualsOrdinal(pattern.HourMinuteSep) + && _literals2.EqualsOrdinal(pattern.AppCompatLiteral) + && _literals3.EqualsOrdinal(pattern.End); /// DHMSF (all values matched) internal bool FullMatch(TimeSpanFormat.FormatLiterals pattern) => _sepCount == MaxLiteralTokens && _numCount == MaxNumericTokens - && StringSpanHelpers.Equals(_literals0, pattern.Start) - && StringSpanHelpers.Equals(_literals1, pattern.DayHourSep) - && StringSpanHelpers.Equals(_literals2, pattern.HourMinuteSep) - && StringSpanHelpers.Equals(_literals3, pattern.MinuteSecondSep) - && StringSpanHelpers.Equals(_literals4, pattern.SecondFractionSep) - && StringSpanHelpers.Equals(_literals5, pattern.End); + && _literals0.EqualsOrdinal(pattern.Start) + && _literals1.EqualsOrdinal(pattern.DayHourSep) + && _literals2.EqualsOrdinal(pattern.HourMinuteSep) + && _literals3.EqualsOrdinal(pattern.MinuteSecondSep) + && _literals4.EqualsOrdinal(pattern.SecondFractionSep) + && _literals5.EqualsOrdinal(pattern.End); /// D (no hours, minutes, seconds, or fractions) internal bool FullDMatch(TimeSpanFormat.FormatLiterals pattern) => _sepCount == 2 && _numCount == 1 - && StringSpanHelpers.Equals(_literals0, pattern.Start) - && StringSpanHelpers.Equals(_literals1, pattern.End); + && _literals0.EqualsOrdinal(pattern.Start) + && _literals1.EqualsOrdinal(pattern.End); /// HM (no days, seconds, or fractions) internal bool FullHMMatch(TimeSpanFormat.FormatLiterals pattern) => _sepCount == 3 && _numCount == 2 - && StringSpanHelpers.Equals(_literals0, pattern.Start) - && StringSpanHelpers.Equals(_literals1, pattern.HourMinuteSep) - && StringSpanHelpers.Equals(_literals2, pattern.End); + && _literals0.EqualsOrdinal(pattern.Start) + && _literals1.EqualsOrdinal(pattern.HourMinuteSep) + && _literals2.EqualsOrdinal(pattern.End); /// DHM (no seconds or fraction) internal bool FullDHMMatch(TimeSpanFormat.FormatLiterals pattern) => _sepCount == 4 && _numCount == 3 - && StringSpanHelpers.Equals(_literals0, pattern.Start) - && StringSpanHelpers.Equals(_literals1, pattern.DayHourSep) - && StringSpanHelpers.Equals(_literals2, pattern.HourMinuteSep) - && StringSpanHelpers.Equals(_literals3, pattern.End); + && _literals0.EqualsOrdinal(pattern.Start) + && _literals1.EqualsOrdinal(pattern.DayHourSep) + && _literals2.EqualsOrdinal(pattern.HourMinuteSep) + && _literals3.EqualsOrdinal(pattern.End); /// HMS (no days or fraction) internal bool FullHMSMatch(TimeSpanFormat.FormatLiterals pattern) => _sepCount == 4 && _numCount == 3 - && StringSpanHelpers.Equals(_literals0, pattern.Start) - && StringSpanHelpers.Equals(_literals1, pattern.HourMinuteSep) - && StringSpanHelpers.Equals(_literals2, pattern.MinuteSecondSep) - && StringSpanHelpers.Equals(_literals3, pattern.End); + && _literals0.EqualsOrdinal(pattern.Start) + && _literals1.EqualsOrdinal(pattern.HourMinuteSep) + && _literals2.EqualsOrdinal(pattern.MinuteSecondSep) + && _literals3.EqualsOrdinal(pattern.End); /// DHMS (no fraction) internal bool FullDHMSMatch(TimeSpanFormat.FormatLiterals pattern) => _sepCount == 5 && _numCount == 4 - && StringSpanHelpers.Equals(_literals0, pattern.Start) - && StringSpanHelpers.Equals(_literals1, pattern.DayHourSep) - && StringSpanHelpers.Equals(_literals2, pattern.HourMinuteSep) - && StringSpanHelpers.Equals(_literals3, pattern.MinuteSecondSep) - && StringSpanHelpers.Equals(_literals4, pattern.End); + && _literals0.EqualsOrdinal(pattern.Start) + && _literals1.EqualsOrdinal(pattern.DayHourSep) + && _literals2.EqualsOrdinal(pattern.HourMinuteSep) + && _literals3.EqualsOrdinal(pattern.MinuteSecondSep) + && _literals4.EqualsOrdinal(pattern.End); /// HMSF (no days) internal bool FullHMSFMatch(TimeSpanFormat.FormatLiterals pattern) => _sepCount == 5 && _numCount == 4 - && StringSpanHelpers.Equals(_literals0, pattern.Start) - && StringSpanHelpers.Equals(_literals1, pattern.HourMinuteSep) - && StringSpanHelpers.Equals(_literals2, pattern.MinuteSecondSep) - && StringSpanHelpers.Equals(_literals3, pattern.SecondFractionSep) - && StringSpanHelpers.Equals(_literals4, pattern.End); + && _literals0.EqualsOrdinal(pattern.Start) + && _literals1.EqualsOrdinal(pattern.HourMinuteSep) + && _literals2.EqualsOrdinal(pattern.MinuteSecondSep) + && _literals3.EqualsOrdinal(pattern.SecondFractionSep) + && _literals4.EqualsOrdinal(pattern.End); internal TTT _lastSeenTTT; internal int _tokenCount; @@ -391,7 +382,7 @@ namespace System.Globalization switch (tok._ttt) { case TTT.Num: - if ((_tokenCount == 0 && !AddSep(default(ReadOnlySpan), ref result)) || !AddNum(tok, ref result)) + if ((_tokenCount == 0 && !AddSep(default, ref result)) || !AddNum(tok, ref result)) { return false; } @@ -405,11 +396,11 @@ namespace System.Globalization break; case TTT.NumOverflow: - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); default: // Some unknown token or a repeat token type in the input - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } _lastSeenTTT = tok._ttt; @@ -421,7 +412,7 @@ namespace System.Globalization { if (_sepCount >= MaxLiteralTokens || _tokenCount >= MaxTokens) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } switch (_sepCount++) @@ -441,7 +432,7 @@ namespace System.Globalization { if (_numCount >= MaxNumericTokens || _tokenCount >= MaxTokens) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } switch (_numCount++) @@ -459,41 +450,88 @@ namespace System.Globalization } /// Store the result of the parsing. - private struct TimeSpanResult + private ref struct TimeSpanResult { internal TimeSpan parsedTimeSpan; private readonly bool _throwOnFailure; + private readonly ReadOnlySpan _originalTimeSpanString; - internal TimeSpanResult(bool throwOnFailure) + internal TimeSpanResult(bool throwOnFailure, ReadOnlySpan originalTimeSpanString) { - parsedTimeSpan = default(TimeSpan); + parsedTimeSpan = default; _throwOnFailure = throwOnFailure; + _originalTimeSpanString = originalTimeSpanString; } - internal bool SetFailure(ParseFailureKind kind, string resourceKey, object messageArgument = null, string argumentName = null) + internal bool SetNoFormatSpecifierFailure() { if (!_throwOnFailure) { return false; } - string message = SR.GetResourceString(resourceKey); - switch (kind) + throw new FormatException(SR.Format_NoFormatSpecifier); + } + + internal bool SetBadQuoteFailure(char failingCharacter) + { + if (!_throwOnFailure) { - case ParseFailureKind.ArgumentNull: - Debug.Assert(argumentName != null); - throw new ArgumentNullException(argumentName, message); - - case ParseFailureKind.FormatWithParameter: - throw new FormatException(SR.Format(message, messageArgument)); - - case ParseFailureKind.Overflow: - throw new OverflowException(message); - - default: - Debug.Assert(kind == ParseFailureKind.Format, $"Unexpected failure {kind}"); - throw new FormatException(message); + return false; } + + throw new FormatException(SR.Format(SR.Format_BadQuote, failingCharacter)); + } + + internal bool SetInvalidStringFailure() + { + if (!_throwOnFailure) + { + return false; + } + + throw new FormatException(SR.Format_InvalidString); + } + + internal bool SetArgumentNullFailure(string argumentName) + { + if (!_throwOnFailure) + { + return false; + } + + Debug.Assert(argumentName != null); + throw new ArgumentNullException(argumentName, SR.ArgumentNull_String); + } + + internal bool SetOverflowFailure() + { + if (!_throwOnFailure) + { + return false; + } + + throw new OverflowException(SR.Format(SR.Overflow_TimeSpanElementTooLarge, new string(_originalTimeSpanString))); + } + + internal bool SetBadTimeSpanFailure() + { + if (!_throwOnFailure) + { + return false; + } + + throw new FormatException(SR.Format(SR.Format_BadTimeSpan, new string(_originalTimeSpanString))); + } + + internal bool SetBadFormatSpecifierFailure(char? formatSpecifierCharacter = null) + { + if (!_throwOnFailure) + { + return false; + } + + throw new FormatException(SR.Format(SR.Format_BadFormatSpecifier, formatSpecifierCharacter)); } } @@ -568,7 +606,7 @@ namespace System.Globalization internal static TimeSpan Parse(ReadOnlySpan input, IFormatProvider formatProvider) { - var parseResult = new TimeSpanResult(throwOnFailure: true); + var parseResult = new TimeSpanResult(throwOnFailure: true, originalTimeSpanString: input); bool success = TryParseTimeSpan(input, TimeSpanStandardStyles.Any, formatProvider, ref parseResult); Debug.Assert(success, "Should have thrown on failure"); return parseResult.parsedTimeSpan; @@ -576,7 +614,7 @@ namespace System.Globalization internal static bool TryParse(ReadOnlySpan input, IFormatProvider formatProvider, out TimeSpan result) { - var parseResult = new TimeSpanResult(throwOnFailure: false); + var parseResult = new TimeSpanResult(throwOnFailure: false, originalTimeSpanString: input); if (TryParseTimeSpan(input, TimeSpanStandardStyles.Any, formatProvider, ref parseResult)) { @@ -584,13 +622,13 @@ namespace System.Globalization return true; } - result = default(TimeSpan); + result = default; return false; } internal static TimeSpan ParseExact(ReadOnlySpan input, ReadOnlySpan format, IFormatProvider formatProvider, TimeSpanStyles styles) { - var parseResult = new TimeSpanResult(throwOnFailure: true); + var parseResult = new TimeSpanResult(throwOnFailure: true, originalTimeSpanString: input); bool success = TryParseExactTimeSpan(input, format, formatProvider, styles, ref parseResult); Debug.Assert(success, "Should have thrown on failure"); return parseResult.parsedTimeSpan; @@ -598,7 +636,7 @@ namespace System.Globalization internal static bool TryParseExact(ReadOnlySpan input, ReadOnlySpan format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) { - var parseResult = new TimeSpanResult(throwOnFailure: false); + var parseResult = new TimeSpanResult(throwOnFailure: false, originalTimeSpanString: input); if (TryParseExactTimeSpan(input, format, formatProvider, styles, ref parseResult)) { @@ -606,13 +644,13 @@ namespace System.Globalization return true; } - result = default(TimeSpan); + result = default; return false; } internal static TimeSpan ParseExactMultiple(ReadOnlySpan input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles) { - var parseResult = new TimeSpanResult(throwOnFailure: true); + var parseResult = new TimeSpanResult(throwOnFailure: true, originalTimeSpanString: input); bool success = TryParseExactMultipleTimeSpan(input, formats, formatProvider, styles, ref parseResult); Debug.Assert(success, "Should have thrown on failure"); return parseResult.parsedTimeSpan; @@ -620,7 +658,7 @@ namespace System.Globalization internal static bool TryParseExactMultiple(ReadOnlySpan input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) { - var parseResult = new TimeSpanResult(throwOnFailure: false); + var parseResult = new TimeSpanResult(throwOnFailure: false, originalTimeSpanString: input); if (TryParseExactMultipleTimeSpan(input, formats, formatProvider, styles, ref parseResult)) { @@ -628,7 +666,7 @@ namespace System.Globalization return true; } - result = default(TimeSpan); + result = default; return false; } @@ -638,7 +676,7 @@ namespace System.Globalization input = input.Trim(); if (input.IsEmpty) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } var tokenizer = new TimeSpanTokenizer(input); @@ -654,7 +692,7 @@ namespace System.Globalization { if (!raw.ProcessToken(ref tok, ref result)) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } tok = tokenizer.GetNextToken(); } @@ -662,7 +700,7 @@ namespace System.Globalization if (!ProcessTerminalState(ref raw, style, ref result)) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } return true; @@ -691,7 +729,7 @@ namespace System.Globalization tok._ttt = TTT.Sep; if (!raw.ProcessToken(ref tok, ref result)) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } } @@ -702,7 +740,7 @@ namespace System.Globalization case 3: return ProcessTerminal_HM_S_D(ref raw, style, ref result); case 4: return ProcessTerminal_HMS_F_D(ref raw, style, ref result); case 5: return ProcessTerminal_DHMSF(ref raw, style, ref result); - default: return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + default: return result.SetBadTimeSpanFailure(); } } @@ -711,7 +749,7 @@ namespace System.Globalization { if (raw._sepCount != 6) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } Debug.Assert(raw._numCount == 5); @@ -754,7 +792,7 @@ namespace System.Globalization if (!TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, raw._numbers4, out ticks)) { - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); } if (!positive) @@ -762,15 +800,15 @@ namespace System.Globalization ticks = -ticks; if (ticks > 0) { - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); } } - result.parsedTimeSpan._ticks = ticks; + result.parsedTimeSpan = new TimeSpan(ticks); return true; } - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } @@ -782,7 +820,7 @@ namespace System.Globalization { if (raw._sepCount != 5 || (style & TimeSpanStandardStyles.RequireFull) != 0) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } Debug.Assert(raw._numCount == 4); @@ -890,17 +928,17 @@ namespace System.Globalization ticks = -ticks; if (ticks > 0) { - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); } } - result.parsedTimeSpan._ticks = ticks; + result.parsedTimeSpan = new TimeSpan(ticks); return true; } return overflow ? - result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)) : // we found at least one literal pattern match but the numbers just didn't fit - result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); // we couldn't find a thing + result.SetOverflowFailure() : // we found at least one literal pattern match but the numbers just didn't fit + result.SetBadTimeSpanFailure(); // we couldn't find a thing } /// Validate the ambiguous 3-number "Hours:Minutes:Seconds", "Days.Hours:Minutes", or "Hours:Minutes:.Fraction" terminal case. @@ -908,7 +946,7 @@ namespace System.Globalization { if (raw._sepCount != 4 || (style & TimeSpanStandardStyles.RequireFull) != 0) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } Debug.Assert(raw._numCount == 3); @@ -1016,17 +1054,17 @@ namespace System.Globalization ticks = -ticks; if (ticks > 0) { - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); } } - result.parsedTimeSpan._ticks = ticks; + result.parsedTimeSpan = new TimeSpan(ticks); return true; } return overflow ? - result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)) : // we found at least one literal pattern match but the numbers just didn't fit - result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); // we couldn't find a thing + result.SetOverflowFailure() : // we found at least one literal pattern match but the numbers just didn't fit + result.SetBadTimeSpanFailure(); // we couldn't find a thing } /// Validate the 2-number "Hours:Minutes" terminal case. @@ -1034,7 +1072,7 @@ namespace System.Globalization { if (raw._sepCount != 3 || (style & TimeSpanStandardStyles.RequireFull) != 0) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } Debug.Assert(raw._numCount == 2); @@ -1080,7 +1118,7 @@ namespace System.Globalization if (!TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, zero, zero, out ticks)) { - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); } if (!positive) @@ -1088,15 +1126,15 @@ namespace System.Globalization ticks = -ticks; if (ticks > 0) { - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); } } - result.parsedTimeSpan._ticks = ticks; + result.parsedTimeSpan = new TimeSpan(ticks); return true; } - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } /// Validate the 1-number "Days" terminal case. @@ -1104,7 +1142,7 @@ namespace System.Globalization { if (raw._sepCount != 2 || (style & TimeSpanStandardStyles.RequireFull) != 0) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } Debug.Assert(raw._numCount == 1); @@ -1150,7 +1188,7 @@ namespace System.Globalization if (!TryTimeToTicks(positive, raw._numbers0, zero, zero, zero, zero, out ticks)) { - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); } if (!positive) @@ -1158,15 +1196,15 @@ namespace System.Globalization ticks = -ticks; if (ticks > 0) { - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); } } - result.parsedTimeSpan._ticks = ticks; + result.parsedTimeSpan = new TimeSpan(ticks); return true; } - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } /// Common private ParseExact method called by both ParseExact and TryParseExact. @@ -1174,7 +1212,7 @@ namespace System.Globalization { if (format.Length == 0) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadFormatSpecifier)); + return result.SetBadFormatSpecifierFailure(); } if (format.Length == 1) @@ -1193,7 +1231,7 @@ namespace System.Globalization return TryParseTimeSpan(input, TimeSpanStandardStyles.Localized | TimeSpanStandardStyles.RequireFull, formatProvider, ref result); default: - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadFormatSpecifier)); + return result.SetBadFormatSpecifierFailure(format[0]); } } @@ -1230,7 +1268,7 @@ namespace System.Globalization tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 2 || seenHH || !ParseExactDigits(ref tokenizer, tokenLen, out hh)) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString)); + return result.SetInvalidStringFailure(); } seenHH = true; break; @@ -1239,7 +1277,7 @@ namespace System.Globalization tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 2 || seenMM || !ParseExactDigits(ref tokenizer, tokenLen, out mm)) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString)); + return result.SetInvalidStringFailure(); } seenMM = true; break; @@ -1248,7 +1286,7 @@ namespace System.Globalization tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 2 || seenSS || !ParseExactDigits(ref tokenizer, tokenLen, out ss)) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString)); + return result.SetInvalidStringFailure(); } seenSS = true; break; @@ -1257,7 +1295,7 @@ namespace System.Globalization tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits || seenFF || !ParseExactDigits(ref tokenizer, tokenLen, tokenLen, out leadingZeroes, out ff)) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString)); + return result.SetInvalidStringFailure(); } seenFF = true; break; @@ -1266,7 +1304,7 @@ namespace System.Globalization tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits || seenFF) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString)); + return result.SetInvalidStringFailure(); } ParseExactDigits(ref tokenizer, tokenLen, tokenLen, out leadingZeroes, out ff); seenFF = true; @@ -1277,7 +1315,7 @@ namespace System.Globalization int tmp = 0; if (tokenLen > 8 || seenDD || !ParseExactDigits(ref tokenizer, (tokenLen < 2) ? 1 : tokenLen, (tokenLen < 2) ? 8 : tokenLen, out tmp, out dd)) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString)); + return result.SetInvalidStringFailure(); } seenDD = true; break; @@ -1288,12 +1326,12 @@ namespace System.Globalization if (!DateTimeParse.TryParseQuoteString(format, i, enquotedString, out tokenLen)) { StringBuilderCache.Release(enquotedString); - return result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadQuote), ch); + return result.SetBadQuoteFailure(ch); } if (!ParseExactLiteral(ref tokenizer, enquotedString)) { StringBuilderCache.Release(enquotedString); - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString)); + return result.SetInvalidStringFailure(); } StringBuilderCache.Release(enquotedString); break; @@ -1315,7 +1353,7 @@ namespace System.Globalization { // This means that '%' is at the end of the format string or // "%%" appears in the format string. - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString)); + return result.SetInvalidStringFailure(); } case '\\': @@ -1330,12 +1368,12 @@ namespace System.Globalization else { // This means that '\' is at the end of the format string or the literal match failed. - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString)); + return result.SetInvalidStringFailure(); } break; default: - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString)); + return result.SetInvalidStringFailure(); } i += tokenLen; @@ -1345,7 +1383,7 @@ namespace System.Globalization if (!tokenizer.EOL) { // the custom format didn't consume the entire input - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } bool positive = (styles & TimeSpanStyles.AssumeNegative) == 0; @@ -1361,12 +1399,12 @@ namespace System.Globalization ticks = -ticks; } - result.parsedTimeSpan._ticks = ticks; + result.parsedTimeSpan = new TimeSpan(ticks); return true; } else { - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); } } @@ -1456,7 +1494,7 @@ namespace System.Globalization internal bool TryParse(ReadOnlySpan input, ref TimeSpanResult result) { - result.parsedTimeSpan._ticks = 0; + result.parsedTimeSpan = default; _str = input; _len = input.Length; @@ -1507,14 +1545,14 @@ namespace System.Globalization // Allow -0 as well if (time > 0) { - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); } } else { if (time < 0) { - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); } } @@ -1522,10 +1560,10 @@ namespace System.Globalization if (_pos < _len) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } - result.parsedTimeSpan._ticks = time; + result.parsedTimeSpan = new TimeSpan(time); return true; } @@ -1537,13 +1575,13 @@ namespace System.Globalization { if ((i & 0xF0000000) != 0) { - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); } i = i * 10 + _ch - '0'; if (i < 0) { - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); } NextChar(); @@ -1551,12 +1589,12 @@ namespace System.Globalization if (p == _pos) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } if (i > max) { - return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)); + return result.SetOverflowFailure(); } return true; @@ -1575,7 +1613,7 @@ namespace System.Globalization time = unit * TimeSpan.TicksPerHour; if (_ch != ':') { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } NextChar(); @@ -1628,17 +1666,17 @@ namespace System.Globalization { if (formats == null) { - return result.SetFailure(ParseFailureKind.ArgumentNull, nameof(SR.ArgumentNull_String), argumentName: nameof(formats)); + return result.SetArgumentNullFailure(nameof(formats)); } if (input.Length == 0) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } if (formats.Length == 0) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadFormatSpecifier)); + return result.SetNoFormatSpecifierFailure(); } // Do a loop through the provided formats and see if we can parse succesfully in @@ -1647,11 +1685,11 @@ namespace System.Globalization { if (formats[i] == null || formats[i].Length == 0) { - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadFormatSpecifier)); + return result.SetBadFormatSpecifierFailure(); } // Create a new non-throwing result each time to ensure the runs are independent. - TimeSpanResult innerResult = new TimeSpanResult(throwOnFailure: false); + TimeSpanResult innerResult = new TimeSpanResult(throwOnFailure: false, originalTimeSpanString: input); if (TryParseExactTimeSpan(input, formats[i], formatProvider, styles, ref innerResult)) { @@ -1660,7 +1698,7 @@ namespace System.Globalization } } - return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); + return result.SetBadTimeSpanFailure(); } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/UmAlQuraCalendar.cs b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/UmAlQuraCalendar.cs index 21a938f8f1..777af1800f 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Globalization/UmAlQuraCalendar.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Globalization/UmAlQuraCalendar.cs @@ -355,7 +355,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( "time", - String.Format( + string.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, minDate, @@ -378,7 +378,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MinCalendarYear, @@ -510,7 +510,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(months), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, @@ -710,7 +710,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(day), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Day, daysInMonth, @@ -774,7 +774,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(day), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Day, daysInMonth, @@ -814,7 +814,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(value), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MinCalendarYear, @@ -845,7 +845,7 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MinCalendarYear, diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Guid.Unix.cs b/external/corert/src/System.Private.CoreLib/shared/System/Guid.Unix.cs new file mode 100644 index 0000000000..442e7f8837 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Guid.Unix.cs @@ -0,0 +1,38 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace System +{ + partial struct Guid + { + // This will create a new random guid based on the https://www.ietf.org/rfc/rfc4122.txt + public static unsafe Guid NewGuid() + { + Guid g; + Interop.GetRandomBytes((byte*)&g, sizeof(Guid)); + + const ushort VersionMask = 0xF000; + const ushort RandomGuidVersion = 0x4000; + + const byte ClockSeqHiAndReservedMask = 0xC0; + const byte ClockSeqHiAndReservedValue = 0x80; + + // Modify bits indicating the type of the GUID + + unchecked + { + // time_hi_and_version + g._c = (short)((g._c & ~VersionMask) | RandomGuidVersion); + // clock_seq_hi_and_reserved + g._d = (byte)((g._d & ~ClockSeqHiAndReservedMask) | ClockSeqHiAndReservedValue); + } + + return g; + } + } +} + diff --git a/external/corert/src/System.Private.CoreLib/src/System/Guid.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/System/Guid.Windows.cs similarity index 67% rename from external/corert/src/System.Private.CoreLib/src/System/Guid.Windows.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Guid.Windows.cs index f21dfbd6b2..6a275084f9 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Guid.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Guid.Windows.cs @@ -6,26 +6,24 @@ namespace System { partial struct Guid { - // This will create a new guid. Since we've now decided that constructors should 0-init, - // we need a method that allows users to create a guid. public static Guid NewGuid() { // CoCreateGuid should never return Guid.Empty, since it attempts to maintain some - // uniqueness guarantees. It should also never return a known GUID, but it's unclear - // how extensively it checks for known values. + // uniqueness guarantees. Guid g; - int hr = Interop.mincore.CoCreateGuid(out g); + int hr = Interop.Ole32.CoCreateGuid(out g); // We don't expect that this will ever throw an error, none are even documented, and so we don't want to pull // in the HR to ComException mappings into the core library just for this so we will try a generic exception if // we ever hit this condition. if (hr != 0) { Exception ex = new Exception(); - ex.SetErrorCode(hr); + ex.HResult = hr; throw ex; } return g; } } } + diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Guid.cs b/external/corert/src/System.Private.CoreLib/shared/System/Guid.cs index 423d5bc78c..6e6ec067a9 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Guid.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Guid.cs @@ -279,7 +279,7 @@ namespace System { if (input == null) { - result = default(Guid); + result = default; return false; } @@ -297,7 +297,7 @@ namespace System } else { - result = default(Guid); + result = default; return false; } } @@ -358,7 +358,7 @@ namespace System { if (input == null) { - result = default(Guid); + result = default; return false; } @@ -369,7 +369,7 @@ namespace System { if (format.Length != 1) { - result = default(Guid); + result = default; return false; } @@ -398,7 +398,7 @@ namespace System break; default: // invalid guid format specification - result = default(Guid); + result = default; return false; } @@ -411,7 +411,7 @@ namespace System } else { - result = default(Guid); + result = default; return false; } } @@ -427,7 +427,7 @@ namespace System } // Check for dashes - bool dashesExistInString = guidString.IndexOf('-') >= 0; + bool dashesExistInString = guidString.Contains('-'); if (dashesExistInString) { @@ -449,7 +449,7 @@ namespace System } // Check for braces - bool bracesExistInString = (guidString.IndexOf('{', 0) >= 0); + bool bracesExistInString = guidString.Contains('{'); if (bracesExistInString) { @@ -471,7 +471,7 @@ namespace System } // Check for parenthesis - bool parenthesisExistInString = (guidString.IndexOf('(', 0) >= 0); + bool parenthesisExistInString = guidString.Contains('('); if (parenthesisExistInString) { @@ -548,7 +548,7 @@ namespace System // Find the end of this hex number (since it is not fixed length) numStart = 3; - numLen = guidString.IndexOf(',', numStart) - numStart; + numLen = guidString.Slice(numStart).IndexOf(','); if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma)); @@ -566,7 +566,7 @@ namespace System } // +3 to get by ',0x' numStart = numStart + numLen + 3; - numLen = guidString.IndexOf(',', numStart) - numStart; + numLen = guidString.Slice(numStart).IndexOf(','); if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma)); @@ -584,7 +584,7 @@ namespace System } // +3 to get by ',0x' numStart = numStart + numLen + 3; - numLen = guidString.IndexOf(',', numStart) - numStart; + numLen = guidString.Slice(numStart).IndexOf(','); if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma)); @@ -621,7 +621,7 @@ namespace System // Calculate number length if (i < 7) // first 7 cases { - numLen = guidString.IndexOf(',', numStart) - numStart; + numLen = guidString.Slice(numStart).IndexOf(','); if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma)); @@ -630,7 +630,7 @@ namespace System } else // last case ends with '}', not ',' { - numLen = guidString.IndexOf('}', numStart) - numStart; + numLen = guidString.Slice(numStart).IndexOf('}'); if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidBraceAfterLastNumber)); @@ -1232,7 +1232,7 @@ namespace System return (char)((a > 9) ? a - 10 + 0x61 : a + 0x30); } - unsafe private static int HexsToChars(char* guidChars, int a, int b) + private static unsafe int HexsToChars(char* guidChars, int a, int b) { guidChars[0] = HexToChar(a >> 4); guidChars[1] = HexToChar(a); @@ -1243,7 +1243,7 @@ namespace System return 4; } - unsafe private static int HexsToCharsHexOutput(char* guidChars, int a, int b) + private static unsafe int HexsToCharsHexOutput(char* guidChars, int a, int b) { guidChars[0] = '0'; guidChars[1] = 'x'; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/HResults.cs b/external/corert/src/System.Private.CoreLib/shared/System/HResults.cs index ffc47d85bf..4a5ec0d635 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/HResults.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/HResults.cs @@ -25,6 +25,7 @@ namespace System { internal static partial class HResults { + internal const int S_OK = unchecked((int)0x00000000); internal const int COR_E_ABANDONEDMUTEX = unchecked((int)0x8013152D); internal const int COR_E_AMBIGUOUSMATCH = unchecked((int)0x8000211D); internal const int COR_E_APPDOMAINUNLOADED = unchecked((int)0x80131014); @@ -122,5 +123,7 @@ namespace System internal const int ERROR_MRM_MAP_NOT_FOUND = unchecked((int)0x80073B1F); internal const int RO_E_CLOSED = unchecked((int)0x80000013); internal const int TYPE_E_TYPEMISMATCH = unchecked((int)0x80028CA0); + internal const int CO_E_NOTINITIALIZED = unchecked((int)0x800401F0); + internal const int RPC_E_CHANGED_MODE = unchecked((int)0x80010106); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IAsyncResult.cs b/external/corert/src/System.Private.CoreLib/shared/System/IAsyncResult.cs index 0abeaca525..56ebcdb2f5 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IAsyncResult.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IAsyncResult.cs @@ -23,7 +23,7 @@ namespace System WaitHandle AsyncWaitHandle { get; } - Object AsyncState { get; } + object AsyncState { get; } bool CompletedSynchronously { get; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IComparable.cs b/external/corert/src/System.Private.CoreLib/shared/System/IComparable.cs index 72aeeb027c..cf71953e25 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IComparable.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IComparable.cs @@ -18,7 +18,7 @@ namespace System // if this is equal to object, or a value greater than zero // if this is greater than object. // - int CompareTo(Object obj); + int CompareTo(object obj); } // Generic version of IComparable. diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IConvertible.cs b/external/corert/src/System.Private.CoreLib/shared/System/IConvertible.cs index 87351127f2..7abd0c45c3 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IConvertible.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IConvertible.cs @@ -54,10 +54,10 @@ namespace System ulong ToUInt64(IFormatProvider provider); float ToSingle(IFormatProvider provider); double ToDouble(IFormatProvider provider); - Decimal ToDecimal(IFormatProvider provider); + decimal ToDecimal(IFormatProvider provider); DateTime ToDateTime(IFormatProvider provider); - String ToString(IFormatProvider provider); - Object ToType(Type conversionType, IFormatProvider provider); + string ToString(IFormatProvider provider); + object ToType(Type conversionType, IFormatProvider provider); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ICustomFormatter.cs b/external/corert/src/System.Private.CoreLib/shared/System/ICustomFormatter.cs index 47340f3093..cd798b4a1e 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ICustomFormatter.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ICustomFormatter.cs @@ -19,6 +19,6 @@ namespace System public interface ICustomFormatter { // Interface does not need to be marked with the serializable attribute - String Format(String format, Object arg, IFormatProvider formatProvider); + string Format(string format, object arg, IFormatProvider formatProvider); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IFormatProvider.cs b/external/corert/src/System.Private.CoreLib/shared/System/IFormatProvider.cs index 0c17354af3..9369b074f9 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IFormatProvider.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IFormatProvider.cs @@ -18,6 +18,6 @@ namespace System public interface IFormatProvider { // Interface does not need to be marked with the serializable attribute - Object GetFormat(Type formatType); + object GetFormat(Type formatType); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IFormattable.cs b/external/corert/src/System.Private.CoreLib/shared/System/IFormattable.cs index 1f2f7022cc..b5ed9bb45b 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IFormattable.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IFormattable.cs @@ -8,6 +8,6 @@ namespace System { public interface IFormattable { - String ToString(String format, IFormatProvider formatProvider); + string ToString(string format, IFormatProvider formatProvider); } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/IO/BinaryReader.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/BinaryReader.cs similarity index 89% rename from external/corert/src/System.Private.CoreLib/src/System/IO/BinaryReader.cs rename to external/corert/src/System.Private.CoreLib/shared/System/IO/BinaryReader.cs index 314d01cc71..1f1b9218f1 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/IO/BinaryReader.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/BinaryReader.cs @@ -2,11 +2,21 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Internal.Runtime.CompilerServices; -using System; -using System.Text; +/*============================================================ +** +** +** +** +** +** Purpose: Wraps a stream and provides convenient read functionality +** for strings and primitive types. +** +** +============================================================*/ + using System.Diagnostics; using System.Runtime.InteropServices; +using System.Text; namespace System.IO { @@ -89,7 +99,7 @@ namespace System.IO _stream = null; if (copyOfStream != null && !_leaveOpen) { - copyOfStream.Dispose(); + copyOfStream.Close(); } } _stream = null; @@ -117,7 +127,7 @@ namespace System.IO { if (_stream == null) { - throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); + throw Error.GetFileNotOpen(); } if (!_stream.CanSeek) @@ -135,9 +145,79 @@ namespace System.IO { if (_stream == null) { - throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); + throw Error.GetFileNotOpen(); } - return InternalReadOneChar(); + + int charsRead = 0; + int numBytes = 0; + long posSav = posSav = 0; + + if (_stream.CanSeek) + { + posSav = _stream.Position; + } + + if (_charBytes == null) + { + _charBytes = new byte[MaxCharBytesSize]; //REVIEW: We need at most 2 bytes/char here? + } + if (_singleChar == null) + { + _singleChar = new char[1]; + } + + while (charsRead == 0) + { + // We really want to know what the minimum number of bytes per char + // is for our encoding. Otherwise for UnicodeEncoding we'd have to + // do ~1+log(n) reads to read n characters. + // Assume 1 byte can be 1 char unless _2BytesPerChar is true. + numBytes = _2BytesPerChar ? 2 : 1; + + int r = _stream.ReadByte(); + _charBytes[0] = (byte)r; + if (r == -1) + { + numBytes = 0; + } + if (numBytes == 2) + { + r = _stream.ReadByte(); + _charBytes[1] = (byte)r; + if (r == -1) + { + numBytes = 1; + } + } + + if (numBytes == 0) + { + return -1; + } + + Debug.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::ReadOneChar assumes it's reading one or 2 bytes only."); + + try + { + charsRead = _decoder.GetChars(_charBytes, 0, numBytes, _singleChar, 0); + } + catch + { + // Handle surrogate char + + if (_stream.CanSeek) + { + _stream.Seek((posSav - _stream.Position), SeekOrigin.Current); + } + // else - we can't do much here + + throw; + } + + Debug.Assert(charsRead < 2, "BinaryReader::ReadOneChar - assuming we only got 0 or 1 char, not 2!"); + } + Debug.Assert(charsRead > 0); + return _singleChar[0]; } public virtual bool ReadBoolean() @@ -151,13 +231,13 @@ namespace System.IO // Inlined to avoid some method call overhead with FillBuffer. if (_stream == null) { - throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); + throw Error.GetFileNotOpen(); } int b = _stream.ReadByte(); if (b == -1) { - throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF); + throw Error.GetEndOfFile(); } return (byte)b; @@ -175,7 +255,7 @@ namespace System.IO int value = Read(); if (value == -1) { - throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF); + throw Error.GetEndOfFile(); } return (char)value; } @@ -199,7 +279,7 @@ namespace System.IO { if (_stream == null) { - throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); + throw Error.GetFileNotOpen(); } // read directly from MemoryStream buffer @@ -265,11 +345,9 @@ namespace System.IO public virtual decimal ReadDecimal() { FillBuffer(16); - int[] ints = new int[4]; - Buffer.BlockCopy(_buffer, 0, ints, 0, 16); try { - return new decimal(ints); + return decimal.ToDecimal(_buffer); } catch (ArgumentException e) { @@ -282,7 +360,7 @@ namespace System.IO { if (_stream == null) { - throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); + throw Error.GetFileNotOpen(); } int currPos = 0; @@ -321,7 +399,7 @@ namespace System.IO n = _stream.Read(_charBytes, 0, readLength); if (n == 0) { - throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF); + throw Error.GetEndOfFile(); } charsRead = _decoder.GetChars(_charBytes, 0, n, _charBuffer, 0); @@ -363,7 +441,7 @@ namespace System.IO } if (_stream == null) { - throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); + throw Error.GetFileNotOpen(); } // SafeCritical: index and count have already been verified to be a valid range for the buffer @@ -374,7 +452,7 @@ namespace System.IO { if (_stream == null) { - throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); + throw Error.GetFileNotOpen(); } return InternalReadChars(buffer); @@ -465,88 +543,6 @@ namespace System.IO return (buffer.Length - charsRemaining); } - private int InternalReadOneChar() - { - // I know having a separate InternalReadOneChar method seems a little - // redundant, but this makes a scenario like the security parser code - // 20% faster, in addition to the optimizations for UnicodeEncoding I - // put in InternalReadChars. - int charsRead = 0; - int numBytes = 0; - long posSav = posSav = 0; - - if (_stream.CanSeek) - { - posSav = _stream.Position; - } - - if (_charBytes == null) - { - _charBytes = new byte[MaxCharBytesSize]; //REVIEW: We need at most 2 bytes/char here? - } - if (_singleChar == null) - { - _singleChar = new char[1]; - } - - while (charsRead == 0) - { - // We really want to know what the minimum number of bytes per char - // is for our encoding. Otherwise for UnicodeEncoding we'd have to - // do ~1+log(n) reads to read n characters. - // Assume 1 byte can be 1 char unless _2BytesPerChar is true. - numBytes = _2BytesPerChar ? 2 : 1; - - int r = _stream.ReadByte(); - _charBytes[0] = (byte)r; - if (r == -1) - { - numBytes = 0; - } - if (numBytes == 2) - { - r = _stream.ReadByte(); - _charBytes[1] = (byte)r; - if (r == -1) - { - numBytes = 1; - } - } - - if (numBytes == 0) - { - // Console.WriteLine("Found no bytes. We're outta here."); - return -1; - } - - Debug.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only."); - - try - { - charsRead = _decoder.GetChars(_charBytes, 0, numBytes, _singleChar, 0); - } - catch - { - // Handle surrogate char - - if (_stream.CanSeek) - { - _stream.Seek((posSav - _stream.Position), SeekOrigin.Current); - } - // else - we can't do much here - - throw; - } - - Debug.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!"); - // Console.WriteLine("That became: " + charsRead + " characters."); - } - - Debug.Assert(charsRead != 0); - - return _singleChar[0]; - } - public virtual char[] ReadChars(int count) { if (count < 0) @@ -555,7 +551,7 @@ namespace System.IO } if (_stream == null) { - throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); + throw Error.GetFileNotOpen(); } if (count == 0) @@ -596,7 +592,7 @@ namespace System.IO } if (_stream == null) { - throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); + throw Error.GetFileNotOpen(); } return _stream.Read(buffer, index, count); @@ -606,7 +602,7 @@ namespace System.IO { if (_stream == null) { - throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); + throw Error.GetFileNotOpen(); } return _stream.Read(buffer); @@ -665,7 +661,7 @@ namespace System.IO if (_stream == null) { - throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); + throw Error.GetFileNotOpen(); } // Need to find a good threshold for calling ReadByte() repeatedly @@ -676,7 +672,7 @@ namespace System.IO n = _stream.ReadByte(); if (n == -1) { - throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF); + throw Error.GetEndOfFile(); } _buffer[0] = (byte)n; @@ -688,7 +684,7 @@ namespace System.IO n = _stream.Read(_buffer, bytesRead, numBytes - bytesRead); if (n == 0) { - throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF); + throw Error.GetEndOfFile(); } bytesRead += n; } while (bytesRead < numBytes); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs index ad1d31f577..d1a333f419 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs @@ -166,7 +166,7 @@ namespace System.IO // public unsafe virtual void Write(char ch) { - if (Char.IsSurrogate(ch)) + if (char.IsSurrogate(ch)) throw new ArgumentException(SR.Arg_SurrogatesNotAllowedAsSingleChar); Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)"); @@ -223,7 +223,7 @@ namespace System.IO public virtual void Write(decimal value) { - Decimal.GetBytes(value, _buffer); + decimal.GetBytes(value, _buffer); OutStream.Write(_buffer, 0, 16); } @@ -325,7 +325,7 @@ namespace System.IO // a four-byte unsigned integer, and then writes that many characters // to the stream. // - public unsafe virtual void Write(String value) + public unsafe virtual void Write(string value) { if (value == null) throw new ArgumentNullException(nameof(value)); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/DisableMediaInsertionPrompt.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/DisableMediaInsertionPrompt.cs index aa10e8d883..a3a2d29837 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/DisableMediaInsertionPrompt.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/DisableMediaInsertionPrompt.cs @@ -2,7 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if MS_IO_REDIST +using System; + +namespace Microsoft.IO +#else namespace System.IO +#endif { /// /// Simple wrapper to safely disable the normal media insertion prompt for diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/DriveNotFoundException.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/DriveNotFoundException.cs deleted file mode 100644 index 3f2c88c74b..0000000000 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/DriveNotFoundException.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.Serialization; - -namespace System.IO -{ - //Thrown when trying to access a drive that is not available. - [Serializable] - [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - internal class DriveNotFoundException : IOException - { - public DriveNotFoundException() - : base(SR.Arg_DriveNotFoundException) - { - HResult = HResults.COR_E_DIRECTORYNOTFOUND; - } - - public DriveNotFoundException(string message) - : base(message) - { - HResult = HResults.COR_E_DIRECTORYNOTFOUND; - } - - public DriveNotFoundException(string message, Exception innerException) - : base(message, innerException) - { - HResult = HResults.COR_E_DIRECTORYNOTFOUND; - } - - protected DriveNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } - } -} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.Unix.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.Unix.cs index d9fcf65711..ae4b709ea1 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.Unix.cs @@ -61,10 +61,12 @@ namespace System.IO return SafeFileHandle.Open(_path, openFlags, (int)OpenPermissions); } + private static bool GetDefaultIsAsync(SafeFileHandle handle) => handle.IsAsync ?? DefaultIsAsync; + /// Initializes a stream for reading or writing a Unix file. /// How the file should be opened. /// What other access to the file should be allowed. This is currently ignored. - private void Init(FileMode mode, FileShare share) + private void Init(FileMode mode, FileShare share, string originalPath) { _fileHandle.IsAsync = _useAsyncIO; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.Win32.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.Win32.cs index 4b75ad6dad..edcf8e546e 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.Win32.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.Win32.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Diagnostics; using Microsoft.Win32.SafeHandles; namespace System.IO @@ -43,5 +44,62 @@ namespace System.IO Interop.Kernel32.CreateFile(_path, fAccess, share, ref secAttrs, mode, flagsAndAttributes, IntPtr.Zero)); } } + + private static bool GetDefaultIsAsync(SafeFileHandle handle) + { + return handle.IsAsync ?? !IsHandleSynchronous(handle, ignoreInvalid: true) ?? DefaultIsAsync; + } + + private static unsafe bool? IsHandleSynchronous(SafeFileHandle fileHandle, bool ignoreInvalid) + { + if (fileHandle.IsInvalid) + return null; + + uint fileMode; + + int status = Interop.NtDll.NtQueryInformationFile( + FileHandle: fileHandle, + IoStatusBlock: out Interop.NtDll.IO_STATUS_BLOCK ioStatus, + FileInformation: &fileMode, + Length: sizeof(uint), + FileInformationClass: Interop.NtDll.FileModeInformation); + + switch (status) + { + case 0: + // We we're successful + break; + case Interop.NtDll.STATUS_INVALID_HANDLE: + if (!ignoreInvalid) + { + throw Win32Marshal.GetExceptionForWin32Error(Interop.Errors.ERROR_INVALID_HANDLE); + } + else + { + return null; + } + default: + // Something else is preventing access + Debug.Fail("Unable to get the file mode information, status was" + status.ToString()); + return null; + } + + // If either of these two flags are set, the file handle is synchronous (not overlapped) + return (fileMode & (Interop.NtDll.FILE_SYNCHRONOUS_IO_ALERT | Interop.NtDll.FILE_SYNCHRONOUS_IO_NONALERT)) > 0; + } + + private static void VerifyHandleIsSync(SafeFileHandle handle, int fileType, FileAccess access) + { + // As we can accurately check the handle type when we have access to NtQueryInformationFile we don't need to skip for + // any particular file handle type. + + // If the handle was passed in without an explicit async setting, we already looked it up in GetDefaultIsAsync + if (!handle.IsAsync.HasValue) + return; + + // If we can't check the handle, just assume it is ok. + if (!(IsHandleSynchronous(handle, ignoreInvalid: false) ?? true)) + throw new ArgumentException(SR.Arg_HandleNotSync, nameof(handle)); + } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.WinRT.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.WinRT.cs index 304088eea7..b326525a7d 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.WinRT.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.WinRT.cs @@ -40,5 +40,58 @@ namespace System.IO pCreateExParams: ref parameters)); } } + + private static bool GetDefaultIsAsync(SafeFileHandle handle) => handle.IsAsync ?? DefaultIsAsync; + + private static unsafe bool? IsHandleSynchronous(SafeFileHandle handle, FileAccess access) + { + // Do NOT use this method on any type other than DISK. Reading or writing to a pipe may + // cause an app to block incorrectly, introducing a deadlock (depending on whether a write + // will wake up an already-blocked thread or this Win32FileStream's thread). + + byte* bytes = stackalloc byte[1]; + int numBytesReadWritten; + int r = -1; + + // If the handle is a pipe, ReadFile will block until there + // has been a write on the other end. We'll just have to deal with it, + // For the read end of a pipe, you can mess up and + // accidentally read synchronously from an async pipe. + if ((access & FileAccess.Read) != 0) + { + r = Interop.Kernel32.ReadFile(handle, bytes, 0, out numBytesReadWritten, IntPtr.Zero); + } + else if ((access & FileAccess.Write) != 0) + { + r = Interop.Kernel32.WriteFile(handle, bytes, 0, out numBytesReadWritten, IntPtr.Zero); + } + + if (r == 0) + { + int errorCode = Marshal.GetLastWin32Error(); + switch (errorCode) + { + case Interop.Errors.ERROR_INVALID_PARAMETER: + return false; + case Interop.Errors.ERROR_INVALID_HANDLE: + throw Win32Marshal.GetExceptionForWin32Error(errorCode); + } + } + + return true; + } + + private static void VerifyHandleIsSync(SafeFileHandle handle, int fileType, FileAccess access) + { + // The technique here only really works for FILE_TYPE_DISK. FileMode is the right thing to check, but it currently + // isn't available in WinRT. + + if (fileType == Interop.Kernel32.FileTypes.FILE_TYPE_DISK) + { + // If we can't check the handle, just assume it is ok. + if (!(IsHandleSynchronous(handle, access) ?? true)) + throw new ArgumentException(SR.Arg_HandleNotSync, nameof(handle)); + } + } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.Windows.cs index 291a30bb53..ddbac1bf7d 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.Windows.cs @@ -52,17 +52,29 @@ namespace System.IO private PreAllocatedOverlapped _preallocatedOverlapped; // optimization for async ops to avoid per-op allocations private FileStreamCompletionSource _currentOverlappedOwner; // async op currently using the preallocated overlapped - private void Init(FileMode mode, FileShare share) + private void Init(FileMode mode, FileShare share, string originalPath) { - // Disallow access to all non-file devices from the Win32FileStream - // constructors that take a String. Everyone else can call - // CreateFile themselves then use the constructor that takes an - // IntPtr. Disallows "con:", "com1:", "lpt1:", etc. - int fileType = Interop.Kernel32.GetFileType(_fileHandle); - if (fileType != Interop.Kernel32.FileTypes.FILE_TYPE_DISK) + if (!PathInternal.IsExtended(originalPath)) { - _fileHandle.Dispose(); - throw new NotSupportedException(SR.NotSupported_FileStreamOnNonFiles); + // To help avoid stumbling into opening COM/LPT ports by accident, we will block on non file handles unless + // we were explicitly passed a path that has \\?\. GetFullPath() will turn paths like C:\foo\con.txt into + // \\.\CON, so we'll only allow the \\?\ syntax. + + int fileType = Interop.Kernel32.GetFileType(_fileHandle); + if (fileType != Interop.Kernel32.FileTypes.FILE_TYPE_DISK) + { + int errorCode = fileType == Interop.Kernel32.FileTypes.FILE_TYPE_UNKNOWN + ? Marshal.GetLastWin32Error() + : Interop.Errors.ERROR_SUCCESS; + + _fileHandle.Dispose(); + + if (errorCode != Interop.Errors.ERROR_SUCCESS) + { + throw Win32Marshal.GetExceptionForWin32Error(errorCode); + } + throw new NotSupportedException(SR.NotSupported_FileStreamOnNonFiles); + } } // This is necessary for async IO using IO Completion ports via our @@ -161,8 +173,7 @@ namespace System.IO } else if (!useAsyncIO) { - if (handleType != Interop.Kernel32.FileTypes.FILE_TYPE_PIPE) - VerifyHandleIsSync(handle, access); + VerifyHandleIsSync(handle, handleType, access); } if (_canSeek) @@ -171,75 +182,31 @@ namespace System.IO _filePosition = 0; } - private unsafe static Interop.Kernel32.SECURITY_ATTRIBUTES GetSecAttrs(FileShare share) + private static unsafe Interop.Kernel32.SECURITY_ATTRIBUTES GetSecAttrs(FileShare share) { - Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); + Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default; if ((share & FileShare.Inheritable) != 0) { - secAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES(); - secAttrs.nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES); - - secAttrs.bInheritHandle = Interop.BOOL.TRUE; + secAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES + { + nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES), + bInheritHandle = Interop.BOOL.TRUE + }; } return secAttrs; } - // Verifies that this handle supports synchronous IO operations (unless you - // didn't open it for either reading or writing). - private unsafe static void VerifyHandleIsSync(SafeFileHandle handle, FileAccess access) - { - // Do NOT use this method on pipes. Reading or writing to a pipe may - // cause an app to block incorrectly, introducing a deadlock (depending - // on whether a write will wake up an already-blocked thread or this - // Win32FileStream's thread). - Debug.Assert(Interop.Kernel32.GetFileType(handle) != Interop.Kernel32.FileTypes.FILE_TYPE_PIPE); - - byte* bytes = stackalloc byte[1]; - int numBytesReadWritten; - int r = -1; - - // If the handle is a pipe, ReadFile will block until there - // has been a write on the other end. We'll just have to deal with it, - // For the read end of a pipe, you can mess up and - // accidentally read synchronously from an async pipe. - if ((access & FileAccess.Read) != 0) // don't use the virtual CanRead or CanWrite, as this may be used in the ctor - { - r = Interop.Kernel32.ReadFile(handle, bytes, 0, out numBytesReadWritten, IntPtr.Zero); - } - else if ((access & FileAccess.Write) != 0) // don't use the virtual CanRead or CanWrite, as this may be used in the ctor - { - r = Interop.Kernel32.WriteFile(handle, bytes, 0, out numBytesReadWritten, IntPtr.Zero); - } - - if (r == 0) - { - int errorCode = Marshal.GetLastWin32Error(); - switch (errorCode) - { - case Interop.Errors.ERROR_INVALID_PARAMETER: - throw new ArgumentException(SR.Arg_HandleNotSync, "handle"); - case Interop.Errors.ERROR_INVALID_HANDLE: - throw Win32Marshal.GetExceptionForWin32Error(errorCode); - } - } - } - private bool HasActiveBufferOperation - { - get { return _activeBufferOperation != null && !_activeBufferOperation.IsCompleted; } - } + => _activeBufferOperation != null && !_activeBufferOperation.IsCompleted; - public override bool CanSeek - { - get { return _canSeek; } - } + public override bool CanSeek => _canSeek; private unsafe long GetLengthInternal() { Interop.Kernel32.FILE_STANDARD_INFO info = new Interop.Kernel32.FILE_STANDARD_INFO(); if (!Interop.Kernel32.GetFileInformationByHandleEx(_fileHandle, Interop.Kernel32.FILE_INFO_BY_HANDLE_CLASS.FileStandardInfo, out info, (uint)sizeof(Interop.Kernel32.FILE_STANDARD_INFO))) - throw Win32Marshal.GetExceptionForLastWin32Error(); + throw Win32Marshal.GetExceptionForLastWin32Error(_path); long len = info.EndOfFile; // If we're writing near the end of the file, we must include our // internal buffer in our Length calculation. Don't flush because @@ -307,7 +274,7 @@ namespace System.IO { if (!Interop.Kernel32.FlushFileBuffers(_fileHandle)) { - throw Win32Marshal.GetExceptionForLastWin32Error(); + throw Win32Marshal.GetExceptionForLastWin32Error(_path); } } @@ -404,7 +371,7 @@ namespace System.IO int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_INVALID_PARAMETER) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_FileLengthTooBig); - throw Win32Marshal.GetExceptionForWin32Error(errorCode); + throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path); } // Return file pointer to where it was before setting length if (origPos != value) @@ -506,8 +473,7 @@ namespace System.IO // Make sure we are reading from the right spot VerifyOSHandlePosition(); - int errorCode = 0; - int r = ReadFileNative(_fileHandle, buffer, null, out errorCode); + int r = ReadFileNative(_fileHandle, buffer, null, out int errorCode); if (r == -1) { @@ -521,7 +487,7 @@ namespace System.IO if (errorCode == ERROR_INVALID_PARAMETER) throw new ArgumentException(SR.Arg_HandleNotSync, "_fileHandle"); - throw Win32Marshal.GetExceptionForWin32Error(errorCode); + throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path); } } Debug.Assert(r >= 0, "FileStream's ReadNative is likely broken."); @@ -621,17 +587,15 @@ namespace System.IO Debug.Assert(!fileHandle.IsClosed && _canSeek, "!fileHandle.IsClosed && _canSeek"); Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End, "origin >= SeekOrigin.Begin && origin <= SeekOrigin.End"); - long ret = 0; - - if (!Interop.Kernel32.SetFilePointerEx(fileHandle, offset, out ret, (uint)origin)) + if (!Interop.Kernel32.SetFilePointerEx(fileHandle, offset, out long ret, (uint)origin)) { if (closeInvalidHandle) { - throw Win32Marshal.GetExceptionForWin32Error(GetLastWin32ErrorAndDisposeHandleIfInvalid(throwIfInvalidHandle: false)); + throw Win32Marshal.GetExceptionForWin32Error(GetLastWin32ErrorAndDisposeHandleIfInvalid(), _path); } else { - throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); + throw Win32Marshal.GetExceptionForLastWin32Error(_path); } } @@ -739,7 +703,7 @@ namespace System.IO // to a handle opened asynchronously. if (errorCode == ERROR_INVALID_PARAMETER) throw new IOException(SR.IO_FileTooLongOrHandleNotSync); - throw Win32Marshal.GetExceptionForWin32Error(errorCode); + throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path); } } Debug.Assert(r >= 0, "FileStream's WriteCore is likely broken."); @@ -850,7 +814,7 @@ namespace System.IO } } - unsafe private Task ReadNativeAsync(Memory destination, int numBufferedBytesRead, CancellationToken cancellationToken) + private unsafe Task ReadNativeAsync(Memory destination, int numBufferedBytesRead, CancellationToken cancellationToken) { AssertCanRead(); Debug.Assert(_useAsyncIO, "ReadNativeAsync doesn't work on synchronous file streams!"); @@ -875,7 +839,7 @@ namespace System.IO } else { - destination = default(Memory); + destination = default; } } @@ -938,7 +902,7 @@ namespace System.IO } else { - throw Win32Marshal.GetExceptionForWin32Error(errorCode); + throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path); } } else if (cancellationToken.CanBeCanceled) // ERROR_IO_PENDING @@ -1141,7 +1105,7 @@ namespace System.IO } else { - throw Win32Marshal.GetExceptionForWin32Error(errorCode); + throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path); } } else if (cancellationToken.CanBeCanceled) // ERROR_IO_PENDING @@ -1238,7 +1202,7 @@ namespace System.IO } } - private int GetLastWin32ErrorAndDisposeHandleIfInvalid(bool throwIfInvalidHandle = false) + private int GetLastWin32ErrorAndDisposeHandleIfInvalid() { int errorCode = Marshal.GetLastWin32Error(); @@ -1262,9 +1226,6 @@ namespace System.IO if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE) { _fileHandle.Dispose(); - - if (throwIfInvalidHandle) - throw Win32Marshal.GetExceptionForWin32Error(errorCode); } return errorCode; @@ -1418,7 +1379,7 @@ namespace System.IO break; default: // Everything else is an error (and there won't be a callback). - throw Win32Marshal.GetExceptionForWin32Error(errorCode); + throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path); } } @@ -1436,7 +1397,7 @@ namespace System.IO case Interop.Errors.ERROR_OPERATION_ABORTED: // canceled throw new OperationCanceledException(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); default: // error - throw Win32Marshal.GetExceptionForWin32Error((int)readAwaitable._errorCode); + throw Win32Marshal.GetExceptionForWin32Error((int)readAwaitable._errorCode, _path); } // Successful operation. If we got zero bytes, we're done: exit the read/write loop. @@ -1535,7 +1496,7 @@ namespace System.IO } /// Overlapped callback: store the results, then invoke the continuation delegate. - internal unsafe static void IOCallback(uint errorCode, uint numBytes, NativeOverlapped* pOVERLAP) + internal static unsafe void IOCallback(uint errorCode, uint numBytes, NativeOverlapped* pOVERLAP) { var awaitable = (AsyncCopyToAwaitable)ThreadPoolBoundHandle.GetNativeOverlappedState(pOVERLAP); @@ -1623,7 +1584,7 @@ namespace System.IO if (!Interop.Kernel32.LockFile(_fileHandle, positionLow, positionHigh, lengthLow, lengthHigh)) { - throw Win32Marshal.GetExceptionForLastWin32Error(); + throw Win32Marshal.GetExceptionForLastWin32Error(_path); } } @@ -1636,9 +1597,10 @@ namespace System.IO if (!Interop.Kernel32.UnlockFile(_fileHandle, positionLow, positionHigh, lengthLow, lengthHigh)) { - throw Win32Marshal.GetExceptionForLastWin32Error(); + throw Win32Marshal.GetExceptionForLastWin32Error(_path); } } + private SafeFileHandle ValidateFileHandle(SafeFileHandle fileHandle) { if (fileHandle.IsInvalid) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.cs index 717b73ff13..fadbef8809 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStream.cs @@ -6,7 +6,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using System.Diagnostics; -using System.Security; namespace System.IO { @@ -233,7 +232,7 @@ namespace System.IO try { - Init(mode, share); + Init(mode, share, path); } catch { @@ -245,12 +244,6 @@ namespace System.IO } } - private static bool GetDefaultIsAsync(SafeFileHandle handle) - { - // This will eventually get more complicated as we can actually check the underlying handle type on Windows - return handle.IsAsync.HasValue ? handle.IsAsync.Value : false; - } - [Obsolete("This property has been deprecated. Please use FileStream's SafeFileHandle property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual IntPtr Handle { get { return SafeFileHandle.DangerousGetHandle(); } } @@ -304,7 +297,7 @@ namespace System.IO ReadSpan(new Span(array, offset, count)); } - public override int Read(Span destination) + public override int Read(Span buffer) { if (GetType() == typeof(FileStream) && !_useAsyncIO) { @@ -312,7 +305,7 @@ namespace System.IO { throw Error.GetFileNotOpen(); } - return ReadSpan(destination); + return ReadSpan(buffer); } else { @@ -322,7 +315,7 @@ namespace System.IO // of Read(byte[],int,int) overload. Or if the stream is in async mode, we can't call the // synchronous ReadSpan, so we similarly call the base Read, which will turn delegate to // Read(byte[],int,int), which will do the right thing if we're in async mode. - return base.Read(destination); + return base.Read(buffer); } } @@ -355,14 +348,14 @@ namespace System.IO return ReadAsyncTask(buffer, offset, count, cancellationToken); } - public override ValueTask ReadAsync(Memory destination, CancellationToken cancellationToken = default(CancellationToken)) + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) { if (!_useAsyncIO || GetType() != typeof(FileStream)) { // If we're not using async I/O, delegate to the base, which will queue a call to Read. // Or if this isn't a concrete FileStream, a derived type may have overridden ReadAsync(byte[],...), // which was introduced first, so delegate to the base which will delegate to that. - return base.ReadAsync(destination, cancellationToken); + return base.ReadAsync(buffer, cancellationToken); } if (cancellationToken.IsCancellationRequested) @@ -375,7 +368,7 @@ namespace System.IO throw Error.GetFileNotOpen(); } - Task t = ReadAsyncInternal(destination, cancellationToken, out int synchronousResult); + Task t = ReadAsyncInternal(buffer, cancellationToken, out int synchronousResult); return t != null ? new ValueTask(t) : new ValueTask(synchronousResult); @@ -412,7 +405,7 @@ namespace System.IO } } - public override void Write(ReadOnlySpan destination) + public override void Write(ReadOnlySpan buffer) { if (GetType() == typeof(FileStream) && !_useAsyncIO) { @@ -420,7 +413,7 @@ namespace System.IO { throw Error.GetFileNotOpen(); } - WriteSpan(destination); + WriteSpan(buffer); } else { @@ -430,7 +423,7 @@ namespace System.IO // of Write(byte[],int,int) overload. Or if the stream is in async mode, we can't call the // synchronous WriteSpan, so we similarly call the base Write, which will turn delegate to // Write(byte[],int,int), which will do the right thing if we're in async mode. - base.Write(destination); + base.Write(buffer); } } @@ -461,14 +454,14 @@ namespace System.IO return WriteAsyncInternal(new ReadOnlyMemory(buffer, offset, count), cancellationToken).AsTask(); } - public override ValueTask WriteAsync(ReadOnlyMemory source, CancellationToken cancellationToken = default(CancellationToken)) + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) { if (!_useAsyncIO || GetType() != typeof(FileStream)) { // If we're not using async I/O, delegate to the base, which will queue a call to Write. // Or if this isn't a concrete FileStream, a derived type may have overridden WriteAsync(byte[],...), // which was introduced first, so delegate to the base which will delegate to that. - return base.WriteAsync(source, cancellationToken); + return base.WriteAsync(buffer, cancellationToken); } if (cancellationToken.IsCancellationRequested) @@ -481,7 +474,7 @@ namespace System.IO throw Error.GetFileNotOpen(); } - return WriteAsyncInternal(source, cancellationToken); + return WriteAsyncInternal(buffer, cancellationToken); } /// diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs index 82274b131f..62ace0918d 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs @@ -246,7 +246,7 @@ namespace System.IO internal MemoryFileStreamCompletionSource(FileStream stream, int numBufferedBytes, ReadOnlyMemory memory) : base(stream, numBufferedBytes, bytes: null) // this type handles the pinning, so null is passed for bytes { - _handle = memory.Retain(pin: true); + _handle = memory.Pin(); } internal override void ReleaseNativeResource() diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/IOException.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/IOException.cs index 89b25d5142..04e6532061 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/IOException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/IOException.cs @@ -17,19 +17,19 @@ namespace System.IO HResult = HResults.COR_E_IO; } - public IOException(String message) + public IOException(string message) : base(message) { HResult = HResults.COR_E_IO; } - public IOException(String message, int hresult) + public IOException(string message, int hresult) : base(message) { HResult = hresult; } - public IOException(String message, Exception innerException) + public IOException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_IO; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs index ffe7f60936..9bac0d818b 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs @@ -208,7 +208,7 @@ namespace System.IO { if (!_exposable) { - buffer = default(ArraySegment); + buffer = default; return false; } @@ -367,19 +367,19 @@ namespace System.IO return n; } - public override int Read(Span destination) + public override int Read(Span buffer) { if (GetType() != typeof(MemoryStream)) { // MemoryStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior // to this Read(Span) overload being introduced. In that case, this Read(Span) overload // should use the behavior of Read(byte[],int,int) overload. - return base.Read(destination); + return base.Read(buffer); } EnsureNotClosed(); - int n = Math.Min(_length - _position, destination.Length); + int n = Math.Min(_length - _position, buffer.Length); if (n <= 0) return 0; @@ -387,13 +387,13 @@ namespace System.IO // Read(byte[], int, int) has an n <= 8 optimization, presumably based // on benchmarking. Determine if/where such a cut-off is here and add // an equivalent optimization if necessary. - new Span(_buffer, _position, n).CopyTo(destination); + new Span(_buffer, _position, n).CopyTo(buffer); _position += n; return n; } - public override Task ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); @@ -426,7 +426,7 @@ namespace System.IO } } - public override ValueTask ReadAsync(Memory destination, CancellationToken cancellationToken = default(CancellationToken)) + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -448,9 +448,9 @@ namespace System.IO // something other than an array and this is a MemoryStream-derived type that doesn't override Read(Span) will // it then fall back to doing the ArrayPool/copy behavior. return new ValueTask( - MemoryMarshal.TryGetArray(destination, out ArraySegment destinationArray) ? + MemoryMarshal.TryGetArray(buffer, out ArraySegment destinationArray) ? Read(destinationArray.Array, destinationArray.Offset, destinationArray.Count) : - Read(destination.Span)); + Read(buffer.Span)); } catch (OperationCanceledException oce) { @@ -681,14 +681,14 @@ namespace System.IO _position = i; } - public override void Write(ReadOnlySpan source) + public override void Write(ReadOnlySpan buffer) { if (GetType() != typeof(MemoryStream)) { // MemoryStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior // to this Write(Span) overload being introduced. In that case, this Write(Span) overload // should use the behavior of Write(byte[],int,int) overload. - base.Write(source); + base.Write(buffer); return; } @@ -696,7 +696,7 @@ namespace System.IO EnsureWriteable(); // Check for overflow - int i = _position + source.Length; + int i = _position + buffer.Length; if (i < 0) throw new IOException(SR.IO_StreamTooLong); @@ -718,11 +718,11 @@ namespace System.IO _length = i; } - source.CopyTo(new Span(_buffer, _position, source.Length)); + buffer.CopyTo(new Span(_buffer, _position, buffer.Length)); _position = i; } - public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); @@ -752,7 +752,7 @@ namespace System.IO } } - public override ValueTask WriteAsync(ReadOnlyMemory source, CancellationToken cancellationToken = default(CancellationToken)) + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -763,13 +763,13 @@ namespace System.IO { // See corresponding comment in ReadAsync for why we don't just always use Write(ReadOnlySpan). // Unlike ReadAsync, we could delegate to WriteAsync(byte[], ...) here, but we don't for consistency. - if (MemoryMarshal.TryGetArray(source, out ArraySegment sourceArray)) + if (MemoryMarshal.TryGetArray(buffer, out ArraySegment sourceArray)) { Write(sourceArray.Array, sourceArray.Offset, sourceArray.Count); } else { - Write(source.Span); + Write(buffer.Span); } return default; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/Path.Unix.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/Path.Unix.cs index fd24cc810c..ecf71e6127 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/Path.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/Path.Unix.cs @@ -23,7 +23,7 @@ namespace System.IO if (path.Length == 0) throw new ArgumentException(SR.Arg_PathEmpty, nameof(path)); - if (path.IndexOf('\0') != -1) + if (path.Contains('\0')) throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path)); // Expand with current directory if necessary @@ -34,7 +34,7 @@ namespace System.IO // We would ideally use realpath to do this, but it resolves symlinks, requires that the file actually exist, // and turns it into a full path, which we only want if fullCheck is true. - string collapsedString = RemoveRelativeSegments(path); + string collapsedString = PathInternal.RemoveRelativeSegments(path, PathInternal.GetRootLength(path)); Debug.Assert(collapsedString.Length < path.Length || collapsedString.ToString() == path, "Either we've removed characters, or the string should be unmodified from the input path."); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/Path.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/Path.Windows.cs index b921db9e61..ddfd7966be 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/Path.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/Path.Windows.cs @@ -5,7 +5,14 @@ using System.Diagnostics; using System.Text; +#if MS_IO_REDIST +using System; +using System.IO; + +namespace Microsoft.IO +#else namespace System.IO +#endif { public static partial class Path { @@ -34,16 +41,16 @@ namespace System.IO throw new ArgumentNullException(nameof(path)); // If the path would normalize to string empty, we'll consider it empty - if (PathInternal.IsEffectivelyEmpty(path)) + if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) throw new ArgumentException(SR.Arg_PathEmpty, nameof(path)); // Embedded null characters are the only invalid character case we trully care about. // This is because the nulls will signal the end of the string to Win32 and therefore have // unpredictable results. - if (path.IndexOf('\0') != -1) + if (path.Contains('\0')) throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path)); - if (PathInternal.IsExtended(path)) + if (PathInternal.IsExtended(path.AsSpan())) { // \\?\ paths are considered normalized by definition. Windows doesn't normalize \\?\ // paths and neither should we. Even if we wanted to GetFullPathName does not work @@ -72,6 +79,9 @@ namespace System.IO if (IsPathFullyQualified(path)) return GetFullPath(path); + if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) + return basePath; + int length = path.Length; string combinedPath = null; @@ -80,30 +90,30 @@ namespace System.IO // Path is current drive rooted i.e. starts with \: // "\Foo" and "C:\Bar" => "C:\Foo" // "\Foo" and "\\?\C:\Bar" => "\\?\C:\Foo" - combinedPath = Join(GetPathRoot(basePath.AsSpan()), path); + combinedPath = Join(GetPathRoot(basePath.AsSpan()), path.AsSpan(1)); // Cut the separator to ensure we don't end up with two separators when joining with the root. } else if (length >= 2 && PathInternal.IsValidDriveChar(path[0]) && path[1] == PathInternal.VolumeSeparatorChar) { // Drive relative paths Debug.Assert(length == 2 || !PathInternal.IsDirectorySeparator(path[2])); - if (StringSpanHelpers.Equals(GetVolumeName(path), GetVolumeName(basePath))) + if (GetVolumeName(path.AsSpan()).EqualsOrdinal(GetVolumeName(basePath.AsSpan()))) { // Matching root // "C:Foo" and "C:\Bar" => "C:\Bar\Foo" // "C:Foo" and "\\?\C:\Bar" => "\\?\C:\Bar\Foo" - combinedPath = Join(basePath, path.AsSpan().Slice(2)); + combinedPath = Join(basePath.AsSpan(), path.AsSpan(2)); } else { // No matching root, root to specified drive // "D:Foo" and "C:\Bar" => "D:Foo" // "D:Foo" and "\\?\C:\Bar" => "\\?\D:\Foo" - combinedPath = !PathInternal.IsDevice(basePath) + combinedPath = !PathInternal.IsDevice(basePath.AsSpan()) ? path.Insert(2, @"\") : length == 2 - ? JoinInternal(basePath.AsSpan().Slice(0, 4), path, @"\") - : JoinInternal(basePath.AsSpan().Slice(0, 4), path.AsSpan().Slice(0, 2), @"\", path.AsSpan().Slice(2)); + ? JoinInternal(basePath.AsSpan(0, 4), path.AsSpan(), @"\".AsSpan()) + : JoinInternal(basePath.AsSpan(0, 4), path.AsSpan(0, 2), @"\".AsSpan(), path.AsSpan(2)); } } else @@ -111,37 +121,70 @@ namespace System.IO // "Simple" relative path // "Foo" and "C:\Bar" => "C:\Bar\Foo" // "Foo" and "\\?\C:\Bar" => "\\?\C:\Bar\Foo" - combinedPath = JoinInternal(basePath, path); + combinedPath = JoinInternal(basePath.AsSpan(), path.AsSpan()); } - // Device paths are normalized by definition, so passing something of this format - // to GetFullPath() won't do anything by design. Additionally, GetFullPathName() in - // Windows doesn't root them properly. As such we need to manually remove segments. - return PathInternal.IsDevice(combinedPath) - ? RemoveRelativeSegments(combinedPath, PathInternal.GetRootLength(combinedPath)) + // Device paths are normalized by definition, so passing something of this format (i.e. \\?\C:\.\tmp, \\.\C:\foo) + // to Windows APIs won't do anything by design. Additionally, GetFullPathName() in Windows doesn't root + // them properly. As such we need to manually remove segments and not use GetFullPath(). + + return PathInternal.IsDevice(combinedPath.AsSpan()) + ? PathInternal.RemoveRelativeSegments(combinedPath, PathInternal.GetRootLength(combinedPath.AsSpan())) : GetFullPath(combinedPath); } public static string GetTempPath() { - StringBuilder sb = StringBuilderCache.Acquire(Interop.Kernel32.MAX_PATH); - uint r = Interop.Kernel32.GetTempPathW(Interop.Kernel32.MAX_PATH, sb); - if (r == 0) + Span initialBuffer = stackalloc char[PathInternal.MaxShortPath]; + var builder = new ValueStringBuilder(initialBuffer); + + GetTempPath(ref builder); + + string path = PathHelper.Normalize(ref builder); + builder.Dispose(); + return path; + } + + private static void GetTempPath(ref ValueStringBuilder builder) + { + uint result = 0; + while ((result = Interop.Kernel32.GetTempPathW(builder.Capacity, ref builder.GetPinnableReference())) > builder.Capacity) + { + // Reported size is greater than the buffer size. Increase the capacity. + builder.EnsureCapacity(checked((int)result)); + } + + if (result == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); - return GetFullPath(StringBuilderCache.GetStringAndRelease(sb)); + + builder.Length = (int)result; } // Returns a unique temporary file name, and creates a 0-byte file by that // name on disk. public static string GetTempFileName() { - string path = GetTempPath(); + Span initialTempPathBuffer = stackalloc char[PathInternal.MaxShortPath]; + ValueStringBuilder tempPathBuilder = new ValueStringBuilder(initialTempPathBuffer); - StringBuilder sb = StringBuilderCache.Acquire(Interop.Kernel32.MAX_PATH); - uint r = Interop.Kernel32.GetTempFileNameW(path, "tmp", 0, sb); - if (r == 0) + GetTempPath(ref tempPathBuilder); + + Span initialBuffer = stackalloc char[PathInternal.MaxShortPath]; + var builder = new ValueStringBuilder(initialBuffer); + + uint result = Interop.Kernel32.GetTempFileNameW( + ref tempPathBuilder.GetPinnableReference(), "tmp", 0, ref builder.GetPinnableReference()); + + tempPathBuilder.Dispose(); + + if (result == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); - return StringBuilderCache.GetStringAndRelease(sb); + + builder.Length = builder.RawChars.IndexOf('\0'); + + string path = PathHelper.Normalize(ref builder); + builder.Dispose(); + return path; } // Tests if the given path contains a root. A path is considered rooted @@ -169,14 +212,14 @@ namespace System.IO // only contains whitespace characters an ArgumentException gets thrown. public static string GetPathRoot(string path) { - if (PathInternal.IsEffectivelyEmpty(path)) + if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) return null; ReadOnlySpan result = GetPathRoot(path.AsSpan()); if (path.Length == result.Length) return PathInternal.NormalizeDirectorySeparators(path); - return PathInternal.NormalizeDirectorySeparators(new string(result)); + return PathInternal.NormalizeDirectorySeparators(result.ToString()); } /// @@ -237,11 +280,11 @@ namespace System.IO { bool isDevice = PathInternal.IsDevice(path); - if (!isDevice && StringSpanHelpers.Equals(path.Slice(0, 2), @"\\") ) + if (!isDevice && path.Slice(0, 2).EqualsOrdinal(@"\\".AsSpan()) ) return 2; else if (isDevice && path.Length >= 8 - && (StringSpanHelpers.Equals(path.Slice(0, 8), PathInternal.UncExtendedPathPrefix) - || StringSpanHelpers.Equals(path.Slice(5, 4), @"UNC\"))) + && (path.Slice(0, 8).EqualsOrdinal(PathInternal.UncExtendedPathPrefix.AsSpan()) + || path.Slice(5, 4).EqualsOrdinal(@"UNC\".AsSpan()))) return 8; return -1; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/Path.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/Path.cs index 41ae1cd0be..7b4565a130 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/Path.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/Path.cs @@ -6,7 +6,14 @@ using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; +#if MS_IO_REDIST +using System; +using System.IO; + +namespace Microsoft.IO +#else namespace System.IO +#endif { // Provides methods for processing file system strings in a cross-platform manner. // Most of the methods don't do a complete parsing (such as examining a UNC hostname), @@ -79,10 +86,10 @@ namespace System.IO /// public static string GetDirectoryName(string path) { - if (path == null || PathInternal.IsEffectivelyEmpty(path)) + if (path == null || PathInternal.IsEffectivelyEmpty(path.AsSpan())) return null; - int end = GetDirectoryNameOffset(path); + int end = GetDirectoryNameOffset(path.AsSpan()); return end >= 0 ? PathInternal.NormalizeDirectorySeparators(path.Substring(0, end)) : null; } @@ -130,7 +137,7 @@ namespace System.IO if (path == null) return null; - return new string(GetExtension(path.AsSpan())); + return GetExtension(path.AsSpan()).ToString(); } /// @@ -173,7 +180,7 @@ namespace System.IO if (path.Length == result.Length) return path; - return new string(result); + return result.ToString(); } /// @@ -204,7 +211,7 @@ namespace System.IO if (path.Length == result.Length) return path; - return new string(result); + return result.ToString(); } /// @@ -388,9 +395,9 @@ namespace System.IO public static string Join(ReadOnlySpan path1, ReadOnlySpan path2) { if (path1.Length == 0) - return new string(path2); + return path2.ToString(); if (path2.Length == 0) - return new string(path1); + return path1.ToString(); return JoinInternal(path1, path2); } @@ -409,6 +416,16 @@ namespace System.IO return JoinInternal(path1, path2, path3); } + public static string Join(string path1, string path2) + { + return Join(path1.AsSpan(), path2.AsSpan()); + } + + public static string Join(string path1, string path2, string path3) + { + return Join(path1.AsSpan(), path2.AsSpan(), path3.AsSpan()); + } + public static bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, Span destination, out int charsWritten) { charsWritten = 0; @@ -477,22 +494,6 @@ namespace System.IO return true; } - private static string CombineInternal(ReadOnlySpan first, ReadOnlySpan second) - { - if (first.Length == 0) - return second.Length == 0 - ? string.Empty - : new string(second); - - if (second.Length == 0) - return new string(first); - - if (IsPathRooted(second)) - return new string(second); - - return JoinInternal(first, second); - } - private static string CombineInternal(string first, string second) { if (string.IsNullOrEmpty(first)) @@ -504,7 +505,7 @@ namespace System.IO if (IsPathRooted(second.AsSpan())) return second; - return JoinInternal(first, second); + return JoinInternal(first.AsSpan(), second.AsSpan()); } private static string CombineInternal(string first, string second, string third) @@ -521,7 +522,7 @@ namespace System.IO if (IsPathRooted(second.AsSpan())) return CombineInternal(second, third); - return JoinInternal(first, second, third); + return JoinInternal(first.AsSpan(), second.AsSpan(), third.AsSpan()); } private static string CombineInternal(string first, string second, string third, string fourth) @@ -542,10 +543,10 @@ namespace System.IO if (IsPathRooted(second.AsSpan())) return CombineInternal(second, third, fourth); - return JoinInternal(first, second, third, fourth); + return JoinInternal(first.AsSpan(), second.AsSpan(), third.AsSpan(), fourth.AsSpan()); } - private unsafe static string JoinInternal(ReadOnlySpan first, ReadOnlySpan second) + private static unsafe string JoinInternal(ReadOnlySpan first, ReadOnlySpan second) { Debug.Assert(first.Length > 0 && second.Length > 0, "should have dealt with empty paths"); @@ -554,7 +555,11 @@ namespace System.IO fixed (char* f = &MemoryMarshal.GetReference(first), s = &MemoryMarshal.GetReference(second)) { +#if MS_IO_REDIST + return StringExtensions.Create( +#else return string.Create( +#endif first.Length + second.Length + (hasSeparator ? 0 : 1), (First: (IntPtr)f, FirstLength: first.Length, Second: (IntPtr)s, SecondLength: second.Length, HasSeparator: hasSeparator), (destination, state) => @@ -567,7 +572,7 @@ namespace System.IO } } - private unsafe static string JoinInternal(ReadOnlySpan first, ReadOnlySpan second, ReadOnlySpan third) + private static unsafe string JoinInternal(ReadOnlySpan first, ReadOnlySpan second, ReadOnlySpan third) { Debug.Assert(first.Length > 0 && second.Length > 0 && third.Length > 0, "should have dealt with empty paths"); @@ -578,7 +583,11 @@ namespace System.IO fixed (char* f = &MemoryMarshal.GetReference(first), s = &MemoryMarshal.GetReference(second), t = &MemoryMarshal.GetReference(third)) { +#if MS_IO_REDIST + return StringExtensions.Create( +#else return string.Create( +#endif first.Length + second.Length + third.Length + (firstHasSeparator ? 0 : 1) + (thirdHasSeparator ? 0 : 1), (First: (IntPtr)f, FirstLength: first.Length, Second: (IntPtr)s, SecondLength: second.Length, Third: (IntPtr)t, ThirdLength: third.Length, FirstHasSeparator: firstHasSeparator, ThirdHasSeparator: thirdHasSeparator), @@ -595,7 +604,7 @@ namespace System.IO } } - private unsafe static string JoinInternal(ReadOnlySpan first, ReadOnlySpan second, ReadOnlySpan third, ReadOnlySpan fourth) + private static unsafe string JoinInternal(ReadOnlySpan first, ReadOnlySpan second, ReadOnlySpan third, ReadOnlySpan fourth) { Debug.Assert(first.Length > 0 && second.Length > 0 && third.Length > 0 && fourth.Length > 0, "should have dealt with empty paths"); @@ -608,7 +617,12 @@ namespace System.IO fixed (char* f = &MemoryMarshal.GetReference(first), s = &MemoryMarshal.GetReference(second), t = &MemoryMarshal.GetReference(third), u = &MemoryMarshal.GetReference(fourth)) { + +#if MS_IO_REDIST + return StringExtensions.Create( +#else return string.Create( +#endif first.Length + second.Length + third.Length + fourth.Length + (firstHasSeparator ? 0 : 1) + (thirdHasSeparator ? 0 : 1) + (fourthHasSeparator ? 0 : 1), (First: (IntPtr)f, FirstLength: first.Length, Second: (IntPtr)s, SecondLength: second.Length, Third: (IntPtr)t, ThirdLength: third.Length, Fourth: (IntPtr)u, FourthLength:fourth.Length, @@ -687,93 +701,6 @@ namespace System.IO chars[11] = s_base32Char[(bytes[7] & 0x1F)]; } - /// - /// Try to remove relative segments from the given path (without combining with a root). - /// - /// Skip the specified number of characters before evaluating. - private static string RemoveRelativeSegments(string path, int skip = 0) - { - bool flippedSeparator = false; - - // Remove "//", "/./", and "/../" from the path by copying each character to the output, - // except the ones we're removing, such that the builder contains the normalized path - // at the end. - StringBuilder sb = StringBuilderCache.Acquire(path.Length); - if (skip > 0) - { - sb.Append(path, 0, skip); - } - - for (int i = skip; i < path.Length; i++) - { - char c = path[i]; - - if (PathInternal.IsDirectorySeparator(c) && i + 1 < path.Length) - { - // Skip this character if it's a directory separator and if the next character is, too, - // e.g. "parent//child" => "parent/child" - if (PathInternal.IsDirectorySeparator(path[i + 1])) - { - continue; - } - - // Skip this character and the next if it's referring to the current directory, - // e.g. "parent/./child" => "parent/child" - if ((i + 2 == path.Length || PathInternal.IsDirectorySeparator(path[i + 2])) && - path[i + 1] == '.') - { - i++; - continue; - } - - // Skip this character and the next two if it's referring to the parent directory, - // e.g. "parent/child/../grandchild" => "parent/grandchild" - if (i + 2 < path.Length && - (i + 3 == path.Length || PathInternal.IsDirectorySeparator(path[i + 3])) && - path[i + 1] == '.' && path[i + 2] == '.') - { - // Unwind back to the last slash (and if there isn't one, clear out everything). - int s; - for (s = sb.Length - 1; s >= 0; s--) - { - if (PathInternal.IsDirectorySeparator(sb[s])) - { - sb.Length = s; - break; - } - } - if (s < 0) - { - sb.Length = 0; - } - - i += 2; - continue; - } - } - - // Normalize the directory separator if needed - if (c != PathInternal.DirectorySeparatorChar && c == PathInternal.AltDirectorySeparatorChar) - { - c = PathInternal.DirectorySeparatorChar; - flippedSeparator = true; - } - - sb.Append(c); - } - - if (flippedSeparator || sb.Length != path.Length) - { - return StringBuilderCache.GetStringAndRelease(sb); - } - else - { - // We haven't changed the source path, return the original - StringBuilderCache.Release(sb); - return path; - } - } - /// /// Create a relative path from one path to another. Paths will be resolved before calculating the difference. /// Default path comparison for the active platform will be used (OrdinalIgnoreCase for Windows or Mac, Ordinal for Unix). @@ -790,7 +717,7 @@ namespace System.IO private static string GetRelativePath(string relativeTo, string path, StringComparison comparisonType) { if (string.IsNullOrEmpty(relativeTo)) throw new ArgumentNullException(nameof(relativeTo)); - if (PathInternal.IsEffectivelyEmpty(path)) throw new ArgumentNullException(nameof(path)); + if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) throw new ArgumentNullException(nameof(path)); Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase); relativeTo = GetFullPath(relativeTo); @@ -808,10 +735,10 @@ namespace System.IO // Trailing separators aren't significant for comparison int relativeToLength = relativeTo.Length; - if (PathInternal.EndsInDirectorySeparator(relativeTo)) + if (PathInternal.EndsInDirectorySeparator(relativeTo.AsSpan())) relativeToLength--; - bool pathEndsInSeparator = PathInternal.EndsInDirectorySeparator(path); + bool pathEndsInSeparator = PathInternal.EndsInDirectorySeparator(path.AsSpan()); int pathLength = path.Length; if (pathEndsInSeparator) pathLength--; @@ -834,13 +761,14 @@ namespace System.IO // Add parent segments for segments past the common on the "from" path if (commonLength < relativeToLength) { - sb.Append(PathInternal.ParentDirectoryPrefix); + sb.Append(".."); - for (int i = commonLength; i < relativeToLength; i++) + for (int i = commonLength + 1; i < relativeToLength; i++) { if (PathInternal.IsDirectorySeparator(relativeTo[i])) { - sb.Append(PathInternal.ParentDirectoryPrefix); + sb.Append(DirectorySeparatorChar); + sb.Append(".."); } } } @@ -852,11 +780,20 @@ namespace System.IO } // Now add the rest of the "to" path, adding back the trailing separator - int count = pathLength - commonLength; + int differenceLength = pathLength - commonLength; if (pathEndsInSeparator) - count++; + differenceLength++; + + if (differenceLength > 0) + { + if (sb.Length > 0) + { + sb.Append(DirectorySeparatorChar); + } + + sb.Append(path, commonLength, differenceLength); + } - sb.Append(path, commonLength, count); return StringBuilderCache.GetStringAndRelease(sb); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/PathHelper.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/PathHelper.Windows.cs index 74ceed10aa..bada2f5cd5 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/PathHelper.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/PathHelper.Windows.cs @@ -26,30 +26,57 @@ namespace System.IO internal static string Normalize(string path) { Span initialBuffer = stackalloc char[PathInternal.MaxShortPath]; - ValueStringBuilder builder = new ValueStringBuilder(initialBuffer); + var builder = new ValueStringBuilder(initialBuffer); // Get the full path - GetFullPathName(path, ref builder); + GetFullPathName(path.AsSpan(), ref builder); // If we have the exact same string we were passed in, don't allocate another string. // TryExpandShortName does this input identity check. - string result = builder.AsSpan().Contains('~') + string result = builder.AsSpan().IndexOf('~') >= 0 ? TryExpandShortFileName(ref builder, originalPath: path) - : builder.AsSpan().Equals(path.AsSpan()) ? path : builder.ToString(); + : builder.AsSpan().Equals(path.AsSpan(), StringComparison.Ordinal) ? path : builder.ToString(); // Clear the buffer builder.Dispose(); return result; } - private static void GetFullPathName(string path, ref ValueStringBuilder builder) + /// + /// Normalize the given path. + /// + /// + /// Exceptions are the same as the string overload. + /// + internal static string Normalize(ref ValueStringBuilder path) + { + Span initialBuffer = stackalloc char[PathInternal.MaxShortPath]; + var builder = new ValueStringBuilder(initialBuffer); + + // Get the full path + GetFullPathName(path.AsSpan(terminate: true), ref builder); + + string result = builder.AsSpan().IndexOf('~') >= 0 + ? TryExpandShortFileName(ref builder, originalPath: null) + : builder.ToString(); + + // Clear the buffer + builder.Dispose(); + return result; + } + + /// + /// Calls GetFullPathName on the given path. + /// + /// The path name. MUST be null terminated after the span. + private static void GetFullPathName(ReadOnlySpan path, ref ValueStringBuilder builder) { // If the string starts with an extended prefix we would need to remove it from the path before we call GetFullPathName as // it doesn't root extended paths correctly. We don't currently resolve extended paths, so we'll just assert here. Debug.Assert(PathInternal.IsPartiallyQualified(path) || !PathInternal.IsExtended(path)); uint result = 0; - while ((result = Interop.Kernel32.GetFullPathNameW(path, (uint)builder.Capacity, ref builder.GetPinnableReference(), IntPtr.Zero)) > builder.Capacity) + while ((result = Interop.Kernel32.GetFullPathNameW(ref MemoryMarshal.GetReference(path), (uint)builder.Capacity, ref builder.GetPinnableReference(), IntPtr.Zero)) > builder.Capacity) { // Reported size is greater than the buffer size. Increase the capacity. builder.EnsureCapacity(checked((int)result)); @@ -61,13 +88,13 @@ namespace System.IO int errorCode = Marshal.GetLastWin32Error(); if (errorCode == 0) errorCode = Interop.Errors.ERROR_BAD_PATHNAME; - throw Win32Marshal.GetExceptionForWin32Error(errorCode, path); + throw Win32Marshal.GetExceptionForWin32Error(errorCode, path.ToString()); } builder.Length = (int)result; } - private static int PrependDevicePathChars(ref ValueStringBuilder content, bool isDosUnc, ref ValueStringBuilder buffer) + internal static int PrependDevicePathChars(ref ValueStringBuilder content, bool isDosUnc, ref ValueStringBuilder buffer) { int length = content.Length; @@ -84,7 +111,7 @@ namespace System.IO buffer.Append(PathInternal.UncExtendedPathPrefix); // Copy Server\Share\... over to the buffer - buffer.Append(content.AsSpan().Slice(PathInternal.UncPrefixLength)); + buffer.Append(content.AsSpan(PathInternal.UncPrefixLength)); // Return the prefix difference return PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength; @@ -98,7 +125,7 @@ namespace System.IO } } - private static string TryExpandShortFileName(ref ValueStringBuilder outputBuilder, string originalPath) + internal static string TryExpandShortFileName(ref ValueStringBuilder outputBuilder, string originalPath) { // We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To // avoid allocating like crazy we'll create only one input array and modify the contents with embedded nulls. @@ -119,7 +146,7 @@ namespace System.IO bool isDevice = PathInternal.IsDevice(outputBuilder.AsSpan()); // As this is a corner case we're not going to add a stackalloc here to keep the stack pressure down. - ValueStringBuilder inputBuilder = new ValueStringBuilder(); + var inputBuilder = new ValueStringBuilder(); bool isDosUnc = false; int rootDifference = 0; @@ -149,12 +176,10 @@ namespace System.IO bool success = false; int foundIndex = inputBuilder.Length - 1; - // Need to null terminate the input builder - inputBuilder.Append('\0'); - while (!success) { - uint result = Interop.Kernel32.GetLongPathNameW(ref inputBuilder.GetPinnableReference(), ref outputBuilder.GetPinnableReference(), (uint)outputBuilder.Capacity); + uint result = Interop.Kernel32.GetLongPathNameW( + ref inputBuilder.GetPinnableReference(terminate: true), ref outputBuilder.GetPinnableReference(), (uint)outputBuilder.Capacity); // Replace any temporary null we added if (inputBuilder[foundIndex] == '\0') inputBuilder[foundIndex] = '\\'; @@ -198,14 +223,11 @@ namespace System.IO if (foundIndex < inputLength - 1) { // It was a partial find, put the non-existent part of the path back - outputBuilder.Append(inputBuilder.AsSpan().Slice(foundIndex, inputBuilder.Length - foundIndex)); + outputBuilder.Append(inputBuilder.AsSpan(foundIndex, inputBuilder.Length - foundIndex)); } } } - // Need to trim out the trailing separator in the input builder - inputBuilder.Length = inputBuilder.Length - 1; - // If we were able to expand the path, use it, otherwise use the original full path result ref ValueStringBuilder builderToUse = ref (success ? ref outputBuilder : ref inputBuilder); @@ -218,10 +240,10 @@ namespace System.IO builderToUse[PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength] = '\\'; // Strip out any added characters at the front of the string - ReadOnlySpan output = builderToUse.AsSpan().Slice(rootDifference); + ReadOnlySpan output = builderToUse.AsSpan(rootDifference); - string returnValue = output.Equals(originalPath.AsSpan()) - ? originalPath : new string(output); + string returnValue = ((originalPath != null) && output.Equals(originalPath.AsSpan(), StringComparison.Ordinal)) + ? originalPath : output.ToString(); inputBuilder.Dispose(); return returnValue; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/PathInternal.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/PathInternal.Windows.cs index 81d51ba4b4..5f9ee0e02d 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/PathInternal.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/PathInternal.Windows.cs @@ -70,7 +70,7 @@ namespace System.IO return ((value >= 'A' && value <= 'Z') || (value >= 'a' && value <= 'z')); } - private static bool EndsWithPeriodOrSpace(string path) + internal static bool EndsWithPeriodOrSpace(string path) { if (string.IsNullOrEmpty(path)) return false; @@ -130,7 +130,7 @@ namespace System.IO // In any case, all internal usages should be hitting normalize path (Path.GetFullPath) before they hit this // shimming method. (Or making a change that doesn't impact normalization, such as adding a filename to a // normalized base path.) - if (IsPartiallyQualified(path) || IsDevice(path)) + if (IsPartiallyQualified(path.AsSpan()) || IsDevice(path.AsSpan())) return path; // Given \\server\share in longpath becomes \\?\UNC\server\share @@ -270,19 +270,6 @@ namespace System.IO return i; } - private static bool StartsWithOrdinal(ReadOnlySpan source, string value) - { - if (source.Length < value.Length) - return false; - - for (int i = 0; i < value.Length; i++) - { - if (value[i] != source[i]) - return false; - } - return true; - } - /// /// Returns true if the path specified is relative to the current drive or working directory. /// Returns false if the path is fixed to a specific drive or UNC path. This method does no diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/PathInternal.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/PathInternal.cs index eb06c2608c..1b08a2612f 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/PathInternal.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/PathInternal.cs @@ -2,6 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Diagnostics; +using System.Text; + namespace System.IO { /// Contains internal path helpers that are shared between many projects. @@ -19,10 +22,10 @@ namespace System.IO internal static bool StartsWithDirectorySeparator(ReadOnlySpan path) => path.Length > 0 && IsDirectorySeparator(path[0]); internal static string EnsureTrailingSeparator(string path) - => EndsInDirectorySeparator(path) ? path : path + DirectorySeparatorCharAsString; + => EndsInDirectorySeparator(path.AsSpan()) ? path : path + DirectorySeparatorCharAsString; internal static string TrimEndingDirectorySeparator(string path) => - EndsInDirectorySeparator(path) && !IsRoot(path) ? + EndsInDirectorySeparator(path.AsSpan()) && !IsRoot(path.AsSpan()) ? path.Substring(0, path.Length - 1) : path; @@ -63,7 +66,7 @@ namespace System.IO /// /// Gets the count of common characters from the left optionally ignoring case /// - unsafe internal static int EqualStartingCharacterCount(string first, string second, bool ignoreCase) + internal static unsafe int EqualStartingCharacterCount(string first, string second, bool ignoreCase) { if (string.IsNullOrEmpty(first) || string.IsNullOrEmpty(second)) return 0; @@ -94,8 +97,8 @@ namespace System.IO /// internal static bool AreRootsEqual(string first, string second, StringComparison comparisonType) { - int firstRootLength = GetRootLength(first); - int secondRootLength = GetRootLength(second); + int firstRootLength = GetRootLength(first.AsSpan()); + int secondRootLength = GetRootLength(second.AsSpan()); return firstRootLength == secondRootLength && string.Compare( @@ -106,5 +109,121 @@ namespace System.IO length: firstRootLength, comparisonType: comparisonType) == 0; } + + /// + /// Try to remove relative segments from the given path (without combining with a root). + /// + /// The length of the root of the given path + internal static string RemoveRelativeSegments(string path, int rootLength) + { + Span initialBuffer = stackalloc char[260 /* PathInternal.MaxShortPath */]; + ValueStringBuilder sb = new ValueStringBuilder(initialBuffer); + + if (RemoveRelativeSegments(path.AsSpan(), rootLength, ref sb)) + { + path = sb.ToString(); + } + + sb.Dispose(); + return path; + } + + /// + /// Try to remove relative segments from the given path (without combining with a root). + /// + /// The length of the root of the given path + /// "true" if the path was modified + internal static bool RemoveRelativeSegments(ReadOnlySpan path, int rootLength, ref ValueStringBuilder sb) + { + Debug.Assert(rootLength > 0); + bool flippedSeparator = false; + + int skip = rootLength; + // We treat "\.." , "\." and "\\" as a relative segment. We want to collapse the first separator past the root presuming + // the root actually ends in a separator. Otherwise the first segment for RemoveRelativeSegments + // in cases like "\\?\C:\.\" and "\\?\C:\..\", the first segment after the root will be ".\" and "..\" which is not considered as a relative segment and hence not be removed. + if (PathInternal.IsDirectorySeparator(path[skip - 1])) + skip--; + + // Remove "//", "/./", and "/../" from the path by copying each character to the output, + // except the ones we're removing, such that the builder contains the normalized path + // at the end. + if (skip > 0) + { + sb.Append(path.Slice(0, skip)); + } + + for (int i = skip; i < path.Length; i++) + { + char c = path[i]; + + if (PathInternal.IsDirectorySeparator(c) && i + 1 < path.Length) + { + // Skip this character if it's a directory separator and if the next character is, too, + // e.g. "parent//child" => "parent/child" + if (PathInternal.IsDirectorySeparator(path[i + 1])) + { + continue; + } + + // Skip this character and the next if it's referring to the current directory, + // e.g. "parent/./child" => "parent/child" + if ((i + 2 == path.Length || PathInternal.IsDirectorySeparator(path[i + 2])) && + path[i + 1] == '.') + { + i++; + continue; + } + + // Skip this character and the next two if it's referring to the parent directory, + // e.g. "parent/child/../grandchild" => "parent/grandchild" + if (i + 2 < path.Length && + (i + 3 == path.Length || PathInternal.IsDirectorySeparator(path[i + 3])) && + path[i + 1] == '.' && path[i + 2] == '.') + { + // Unwind back to the last slash (and if there isn't one, clear out everything). + int s; + for (s = sb.Length - 1; s >= skip; s--) + { + if (PathInternal.IsDirectorySeparator(sb[s])) + { + sb.Length = (i + 3 >= path.Length && s == skip) ? s + 1 : s; // to avoid removing the complete "\tmp\" segment in cases like \\?\C:\tmp\..\, C:\tmp\.. + break; + } + } + if (s < skip) + { + sb.Length = skip; + } + + i += 2; + continue; + } + } + + // Normalize the directory separator if needed + if (c != PathInternal.DirectorySeparatorChar && c == PathInternal.AltDirectorySeparatorChar) + { + c = PathInternal.DirectorySeparatorChar; + flippedSeparator = true; + } + + sb.Append(c); + } + + // If we haven't changed the source path, return the original + if (!flippedSeparator && sb.Length == path.Length) + { + return false; + } + + // We may have eaten the trailing separator from the root when we started and not replaced it + if (skip != rootLength && sb.Length < rootLength) + { + sb.Append(path[rootLength - 1]); + } + + return true; + } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/PinnedBufferMemoryStream.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/PinnedBufferMemoryStream.cs index dfcc05d066..94331a2ef8 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/PinnedBufferMemoryStream.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/PinnedBufferMemoryStream.cs @@ -38,9 +38,9 @@ namespace System.IO Initialize(ptr, len, len, FileAccess.Read); } - public override int Read(Span destination) => ReadCore(destination); + public override int Read(Span buffer) => ReadCore(buffer); - public override void Write(ReadOnlySpan source) => WriteCore(source); + public override void Write(ReadOnlySpan buffer) => WriteCore(buffer); ~PinnedBufferMemoryStream() { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/Stream.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/Stream.cs new file mode 100644 index 0000000000..faeb69fb54 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/Stream.cs @@ -0,0 +1,1322 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/*============================================================ +** +** +** +** +** +** Purpose: Abstract base class for all Streams. Provides +** default implementations of asynchronous reads & writes, in +** terms of the synchronous reads & writes (and vice versa). +** +** +===========================================================*/ + +using System.Buffers; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; + +namespace System.IO +{ + public abstract partial class Stream : MarshalByRefObject, IDisposable + { + public static readonly Stream Null = new NullStream(); + + // We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K). + // The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant + // improvement in Copy performance. + private const int DefaultCopyBufferSize = 81920; + + // To implement Async IO operations on streams that don't support async IO + + private ReadWriteTask _activeReadWriteTask; + private SemaphoreSlim _asyncActiveSemaphore; + + internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() + { + // Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's + // WaitHandle, we don't need to worry about Disposing it. + return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); + } + + public abstract bool CanRead + { + get; + } + + // If CanSeek is false, Position, Seek, Length, and SetLength should throw. + public abstract bool CanSeek + { + get; + } + + public virtual bool CanTimeout + { + get + { + return false; + } + } + + public abstract bool CanWrite + { + get; + } + + public abstract long Length + { + get; + } + + public abstract long Position + { + get; + set; + } + + public virtual int ReadTimeout + { + get + { + throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); + } + set + { + throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); + } + } + + public virtual int WriteTimeout + { + get + { + throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); + } + set + { + throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); + } + } + + public Task CopyToAsync(Stream destination) + { + int bufferSize = GetCopyBufferSize(); + + return CopyToAsync(destination, bufferSize); + } + + public Task CopyToAsync(Stream destination, int bufferSize) + { + return CopyToAsync(destination, bufferSize, CancellationToken.None); + } + + public Task CopyToAsync(Stream destination, CancellationToken cancellationToken) + { + int bufferSize = GetCopyBufferSize(); + + return CopyToAsync(destination, bufferSize, cancellationToken); + } + + public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) + { + StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); + + return CopyToAsyncInternal(destination, bufferSize, cancellationToken); + } + + private async Task CopyToAsyncInternal(Stream destination, int bufferSize, CancellationToken cancellationToken) + { + byte[] buffer = ArrayPool.Shared.Rent(bufferSize); + try + { + while (true) + { + int bytesRead = await ReadAsync(new Memory(buffer), cancellationToken).ConfigureAwait(false); + if (bytesRead == 0) break; + await destination.WriteAsync(new ReadOnlyMemory(buffer, 0, bytesRead), cancellationToken).ConfigureAwait(false); + } + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + // Reads the bytes from the current stream and writes the bytes to + // the destination stream until all bytes are read, starting at + // the current position. + public void CopyTo(Stream destination) + { + int bufferSize = GetCopyBufferSize(); + + CopyTo(destination, bufferSize); + } + + public virtual void CopyTo(Stream destination, int bufferSize) + { + StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); + + byte[] buffer = ArrayPool.Shared.Rent(bufferSize); + try + { + int read; + while ((read = Read(buffer, 0, buffer.Length)) != 0) + { + destination.Write(buffer, 0, read); + } + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + private int GetCopyBufferSize() + { + int bufferSize = DefaultCopyBufferSize; + + if (CanSeek) + { + long length = Length; + long position = Position; + if (length <= position) // Handles negative overflows + { + // There are no bytes left in the stream to copy. + // However, because CopyTo{Async} is virtual, we need to + // ensure that any override is still invoked to provide its + // own validation, so we use the smallest legal buffer size here. + bufferSize = 1; + } + else + { + long remaining = length - position; + if (remaining > 0) + { + // In the case of a positive overflow, stick to the default size + bufferSize = (int)Math.Min(bufferSize, remaining); + } + } + } + + return bufferSize; + } + + // Stream used to require that all cleanup logic went into Close(), + // which was thought up before we invented IDisposable. However, we + // need to follow the IDisposable pattern so that users can write + // sensible subclasses without needing to inspect all their base + // classes, and without worrying about version brittleness, from a + // base class switching to the Dispose pattern. We're moving + // Stream to the Dispose(bool) pattern - that's where all subclasses + // should put their cleanup now. + public virtual void Close() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + public void Dispose() + { + Close(); + } + + protected virtual void Dispose(bool disposing) + { + // Note: Never change this to call other virtual methods on Stream + // like Write, since the state on subclasses has already been + // torn down. This is the last code to run on cleanup for a stream. + } + + public abstract void Flush(); + + public Task FlushAsync() + { + return FlushAsync(CancellationToken.None); + } + + public virtual Task FlushAsync(CancellationToken cancellationToken) + { + return Task.Factory.StartNew(state => ((Stream)state).Flush(), this, + cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); + } + + [Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")] + protected virtual WaitHandle CreateWaitHandle() + { + return new ManualResetEvent(false); + } + + public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); + } + + internal IAsyncResult BeginReadInternal( + byte[] buffer, int offset, int count, AsyncCallback callback, object state, + bool serializeAsynchronously, bool apm) + { + if (!CanRead) throw Error.GetReadNotSupported(); + + // To avoid a race with a stream's position pointer & generating race conditions + // with internal buffer indexes in our own streams that + // don't natively support async IO operations when there are multiple + // async requests outstanding, we will block the application's main + // thread if it does a second IO request until the first one completes. + var semaphore = EnsureAsyncActiveSemaphoreInitialized(); + Task semaphoreTask = null; + if (serializeAsynchronously) + { + semaphoreTask = semaphore.WaitAsync(); + } + else + { + semaphore.Wait(); + } + + // Create the task to asynchronously do a Read. This task serves both + // as the asynchronous work item and as the IAsyncResult returned to the user. + var asyncResult = new ReadWriteTask(true /*isRead*/, apm, delegate + { + // The ReadWriteTask stores all of the parameters to pass to Read. + // As we're currently inside of it, we can get the current task + // and grab the parameters from it. + var thisTask = Task.InternalCurrent as ReadWriteTask; + Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask"); + + try + { + // Do the Read and return the number of bytes read + return thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count); + } + finally + { + // If this implementation is part of Begin/EndXx, then the EndXx method will handle + // finishing the async operation. However, if this is part of XxAsync, then there won't + // be an end method, and this task is responsible for cleaning up. + if (!thisTask._apm) + { + thisTask._stream.FinishTrackingAsyncOperation(); + } + + thisTask.ClearBeginState(); // just to help alleviate some memory pressure + } + }, state, this, buffer, offset, count, callback); + + // Schedule it + if (semaphoreTask != null) + RunReadWriteTaskWhenReady(semaphoreTask, asyncResult); + else + RunReadWriteTask(asyncResult); + + + return asyncResult; // return it + } + + public virtual int EndRead(IAsyncResult asyncResult) + { + if (asyncResult == null) + throw new ArgumentNullException(nameof(asyncResult)); + + var readTask = _activeReadWriteTask; + + if (readTask == null) + { + throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple); + } + else if (readTask != asyncResult) + { + throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple); + } + else if (!readTask._isRead) + { + throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple); + } + + try + { + return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception + } + finally + { + FinishTrackingAsyncOperation(); + } + } + + public Task ReadAsync(byte[] buffer, int offset, int count) + { + return ReadAsync(buffer, offset, count, CancellationToken.None); + } + + public virtual Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + // If cancellation was requested, bail early with an already completed task. + // Otherwise, return a task that represents the Begin/End methods. + return cancellationToken.IsCancellationRequested + ? Task.FromCanceled(cancellationToken) + : BeginEndReadAsync(buffer, offset, count); + } + + public virtual ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (MemoryMarshal.TryGetArray(buffer, out ArraySegment array)) + { + return new ValueTask(ReadAsync(array.Array, array.Offset, array.Count, cancellationToken)); + } + else + { + byte[] sharedBuffer = ArrayPool.Shared.Rent(buffer.Length); + return FinishReadAsync(ReadAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer, buffer); + + async ValueTask FinishReadAsync(Task readTask, byte[] localBuffer, Memory localDestination) + { + try + { + int result = await readTask.ConfigureAwait(false); + new Span(localBuffer, 0, result).CopyTo(localDestination.Span); + return result; + } + finally + { + ArrayPool.Shared.Return(localBuffer); + } + } + } + } + + private Task BeginEndReadAsync(byte[] buffer, int offset, int count) + { + if (!HasOverriddenBeginEndRead()) + { + // If the Stream does not override Begin/EndRead, then we can take an optimized path + // that skips an extra layer of tasks / IAsyncResults. + return (Task)BeginReadInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false); + } + + // Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality. + return TaskFactory.FromAsyncTrim( + this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count }, + (stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler + (stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler + } + + private struct ReadWriteParameters // struct for arguments to Read and Write calls + { + internal byte[] Buffer; + internal int Offset; + internal int Count; + } + + + + public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); + } + + internal IAsyncResult BeginWriteInternal( + byte[] buffer, int offset, int count, AsyncCallback callback, object state, + bool serializeAsynchronously, bool apm) + { + if (!CanWrite) throw Error.GetWriteNotSupported(); + + // To avoid a race condition with a stream's position pointer & generating conditions + // with internal buffer indexes in our own streams that + // don't natively support async IO operations when there are multiple + // async requests outstanding, we will block the application's main + // thread if it does a second IO request until the first one completes. + var semaphore = EnsureAsyncActiveSemaphoreInitialized(); + Task semaphoreTask = null; + if (serializeAsynchronously) + { + semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block + } + else + { + semaphore.Wait(); // synchronously wait here + } + + // Create the task to asynchronously do a Write. This task serves both + // as the asynchronous work item and as the IAsyncResult returned to the user. + var asyncResult = new ReadWriteTask(false /*isRead*/, apm, delegate + { + // The ReadWriteTask stores all of the parameters to pass to Write. + // As we're currently inside of it, we can get the current task + // and grab the parameters from it. + var thisTask = Task.InternalCurrent as ReadWriteTask; + Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask"); + + try + { + // Do the Write + thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count); + return 0; // not used, but signature requires a value be returned + } + finally + { + // If this implementation is part of Begin/EndXx, then the EndXx method will handle + // finishing the async operation. However, if this is part of XxAsync, then there won't + // be an end method, and this task is responsible for cleaning up. + if (!thisTask._apm) + { + thisTask._stream.FinishTrackingAsyncOperation(); + } + + thisTask.ClearBeginState(); // just to help alleviate some memory pressure + } + }, state, this, buffer, offset, count, callback); + + // Schedule it + if (semaphoreTask != null) + RunReadWriteTaskWhenReady(semaphoreTask, asyncResult); + else + RunReadWriteTask(asyncResult); + + return asyncResult; // return it + } + + private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask) + { + Debug.Assert(readWriteTask != null); + Debug.Assert(asyncWaiter != null); + + // If the wait has already completed, run the task. + if (asyncWaiter.IsCompleted) + { + Debug.Assert(asyncWaiter.IsCompletedSuccessfully, "The semaphore wait should always complete successfully."); + RunReadWriteTask(readWriteTask); + } + else // Otherwise, wait for our turn, and then run the task. + { + asyncWaiter.ContinueWith((t, state) => + { + Debug.Assert(t.IsCompletedSuccessfully, "The semaphore wait should always complete successfully."); + var rwt = (ReadWriteTask)state; + rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask); + }, readWriteTask, default, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + } + + private void RunReadWriteTask(ReadWriteTask readWriteTask) + { + Debug.Assert(readWriteTask != null); + Debug.Assert(_activeReadWriteTask == null, "Expected no other readers or writers"); + + // Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race. + // Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding + // two interlocked operations. However, if ReadWriteTask is ever changed to use + // a cancellation token, this should be changed to use Start. + _activeReadWriteTask = readWriteTask; // store the task so that EndXx can validate it's given the right one + readWriteTask.m_taskScheduler = TaskScheduler.Default; + readWriteTask.ScheduleAndStart(needsProtection: false); + } + + private void FinishTrackingAsyncOperation() + { + _activeReadWriteTask = null; + Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here."); + _asyncActiveSemaphore.Release(); + } + + public virtual void EndWrite(IAsyncResult asyncResult) + { + if (asyncResult == null) + throw new ArgumentNullException(nameof(asyncResult)); + + var writeTask = _activeReadWriteTask; + if (writeTask == null) + { + throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple); + } + else if (writeTask != asyncResult) + { + throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple); + } + else if (writeTask._isRead) + { + throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple); + } + + try + { + writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions + Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion); + } + finally + { + FinishTrackingAsyncOperation(); + } + } + + // Task used by BeginRead / BeginWrite to do Read / Write asynchronously. + // A single instance of this task serves four purposes: + // 1. The work item scheduled to run the Read / Write operation + // 2. The state holding the arguments to be passed to Read / Write + // 3. The IAsyncResult returned from BeginRead / BeginWrite + // 4. The completion action that runs to invoke the user-provided callback. + // This last item is a bit tricky. Before the AsyncCallback is invoked, the + // IAsyncResult must have completed, so we can't just invoke the handler + // from within the task, since it is the IAsyncResult, and thus it's not + // yet completed. Instead, we use AddCompletionAction to install this + // task as its own completion handler. That saves the need to allocate + // a separate completion handler, it guarantees that the task will + // have completed by the time the handler is invoked, and it allows + // the handler to be invoked synchronously upon the completion of the + // task. This all enables BeginRead / BeginWrite to be implemented + // with a single allocation. + private sealed class ReadWriteTask : Task, ITaskCompletionAction + { + internal readonly bool _isRead; + internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync + internal Stream _stream; + internal byte[] _buffer; + internal readonly int _offset; + internal readonly int _count; + private AsyncCallback _callback; + private ExecutionContext _context; + + internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC + { + _stream = null; + _buffer = null; + } + + public ReadWriteTask( + bool isRead, + bool apm, + Func function, object state, + Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) : + base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach) + { + Debug.Assert(function != null); + Debug.Assert(stream != null); + Debug.Assert(buffer != null); + + // Store the arguments + _isRead = isRead; + _apm = apm; + _stream = stream; + _buffer = buffer; + _offset = offset; + _count = count; + + // If a callback was provided, we need to: + // - Store the user-provided handler + // - Capture an ExecutionContext under which to invoke the handler + // - Add this task as its own completion handler so that the Invoke method + // will run the callback when this task completes. + if (callback != null) + { + _callback = callback; + _context = ExecutionContext.Capture(); + base.AddCompletionAction(this); + } + } + + private static void InvokeAsyncCallback(object completedTask) + { + var rwc = (ReadWriteTask)completedTask; + var callback = rwc._callback; + rwc._callback = null; + callback(rwc); + } + + private static ContextCallback s_invokeAsyncCallback; + + void ITaskCompletionAction.Invoke(Task completingTask) + { + // Get the ExecutionContext. If there is none, just run the callback + // directly, passing in the completed task as the IAsyncResult. + // If there is one, process it with ExecutionContext.Run. + var context = _context; + if (context == null) + { + var callback = _callback; + _callback = null; + callback(completingTask); + } + else + { + _context = null; + + var invokeAsyncCallback = s_invokeAsyncCallback; + if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition + + ExecutionContext.RunInternal(context, invokeAsyncCallback, this); + } + } + + bool ITaskCompletionAction.InvokeMayRunArbitraryCode { get { return true; } } + } + + public Task WriteAsync(byte[] buffer, int offset, int count) + { + return WriteAsync(buffer, offset, count, CancellationToken.None); + } + + public virtual Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + // If cancellation was requested, bail early with an already completed task. + // Otherwise, return a task that represents the Begin/End methods. + return cancellationToken.IsCancellationRequested + ? Task.FromCanceled(cancellationToken) + : BeginEndWriteAsync(buffer, offset, count); + } + + public virtual ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + if (MemoryMarshal.TryGetArray(buffer, out ArraySegment array)) + { + return new ValueTask(WriteAsync(array.Array, array.Offset, array.Count, cancellationToken)); + } + else + { + byte[] sharedBuffer = ArrayPool.Shared.Rent(buffer.Length); + buffer.Span.CopyTo(sharedBuffer); + return new ValueTask(FinishWriteAsync(WriteAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer)); + } + } + + private async Task FinishWriteAsync(Task writeTask, byte[] localBuffer) + { + try + { + await writeTask.ConfigureAwait(false); + } + finally + { + ArrayPool.Shared.Return(localBuffer); + } + } + + private Task BeginEndWriteAsync(byte[] buffer, int offset, int count) + { + if (!HasOverriddenBeginEndWrite()) + { + // If the Stream does not override Begin/EndWrite, then we can take an optimized path + // that skips an extra layer of tasks / IAsyncResults. + return (Task)BeginWriteInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false); + } + + // Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality. + return TaskFactory.FromAsyncTrim( + this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count }, + (stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler + (stream, asyncResult) => // cached by compiler + { + stream.EndWrite(asyncResult); + return default; + }); + } + + public abstract long Seek(long offset, SeekOrigin origin); + + public abstract void SetLength(long value); + + public abstract int Read(byte[] buffer, int offset, int count); + + public virtual int Read(Span buffer) + { + byte[] sharedBuffer = ArrayPool.Shared.Rent(buffer.Length); + try + { + int numRead = Read(sharedBuffer, 0, buffer.Length); + if ((uint)numRead > buffer.Length) + { + throw new IOException(SR.IO_StreamTooLong); + } + new Span(sharedBuffer, 0, numRead).CopyTo(buffer); + return numRead; + } + finally { ArrayPool.Shared.Return(sharedBuffer); } + } + + // Reads one byte from the stream by calling Read(byte[], int, int). + // Will return an unsigned byte cast to an int or -1 on end of stream. + // This implementation does not perform well because it allocates a new + // byte[] each time you call it, and should be overridden by any + // subclass that maintains an internal buffer. Then, it can help perf + // significantly for people who are reading one byte at a time. + public virtual int ReadByte() + { + byte[] oneByteArray = new byte[1]; + int r = Read(oneByteArray, 0, 1); + if (r == 0) + return -1; + return oneByteArray[0]; + } + + public abstract void Write(byte[] buffer, int offset, int count); + + public virtual void Write(ReadOnlySpan buffer) + { + byte[] sharedBuffer = ArrayPool.Shared.Rent(buffer.Length); + try + { + buffer.CopyTo(sharedBuffer); + Write(sharedBuffer, 0, buffer.Length); + } + finally { ArrayPool.Shared.Return(sharedBuffer); } + } + + // Writes one byte from the stream by calling Write(byte[], int, int). + // This implementation does not perform well because it allocates a new + // byte[] each time you call it, and should be overridden by any + // subclass that maintains an internal buffer. Then, it can help perf + // significantly for people who are writing one byte at a time. + public virtual void WriteByte(byte value) + { + byte[] oneByteArray = new byte[1]; + oneByteArray[0] = value; + Write(oneByteArray, 0, 1); + } + + public static Stream Synchronized(Stream stream) + { + if (stream == null) + throw new ArgumentNullException(nameof(stream)); + if (stream is SyncStream) + return stream; + + return new SyncStream(stream); + } + + [Obsolete("Do not call or override this method.")] + protected virtual void ObjectInvariant() + { + } + + internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + // To avoid a race with a stream's position pointer & generating conditions + // with internal buffer indexes in our own streams that + // don't natively support async IO operations when there are multiple + // async requests outstanding, we will block the application's main + // thread and do the IO synchronously. + // This can't perform well - use a different approach. + SynchronousAsyncResult asyncResult; + try + { + int numRead = Read(buffer, offset, count); + asyncResult = new SynchronousAsyncResult(numRead, state); + } + catch (IOException ex) + { + asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false); + } + + if (callback != null) + { + callback(asyncResult); + } + + return asyncResult; + } + + internal static int BlockingEndRead(IAsyncResult asyncResult) + { + return SynchronousAsyncResult.EndRead(asyncResult); + } + + internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + // To avoid a race condition with a stream's position pointer & generating conditions + // with internal buffer indexes in our own streams that + // don't natively support async IO operations when there are multiple + // async requests outstanding, we will block the application's main + // thread and do the IO synchronously. + // This can't perform well - use a different approach. + SynchronousAsyncResult asyncResult; + try + { + Write(buffer, offset, count); + asyncResult = new SynchronousAsyncResult(state); + } + catch (IOException ex) + { + asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true); + } + + if (callback != null) + { + callback(asyncResult); + } + + return asyncResult; + } + + internal static void BlockingEndWrite(IAsyncResult asyncResult) + { + SynchronousAsyncResult.EndWrite(asyncResult); + } + + private sealed class NullStream : Stream + { + private static readonly Task s_zeroTask = Task.FromResult(0); + + internal NullStream() { } + + public override bool CanRead => true; + + public override bool CanWrite => true; + + public override bool CanSeek => true; + + public override long Length => 0; + + public override long Position + { + get { return 0; } + set { } + } + + public override void CopyTo(Stream destination, int bufferSize) + { + StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); + + // After we validate arguments this is a nop. + } + + public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) + { + // Validate arguments here for compat, since previously this method + // was inherited from Stream (which did check its arguments). + StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); + + return cancellationToken.IsCancellationRequested ? + Task.FromCanceled(cancellationToken) : + Task.CompletedTask; + } + + protected override void Dispose(bool disposing) + { + // Do nothing - we don't want NullStream singleton (static) to be closable + } + + public override void Flush() + { + } + + public override Task FlushAsync(CancellationToken cancellationToken) + { + return cancellationToken.IsCancellationRequested ? + Task.FromCanceled(cancellationToken) : + Task.CompletedTask; + } + + public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + if (!CanRead) throw Error.GetReadNotSupported(); + + return BlockingBeginRead(buffer, offset, count, callback, state); + } + + public override int EndRead(IAsyncResult asyncResult) + { + if (asyncResult == null) + throw new ArgumentNullException(nameof(asyncResult)); + + return BlockingEndRead(asyncResult); + } + + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + if (!CanWrite) throw Error.GetWriteNotSupported(); + + return BlockingBeginWrite(buffer, offset, count, callback, state); + } + + public override void EndWrite(IAsyncResult asyncResult) + { + if (asyncResult == null) + throw new ArgumentNullException(nameof(asyncResult)); + + BlockingEndWrite(asyncResult); + } + + public override int Read(byte[] buffer, int offset, int count) + { + return 0; + } + + public override int Read(Span buffer) + { + return 0; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return s_zeroTask; + } + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + return new ValueTask(0); + } + + public override int ReadByte() + { + return -1; + } + + public override void Write(byte[] buffer, int offset, int count) + { + } + + public override void Write(ReadOnlySpan buffer) + { + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return cancellationToken.IsCancellationRequested ? + Task.FromCanceled(cancellationToken) : + Task.CompletedTask; + } + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + return cancellationToken.IsCancellationRequested ? + new ValueTask(Task.FromCanceled(cancellationToken)) : + default; + } + + public override void WriteByte(byte value) + { + } + + public override long Seek(long offset, SeekOrigin origin) + { + return 0; + } + + public override void SetLength(long length) + { + } + } + + + /// Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class. + private sealed class SynchronousAsyncResult : IAsyncResult + { + private readonly object _stateObject; + private readonly bool _isWrite; + private ManualResetEvent _waitHandle; + private ExceptionDispatchInfo _exceptionInfo; + + private bool _endXxxCalled; + private int _bytesRead; + + internal SynchronousAsyncResult(int bytesRead, object asyncStateObject) + { + _bytesRead = bytesRead; + _stateObject = asyncStateObject; + //_isWrite = false; + } + + internal SynchronousAsyncResult(object asyncStateObject) + { + _stateObject = asyncStateObject; + _isWrite = true; + } + + internal SynchronousAsyncResult(Exception ex, object asyncStateObject, bool isWrite) + { + _exceptionInfo = ExceptionDispatchInfo.Capture(ex); + _stateObject = asyncStateObject; + _isWrite = isWrite; + } + + public bool IsCompleted + { + // We never hand out objects of this type to the user before the synchronous IO completed: + get { return true; } + } + + public WaitHandle AsyncWaitHandle + { + get + { + return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true)); + } + } + + public object AsyncState + { + get { return _stateObject; } + } + + public bool CompletedSynchronously + { + get { return true; } + } + + internal void ThrowIfError() + { + if (_exceptionInfo != null) + _exceptionInfo.Throw(); + } + + internal static int EndRead(IAsyncResult asyncResult) + { + SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; + if (ar == null || ar._isWrite) + throw new ArgumentException(SR.Arg_WrongAsyncResult); + + if (ar._endXxxCalled) + throw new ArgumentException(SR.InvalidOperation_EndReadCalledMultiple); + + ar._endXxxCalled = true; + + ar.ThrowIfError(); + return ar._bytesRead; + } + + internal static void EndWrite(IAsyncResult asyncResult) + { + SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; + if (ar == null || !ar._isWrite) + throw new ArgumentException(SR.Arg_WrongAsyncResult); + + if (ar._endXxxCalled) + throw new ArgumentException(SR.InvalidOperation_EndWriteCalledMultiple); + + ar._endXxxCalled = true; + + ar.ThrowIfError(); + } + } // class SynchronousAsyncResult + + + // SyncStream is a wrapper around a stream that takes + // a lock for every operation making it thread safe. + private sealed class SyncStream : Stream, IDisposable + { + private Stream _stream; + + internal SyncStream(Stream stream) + { + if (stream == null) + throw new ArgumentNullException(nameof(stream)); + _stream = stream; + } + + public override bool CanRead => _stream.CanRead; + + public override bool CanWrite => _stream.CanWrite; + + public override bool CanSeek => _stream.CanSeek; + + public override bool CanTimeout => _stream.CanTimeout; + + public override long Length + { + get + { + lock (_stream) + { + return _stream.Length; + } + } + } + + public override long Position + { + get + { + lock (_stream) + { + return _stream.Position; + } + } + set + { + lock (_stream) + { + _stream.Position = value; + } + } + } + + public override int ReadTimeout + { + get + { + return _stream.ReadTimeout; + } + set + { + _stream.ReadTimeout = value; + } + } + + public override int WriteTimeout + { + get + { + return _stream.WriteTimeout; + } + set + { + _stream.WriteTimeout = value; + } + } + + // In the off chance that some wrapped stream has different + // semantics for Close vs. Dispose, let's preserve that. + public override void Close() + { + lock (_stream) + { + try + { + _stream.Close(); + } + finally + { + base.Dispose(true); + } + } + } + + protected override void Dispose(bool disposing) + { + lock (_stream) + { + try + { + // Explicitly pick up a potentially methodimpl'ed Dispose + if (disposing) + ((IDisposable)_stream).Dispose(); + } + finally + { + base.Dispose(disposing); + } + } + } + + public override void Flush() + { + lock (_stream) + _stream.Flush(); + } + + public override int Read(byte[] bytes, int offset, int count) + { + lock (_stream) + return _stream.Read(bytes, offset, count); + } + + public override int Read(Span buffer) + { + lock (_stream) + return _stream.Read(buffer); + } + + public override int ReadByte() + { + lock (_stream) + return _stream.ReadByte(); + } + + public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { +#if CORERT + throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251 +#else + bool overridesBeginRead = _stream.HasOverriddenBeginEndRead(); + + lock (_stream) + { + // If the Stream does have its own BeginRead implementation, then we must use that override. + // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic + // which ensures only one asynchronous operation does so with an asynchronous wait rather + // than a synchronous wait. A synchronous wait will result in a deadlock condition, because + // the EndXx method for the outstanding async operation won't be able to acquire the lock on + // _stream due to this call blocked while holding the lock. + return overridesBeginRead ? + _stream.BeginRead(buffer, offset, count, callback, state) : + _stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true); + } +#endif + } + + public override int EndRead(IAsyncResult asyncResult) + { + if (asyncResult == null) + throw new ArgumentNullException(nameof(asyncResult)); + + lock (_stream) + return _stream.EndRead(asyncResult); + } + + public override long Seek(long offset, SeekOrigin origin) + { + lock (_stream) + return _stream.Seek(offset, origin); + } + + public override void SetLength(long length) + { + lock (_stream) + _stream.SetLength(length); + } + + public override void Write(byte[] bytes, int offset, int count) + { + lock (_stream) + _stream.Write(bytes, offset, count); + } + + public override void Write(ReadOnlySpan buffer) + { + lock (_stream) + _stream.Write(buffer); + } + + public override void WriteByte(byte b) + { + lock (_stream) + _stream.WriteByte(b); + } + + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { +#if CORERT + throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251 +#else + bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite(); + + lock (_stream) + { + // If the Stream does have its own BeginWrite implementation, then we must use that override. + // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic + // which ensures only one asynchronous operation does so with an asynchronous wait rather + // than a synchronous wait. A synchronous wait will result in a deadlock condition, because + // the EndXx method for the outstanding async operation won't be able to acquire the lock on + // _stream due to this call blocked while holding the lock. + return overridesBeginWrite ? + _stream.BeginWrite(buffer, offset, count, callback, state) : + _stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true); + } +#endif + } + + public override void EndWrite(IAsyncResult asyncResult) + { + if (asyncResult == null) + throw new ArgumentNullException(nameof(asyncResult)); + + lock (_stream) + _stream.EndWrite(asyncResult); + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs index 22ec6e645b..5c3cc9157d 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs @@ -70,21 +70,21 @@ namespace System.IO // We don't guarantee thread safety on StreamReader, but we should at // least prevent users from trying to read anything while an Async // read from the same thread is in progress. - private volatile Task _asyncReadTask; + private Task _asyncReadTask = Task.CompletedTask; private void CheckAsyncTaskInProgress() { // We are not locking the access to _asyncReadTask because this is not meant to guarantee thread safety. // We are simply trying to deter calling any Read APIs while an async Read from the same thread is in progress. - - Task t = _asyncReadTask; - - if (t != null && !t.IsCompleted) + if (!_asyncReadTask.IsCompleted) { - throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress); + ThrowAsyncIOInProgress(); } } + private static void ThrowAsyncIOInProgress() => + throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress); + // StreamReader by default will ignore illegal UTF8 characters. We don't want to // throw here because we want to be able to read ill-formed data without choking. // The high level goal is to be tolerant of encoding errors when we read and very strict @@ -1059,7 +1059,7 @@ namespace System.IO // data read in, let's try writing directly to the user's buffer. bool readToUserBuffer = false; - Byte[] tmpByteBuffer = _byteBuffer; + byte[] tmpByteBuffer = _byteBuffer; Stream tmpStream = _stream; int count = buffer.Length; @@ -1290,7 +1290,7 @@ namespace System.IO { _charLen = 0; _charPos = 0; - Byte[] tmpByteBuffer = _byteBuffer; + byte[] tmpByteBuffer = _byteBuffer; Stream tmpStream = _stream; if (!_checkPreamble) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/StreamWriter.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/StreamWriter.cs index a376244280..8d94ac60b9 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/StreamWriter.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/StreamWriter.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; @@ -44,19 +45,21 @@ namespace System.IO // We don't guarantee thread safety on StreamWriter, but we should at // least prevent users from trying to write anything while an Async // write from the same thread is in progress. - private volatile Task _asyncWriteTask; + private Task _asyncWriteTask = Task.CompletedTask; private void CheckAsyncTaskInProgress() { // We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety. // We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress. - - Task t = _asyncWriteTask; - - if (t != null && !t.IsCompleted) - throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress); + if (!_asyncWriteTask.IsCompleted) + { + ThrowAsyncIOInProgress(); + } } + private static void ThrowAsyncIOInProgress() => + throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress); + // The high level goal is to be tolerant of encoding errors when we read and very strict // when we write. Hence, default StreamWriter encoding will throw on encoding error. // Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character @@ -323,14 +326,13 @@ namespace System.IO } } + [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites public override void Write(char[] buffer) { - if (buffer != null) - { - WriteCore(buffer, _autoFlush); - } + WriteSpan(buffer, appendNewLine: false); } + [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites public override void Write(char[] buffer, int index, int count) { if (buffer == null) @@ -350,14 +352,15 @@ namespace System.IO throw new ArgumentException(SR.Argument_InvalidOffLen); } - WriteCore(new ReadOnlySpan(buffer, index, count), _autoFlush); + WriteSpan(buffer.AsSpan(index, count), appendNewLine: false); } + [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites public override void Write(ReadOnlySpan buffer) { if (GetType() == typeof(StreamWriter)) { - WriteCore(buffer, _autoFlush); + WriteSpan(buffer, appendNewLine: false); } else { @@ -367,7 +370,8 @@ namespace System.IO } } - private unsafe void WriteCore(ReadOnlySpan buffer, bool autoFlush) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe void WriteSpan(ReadOnlySpan buffer, bool appendNewLine) { CheckAsyncTaskInProgress(); @@ -422,41 +426,47 @@ namespace System.IO } } - if (autoFlush) + if (appendNewLine) + { + char[] coreNewLine = CoreNewLine; + for (int i = 0; i < coreNewLine.Length; i++) // Generally 1 (\n) or 2 (\r\n) iterations + { + if (_charPos == _charLen) + { + Flush(false, false); + } + + _charBuffer[_charPos] = coreNewLine[i]; + _charPos++; + } + } + + if (_autoFlush) { Flush(true, false); } } + [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites public override void Write(string value) { - if (value != null) - { - WriteCore(value.AsSpan(), _autoFlush); - } + WriteSpan(value, appendNewLine: false); } - // - // Optimize the most commonly used WriteLine overload. This optimization is important for System.Console in particular - // because of it will make one WriteLine equal to one call to the OS instead of two in the common case. - // + [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites public override void WriteLine(string value) { CheckAsyncTaskInProgress(); - if (value != null) - { - WriteCore(value.AsSpan(), autoFlush: false); - } - WriteCore(new ReadOnlySpan(CoreNewLine), autoFlush: true); + WriteSpan(value, appendNewLine: true); } + [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites public override void WriteLine(ReadOnlySpan value) { if (GetType() == typeof(StreamWriter)) { CheckAsyncTaskInProgress(); - WriteCore(value, autoFlush: false); - WriteCore(new ReadOnlySpan(CoreNewLine), autoFlush: true); + WriteSpan(value, appendNewLine: true); } else { @@ -466,6 +476,123 @@ namespace System.IO } } + private void WriteFormatHelper(string format, ParamsArray args, bool appendNewLine) + { + StringBuilder sb = + StringBuilderCache.Acquire(format.Length + args.Length * 8) + .AppendFormatHelper(null, format, args); + + StringBuilder.ChunkEnumerator chunks = sb.GetChunks(); + + bool more = chunks.MoveNext(); + while (more) + { + ReadOnlySpan current = chunks.Current.Span; + more = chunks.MoveNext(); + + // If final chunk, include the newline if needed + WriteSpan(current, appendNewLine: more ? false : appendNewLine); + } + + StringBuilderCache.Release(sb); + } + + public override void Write(string format, object arg0) + { + if (GetType() == typeof(StreamWriter)) + { + WriteFormatHelper(format, new ParamsArray(arg0), appendNewLine: false); + } + else + { + base.Write(format, arg0); + } + } + + public override void Write(string format, object arg0, object arg1) + { + if (GetType() == typeof(StreamWriter)) + { + WriteFormatHelper(format, new ParamsArray(arg0, arg1), appendNewLine: false); + } + else + { + base.Write(format, arg0, arg1); + } + } + + public override void Write(string format, object arg0, object arg1, object arg2) + { + if (GetType() == typeof(StreamWriter)) + { + WriteFormatHelper(format, new ParamsArray(arg0, arg1, arg2), appendNewLine: false); + } + else + { + base.Write(format, arg0, arg1, arg2); + } + } + + public override void Write(string format, params object[] arg) + { + if (GetType() == typeof(StreamWriter)) + { + WriteFormatHelper(format, new ParamsArray(arg), appendNewLine: false); + } + else + { + base.Write(format, arg); + } + } + + public override void WriteLine(string format, object arg0) + { + if (GetType() == typeof(StreamWriter)) + { + WriteFormatHelper(format, new ParamsArray(arg0), appendNewLine: true); + } + else + { + base.WriteLine(format, arg0); + } + } + + public override void WriteLine(string format, object arg0, object arg1) + { + if (GetType() == typeof(StreamWriter)) + { + WriteFormatHelper(format, new ParamsArray(arg0, arg1), appendNewLine: true); + } + else + { + base.WriteLine(format, arg0, arg1); + } + } + + public override void WriteLine(string format, object arg0, object arg1, object arg2) + { + if (GetType() == typeof(StreamWriter)) + { + WriteFormatHelper(format, new ParamsArray(arg0, arg1, arg2), appendNewLine: true); + } + else + { + base.WriteLine(format, arg0, arg1, arg2); + } + } + + public override void WriteLine(string format, params object[] arg) + { + if (GetType() == typeof(StreamWriter)) + { + WriteFormatHelper(format, new ParamsArray(arg), appendNewLine: true); + } + else + { + base.WriteLine(format, arg); + } + } + #region Task based Async APIs public override Task WriteAsync(char value) { @@ -955,7 +1082,7 @@ namespace System.IO // to ensure performant access inside the state machine that corresponds this async method. private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder, char[] charBuffer, int charPos, bool haveWrittenPreamble, - Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream, CancellationToken cancellationToken) + Encoding encoding, Encoder encoder, byte[] byteBuffer, Stream stream, CancellationToken cancellationToken) { if (!haveWrittenPreamble) { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/TextReader.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/TextReader.cs index eb94dd7594..bb5b142bde 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/TextReader.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/TextReader.cs @@ -207,7 +207,7 @@ namespace System.IO #region Task based Async APIs public virtual Task ReadLineAsync() { - return Task.Factory.StartNew(state => + return Task.Factory.StartNew(state => { return ((TextReader)state).ReadLine(); }, @@ -251,7 +251,7 @@ namespace System.IO return ReadAsyncInternal(new Memory(buffer, index, count), default).AsTask(); } - public virtual ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default(CancellationToken)) => + public virtual ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => new ValueTask(MemoryMarshal.TryGetArray(buffer, out ArraySegment array) ? ReadAsync(array.Array, array.Offset, array.Count) : Task.Factory.StartNew(state => @@ -289,7 +289,7 @@ namespace System.IO return ReadBlockAsyncInternal(new Memory(buffer, index, count), default).AsTask(); } - public virtual ValueTask ReadBlockAsync(Memory buffer, CancellationToken cancellationToken = default(CancellationToken)) => + public virtual ValueTask ReadBlockAsync(Memory buffer, CancellationToken cancellationToken = default) => new ValueTask(MemoryMarshal.TryGetArray(buffer, out ArraySegment array) ? ReadBlockAsync(array.Array, array.Offset, array.Count) : Task.Factory.StartNew(state => diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs index 48e702be67..547c597f03 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs @@ -13,24 +13,24 @@ using System.Buffers; namespace System.IO { // This abstract base class represents a writer that can write a sequential - // stream of characters. A subclass must minimally implement the + // stream of characters. A subclass must minimally implement the // Write(char) method. // - // This class is intended for character output, not bytes. - // There are methods on the Stream class for writing bytes. + // This class is intended for character output, not bytes. + // There are methods on the Stream class for writing bytes. public abstract partial class TextWriter : MarshalByRefObject, IDisposable { public static readonly TextWriter Null = new NullTextWriter(); - // We don't want to allocate on every TextWriter creation, so cache the char array. + // We don't want to allocate on every TextWriter creation, so cache the char array. private static readonly char[] s_coreNewLine = Environment.NewLine.ToCharArray(); /// - /// This is the 'NewLine' property expressed as a char[]. + /// This is the 'NewLine' property expressed as a char[]. /// It is exposed to subclasses as a protected field for read-only - /// purposes. You should only modify it by using the 'NewLine' property. - /// In particular you should never modify the elements of the array - /// as they are shared among many instances of TextWriter. + /// purposes. You should only modify it by using the 'NewLine' property. + /// In particular you should never modify the elements of the array + /// as they are shared among many instances of TextWriter. /// protected char[] CoreNewLine = s_coreNewLine; private string CoreNewLineStr = Environment.NewLine; @@ -94,7 +94,7 @@ namespace System.IO /// /// Returns the line terminator string used by this TextWriter. The default line - /// terminator string is Environment.NewLine, which is platform specific. + /// terminator string is Environment.NewLine, which is platform specific. /// On Windows this is a carriage return followed by a line feed ("\r\n"). /// On OSX and Linux this is a line feed ("\n"). /// @@ -184,7 +184,7 @@ namespace System.IO } // Writes the text representation of a boolean to the text stream. This - // method outputs either Boolean.TrueString or Boolean.FalseString. + // method outputs either bool.TrueString or bool.FalseString. // public virtual void Write(bool value) { @@ -193,7 +193,7 @@ namespace System.IO // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the - // Int32.ToString() method. + // int.ToString() method. // public virtual void Write(int value) { @@ -202,7 +202,7 @@ namespace System.IO // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the - // UInt32.ToString() method. + // uint.ToString() method. // [CLSCompliant(false)] public virtual void Write(uint value) @@ -212,16 +212,16 @@ namespace System.IO // Writes the text representation of a long to the text stream. The // text representation of the given value is produced by calling the - // Int64.ToString() method. + // long.ToString() method. // public virtual void Write(long value) { Write(value.ToString(FormatProvider)); } - // Writes the text representation of an unsigned long to the text - // stream. The text representation of the given value is produced - // by calling the UInt64.ToString() method. + // Writes the text representation of an unsigned long to the text + // stream. The text representation of the given value is produced + // by calling the ulong.ToString() method. // [CLSCompliant(false)] public virtual void Write(ulong value) @@ -231,7 +231,7 @@ namespace System.IO // Writes the text representation of a float to the text stream. The // text representation of the given value is produced by calling the - // Float.toString(float) method. + // float.ToString(float) method. // public virtual void Write(float value) { @@ -240,7 +240,7 @@ namespace System.IO // Writes the text representation of a double to the text stream. The // text representation of the given value is produced by calling the - // Double.toString(double) method. + // double.ToString(double) method. // public virtual void Write(double value) { @@ -283,33 +283,48 @@ namespace System.IO } } + /// + /// Equivalent to Write(stringBuilder.ToString()) however it uses the + /// StringBuilder.GetChunks() method to avoid creating the intermediate string + /// + /// The string (as a StringBuilder) to write to the stream + public virtual void Write(StringBuilder value) + { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + foreach (ReadOnlyMemory chunk in value.GetChunks()) + Write(chunk); + } + // Writes out a formatted string. Uses the same semantics as - // String.Format. - // + // string.Format. + // public virtual void Write(string format, object arg0) { Write(string.Format(FormatProvider, format, arg0)); } // Writes out a formatted string. Uses the same semantics as - // String.Format. - // + // string.Format. + // public virtual void Write(string format, object arg0, object arg1) { Write(string.Format(FormatProvider, format, arg0, arg1)); } // Writes out a formatted string. Uses the same semantics as - // String.Format. - // + // string.Format. + // public virtual void Write(string format, object arg0, object arg1, object arg2) { Write(string.Format(FormatProvider, format, arg0, arg1, arg2)); } // Writes out a formatted string. Uses the same semantics as - // String.Format. - // + // string.Format. + // public virtual void Write(string format, params object[] arg) { Write(string.Format(FormatProvider, format, arg)); @@ -383,7 +398,7 @@ namespace System.IO WriteLine(); } - // Writes the text representation of an unsigned integer followed by + // Writes the text representation of an unsigned integer followed by // a line terminator to the text stream. // [CLSCompliant(false)] @@ -402,7 +417,7 @@ namespace System.IO WriteLine(); } - // Writes the text representation of an unsigned long followed by + // Writes the text representation of an unsigned long followed by // a line terminator to the text stream. // [CLSCompliant(false)] @@ -447,6 +462,16 @@ namespace System.IO Write(CoreNewLineStr); } + /// + /// Equivalent to WriteLine(stringBuilder.ToString()) however it uses the + /// StringBuilder.GetChunks() method to avoid creating the intermediate string + /// + public virtual void WriteLine(StringBuilder value) + { + Write(value); + WriteLine(); + } + // Writes the text representation of an object followed by a line // terminator to the text stream. // @@ -472,33 +497,33 @@ namespace System.IO } } - // Writes out a formatted string and a new line. Uses the same - // semantics as String.Format. - // + // Writes out a formatted string and a new line. Uses the same + // semantics as string.Format. + // public virtual void WriteLine(string format, object arg0) { WriteLine(string.Format(FormatProvider, format, arg0)); } - // Writes out a formatted string and a new line. Uses the same - // semantics as String.Format. - // + // Writes out a formatted string and a new line. Uses the same + // semantics as string.Format. + // public virtual void WriteLine(string format, object arg0, object arg1) { WriteLine(string.Format(FormatProvider, format, arg0, arg1)); } - // Writes out a formatted string and a new line. Uses the same - // semantics as String.Format. - // + // Writes out a formatted string and a new line. Uses the same + // semantics as string.Format. + // public virtual void WriteLine(string format, object arg0, object arg1, object arg2) { WriteLine(string.Format(FormatProvider, format, arg0, arg1, arg2)); } - // Writes out a formatted string and a new line. Uses the same - // semantics as String.Format. - // + // Writes out a formatted string and a new line. Uses the same + // semantics as string.Format. + // public virtual void WriteLine(string format, params object[] arg) { WriteLine(string.Format(FormatProvider, format, arg)); @@ -527,6 +552,27 @@ namespace System.IO tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } + /// + /// Equivalent to WriteAsync(stringBuilder.ToString()) however it uses the + /// StringBuilder.GetChunks() method to avoid creating the intermediate string + /// + /// The string (as a StringBuilder) to write to the stream + public virtual Task WriteAsync(StringBuilder value, CancellationToken cancellationToken = default) + { + return + cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : + value == null ? Task.CompletedTask : + WriteAsyncCore(value, cancellationToken); + + async Task WriteAsyncCore(StringBuilder sb, CancellationToken ct) + { + foreach (ReadOnlyMemory chunk in sb.GetChunks()) + { + await WriteAsync(chunk, ct).ConfigureAwait(false); + } + } + } + public Task WriteAsync(char[] buffer) { if (buffer == null) @@ -548,7 +594,8 @@ namespace System.IO tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } - public virtual Task WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default(CancellationToken)) => + public virtual Task WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => + cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : MemoryMarshal.TryGetArray(buffer, out ArraySegment array) ? WriteAsync(array.Array, array.Offset, array.Count) : Task.Factory.StartNew(state => @@ -579,6 +626,28 @@ namespace System.IO tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } + /// + /// Equivalent to WriteLineAsync(stringBuilder.ToString()) however it uses the + /// StringBuilder.GetChunks() method to avoid creating the intermediate string + /// + /// The string (as a StringBuilder) to write to the stream + public virtual Task WriteLineAsync(StringBuilder value, CancellationToken cancellationToken = default) + { + return + cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : + value == null ? WriteAsync(CoreNewLine, cancellationToken) : + WriteLineAsyncCore(value, cancellationToken); + + async Task WriteLineAsyncCore(StringBuilder sb, CancellationToken ct) + { + foreach (ReadOnlyMemory chunk in sb.GetChunks()) + { + await WriteAsync(chunk, ct).ConfigureAwait(false); + } + await WriteAsync(CoreNewLine, ct).ConfigureAwait(false); + } + } + public Task WriteLineAsync(char[] buffer) { if (buffer == null) @@ -600,7 +669,8 @@ namespace System.IO tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } - public virtual Task WriteLineAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default(CancellationToken)) => + public virtual Task WriteLineAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => + cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : MemoryMarshal.TryGetArray(buffer, out ArraySegment array) ? WriteLineAsync(array.Array, array.Offset, array.Count) : Task.Factory.StartNew(state => @@ -739,11 +809,14 @@ namespace System.IO public override void Write(double value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] - public override void Write(Decimal value) => _out.Write(value); + public override void Write(decimal value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string value) => _out.Write(value); + [MethodImpl(MethodImplOptions.Synchronized)] + public override void Write(StringBuilder value) => _out.Write(value); + [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(object value) => _out.Write(value); @@ -798,6 +871,9 @@ namespace System.IO [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string value) => _out.WriteLine(value); + [MethodImpl(MethodImplOptions.Synchronized)] + public override void WriteLine(StringBuilder value) => _out.WriteLine(value); + [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(object value) => _out.WriteLine(value); @@ -831,6 +907,13 @@ namespace System.IO return Task.CompletedTask; } + [MethodImpl(MethodImplOptions.Synchronized)] + public override Task WriteAsync(StringBuilder value, CancellationToken cancellationToken = default) + { + Write(value); + return Task.CompletedTask; + } + [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteAsync(char[] buffer, int index, int count) { @@ -852,6 +935,13 @@ namespace System.IO return Task.CompletedTask; } + [MethodImpl(MethodImplOptions.Synchronized)] + public override Task WriteLineAsync(StringBuilder value, CancellationToken cancellationToken = default) + { + WriteLine(value); + return Task.CompletedTask; + } + [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteLineAsync(char[] buffer, int index, int count) { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStream.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStream.cs index d1a13156a8..d4af4cfee3 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStream.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStream.cs @@ -47,7 +47,7 @@ namespace System.IO private long _offset; private FileAccess _access; private bool _isOpen; - private Task _lastReadTask; // The last successful task returned from ReadAsync + private Task _lastReadTask; // The last successful task returned from ReadAsync /// /// Creates a closed stream. @@ -379,22 +379,22 @@ namespace System.IO return ReadCore(new Span(buffer, offset, count)); } - public override int Read(Span destination) + public override int Read(Span buffer) { if (GetType() == typeof(UnmanagedMemoryStream)) { - return ReadCore(destination); + return ReadCore(buffer); } else { // UnmanagedMemoryStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior // to this Read(Span) overload being introduced. In that case, this Read(Span) overload // should use the behavior of Read(byte[],int,int) overload. - return base.Read(destination); + return base.Read(buffer); } } - internal int ReadCore(Span destination) + internal int ReadCore(Span buffer) { EnsureNotClosed(); EnsureReadable(); @@ -403,7 +403,7 @@ namespace System.IO // changes our position after we decide we can read some bytes. long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); - long n = Math.Min(len - pos, destination.Length); + long n = Math.Min(len - pos, buffer.Length); if (n <= 0) { return 0; @@ -418,7 +418,7 @@ namespace System.IO unsafe { - fixed (byte* pBuffer = &MemoryMarshal.GetReference(destination)) + fixed (byte* pBuffer = &MemoryMarshal.GetReference(buffer)) { if (_buffer != null) { @@ -456,7 +456,7 @@ namespace System.IO /// Maximum number of bytes to read. /// Token that can be used to cancel this operation. /// Task that can be used to access the number of bytes actually read. - public override Task ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); @@ -468,27 +468,27 @@ namespace System.IO throw new ArgumentException(SR.Argument_InvalidOffLen); if (cancellationToken.IsCancellationRequested) - return Task.FromCanceled(cancellationToken); + return Task.FromCanceled(cancellationToken); try { - Int32 n = Read(buffer, offset, count); - Task t = _lastReadTask; + int n = Read(buffer, offset, count); + Task t = _lastReadTask; return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult(n)); } catch (Exception ex) { Debug.Assert(!(ex is OperationCanceledException)); - return Task.FromException(ex); + return Task.FromException(ex); } } /// /// Reads bytes from stream and puts them into the buffer /// - /// Buffer to read the bytes to. + /// Buffer to read the bytes to. /// Token that can be used to cancel this operation. - public override ValueTask ReadAsync(Memory destination, CancellationToken cancellationToken = default(CancellationToken)) + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -510,9 +510,9 @@ namespace System.IO // something other than an array and this is an UnmanagedMemoryStream-derived type that doesn't override Read(Span) will // it then fall back to doing the ArrayPool/copy behavior. return new ValueTask( - MemoryMarshal.TryGetArray(destination, out ArraySegment destinationArray) ? + MemoryMarshal.TryGetArray(buffer, out ArraySegment destinationArray) ? Read(destinationArray.Array, destinationArray.Offset, destinationArray.Count) : - Read(destination.Span)); + Read(buffer.Span)); } catch (Exception ex) { @@ -659,29 +659,29 @@ namespace System.IO WriteCore(new Span(buffer, offset, count)); } - public override void Write(ReadOnlySpan source) + public override void Write(ReadOnlySpan buffer) { if (GetType() == typeof(UnmanagedMemoryStream)) { - WriteCore(source); + WriteCore(buffer); } else { // UnmanagedMemoryStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior // to this Write(Span) overload being introduced. In that case, this Write(Span) overload // should use the behavior of Write(byte[],int,int) overload. - base.Write(source); + base.Write(buffer); } } - internal unsafe void WriteCore(ReadOnlySpan source) + internal unsafe void WriteCore(ReadOnlySpan buffer) { EnsureNotClosed(); EnsureWriteable(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); - long n = pos + source.Length; + long n = pos + buffer.Length; // Check for overflow if (n < 0) { @@ -709,12 +709,12 @@ namespace System.IO } } - fixed (byte* pBuffer = &MemoryMarshal.GetReference(source)) + fixed (byte* pBuffer = &MemoryMarshal.GetReference(buffer)) { if (_buffer != null) { long bytesLeft = _capacity - pos; - if (bytesLeft < source.Length) + if (bytesLeft < buffer.Length) { throw new ArgumentException(SR.Arg_BufferTooSmall); } @@ -724,7 +724,7 @@ namespace System.IO try { _buffer.AcquirePointer(ref pointer); - Buffer.Memcpy(pointer + pos + _offset, pBuffer, source.Length); + Buffer.Memcpy(pointer + pos + _offset, pBuffer, buffer.Length); } finally { @@ -736,7 +736,7 @@ namespace System.IO } else { - Buffer.Memcpy(_mem + pos, pBuffer, source.Length); + Buffer.Memcpy(_mem + pos, pBuffer, buffer.Length); } } @@ -752,7 +752,7 @@ namespace System.IO /// Number of bytes to write. /// Token that can be used to cancel the operation. /// Task that can be awaited - public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); @@ -783,7 +783,7 @@ namespace System.IO /// /// Buffer that will be written. /// Token that can be used to cancel the operation. - public override ValueTask WriteAsync(ReadOnlyMemory source, CancellationToken cancellationToken = default(CancellationToken)) + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -794,13 +794,13 @@ namespace System.IO { // See corresponding comment in ReadAsync for why we don't just always use Write(ReadOnlySpan). // Unlike ReadAsync, we could delegate to WriteAsync(byte[], ...) here, but we don't for consistency. - if (MemoryMarshal.TryGetArray(source, out ArraySegment sourceArray)) + if (MemoryMarshal.TryGetArray(buffer, out ArraySegment sourceArray)) { Write(sourceArray.Array, sourceArray.Offset, sourceArray.Count); } else { - Write(source.Span); + Write(buffer.Span); } return default; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs index f34c3c4137..9a598951ee 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs @@ -71,7 +71,7 @@ namespace System.IO public override bool TryGetBuffer(out ArraySegment buffer) { - buffer = default(ArraySegment); + buffer = default; return false; } @@ -112,9 +112,9 @@ namespace System.IO return _unmanagedStream.Read(buffer, offset, count); } - public override int Read(Span destination) + public override int Read(Span buffer) { - return _unmanagedStream.Read(destination); + return _unmanagedStream.Read(buffer); } public override int ReadByte() @@ -139,9 +139,9 @@ namespace System.IO _unmanagedStream.Write(buffer, offset, count); } - public override void Write(ReadOnlySpan source) + public override void Write(ReadOnlySpan buffer) { - _unmanagedStream.Write(source); + _unmanagedStream.Write(buffer); } public override void WriteByte(byte value) @@ -160,7 +160,7 @@ namespace System.IO stream.Write(buffer, 0, buffer.Length); } - public override void SetLength(Int64 value) + public override void SetLength(long value) { // This was probably meant to call _unmanagedStream.SetLength(value), but it was forgotten in V.4.0. // Now this results in a call to the base which touches the underlying array which is never actually used. @@ -169,7 +169,7 @@ namespace System.IO } - public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) + public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { // The parameter checks must be in sync with the base version: if (destination == null) @@ -201,25 +201,25 @@ namespace System.IO } - public override Task ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _unmanagedStream.ReadAsync(buffer, offset, count, cancellationToken); } - public override ValueTask ReadAsync(Memory destination, CancellationToken cancellationToken = default(CancellationToken)) + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) { - return _unmanagedStream.ReadAsync(destination, cancellationToken); + return _unmanagedStream.ReadAsync(buffer, cancellationToken); } - public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _unmanagedStream.WriteAsync(buffer, offset, count, cancellationToken); } - public override ValueTask WriteAsync(ReadOnlyMemory source, CancellationToken cancellationToken = default(CancellationToken)) + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) { - return _unmanagedStream.WriteAsync(source, cancellationToken); + return _unmanagedStream.WriteAsync(buffer, cancellationToken); } } // class UnmanagedMemoryStreamWrapper } // namespace diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IO/Win32Marshal.cs b/external/corert/src/System.Private.CoreLib/shared/System/IO/Win32Marshal.cs index b8b3057769..cf1d94cba3 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IO/Win32Marshal.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IO/Win32Marshal.cs @@ -2,14 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Diagnostics; using System.Runtime.InteropServices; namespace System.IO { /// - /// Provides static methods for converting from Win32 errors codes to exceptions, HRESULTS and error messages. + /// Provides static methods for converting from Win32 errors codes to exceptions, HRESULTS and error messages. /// internal static class Win32Marshal { @@ -22,94 +20,84 @@ namespace System.IO #endif /// - /// Converts, resetting it, the last Win32 error into a corresponding object. + /// Converts, resetting it, the last Win32 error into a corresponding object, optionally + /// including the specified path in the error message. /// - internal static Exception GetExceptionForLastWin32Error() - { - int errorCode = Marshal.GetLastWin32Error(); - return GetExceptionForWin32Error(errorCode, string.Empty); - } + internal static Exception GetExceptionForLastWin32Error(string path = "") + => GetExceptionForWin32Error(Marshal.GetLastWin32Error(), path); /// - /// Converts the specified Win32 error into a corresponding object. + /// Converts the specified Win32 error into a corresponding object, optionally + /// including the specified path in the error message. /// - internal static Exception GetExceptionForWin32Error(int errorCode) - { - return GetExceptionForWin32Error(errorCode, string.Empty); - } - - /// - /// Converts the specified Win32 error into a corresponding object, optionally - /// including the specified path in the error message. - /// - internal static Exception GetExceptionForWin32Error(int errorCode, string path) + internal static Exception GetExceptionForWin32Error(int errorCode, string path = "") { switch (errorCode) { case Interop.Errors.ERROR_FILE_NOT_FOUND: - if (path.Length == 0) - return new FileNotFoundException(SR.IO_FileNotFound); - else - return new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, path), path); - + return new FileNotFoundException( + string.IsNullOrEmpty(path) ? SR.IO_FileNotFound : SR.Format(SR.IO_FileNotFound_FileName, path), path); case Interop.Errors.ERROR_PATH_NOT_FOUND: - if (path.Length == 0) - return new DirectoryNotFoundException(SR.IO_PathNotFound_NoPathName); - else - return new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, path)); - + return new DirectoryNotFoundException( + string.IsNullOrEmpty(path) ? SR.IO_PathNotFound_NoPathName : SR.Format(SR.IO_PathNotFound_Path, path)); case Interop.Errors.ERROR_ACCESS_DENIED: - if (path.Length == 0) - return new UnauthorizedAccessException(SR.UnauthorizedAccess_IODenied_NoPathName); - else - return new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, path)); - + return new UnauthorizedAccessException( + string.IsNullOrEmpty(path) ? SR.UnauthorizedAccess_IODenied_NoPathName : SR.Format(SR.UnauthorizedAccess_IODenied_Path, path)); case Interop.Errors.ERROR_ALREADY_EXISTS: - if (path.Length == 0) + if (string.IsNullOrEmpty(path)) goto default; - return new IOException(SR.Format(SR.IO_AlreadyExists_Name, path), MakeHRFromErrorCode(errorCode)); - case Interop.Errors.ERROR_FILENAME_EXCED_RANGE: - if (path.Length == 0) - return new PathTooLongException(SR.IO_PathTooLong); - else - return new PathTooLongException(SR.Format(SR.IO_PathTooLong_Path, path)); - - case Interop.Errors.ERROR_INVALID_DRIVE: - throw new DriveNotFoundException(SR.Format(SR.IO_DriveNotFound_Drive, path)); - - case Interop.Errors.ERROR_INVALID_PARAMETER: - return new IOException(Interop.Kernel32.GetMessage(errorCode), MakeHRFromErrorCode(errorCode)); - + return new PathTooLongException( + string.IsNullOrEmpty(path) ? SR.IO_PathTooLong : SR.Format(SR.IO_PathTooLong_Path, path)); case Interop.Errors.ERROR_SHARING_VIOLATION: - if (path.Length == 0) - return new IOException(SR.IO_SharingViolation_NoFileName, MakeHRFromErrorCode(errorCode)); - else - return new IOException(SR.Format(SR.IO_SharingViolation_File, path), MakeHRFromErrorCode(errorCode)); - + return new IOException( + string.IsNullOrEmpty(path) ? SR.IO_SharingViolation_NoFileName : SR.Format(SR.IO_SharingViolation_File, path), + MakeHRFromErrorCode(errorCode)); case Interop.Errors.ERROR_FILE_EXISTS: - if (path.Length == 0) + if (string.IsNullOrEmpty(path)) goto default; - return new IOException(SR.Format(SR.IO_FileExists_Name, path), MakeHRFromErrorCode(errorCode)); - case Interop.Errors.ERROR_OPERATION_ABORTED: return new OperationCanceledException(); - + case Interop.Errors.ERROR_INVALID_PARAMETER: default: - return new IOException(Interop.Kernel32.GetMessage(errorCode), MakeHRFromErrorCode(errorCode)); + return new IOException( + string.IsNullOrEmpty(path) ? GetMessage(errorCode) : $"{GetMessage(errorCode)} : '{path}'", + MakeHRFromErrorCode(errorCode)); } } /// - /// Returns a HRESULT for the specified Win32 error code. + /// If not already an HRESULT, returns an HRESULT for the specified Win32 error code. /// internal static int MakeHRFromErrorCode(int errorCode) { - Debug.Assert((0xFFFF0000 & errorCode) == 0, "This is an HRESULT, not an error code!"); + // Don't convert it if it is already an HRESULT + if ((0xFFFF0000 & errorCode) != 0) + return errorCode; return unchecked(((int)0x80070000) | errorCode); } + + /// + /// Returns a Win32 error code for the specified HRESULT if it came from FACILITY_WIN32 + /// If not, returns the HRESULT unchanged + /// + internal static int TryMakeWin32ErrorCodeFromHR(int hr) + { + if ((0xFFFF0000 & hr) == 0x80070000) + { + // Win32 error, Win32Marshal.GetExceptionForWin32Error expects the Win32 format + hr &= 0x0000FFFF; + } + + return hr; + } + + /// + /// Returns a string message for the specified Win32 error code. + /// + internal static string GetMessage(int errorCode) => Interop.Kernel32.GetMessage(errorCode); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IndexOutOfRangeException.cs b/external/corert/src/System.Private.CoreLib/shared/System/IndexOutOfRangeException.cs index b6d93ef568..aadc942314 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IndexOutOfRangeException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IndexOutOfRangeException.cs @@ -25,13 +25,13 @@ namespace System HResult = HResults.COR_E_INDEXOUTOFRANGE; } - public IndexOutOfRangeException(String message) + public IndexOutOfRangeException(string message) : base(message) { HResult = HResults.COR_E_INDEXOUTOFRANGE; } - public IndexOutOfRangeException(String message, Exception innerException) + public IndexOutOfRangeException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_INDEXOUTOFRANGE; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/InsufficientExecutionStackException.cs b/external/corert/src/System.Private.CoreLib/shared/System/InsufficientExecutionStackException.cs index 4822028f85..4c4bf242e1 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/InsufficientExecutionStackException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/InsufficientExecutionStackException.cs @@ -16,13 +16,13 @@ namespace System HResult = HResults.COR_E_INSUFFICIENTEXECUTIONSTACK; } - public InsufficientExecutionStackException(String message) + public InsufficientExecutionStackException(string message) : base(message) { HResult = HResults.COR_E_INSUFFICIENTEXECUTIONSTACK; } - public InsufficientExecutionStackException(String message, Exception innerException) + public InsufficientExecutionStackException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_INSUFFICIENTEXECUTIONSTACK; diff --git a/external/corert/src/System.Private.CoreLib/src/System/InsufficientMemoryException.cs b/external/corert/src/System.Private.CoreLib/shared/System/InsufficientMemoryException.cs similarity index 52% rename from external/corert/src/System.Private.CoreLib/src/System/InsufficientMemoryException.cs rename to external/corert/src/System.Private.CoreLib/shared/System/InsufficientMemoryException.cs index 4c510c4d7e..baa5c9e24a 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/InsufficientMemoryException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/InsufficientMemoryException.cs @@ -2,46 +2,43 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: The exception class for running out of memory -** but most likely in a non-fatal way that shouldn't -** be affected by escalation policy. Use this for cases -** like MemoryFailPoint or a TryAllocate method, where you -** expect OOM's with no shared state corruption and you -** want to recover from these errors. -** -** -=============================================================================*/ - using System; using System.Runtime.Serialization; namespace System { + /// + /// Purpose: The exception class for running out of memory + /// but most likely in a non-fatal way that shouldn't + /// be affected by escalation policy. Use this for cases + /// like MemoryFailPoint or a TryAllocate method, where you + /// expect OOM's with no shared state corruption and you + /// want to recover from these errors. + /// [Serializable] #if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] #endif public sealed class InsufficientMemoryException : OutOfMemoryException { - // There may be a problem here interacting with the ResourceManager in out of memory conditions, - // CoreCLR can fall back to literal strings. - public InsufficientMemoryException() - : base(SR.Arg_OutOfMemoryException) + public InsufficientMemoryException() : base( +#if CORECLR + GetMessageFromNativeResources(ExceptionMessageKind.OutOfMemory) +#else + SR.Arg_OutOfMemoryException +#endif + ) { HResult = HResults.COR_E_INSUFFICIENTMEMORY; } - public InsufficientMemoryException(String message) + public InsufficientMemoryException(string message) : base(message) { HResult = HResults.COR_E_INSUFFICIENTMEMORY; } - public InsufficientMemoryException(String message, Exception innerException) + public InsufficientMemoryException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_INSUFFICIENTMEMORY; @@ -49,6 +46,6 @@ namespace System private InsufficientMemoryException(SerializationInfo info, StreamingContext context) : base(info, context) { - } + } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Int16.cs b/external/corert/src/System.Private.CoreLib/shared/System/Int16.cs index fecc87e9fe..4973299763 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Int16.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Int16.cs @@ -12,9 +12,9 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Int16 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct Int16 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private short m_value; // Do not rename (binary serialization) + private readonly short m_value; // Do not rename (binary serialization) public const short MaxValue = (short)0x7FFF; public const short MinValue = unchecked((short)0x8000); @@ -25,37 +25,37 @@ namespace System // null is considered to be less than any instance. // If object is not of type Int16, this method throws an ArgumentException. // - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) { return 1; } - if (value is Int16) + if (value is short) { - return m_value - ((Int16)value).m_value; + return m_value - ((short)value).m_value; } throw new ArgumentException(SR.Arg_MustBeInt16); } - public int CompareTo(Int16 value) + public int CompareTo(short value) { return m_value - value; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is Int16)) + if (!(obj is short)) { return false; } - return m_value == ((Int16)obj).m_value; + return m_value == ((short)obj).m_value; } [NonVersionable] - public bool Equals(Int16 obj) + public bool Equals(short obj) { return m_value == obj; } @@ -67,22 +67,22 @@ namespace System } - public override String ToString() + public override string ToString() { return Number.FormatInt32(m_value, null, null); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatInt32(m_value, null, provider); } - public String ToString(String format) + public string ToString(string format) { return ToString(format, null); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { @@ -103,26 +103,26 @@ namespace System return Number.TryFormatInt32(m_value, format, provider, destination, out charsWritten); } - public static short Parse(String s) + public static short Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } - public static short Parse(String s, NumberStyles style) + public static short Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, style, NumberFormatInfo.CurrentInfo); } - public static short Parse(String s, IFormatProvider provider) + public static short Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } - public static short Parse(String s, NumberStyles style, IFormatProvider provider) + public static short Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -151,7 +151,7 @@ namespace System // for negative numbers if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number - if ((i < 0) || (i > UInt16.MaxValue)) + if ((i < 0) || (i > ushort.MaxValue)) { throw new OverflowException(SR.Overflow_Int16); } @@ -162,7 +162,7 @@ namespace System return (short)i; } - public static bool TryParse(String s, out Int16 result) + public static bool TryParse(string s, out short result) { if (s == null) { @@ -178,7 +178,7 @@ namespace System return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } - public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int16 result) + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out short result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -197,7 +197,7 @@ namespace System return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } - private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out Int16 result) + private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out short result) { result = 0; int i; @@ -210,11 +210,11 @@ namespace System // for negative numbers if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number - if ((i < 0) || i > UInt16.MaxValue) + if ((i < 0) || i > ushort.MaxValue) { return false; } - result = (Int16)i; + result = (short)i; return true; } @@ -222,7 +222,7 @@ namespace System { return false; } - result = (Int16)i; + result = (short)i; return true; } @@ -296,7 +296,7 @@ namespace System return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -306,7 +306,7 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int16", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Int32.cs b/external/corert/src/System.Private.CoreLib/shared/System/Int32.cs index b573e950e4..1d0aefe73c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Int32.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Int32.cs @@ -12,9 +12,9 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Int32 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct Int32 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private int m_value; // Do not rename (binary serialization) + private readonly int m_value; // Do not rename (binary serialization) public const int MaxValue = 0x7fffffff; public const int MinValue = unchecked((int)0x80000000); @@ -28,13 +28,13 @@ namespace System // null is considered to be less than any instance, hence returns positive number // If object is not of type Int32, this method throws an ArgumentException. // - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) { return 1; } - if (value is Int32) + if (value is int) { // NOTE: Cannot use return (_value - value) as this causes a wrap // around in cases where _value - value > MaxValue. @@ -55,17 +55,17 @@ namespace System return 0; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is Int32)) + if (!(obj is int)) { return false; } - return m_value == ((Int32)obj).m_value; + return m_value == ((int)obj).m_value; } [NonVersionable] - public bool Equals(Int32 obj) + public bool Equals(int obj) { return m_value == obj; } @@ -76,22 +76,22 @@ namespace System return m_value; } - public override String ToString() + public override string ToString() { return Number.FormatInt32(m_value, null, null); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatInt32(m_value, format, null); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatInt32(m_value, null, provider); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatInt32(m_value, format, provider); } @@ -101,13 +101,13 @@ namespace System return Number.TryFormatInt32(m_value, format, provider, destination, out charsWritten); } - public static int Parse(String s) + public static int Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } - public static int Parse(String s, NumberStyles style) + public static int Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -118,7 +118,7 @@ namespace System // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // - public static int Parse(String s, IFormatProvider provider) + public static int Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); @@ -128,7 +128,7 @@ namespace System // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // - public static int Parse(String s, NumberStyles style, IFormatProvider provider) + public static int Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -144,7 +144,7 @@ namespace System // Parses an integer from a String. Returns false rather // than throwing exceptin if input is invalid // - public static bool TryParse(String s, out Int32 result) + public static bool TryParse(string s, out int result) { if (s == null) { @@ -163,7 +163,7 @@ namespace System // Parses an integer from a String in the given style. Returns false rather // than throwing exceptin if input is invalid // - public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result) + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out int result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -251,7 +251,7 @@ namespace System return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -261,7 +261,7 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int32", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Int64.cs b/external/corert/src/System.Private.CoreLib/shared/System/Int64.cs index 0bcca87309..62c9ffd4fe 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Int64.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Int64.cs @@ -12,9 +12,9 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Int64 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct Int64 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private long m_value; // Do not rename (binary serialization) + private readonly long m_value; // Do not rename (binary serialization) public const long MaxValue = 0x7fffffffffffffffL; public const long MinValue = unchecked((long)0x8000000000000000L); @@ -25,13 +25,13 @@ namespace System // null is considered to be less than any instance. // If object is not of type Int64, this method throws an ArgumentException. // - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) { return 1; } - if (value is Int64) + if (value is long) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. @@ -43,7 +43,7 @@ namespace System throw new ArgumentException(SR.Arg_MustBeInt64); } - public int CompareTo(Int64 value) + public int CompareTo(long value) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. @@ -52,17 +52,17 @@ namespace System return 0; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is Int64)) + if (!(obj is long)) { return false; } - return m_value == ((Int64)obj).m_value; + return m_value == ((long)obj).m_value; } [NonVersionable] - public bool Equals(Int64 obj) + public bool Equals(long obj) { return m_value == obj; } @@ -73,22 +73,22 @@ namespace System return (unchecked((int)((long)m_value)) ^ (int)(m_value >> 32)); } - public override String ToString() + public override string ToString() { return Number.FormatInt64(m_value, null, null); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatInt64(m_value, null, provider); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatInt64(m_value, format, null); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatInt64(m_value, format, provider); } @@ -98,20 +98,20 @@ namespace System return Number.TryFormatInt64(m_value, format, provider, destination, out charsWritten); } - public static long Parse(String s) + public static long Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } - public static long Parse(String s, NumberStyles style) + public static long Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt64(s, style, NumberFormatInfo.CurrentInfo); } - public static long Parse(String s, IFormatProvider provider) + public static long Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); @@ -122,7 +122,7 @@ namespace System // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // - public static long Parse(String s, NumberStyles style, IFormatProvider provider) + public static long Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -135,7 +135,7 @@ namespace System return Number.ParseInt64(s, style, NumberFormatInfo.GetInstance(provider)); } - public static Boolean TryParse(String s, out Int64 result) + public static bool TryParse(string s, out long result) { if (s == null) { @@ -151,7 +151,7 @@ namespace System return Number.TryParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } - public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Int64 result) + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out long result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -239,7 +239,7 @@ namespace System return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -249,7 +249,7 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int64", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/IntPtr.cs b/external/corert/src/System.Private.CoreLib/shared/System/IntPtr.cs index 45c2ded160..d23742fa7b 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/IntPtr.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/IntPtr.cs @@ -17,13 +17,13 @@ namespace System { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct IntPtr : IEquatable, ISerializable + public readonly struct IntPtr : IEquatable, ISerializable { // WARNING: We allow diagnostic tools to directly inspect this member (_value). // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. - unsafe private void* _value; // Do not rename (binary serialization) + private readonly unsafe void* _value; // Do not rename (binary serialization) [Intrinsic] public static readonly IntPtr Zero; @@ -72,7 +72,7 @@ namespace System info.AddValue("value", ToInt64()); } - public unsafe override bool Equals(Object obj) + public unsafe override bool Equals(object obj) { if (obj is IntPtr) { @@ -81,9 +81,9 @@ namespace System return false; } - unsafe bool IEquatable.Equals(IntPtr value) + unsafe bool IEquatable.Equals(IntPtr other) { - return _value == value._value; + return _value == other._value; } public unsafe override int GetHashCode() @@ -217,6 +217,9 @@ namespace System [CLSCompliant(false)] [Intrinsic] [NonVersionable] +#if PROJECTN + [System.Runtime.CompilerServices.DependencyReductionRootAttribute] +#endif public unsafe void* ToPointer() { return _value; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/InvalidCastException.cs b/external/corert/src/System.Private.CoreLib/shared/System/InvalidCastException.cs index 055643278a..cb6036aeb4 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/InvalidCastException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/InvalidCastException.cs @@ -22,19 +22,19 @@ namespace System HResult = HResults.COR_E_INVALIDCAST; } - public InvalidCastException(String message) + public InvalidCastException(string message) : base(message) { HResult = HResults.COR_E_INVALIDCAST; } - public InvalidCastException(String message, Exception innerException) + public InvalidCastException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_INVALIDCAST; } - public InvalidCastException(String message, int errorCode) + public InvalidCastException(string message, int errorCode) : base(message) { HResult = errorCode; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/InvalidOperationException.cs b/external/corert/src/System.Private.CoreLib/shared/System/InvalidOperationException.cs index 62c222af40..9fffbec433 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/InvalidOperationException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/InvalidOperationException.cs @@ -26,13 +26,13 @@ namespace System HResult = HResults.COR_E_INVALIDOPERATION; } - public InvalidOperationException(String message) + public InvalidOperationException(string message) : base(message) { HResult = HResults.COR_E_INVALIDOPERATION; } - public InvalidOperationException(String message, Exception innerException) + public InvalidOperationException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_INVALIDOPERATION; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/InvalidProgramException.cs b/external/corert/src/System.Private.CoreLib/shared/System/InvalidProgramException.cs index c8047c548b..62a14f9116 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/InvalidProgramException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/InvalidProgramException.cs @@ -25,13 +25,13 @@ namespace System HResult = HResults.COR_E_INVALIDPROGRAM; } - public InvalidProgramException(String message) + public InvalidProgramException(string message) : base(message) { HResult = HResults.COR_E_INVALIDPROGRAM; } - public InvalidProgramException(String message, Exception inner) + public InvalidProgramException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_INVALIDPROGRAM; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/InvalidTimeZoneException.cs b/external/corert/src/System.Private.CoreLib/shared/System/InvalidTimeZoneException.cs index 25b155e8d1..1bbb7e067b 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/InvalidTimeZoneException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/InvalidTimeZoneException.cs @@ -14,12 +14,12 @@ namespace System { } - public InvalidTimeZoneException(String message) + public InvalidTimeZoneException(string message) : base(message) { } - public InvalidTimeZoneException(String message, Exception innerException) + public InvalidTimeZoneException(string message, Exception innerException) : base(message, innerException) { } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Lazy.cs b/external/corert/src/System.Private.CoreLib/shared/System/Lazy.cs index 6410c2e285..02122ca05e 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Lazy.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Lazy.cs @@ -119,7 +119,7 @@ namespace System default: Debug.Fail("Invalid logic; State should always have a valid value"); - return default(LazyThreadSafetyMode); + return default; } } @@ -454,7 +454,7 @@ namespace System { if (!IsValueCreated) { - return default(T); + return default; } return _value; } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Marvin.cs b/external/corert/src/System.Private.CoreLib/shared/System/Marvin.cs similarity index 61% rename from external/corert/src/System.Private.CoreLib/src/System/Marvin.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Marvin.cs index f703423e67..d25a244c93 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Marvin.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Marvin.cs @@ -2,42 +2,44 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics.Private; +using System.Diagnostics; using System.Runtime.CompilerServices; - +using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; +#if BIT64 +using nuint = System.UInt64; +#else +using nuint = System.UInt32; +#endif + namespace System { internal static class Marvin { /// - /// Convenience method to compute a Marvin hash and collapse it into a 32-bit hash. + /// Compute a Marvin hash and collapse it into a 32-bit hash. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int ComputeHash32(ref byte data, int count, ulong seed) - { - long hash64 = ComputeHash(ref data, count, seed); - return ((int)(hash64 >> 32)) ^ (int)hash64; - } + public static int ComputeHash32(ReadOnlySpan data, ulong seed) => ComputeHash32(ref MemoryMarshal.GetReference(data), data.Length, seed); /// - /// Computes a 64-hash using the Marvin algorithm. + /// Compute a Marvin hash and collapse it into a 32-bit hash. /// - public static long ComputeHash(ref byte data, int count, ulong seed) + public static int ComputeHash32(ref byte data, int count, ulong seed) { - uint ucount = (uint)count; + nuint ucount = (nuint)count; uint p0 = (uint)seed; uint p1 = (uint)(seed >> 32); - int byteOffset = 0; // declared as signed int so we don't have to cast everywhere (it's passed to Unsafe.Add() and used for nothing else.) + nuint byteOffset = 0; while (ucount >= 8) { - p0 += Unsafe.As(ref Unsafe.Add(ref data, byteOffset)); + p0 += Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref data, byteOffset)); Block(ref p0, ref p1); - p0 += Unsafe.As(ref Unsafe.Add(ref data, byteOffset + 4)); + p0 += Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref data, byteOffset + 4)); Block(ref p0, ref p1); byteOffset += 8; @@ -47,7 +49,7 @@ namespace System switch (ucount) { case 4: - p0 += Unsafe.As(ref Unsafe.Add(ref data, byteOffset)); + p0 += Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref data, byteOffset)); Block(ref p0, ref p1); goto case 0; @@ -56,33 +58,33 @@ namespace System break; case 5: - p0 += Unsafe.As(ref Unsafe.Add(ref data, byteOffset)); + p0 += Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref data, byteOffset)); byteOffset += 4; Block(ref p0, ref p1); goto case 1; case 1: - p0 += 0x8000u | Unsafe.Add(ref data, byteOffset); + p0 += 0x8000u | Unsafe.AddByteOffset(ref data, byteOffset); break; case 6: - p0 += Unsafe.As(ref Unsafe.Add(ref data, byteOffset)); + p0 += Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref data, byteOffset)); byteOffset += 4; Block(ref p0, ref p1); goto case 2; case 2: - p0 += 0x800000u | Unsafe.As(ref Unsafe.Add(ref data, byteOffset)); + p0 += 0x800000u | Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref data, byteOffset)); break; case 7: - p0 += Unsafe.As(ref Unsafe.Add(ref data, byteOffset)); + p0 += Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref data, byteOffset)); byteOffset += 4; Block(ref p0, ref p1); goto case 3; case 3: - p0 += 0x80000000u | (((uint)(Unsafe.Add(ref data, byteOffset + 2))) << 16)| (uint)(Unsafe.As(ref Unsafe.Add(ref data, byteOffset))); + p0 += 0x80000000u | (((uint)(Unsafe.AddByteOffset(ref data, byteOffset + 2))) << 16)| (uint)(Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref data, byteOffset))); break; default: @@ -93,7 +95,7 @@ namespace System Block(ref p0, ref p1); Block(ref p0, ref p1); - return (((long)p1) << 32) | p0; + return (int)(p1 ^ p0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -125,20 +127,15 @@ namespace System return (value << shift) | (value >> (32 - shift)); } - public static ulong DefaultSeed => s_defaultSeed; + public static ulong DefaultSeed { get; } = GenerateSeed(); - private static ulong s_defaultSeed = GenerateSeed(); - - private static ulong GenerateSeed() + private static unsafe ulong GenerateSeed() { #if MONO return 839433921; #else ulong seed; - unsafe - { - Interop.GetRandomBytes((byte*)&seed, sizeof(ulong)); - } + Interop.GetRandomBytes((byte*)&seed, sizeof(ulong)); return seed; #endif } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Math.cs b/external/corert/src/System.Private.CoreLib/shared/System/Math.cs index a175103f81..ef46869e22 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Math.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Math.cs @@ -123,15 +123,25 @@ namespace System public static long DivRem(long a, long b, out long result) { - // TODO https://github.com/dotnet/coreclr/issues/3439: - // Restore to using % and / when the JIT is able to eliminate one of the idivs. - // In the meantime, a * and - is measurably faster than an extra /. - long div = a / b; result = a - (div * b); return div; } + internal static uint DivRem(uint a, uint b, out uint result) + { + uint div = a / b; + result = a - (div * b); + return div; + } + + internal static ulong DivRem(ulong a, ulong b, out ulong result) + { + ulong div = a / b; + result = a - (div * b); + return div; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Ceiling(decimal d) { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/MemberAccessException.cs b/external/corert/src/System.Private.CoreLib/shared/System/MemberAccessException.cs index dfea52dbed..0cf1e0fbeb 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/MemberAccessException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/MemberAccessException.cs @@ -31,13 +31,13 @@ namespace System // message, its HRESULT set to COR_E_ACCESS, // and its ExceptionInfo reference set to null. // - public MemberAccessException(String message) + public MemberAccessException(string message) : base(message) { HResult = HResults.COR_E_MEMBERACCESS; } - public MemberAccessException(String message, Exception inner) + public MemberAccessException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_MEMBERACCESS; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Memory.cs b/external/corert/src/System.Private.CoreLib/shared/System/Memory.cs index fca015f5e5..1a7556720d 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Memory.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Memory.cs @@ -8,9 +8,8 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; -#if !FEATURE_PORTABLE_SPAN + using Internal.Runtime.CompilerServices; -#endif // FEATURE_PORTABLE_SPAN namespace System { @@ -18,23 +17,26 @@ namespace System /// Memory represents a contiguous region of arbitrary memory similar to . /// Unlike , it is not a byref-like type. /// - [DebuggerDisplay("{DebuggerDisplay,nq}")] [DebuggerTypeProxy(typeof(MemoryDebugView<>))] + [DebuggerDisplay("{ToString(),raw}")] public readonly struct Memory { // NOTE: With the current implementation, Memory and ReadOnlyMemory must have the same layout, // as code uses Unsafe.As to cast between them. // The highest order bit of _index is used to discern whether _object is an array/string or an owned memory - // if (_index >> 31) == 1, object _object is an OwnedMemory - // else, object _object is a T[] or a string. It can only be a string if the Memory was created by + // if (_index >> 31) == 1, object _object is an MemoryManager + // else, object _object is a T[] or a string. + // if (_length >> 31) == 1, _object is a pre-pinned array, so Pin() will not allocate a new GCHandle + // else, Pin() needs to allocate a new GCHandle to pin the object. + // It can only be a string if the Memory was created by // using unsafe / marshaling code to reinterpret a ReadOnlyMemory wrapped around a string as // a Memory. private readonly object _object; private readonly int _index; private readonly int _length; - private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF; + private const int RemoveFlagsBitMask = 0x7FFFFFFF; /// /// Creates a new memory over the entirety of the target array. @@ -110,22 +112,61 @@ namespace System _length = length; } - // Constructor for internal use only. + /// + /// Creates a new memory from a memory manager that provides specific method implementations beginning + /// at 0 index and ending at 'end' index (exclusive). + /// + /// The memory manager. + /// The number of items in the memory. + /// + /// Thrown when the specified is negative. + /// + /// For internal infrastructure only [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal Memory(OwnedMemory owner, int index, int length) + internal Memory(MemoryManager manager, int length) { - // No validation performed; caller must provide any necessary validation. - _object = owner; - _index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask + Debug.Assert(manager != null); + + if (length < 0) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + _object = manager; + _index = (1 << 31); // Mark as MemoryManager type + // Before using _index, check if _index < 0, then 'and' it with RemoveFlagsBitMask + _length = length; + } + + /// + /// Creates a new memory from a memory manager that provides specific method implementations beginning + /// at 'start' index and ending at 'end' index (exclusive). + /// + /// The memory manager. + /// The index at which to begin the memory. + /// The number of items in the memory. + /// + /// Thrown when the specified or is negative. + /// + /// For internal infrastructure only + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Memory(MemoryManager manager, int start, int length) + { + Debug.Assert(manager != null); + + if (length < 0 || start < 0) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + _object = manager; + _index = start | (1 << 31); // Mark as MemoryManager type + // Before using _index, check if _index < 0, then 'and' it with RemoveFlagsBitMask _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private Memory(object obj, int index, int length) + internal Memory(object obj, int start, int length) { // No validation performed; caller must provide any necessary validation. _object = obj; - _index = index; + _index = start; _length = length; } @@ -137,7 +178,7 @@ namespace System /// /// Defines an implicit conversion of a to a /// - public static implicit operator Memory(ArraySegment arraySegment) => new Memory(arraySegment.Array, arraySegment.Offset, arraySegment.Count); + public static implicit operator Memory(ArraySegment segment) => new Memory(segment.Array, segment.Offset, segment.Count); /// /// Defines an implicit conversion of a to a @@ -145,9 +186,6 @@ namespace System public static implicit operator ReadOnlyMemory(Memory memory) => Unsafe.As, ReadOnlyMemory>(ref memory); - //Debugger Display = {T[length]} - private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length); - /// /// Returns an empty /// @@ -156,12 +194,25 @@ namespace System /// /// The number of items in the memory. /// - public int Length => _length; + public int Length => _length & RemoveFlagsBitMask; /// /// Returns true if Length is 0. /// - public bool IsEmpty => _length == 0; + public bool IsEmpty => (_length & RemoveFlagsBitMask) == 0; + + /// + /// For , returns a new instance of string that represents the characters pointed to by the memory. + /// Otherwise, returns a with the name of the type and the number of elements. + /// + public override string ToString() + { + if (typeof(T) == typeof(char)) + { + return (_object is string str) ? str.Substring(_index, _length & RemoveFlagsBitMask) : Span.ToString(); + } + return string.Format("System.Memory<{0}>[{1}]", typeof(T).Name, _length & RemoveFlagsBitMask); + } /// /// Forms a slice out of the given memory, beginning at 'start'. @@ -173,12 +224,16 @@ namespace System [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory Slice(int start) { - if ((uint)start > (uint)_length) + // Used to maintain the high-bit which indicates whether the Memory has been pre-pinned or not. + int capturedLength = _length; + int actualLength = capturedLength & RemoveFlagsBitMask; + if ((uint)start > (uint)actualLength) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } - return new Memory(_object, _index + start, _length - start); + // It is expected for (capturedLength - start) to be negative if the memory is already pre-pinned. + return new Memory(_object, _index + start, capturedLength - start); } /// @@ -192,12 +247,16 @@ namespace System [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory Slice(int start, int length) { - if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) + // Used to maintain the high-bit which indicates whether the Memory has been pre-pinned or not. + int capturedLength = _length; + int actualLength = capturedLength & RemoveFlagsBitMask; + if ((uint)start > (uint)actualLength || (uint)length > (uint)(actualLength - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(); } - return new Memory(_object, _index + start, length); + // Set the high-bit to match the this._length high bit (1 for pre-pinned, 0 for unpinned). + return new Memory(_object, _index + start, length | (capturedLength & ~RemoveFlagsBitMask)); } /// @@ -210,24 +269,23 @@ namespace System { if (_index < 0) { - return ((OwnedMemory)_object).Span.Slice(_index & RemoveOwnedFlagBitMask, _length); + Debug.Assert(_length >= 0); + Debug.Assert(_object != null); + return ((MemoryManager)_object).GetSpan().Slice(_index & RemoveFlagsBitMask, _length); } else if (typeof(T) == typeof(char) && _object is string s) { + Debug.Assert(_length >= 0); // This is dangerous, returning a writable span for a string that should be immutable. // However, we need to handle the case where a ReadOnlyMemory was created from a string // and then cast to a Memory. Such a cast can only be done with unsafe or marshaling code, // in which case that's the dangerous operation performed by the dev, and we're just following // suit here to make it work as best as possible. -#if FEATURE_PORTABLE_SPAN - return new Span(Unsafe.As>(s), MemoryExtensions.StringAdjustment, s.Length).Slice(_index, _length); -#else return new Span(ref Unsafe.As(ref s.GetRawStringData()), s.Length).Slice(_index, _length); -#endif // FEATURE_PORTABLE_SPAN } else if (_object != null) { - return new Span((T[])_object, _index, _length); + return new Span((T[])_object, _index, _length & RemoveFlagsBitMask); } else { @@ -260,53 +318,47 @@ namespace System public bool TryCopyTo(Memory destination) => Span.TryCopyTo(destination.Span); /// - /// Returns a handle for the array. - /// If pin is true, the GC will not move the array and hence its address can be taken + /// Creates a handle for the memory. + /// The GC will not move the memory until the returned + /// is disposed, enabling taking and using the memory's address. + /// + /// An instance with nonprimitive (non-blittable) members cannot be pinned. + /// /// - public unsafe MemoryHandle Retain(bool pin = false) + public unsafe MemoryHandle Pin() { - MemoryHandle memoryHandle = default; - if (pin) + if (_index < 0) { - if (_index < 0) + Debug.Assert(_object != null); + return ((MemoryManager)_object).Pin((_index & RemoveFlagsBitMask)); + } + else if (typeof(T) == typeof(char) && _object is string s) + { + // This case can only happen if a ReadOnlyMemory was created around a string + // and then that was cast to a Memory using unsafe / marshaling code. This needs + // to work, however, so that code that uses a single Memory field to store either + // a readable ReadOnlyMemory or a writable Memory can still be pinned and + // used for interop purposes. + GCHandle handle = GCHandle.Alloc(s, GCHandleType.Pinned); + void* pointer = Unsafe.Add(Unsafe.AsPointer(ref s.GetRawStringData()), _index); + return new MemoryHandle(pointer, handle); + } + else if (_object is T[] array) + { + // Array is already pre-pinned + if (_length < 0) { - memoryHandle = ((OwnedMemory)_object).Pin((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf()); - } - else if (typeof(T) == typeof(char) && _object is string s) - { - // This case can only happen if a ReadOnlyMemory was created around a string - // and then that was cast to a Memory using unsafe / marshaling code. This needs - // to work, however, so that code that uses a single Memory field to store either - // a readable ReadOnlyMemory or a writable Memory can still be pinned and - // used for interop purposes. - GCHandle handle = GCHandle.Alloc(s, GCHandleType.Pinned); -#if FEATURE_PORTABLE_SPAN - void* pointer = Unsafe.Add((void*)handle.AddrOfPinnedObject(), _index); -#else - void* pointer = Unsafe.Add(Unsafe.AsPointer(ref s.GetRawStringData()), _index); -#endif // FEATURE_PORTABLE_SPAN - memoryHandle = new MemoryHandle(null, pointer, handle); - } - else if (_object is T[] array) - { - var handle = GCHandle.Alloc(array, GCHandleType.Pinned); -#if FEATURE_PORTABLE_SPAN - void* pointer = Unsafe.Add((void*)handle.AddrOfPinnedObject(), _index); -#else void* pointer = Unsafe.Add(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index); -#endif // FEATURE_PORTABLE_SPAN - memoryHandle = new MemoryHandle(null, pointer, handle); + return new MemoryHandle(pointer); } - } - else - { - if (_index < 0) + else { - ((OwnedMemory)_object).Retain(); - memoryHandle = new MemoryHandle((OwnedMemory)_object); + GCHandle handle = GCHandle.Alloc(array, GCHandleType.Pinned); + void* pointer = Unsafe.Add(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index); + return new MemoryHandle(pointer, handle); } } - return memoryHandle; + return default; } /// diff --git a/external/corert/src/System.Private.CoreLib/shared/System/MemoryDebugView.cs b/external/corert/src/System.Private.CoreLib/shared/System/MemoryDebugView.cs index b1ed881990..6ab6e5065c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/MemoryDebugView.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/MemoryDebugView.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Runtime.InteropServices; namespace System { @@ -22,31 +21,6 @@ namespace System } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public T[] Items - { - // This is a work around since we cannot use _memory.ToArray() due to - // https://devdiv.visualstudio.com/DevDiv/_workitems?id=286592 - get - { - if (MemoryMarshal.TryGetArray(_memory, out ArraySegment segment)) - { - T[] array = new T[_memory.Length]; - Array.Copy(segment.Array, segment.Offset, array, 0, array.Length); - return array; - } - - if (typeof(T) == typeof(char) && - MemoryMarshal.TryGetString((ReadOnlyMemory)(object)_memory, out string text, out int start, out int length)) - { - return (T[])(object)text.Substring(start, length).ToCharArray(); - } - -#if FEATURE_PORTABLE_SPAN - return SpanHelpers.PerTypeValues.EmptyArray; -#else - return Array.Empty(); -#endif // FEATURE_PORTABLE_SPAN - } - } + public T[] Items => _memory.ToArray(); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs b/external/corert/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs index 56dd203e1f..e86ca4fcd6 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs @@ -28,81 +28,93 @@ namespace System } /// - /// Determines whether this and the specified span have the same characters + /// Determines whether this and the specified span have the same characters /// when compared using the specified option. /// The source span. - /// The value to compare with the source span. - /// One of the enumeration values that determines how the and are compared. + /// The value to compare with the source span. + /// One of the enumeration values that determines how the and are compared. /// - public static bool Equals(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) + public static bool Equals(this ReadOnlySpan span, ReadOnlySpan other, StringComparison comparisonType) { - StringSpanHelpers.CheckStringComparison(comparisonType); + string.CheckStringComparison(comparisonType); switch (comparisonType) { case StringComparison.CurrentCulture: - return (CultureInfo.CurrentCulture.CompareInfo.Compare(span, value, CompareOptions.None) == 0); + return (CultureInfo.CurrentCulture.CompareInfo.CompareOptionNone(span, other) == 0); case StringComparison.CurrentCultureIgnoreCase: - return (CultureInfo.CurrentCulture.CompareInfo.Compare(span, value, CompareOptions.IgnoreCase) == 0); + return (CultureInfo.CurrentCulture.CompareInfo.CompareOptionIgnoreCase(span, other) == 0); case StringComparison.InvariantCulture: - return (CompareInfo.Invariant.Compare(span, value, CompareOptions.None) == 0); + return (CompareInfo.Invariant.CompareOptionNone(span, other) == 0); case StringComparison.InvariantCultureIgnoreCase: - return (CompareInfo.Invariant.Compare(span, value, CompareOptions.IgnoreCase) == 0); + return (CompareInfo.Invariant.CompareOptionIgnoreCase(span, other) == 0); case StringComparison.Ordinal: - if (span.Length != value.Length) - return false; - if (value.Length == 0) // span.Length == value.Length == 0 - return true; - return span.SequenceEqual(value); //TODO: Optimize - https://github.com/dotnet/corefx/issues/27487 + return EqualsOrdinal(span, other); case StringComparison.OrdinalIgnoreCase: - if (span.Length != value.Length) - return false; - if (value.Length == 0) // span.Length == value.Length == 0 - return true; - return (CompareInfo.CompareOrdinalIgnoreCase(span, value) == 0); + return EqualsOrdinalIgnoreCase(span, other); } Debug.Fail("StringComparison outside range"); return false; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool EqualsOrdinal(this ReadOnlySpan span, ReadOnlySpan value) + { + if (span.Length != value.Length) + return false; + if (value.Length == 0) // span.Length == value.Length == 0 + return true; + return span.SequenceEqual(value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool EqualsOrdinalIgnoreCase(this ReadOnlySpan span, ReadOnlySpan value) + { + if (span.Length != value.Length) + return false; + if (value.Length == 0) // span.Length == value.Length == 0 + return true; + return CompareInfo.EqualsOrdinalIgnoreCase(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), span.Length); + } + /// - /// Compares the specified and using the specified , + /// Compares the specified and using the specified , /// and returns an integer that indicates their relative position in the sort order. /// The source span. - /// The value to compare with the source span. - /// One of the enumeration values that determines how the and are compared. + /// The value to compare with the source span. + /// One of the enumeration values that determines how the and are compared. /// - public static int CompareTo(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) + public static int CompareTo(this ReadOnlySpan span, ReadOnlySpan other, StringComparison comparisonType) { - StringSpanHelpers.CheckStringComparison(comparisonType); + string.CheckStringComparison(comparisonType); switch (comparisonType) { case StringComparison.CurrentCulture: - return CultureInfo.CurrentCulture.CompareInfo.Compare(span, value, CompareOptions.None); + return CultureInfo.CurrentCulture.CompareInfo.CompareOptionNone(span, other); case StringComparison.CurrentCultureIgnoreCase: - return CultureInfo.CurrentCulture.CompareInfo.Compare(span, value, CompareOptions.IgnoreCase); + return CultureInfo.CurrentCulture.CompareInfo.CompareOptionIgnoreCase(span, other); case StringComparison.InvariantCulture: - return CompareInfo.Invariant.Compare(span, value, CompareOptions.None); + return CompareInfo.Invariant.CompareOptionNone(span, other); case StringComparison.InvariantCultureIgnoreCase: - return CompareInfo.Invariant.Compare(span, value, CompareOptions.IgnoreCase); + return CompareInfo.Invariant.CompareOptionIgnoreCase(span, other); case StringComparison.Ordinal: - if (span.Length == 0 || value.Length == 0) - return span.Length - value.Length; - return string.CompareOrdinal(span, value); + if (span.Length == 0 || other.Length == 0) + return span.Length - other.Length; + return string.CompareOrdinal(span, other); case StringComparison.OrdinalIgnoreCase: - return CompareInfo.CompareOrdinalIgnoreCase(span, value); + return CompareInfo.CompareOrdinalIgnoreCase(span, other); } Debug.Fail("StringComparison outside range"); @@ -117,7 +129,7 @@ namespace System /// public static int IndexOf(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) { - StringSpanHelpers.CheckStringComparison(comparisonType); + string.CheckStringComparison(comparisonType); if (value.Length == 0) { @@ -129,29 +141,66 @@ namespace System return -1; } + if (GlobalizationMode.Invariant) + { + return CompareInfo.InvariantIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None); + } + switch (comparisonType) { case StringComparison.CurrentCulture: - return SpanHelpers.IndexOfCultureHelper(span, value, CultureInfo.CurrentCulture.CompareInfo); - case StringComparison.CurrentCultureIgnoreCase: - return SpanHelpers.IndexOfCultureIgnoreCaseHelper(span, value, CultureInfo.CurrentCulture.CompareInfo); + return CultureInfo.CurrentCulture.CompareInfo.IndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: - return SpanHelpers.IndexOfCultureHelper(span, value, CompareInfo.Invariant); - case StringComparison.InvariantCultureIgnoreCase: - return SpanHelpers.IndexOfCultureIgnoreCaseHelper(span, value, CompareInfo.Invariant); + return CompareInfo.Invariant.IndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); - case StringComparison.Ordinal: - return SpanHelpers.IndexOfOrdinalHelper(span, value, ignoreCase: false); + default: + Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase); + return CompareInfo.Invariant.IndexOfOrdinal(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None); + } + } - case StringComparison.OrdinalIgnoreCase: - return SpanHelpers.IndexOfOrdinalHelper(span, value, ignoreCase: true); + /// + /// Reports the zero-based index of the last occurrence of the specified in the current . + /// The source span. + /// The value to seek within the source span. + /// One of the enumeration values that determines how the and are compared. + /// + public static int LastIndexOf(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) + { + string.CheckStringComparison(comparisonType); + + if (value.Length == 0) + { + return span.Length > 0 ? span.Length - 1 : 0; } - Debug.Fail("StringComparison outside range"); - return -1; + if (span.Length == 0) + { + return -1; + } + + if (GlobalizationMode.Invariant) + { + return CompareInfo.InvariantIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None, fromBeginning: false); + } + + switch (comparisonType) + { + case StringComparison.CurrentCulture: + case StringComparison.CurrentCultureIgnoreCase: + return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); + + case StringComparison.InvariantCulture: + case StringComparison.InvariantCultureIgnoreCase: + return CompareInfo.Invariant.LastIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); + + default: + Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase); + return CompareInfo.Invariant.LastIndexOfOrdinal(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None); + } } /// @@ -163,6 +212,7 @@ namespace System /// An object that supplies culture-specific casing rules. /// If the source and destinations overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten. + /// The number of characters written into the destination span. If the destination is too small, returns -1. /// /// Thrown when is null. /// @@ -176,7 +226,7 @@ namespace System return -1; if (GlobalizationMode.Invariant) - culture.TextInfo.ToLowerAsciiInvariant(source, destination); + TextInfo.ToLowerAsciiInvariant(source, destination); else culture.TextInfo.ChangeCase(source, destination, toUpper: false); return source.Length; @@ -190,6 +240,7 @@ namespace System /// The destination span which contains the transformed characters. /// If the source and destinations overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten. + /// The number of characters written into the destination span. If the destination is too small, returns -1. public static int ToLowerInvariant(this ReadOnlySpan source, Span destination) { // Assuming that changing case does not affect length @@ -197,7 +248,7 @@ namespace System return -1; if (GlobalizationMode.Invariant) - CultureInfo.InvariantCulture.TextInfo.ToLowerAsciiInvariant(source, destination); + TextInfo.ToLowerAsciiInvariant(source, destination); else CultureInfo.InvariantCulture.TextInfo.ChangeCase(source, destination, toUpper: false); return source.Length; @@ -212,6 +263,7 @@ namespace System /// An object that supplies culture-specific casing rules. /// If the source and destinations overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten. + /// The number of characters written into the destination span. If the destination is too small, returns -1. /// /// Thrown when is null. /// @@ -225,7 +277,7 @@ namespace System return -1; if (GlobalizationMode.Invariant) - culture.TextInfo.ToUpperAsciiInvariant(source, destination); + TextInfo.ToUpperAsciiInvariant(source, destination); else culture.TextInfo.ChangeCase(source, destination, toUpper: true); return source.Length; @@ -239,6 +291,7 @@ namespace System /// The destination span which contains the transformed characters. /// If the source and destinations overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten. + /// The number of characters written into the destination span. If the destination is too small, returns -1. public static int ToUpperInvariant(this ReadOnlySpan source, Span destination) { // Assuming that changing case does not affect length @@ -246,7 +299,7 @@ namespace System return -1; if (GlobalizationMode.Invariant) - CultureInfo.InvariantCulture.TextInfo.ToUpperAsciiInvariant(source, destination); + TextInfo.ToUpperAsciiInvariant(source, destination); else CultureInfo.InvariantCulture.TextInfo.ChangeCase(source, destination, toUpper: true); return source.Length; @@ -260,35 +313,29 @@ namespace System /// One of the enumeration values that determines how the and are compared. public static bool EndsWith(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) { + string.CheckStringComparison(comparisonType); + if (value.Length == 0) { - StringSpanHelpers.CheckStringComparison(comparisonType); return true; } - switch (comparisonType) + if (comparisonType >= StringComparison.Ordinal || GlobalizationMode.Invariant) { - case StringComparison.CurrentCulture: - return SpanHelpers.EndsWithCultureHelper(span, value, CultureInfo.CurrentCulture.CompareInfo); + if (string.GetCaseCompareOfComparisonCulture(comparisonType) == CompareOptions.None) + return span.EndsWith(value); - case StringComparison.CurrentCultureIgnoreCase: - return SpanHelpers.EndsWithCultureIgnoreCaseHelper(span, value, CultureInfo.CurrentCulture.CompareInfo); - - case StringComparison.InvariantCulture: - return SpanHelpers.EndsWithCultureHelper(span, value, CompareInfo.Invariant); - - case StringComparison.InvariantCultureIgnoreCase: - return SpanHelpers.EndsWithCultureIgnoreCaseHelper(span, value, CompareInfo.Invariant); - - case StringComparison.Ordinal: - return span.EndsWith(value); //TODO: Optimize - https://github.com/dotnet/corefx/issues/27487 - - case StringComparison.OrdinalIgnoreCase: - return SpanHelpers.EndsWithOrdinalIgnoreCaseHelper(span, value); - - default: - throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); + return (span.Length >= value.Length) ? (CompareInfo.CompareOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value) == 0) : false; } + + if (span.Length == 0) + { + return false; + } + + return (comparisonType >= StringComparison.InvariantCulture) ? + CompareInfo.Invariant.IsSuffix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)) : + CultureInfo.CurrentCulture.CompareInfo.IsSuffix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); } /// @@ -299,86 +346,35 @@ namespace System /// One of the enumeration values that determines how the and are compared. public static bool StartsWith(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) { + string.CheckStringComparison(comparisonType); + if (value.Length == 0) { - StringSpanHelpers.CheckStringComparison(comparisonType); return true; } - switch (comparisonType) + if (comparisonType >= StringComparison.Ordinal || GlobalizationMode.Invariant) { - case StringComparison.CurrentCulture: - return SpanHelpers.StartsWithCultureHelper(span, value, CultureInfo.CurrentCulture.CompareInfo); + if (string.GetCaseCompareOfComparisonCulture(comparisonType) == CompareOptions.None) + return span.StartsWith(value); - case StringComparison.CurrentCultureIgnoreCase: - return SpanHelpers.StartsWithCultureIgnoreCaseHelper(span, value, CultureInfo.CurrentCulture.CompareInfo); - - case StringComparison.InvariantCulture: - return SpanHelpers.StartsWithCultureHelper(span, value, CompareInfo.Invariant); - - case StringComparison.InvariantCultureIgnoreCase: - return SpanHelpers.StartsWithCultureIgnoreCaseHelper(span, value, CompareInfo.Invariant); - - case StringComparison.Ordinal: - return span.StartsWith(value); //TODO: Optimize - https://github.com/dotnet/corefx/issues/27487 - - case StringComparison.OrdinalIgnoreCase: - return SpanHelpers.StartsWithOrdinalIgnoreCaseHelper(span, value); - - default: - throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); + return (span.Length >= value.Length) ? (CompareInfo.CompareOrdinalIgnoreCase(span.Slice(0, value.Length), value) == 0) : false; } - } - /// - /// Casts a Span of one primitive type to Span of bytes. - /// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety. - /// - /// The source slice, of type . - /// - /// Thrown when contains pointers. - /// - /// - /// Thrown if the Length property of the new Span would exceed Int32.MaxValue. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Span AsBytes(this Span source) - where T : struct - { - if (RuntimeHelpers.IsReferenceOrContainsReferences()) - ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); + if (span.Length == 0) + { + return false; + } - return new Span( - ref Unsafe.As(ref MemoryMarshal.GetReference(source)), - checked(source.Length * Unsafe.SizeOf())); - } - - /// - /// Casts a ReadOnlySpan of one primitive type to ReadOnlySpan of bytes. - /// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety. - /// - /// The source slice, of type . - /// - /// Thrown when contains pointers. - /// - /// - /// Thrown if the Length property of the new Span would exceed Int32.MaxValue. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlySpan AsBytes(this ReadOnlySpan source) - where T : struct - { - if (RuntimeHelpers.IsReferenceOrContainsReferences()) - ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); - - return new ReadOnlySpan( - ref Unsafe.As(ref MemoryMarshal.GetReference(source)), - checked(source.Length * Unsafe.SizeOf())); + return (comparisonType >= StringComparison.InvariantCulture) ? + CompareInfo.Invariant.IsPrefix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)) : + CultureInfo.CurrentCulture.CompareInfo.IsPrefix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); } /// /// Creates a new span over the portion of the target array. /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this T[] array, int start) { if (array == null) @@ -400,6 +396,7 @@ namespace System /// /// The target string. /// Returns default when is null. + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan AsSpan(this string text) { if (text == null) @@ -417,6 +414,7 @@ namespace System /// /// Thrown when the specified index is not in range (<0 or >text.Length). /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan AsSpan(this string text, int start) { if (text == null) @@ -442,6 +440,7 @@ namespace System /// /// Thrown when the specified index or is not in range. /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan AsSpan(this string text, int start, int length) { if (text == null) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/MemoryExtensions.cs b/external/corert/src/System.Private.CoreLib/shared/System/MemoryExtensions.cs index effdecf92c..f0937c448b 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/MemoryExtensions.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/MemoryExtensions.cs @@ -6,9 +6,13 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -#if !netstandard using Internal.Runtime.CompilerServices; -#endif + +#if BIT64 +using nuint = System.UInt64; +#else +using nuint = System.UInt32; +#endif // BIT64 namespace System { @@ -58,7 +62,6 @@ namespace System /// /// The source span from which the character is removed. /// The specified character to look for and remove. - //[MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan Trim(this ReadOnlySpan span, char trimChar) { return span.TrimStart(trimChar).TrimEnd(trimChar); @@ -69,7 +72,6 @@ namespace System /// /// The source span from which the character is removed. /// The specified character to look for and remove. - //[MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan TrimStart(this ReadOnlySpan span, char trimChar) { int start = 0; @@ -103,6 +105,7 @@ namespace System /// /// The source span from which the characters are removed. /// The span which contains the set of characters to remove. + /// If is empty, white-space characters are removed instead. public static ReadOnlySpan Trim(this ReadOnlySpan span, ReadOnlySpan trimChars) { return span.TrimStart(trimChars).TrimEnd(trimChars); @@ -114,8 +117,14 @@ namespace System /// /// The source span from which the characters are removed. /// The span which contains the set of characters to remove. + /// If is empty, white-space characters are removed instead. public static ReadOnlySpan TrimStart(this ReadOnlySpan span, ReadOnlySpan trimChars) { + if (trimChars.IsEmpty) + { + return span.TrimStart(); + } + int start = 0; for (; start < span.Length; start++) { @@ -137,8 +146,14 @@ namespace System /// /// The source span from which the characters are removed. /// The span which contains the set of characters to remove. + /// If is empty, white-space characters are removed instead. public static ReadOnlySpan TrimEnd(this ReadOnlySpan span, ReadOnlySpan trimChars) { + if (trimChars.IsEmpty) + { + return span.TrimEnd(); + } + int end = span.Length - 1; for (; end >= 0; end--) { @@ -167,6 +182,56 @@ namespace System return true; } + /// + /// Searches for the specified value and returns true if found. If not found, returns false. Values are compared using IEquatable{T}.Equals(T). + /// + /// + /// The span to search. + /// The value to search for. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Contains(this Span span, T value) + where T : IEquatable + { + if (typeof(T) == typeof(byte)) + return SpanHelpers.Contains( + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + Unsafe.As(ref value), + span.Length); + + if (typeof(T) == typeof(char)) + return SpanHelpers.Contains( + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + Unsafe.As(ref value), + span.Length); + + return SpanHelpers.Contains(ref MemoryMarshal.GetReference(span), value, span.Length); + } + + /// + /// Searches for the specified value and returns true if found. If not found, returns false. Values are compared using IEquatable{T}.Equals(T). + /// + /// + /// The span to search. + /// The value to search for. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Contains(this ReadOnlySpan span, T value) + where T : IEquatable + { + if (typeof(T) == typeof(byte)) + return SpanHelpers.Contains( + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + Unsafe.As(ref value), + span.Length); + + if (typeof(T) == typeof(char)) + return SpanHelpers.Contains( + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + Unsafe.As(ref value), + span.Length); + + return SpanHelpers.Contains(ref MemoryMarshal.GetReference(span), value, span.Length); + } + /// /// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). /// @@ -181,7 +246,14 @@ namespace System ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); - return SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); + + if (typeof(T) == typeof(char)) + return SpanHelpers.IndexOf( + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + Unsafe.As(ref value), + span.Length); + + return SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } /// @@ -199,7 +271,8 @@ namespace System span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(value)), value.Length); - return SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); + + return SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } /// @@ -216,6 +289,13 @@ namespace System ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); + + if (typeof(T) == typeof(char)) + return SpanHelpers.LastIndexOf( + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + Unsafe.As(ref value), + span.Length); + return SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } @@ -234,6 +314,7 @@ namespace System span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(value)), value.Length); + return SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } @@ -241,50 +322,42 @@ namespace System /// Determines whether two sequences are equal by comparing the elements using IEquatable{T}.Equals(T). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool SequenceEqual(this Span first, ReadOnlySpan second) + public static bool SequenceEqual(this Span span, ReadOnlySpan other) where T : IEquatable { - int length = first.Length; - if (typeof(T) == typeof(byte)) - return length == second.Length && + int length = span.Length; + + if (default(T) != null && IsTypeComparableAsBytes(out nuint size)) + return length == other.Length && SpanHelpers.SequenceEqual( - ref Unsafe.As(ref MemoryMarshal.GetReference(first)), - ref Unsafe.As(ref MemoryMarshal.GetReference(second)), - length); - return length == second.Length && SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(first), ref MemoryMarshal.GetReference(second), length); + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + ref Unsafe.As(ref MemoryMarshal.GetReference(other)), + ((nuint)length) * size); // If this multiplication overflows, the Span we got overflows the entire address range. There's no happy outcome for this api in such a case so we choose not to take the overhead of checking. + + return length == other.Length && SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); } /// /// Determines the relative order of the sequences being compared by comparing the elements using IComparable{T}.CompareTo(T). /// - public static int SequenceCompareTo(this Span first, ReadOnlySpan second) + public static int SequenceCompareTo(this Span span, ReadOnlySpan other) where T : IComparable { if (typeof(T) == typeof(byte)) return SpanHelpers.SequenceCompareTo( - ref Unsafe.As(ref MemoryMarshal.GetReference(first)), - first.Length, - ref Unsafe.As(ref MemoryMarshal.GetReference(second)), - second.Length); - return SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(first), first.Length, ref MemoryMarshal.GetReference(second), second.Length); - } + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + span.Length, + ref Unsafe.As(ref MemoryMarshal.GetReference(other)), + other.Length); - /// - /// Reverses the sequence of the elements in the entire span. - /// - public static void Reverse(this Span span) - { - ref T p = ref MemoryMarshal.GetReference(span); - int i = 0; - int j = span.Length - 1; - while (i < j) - { - T temp = Unsafe.Add(ref p, i); - Unsafe.Add(ref p, i) = Unsafe.Add(ref p, j); - Unsafe.Add(ref p, j) = temp; - i++; - j--; - } + if (typeof(T) == typeof(char)) + return SpanHelpers.SequenceCompareTo( + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + span.Length, + ref Unsafe.As(ref MemoryMarshal.GetReference(other)), + other.Length); + + return SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } /// @@ -301,7 +374,14 @@ namespace System ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); - return SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); + + if (typeof(T) == typeof(char)) + return SpanHelpers.IndexOf( + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + Unsafe.As(ref value), + span.Length); + + return SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } /// @@ -319,7 +399,8 @@ namespace System span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(value)), value.Length); - return SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); + + return SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } /// @@ -336,6 +417,13 @@ namespace System ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); + + if (typeof(T) == typeof(char)) + return SpanHelpers.LastIndexOf( + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + Unsafe.As(ref value), + span.Length); + return SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } @@ -354,6 +442,7 @@ namespace System span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(value)), value.Length); + return SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } @@ -495,6 +584,7 @@ namespace System Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); + return SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } @@ -516,6 +606,7 @@ namespace System Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); + return SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } @@ -534,6 +625,7 @@ namespace System span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(values)), values.Length); + return SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } @@ -553,6 +645,7 @@ namespace System Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); + return SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } @@ -574,6 +667,7 @@ namespace System Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); + return SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } @@ -592,6 +686,7 @@ namespace System span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(values)), values.Length); + return SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } @@ -599,33 +694,42 @@ namespace System /// Determines whether two sequences are equal by comparing the elements using IEquatable{T}.Equals(T). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool SequenceEqual(this ReadOnlySpan first, ReadOnlySpan second) + public static bool SequenceEqual(this ReadOnlySpan span, ReadOnlySpan other) where T : IEquatable { - int length = first.Length; - if (typeof(T) == typeof(byte)) - return length == second.Length && + int length = span.Length; + if (default(T) != null && IsTypeComparableAsBytes(out nuint size)) + return length == other.Length && SpanHelpers.SequenceEqual( - ref Unsafe.As(ref MemoryMarshal.GetReference(first)), - ref Unsafe.As(ref MemoryMarshal.GetReference(second)), - length); - return length == second.Length && SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(first), ref MemoryMarshal.GetReference(second), length); + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + ref Unsafe.As(ref MemoryMarshal.GetReference(other)), + ((nuint)length) * size); // If this multiplication overflows, the Span we got overflows the entire address range. There's no happy outcome for this api in such a case so we choose not to take the overhead of checking. + + return length == other.Length && SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); } /// /// Determines the relative order of the sequences being compared by comparing the elements using IComparable{T}.CompareTo(T). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int SequenceCompareTo(this ReadOnlySpan first, ReadOnlySpan second) + public static int SequenceCompareTo(this ReadOnlySpan span, ReadOnlySpan other) where T : IComparable { if (typeof(T) == typeof(byte)) return SpanHelpers.SequenceCompareTo( - ref Unsafe.As(ref MemoryMarshal.GetReference(first)), - first.Length, - ref Unsafe.As(ref MemoryMarshal.GetReference(second)), - second.Length); - return SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(first), first.Length, ref MemoryMarshal.GetReference(second), second.Length); + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + span.Length, + ref Unsafe.As(ref MemoryMarshal.GetReference(other)), + other.Length); + + if (typeof(T) == typeof(char)) + return SpanHelpers.SequenceCompareTo( + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + span.Length, + ref Unsafe.As(ref MemoryMarshal.GetReference(other)), + other.Length); + + return SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } /// @@ -636,12 +740,13 @@ namespace System where T : IEquatable { int valueLength = value.Length; - if (typeof(T) == typeof(byte)) + if (default(T) != null && IsTypeComparableAsBytes(out nuint size)) return valueLength <= span.Length && SpanHelpers.SequenceEqual( ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(ref MemoryMarshal.GetReference(value)), - valueLength); + ((nuint)valueLength) * size); // If this multiplication overflows, the Span we got overflows the entire address range. There's no happy outcome for this api in such a case so we choose not to take the overhead of checking. + return valueLength <= span.Length && SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), valueLength); } @@ -653,12 +758,13 @@ namespace System where T : IEquatable { int valueLength = value.Length; - if (typeof(T) == typeof(byte)) + if (default(T) != null && IsTypeComparableAsBytes(out nuint size)) return valueLength <= span.Length && SpanHelpers.SequenceEqual( ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(ref MemoryMarshal.GetReference(value)), - valueLength); + ((nuint)valueLength) * size); // If this multiplication overflows, the Span we got overflows the entire address range. There's no happy outcome for this api in such a case so we choose not to take the overhead of checking. + return valueLength <= span.Length && SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), valueLength); } @@ -671,12 +777,13 @@ namespace System { int spanLength = span.Length; int valueLength = value.Length; - if (typeof(T) == typeof(byte)) + if (default(T) != null && IsTypeComparableAsBytes(out nuint size)) return valueLength <= spanLength && SpanHelpers.SequenceEqual( ref Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), spanLength - valueLength)), ref Unsafe.As(ref MemoryMarshal.GetReference(value)), - valueLength); + ((nuint)valueLength) * size); // If this multiplication overflows, the Span we got overflows the entire address range. There's no happy outcome for this api in such a case so we choose not to take the overhead of checking. + return valueLength <= spanLength && SpanHelpers.SequenceEqual( ref Unsafe.Add(ref MemoryMarshal.GetReference(span), spanLength - valueLength), @@ -693,12 +800,13 @@ namespace System { int spanLength = span.Length; int valueLength = value.Length; - if (typeof(T) == typeof(byte)) + if (default(T) != null && IsTypeComparableAsBytes(out nuint size)) return valueLength <= spanLength && SpanHelpers.SequenceEqual( ref Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), spanLength - valueLength)), ref Unsafe.As(ref MemoryMarshal.GetReference(value)), - valueLength); + ((nuint)valueLength) * size); // If this multiplication overflows, the Span we got overflows the entire address range. There's no happy outcome for this api in such a case so we choose not to take the overhead of checking. + return valueLength <= spanLength && SpanHelpers.SequenceEqual( ref Unsafe.Add(ref MemoryMarshal.GetReference(span), spanLength - valueLength), @@ -707,7 +815,29 @@ namespace System } /// - /// Creates a new span over the portion of the target array. + /// Reverses the sequence of the elements in the entire span. + /// + public static void Reverse(this Span span) + { + if (span.Length <= 1) + { + return; + } + + ref T first = ref MemoryMarshal.GetReference(span); + ref T last = ref Unsafe.Add(ref Unsafe.Add(ref first, span.Length), -1); + do + { + T temp = first; + first = last; + last = temp; + first = ref Unsafe.Add(ref first, 1); + last = ref Unsafe.Add(ref last, -1); + } while (Unsafe.IsAddressLessThan(ref first, ref last)); + } + + /// + /// Creates a new span over the target array. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this T[] array) @@ -715,63 +845,169 @@ namespace System return new Span(array); } + /// + /// Creates a new Span over the portion of the target array beginning + /// at 'start' index and ending at 'end' index (exclusive). + /// + /// The target array. + /// The index at which to begin the Span. + /// The number of items in the Span. + /// Returns default when is null. + /// Thrown when is covariant and array's type is not exactly T[]. + /// + /// Thrown when the specified or end index is not in the range (<0 or >=Length). + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span AsSpan(this T[] array, int start, int length) + { + return new Span(array, start, length); + } + /// /// Creates a new span over the portion of the target array segment. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Span AsSpan(this ArraySegment arraySegment) + public static Span AsSpan(this ArraySegment segment) { - return new Span(arraySegment.Array, arraySegment.Offset, arraySegment.Count); + return new Span(segment.Array, segment.Offset, segment.Count); } /// - /// Creates a new readonly span over the entire target array. + /// Creates a new Span over the portion of the target array beginning + /// at 'start' index and ending at 'end' index (exclusive). /// + /// The target array. + /// The index at which to begin the Span. + /// Returns default when is null. + /// Thrown when is covariant and array's type is not exactly T[]. + /// + /// Thrown when the specified or end index is not in the range (<0 or >=segment.Count). + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlySpan AsReadOnlySpan(this T[] array) + public static Span AsSpan(this ArraySegment segment, int start) { - return new ReadOnlySpan(array); + if (((uint)start) > segment.Count) + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); + + return new Span(segment.Array, segment.Offset + start, segment.Count - start); } /// - /// Creates a new readonly span over the entire target span. - /// - public static ReadOnlySpan AsReadOnlySpan(this Span span) => span; - - /// - /// Creates a new readonly span over the target array segment. + /// Creates a new Span over the portion of the target array beginning + /// at 'start' index and ending at 'end' index (exclusive). /// + /// The target array. + /// The index at which to begin the Span. + /// The number of items in the Span. + /// Returns default when is null. + /// Thrown when is covariant and array's type is not exactly T[]. + /// + /// Thrown when the specified or end index is not in the range (<0 or >=segment.Count). + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlySpan AsReadOnlySpan(this ArraySegment arraySegment) + public static Span AsSpan(this ArraySegment segment, int start, int length) { - return new ReadOnlySpan(arraySegment.Array, arraySegment.Offset, arraySegment.Count); + if (((uint)start) > segment.Count) + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); + if (((uint)length) > segment.Count - start) + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); + + return new Span(segment.Array, segment.Offset + start, length); } /// - /// Creates a new readonly memory over the entire target memory. + /// Creates a new memory over the target array. /// - public static ReadOnlyMemory AsReadOnlyMemory(this Memory memory) => memory; + public static Memory AsMemory(this T[] array) => new Memory(array); + + /// + /// Creates a new memory over the portion of the target array beginning + /// at 'start' index and ending at 'end' index (exclusive). + /// + /// The target array. + /// The index at which to begin the memory. + /// Returns default when is null. + /// Thrown when is covariant and array's type is not exactly T[]. + /// + /// Thrown when the specified or end index is not in the range (<0 or >=array.Length). + /// + public static Memory AsMemory(this T[] array, int start) => new Memory(array, start); + + /// + /// Creates a new memory over the portion of the target array beginning + /// at 'start' index and ending at 'end' index (exclusive). + /// + /// The target array. + /// The index at which to begin the memory. + /// The number of items in the memory. + /// Returns default when is null. + /// Thrown when is covariant and array's type is not exactly T[]. + /// + /// Thrown when the specified or end index is not in the range (<0 or >=Length). + /// + public static Memory AsMemory(this T[] array, int start, int length) => new Memory(array, start, length); /// /// Creates a new memory over the portion of the target array. /// - public static Memory AsMemory(this T[] array, int start) => new Memory(array, start); + public static Memory AsMemory(this ArraySegment segment) => new Memory(segment.Array, segment.Offset, segment.Count); + + /// + /// Creates a new memory over the portion of the target array beginning + /// at 'start' index and ending at 'end' index (exclusive). + /// + /// The target array. + /// The index at which to begin the memory. + /// Returns default when is null. + /// Thrown when is covariant and array's type is not exactly T[]. + /// + /// Thrown when the specified or end index is not in the range (<0 or >=segment.Count). + /// + public static Memory AsMemory(this ArraySegment segment, int start) + { + if (((uint)start) > segment.Count) + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); + + return new Memory(segment.Array, segment.Offset + start, segment.Count - start); + } + + /// + /// Creates a new memory over the portion of the target array beginning + /// at 'start' index and ending at 'end' index (exclusive). + /// + /// The target array. + /// The index at which to begin the memory. + /// The number of items in the memory. + /// Returns default when is null. + /// Thrown when is covariant and array's type is not exactly T[]. + /// + /// Thrown when the specified or end index is not in the range (<0 or >=segment.Count). + /// + public static Memory AsMemory(this ArraySegment segment, int start, int length) + { + if (((uint)start) > segment.Count) + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); + if (((uint)length) > segment.Count - start) + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); + + return new Memory(segment.Array, segment.Offset + start, length); + } /// /// Copies the contents of the array into the span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// - ///The array to copy items from. + ///The array to copy items from. /// The span to copy items into. /// /// Thrown when the destination Span is shorter than the source array. /// /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void CopyTo(this T[] array, Span destination) + public static void CopyTo(this T[] source, Span destination) { - new ReadOnlySpan(array).CopyTo(destination); + new ReadOnlySpan(source).CopyTo(destination); } /// @@ -779,16 +1015,16 @@ namespace System /// and destinations overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten. /// - ///The array to copy items from. + ///The array to copy items from. /// The memory to copy items into. /// /// Thrown when the destination is shorter than the source array. /// /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void CopyTo(this T[] array, Memory destination) + public static void CopyTo(this T[] source, Memory destination) { - array.CopyTo(destination.Span); + source.CopyTo(destination.Span); } // @@ -923,65 +1159,65 @@ namespace System /// Determines whether two sequences overlap in memory. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool Overlaps(this Span first, ReadOnlySpan second) + public static bool Overlaps(this Span span, ReadOnlySpan other) { - return Overlaps((ReadOnlySpan)first, second); + return Overlaps((ReadOnlySpan)span, other); } /// /// Determines whether two sequences overlap in memory and outputs the element offset. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool Overlaps(this Span first, ReadOnlySpan second, out int elementOffset) + public static bool Overlaps(this Span span, ReadOnlySpan other, out int elementOffset) { - return Overlaps((ReadOnlySpan)first, second, out elementOffset); + return Overlaps((ReadOnlySpan)span, other, out elementOffset); } /// /// Determines whether two sequences overlap in memory. /// - public static bool Overlaps(this ReadOnlySpan first, ReadOnlySpan second) + public static bool Overlaps(this ReadOnlySpan span, ReadOnlySpan other) { - if (first.IsEmpty || second.IsEmpty) + if (span.IsEmpty || other.IsEmpty) { return false; } IntPtr byteOffset = Unsafe.ByteOffset( - ref MemoryMarshal.GetReference(first), - ref MemoryMarshal.GetReference(second)); + ref MemoryMarshal.GetReference(span), + ref MemoryMarshal.GetReference(other)); if (Unsafe.SizeOf() == sizeof(int)) { - return (uint)byteOffset < (uint)(first.Length * Unsafe.SizeOf()) || - (uint)byteOffset > (uint)-(second.Length * Unsafe.SizeOf()); + return (uint)byteOffset < (uint)(span.Length * Unsafe.SizeOf()) || + (uint)byteOffset > (uint)-(other.Length * Unsafe.SizeOf()); } else { - return (ulong)byteOffset < (ulong)((long)first.Length * Unsafe.SizeOf()) || - (ulong)byteOffset > (ulong)-((long)second.Length * Unsafe.SizeOf()); + return (ulong)byteOffset < (ulong)((long)span.Length * Unsafe.SizeOf()) || + (ulong)byteOffset > (ulong)-((long)other.Length * Unsafe.SizeOf()); } } /// /// Determines whether two sequences overlap in memory and outputs the element offset. /// - public static bool Overlaps(this ReadOnlySpan first, ReadOnlySpan second, out int elementOffset) + public static bool Overlaps(this ReadOnlySpan span, ReadOnlySpan other, out int elementOffset) { - if (first.IsEmpty || second.IsEmpty) + if (span.IsEmpty || other.IsEmpty) { elementOffset = 0; return false; } IntPtr byteOffset = Unsafe.ByteOffset( - ref MemoryMarshal.GetReference(first), - ref MemoryMarshal.GetReference(second)); + ref MemoryMarshal.GetReference(span), + ref MemoryMarshal.GetReference(other)); if (Unsafe.SizeOf() == sizeof(int)) { - if ((uint)byteOffset < (uint)(first.Length * Unsafe.SizeOf()) || - (uint)byteOffset > (uint)-(second.Length * Unsafe.SizeOf())) + if ((uint)byteOffset < (uint)(span.Length * Unsafe.SizeOf()) || + (uint)byteOffset > (uint)-(other.Length * Unsafe.SizeOf())) { if ((int)byteOffset % Unsafe.SizeOf() != 0) ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); @@ -997,8 +1233,8 @@ namespace System } else { - if ((ulong)byteOffset < (ulong)((long)first.Length * Unsafe.SizeOf()) || - (ulong)byteOffset > (ulong)-((long)second.Length * Unsafe.SizeOf())) + if ((ulong)byteOffset < (ulong)((long)span.Length * Unsafe.SizeOf()) || + (ulong)byteOffset > (ulong)-((long)other.Length * Unsafe.SizeOf())) { if ((long)byteOffset % Unsafe.SizeOf() != 0) ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); @@ -1028,7 +1264,7 @@ namespace System /// no larger element, the bitwise complement of . /// /// - /// is . + /// is . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch( @@ -1052,7 +1288,7 @@ namespace System /// no larger element, the bitwise complement of . /// /// - /// is . + /// is . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch( @@ -1102,7 +1338,7 @@ namespace System /// no larger element, the bitwise complement of . /// /// - /// is . + /// is . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch( @@ -1126,7 +1362,7 @@ namespace System /// no larger element, the bitwise complement of . /// /// - /// is . + /// is . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch( @@ -1166,5 +1402,36 @@ namespace System value, comparer); return BinarySearch(span, comparable); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool IsTypeComparableAsBytes(out nuint size) + { + if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte)) + { + size = sizeof(byte); + return true; + } + + if (typeof(T) == typeof(char) || typeof(T) == typeof(short) || typeof(T) == typeof(ushort)) + { + size = sizeof(char); + return true; + } + + if (typeof(T) == typeof(int) || typeof(T) == typeof(uint)) + { + size = sizeof(int); + return true; + } + + if (typeof(T) == typeof(long) || typeof(T) == typeof(ulong)) + { + size = sizeof(long); + return true; + } + + size = default; + return false; + } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/MethodAccessException.cs b/external/corert/src/System.Private.CoreLib/shared/System/MethodAccessException.cs index 1ca0297b94..f329334b23 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/MethodAccessException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/MethodAccessException.cs @@ -23,13 +23,13 @@ namespace System HResult = HResults.COR_E_METHODACCESS; } - public MethodAccessException(String message) + public MethodAccessException(string message) : base(message) { HResult = HResults.COR_E_METHODACCESS; } - public MethodAccessException(String message, Exception inner) + public MethodAccessException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_METHODACCESS; diff --git a/external/corert/src/System.Private.CoreLib/src/System/MissingFieldException.cs b/external/corert/src/System.Private.CoreLib/shared/System/MissingFieldException.cs similarity index 64% rename from external/corert/src/System.Private.CoreLib/src/System/MissingFieldException.cs rename to external/corert/src/System.Private.CoreLib/shared/System/MissingFieldException.cs index edac0614d2..51078acbc0 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/MissingFieldException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/MissingFieldException.cs @@ -2,13 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** Purpose: The exception class for class loading failures. -** -=============================================================================*/ - using System.Runtime.Serialization; namespace System @@ -17,7 +10,7 @@ namespace System #if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] #endif - public class MissingFieldException : MissingMemberException + public class MissingFieldException : MissingMemberException, ISerializable { public MissingFieldException() : base(SR.Arg_MissingFieldException) @@ -25,13 +18,13 @@ namespace System HResult = HResults.COR_E_MISSINGFIELD; } - public MissingFieldException(String message) + public MissingFieldException(string message) : base(message) { HResult = HResults.COR_E_MISSINGFIELD; } - public MissingFieldException(String message, Exception inner) + public MissingFieldException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_MISSINGFIELD; @@ -48,11 +41,19 @@ namespace System { } - public override String Message + public override string Message { get { - return ClassName == null ? base.Message : SR.Format(SR.MissingField_Name, ClassName + "." + MemberName + (Signature != null ? " " + FormatSignature(Signature) : string.Empty)); + if (ClassName == null) + { + return base.Message; + } + else + { + // do any desired fixups to classname here. + return SR.Format(SR.MissingField_Name, (Signature != null ? FormatSignature(Signature) + " " : "") + ClassName + "." + MemberName); + } } } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/MissingMemberException.cs b/external/corert/src/System.Private.CoreLib/shared/System/MissingMemberException.cs similarity index 64% rename from external/corert/src/System.Private.CoreLib/src/System/MissingMemberException.cs rename to external/corert/src/System.Private.CoreLib/shared/System/MissingMemberException.cs index 3be1cfe6a1..7aaa38d31b 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/MissingMemberException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/MissingMemberException.cs @@ -2,15 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: The exception class for versioning problems with DLLS. -** -** -=============================================================================*/ - using System.Runtime.Serialization; namespace System @@ -19,7 +10,7 @@ namespace System #if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] #endif - public class MissingMemberException : MemberAccessException + public partial class MissingMemberException : MemberAccessException { public MissingMemberException() : base(SR.Arg_MissingMemberException) @@ -27,13 +18,13 @@ namespace System HResult = HResults.COR_E_MISSINGMEMBER; } - public MissingMemberException(String message) + public MissingMemberException(string message) : base(message) { HResult = HResults.COR_E_MISSINGMEMBER; } - public MissingMemberException(String message, Exception inner) + public MissingMemberException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_MISSINGMEMBER; @@ -65,19 +56,18 @@ namespace System { get { - return ClassName == null ? base.Message : SR.Format(SR.MissingMember_Name, ClassName + "." + MemberName + (Signature != null ? " " + FormatSignature(Signature) : string.Empty)); + if (ClassName == null) + { + return base.Message; + } + else + { + // do any desired fixups to classname here. + return SR.Format(SR.MissingMember_Name, ClassName + "." + MemberName + (Signature != null ? " " + FormatSignature(Signature) : string.Empty)); + } } } - internal static string FormatSignature(byte[] signature) - { - // This is not the correct implementation, however, it's probably not worth the time to port given that - // (1) it's for a diagnostic - // (2) Signature is non-null when this exception is created from the native runtime. Which we don't do in .Net Native. - // (3) Only other time the signature is non-null is if this exception object is deserialized from a persisted blob from an older runtime. - return string.Empty; - } - // If ClassName != null, GetMessage will construct on the fly using it // and the other variables. This allows customization of the // format depending on the language environment. diff --git a/external/corert/src/System.Private.CoreLib/shared/System/MulticastNotSupportedException.cs b/external/corert/src/System.Private.CoreLib/shared/System/MulticastNotSupportedException.cs index cc6c77023e..cb07ac7d09 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/MulticastNotSupportedException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/MulticastNotSupportedException.cs @@ -21,13 +21,13 @@ namespace System HResult = HResults.COR_E_MULTICASTNOTSUPPORTED; } - public MulticastNotSupportedException(String message) + public MulticastNotSupportedException(string message) : base(message) { HResult = HResults.COR_E_MULTICASTNOTSUPPORTED; } - public MulticastNotSupportedException(String message, Exception inner) + public MulticastNotSupportedException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_MULTICASTNOTSUPPORTED; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/NotFiniteNumberException.cs b/external/corert/src/System.Private.CoreLib/shared/System/NotFiniteNumberException.cs index b9c9af06d3..9afc104588 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/NotFiniteNumberException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/NotFiniteNumberException.cs @@ -55,13 +55,13 @@ namespace System protected NotFiniteNumberException(SerializationInfo info, StreamingContext context) : base(info, context) { - _offendingNumber = info.GetInt32("OffendingNumber"); + _offendingNumber = info.GetDouble("OffendingNumber"); // Do not rename (binary serialization) } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); - info.AddValue("OffendingNumber", _offendingNumber, typeof(int)); + info.AddValue("OffendingNumber", _offendingNumber, typeof(double)); // Do not rename (binary serialization) } public double OffendingNumber diff --git a/external/corert/src/System.Private.CoreLib/shared/System/NotImplementedException.cs b/external/corert/src/System.Private.CoreLib/shared/System/NotImplementedException.cs index 1a3b6afcd4..e5f378fed3 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/NotImplementedException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/NotImplementedException.cs @@ -25,12 +25,12 @@ namespace System { HResult = HResults.E_NOTIMPL; } - public NotImplementedException(String message) + public NotImplementedException(string message) : base(message) { HResult = HResults.E_NOTIMPL; } - public NotImplementedException(String message, Exception inner) + public NotImplementedException(string message, Exception inner) : base(message, inner) { HResult = HResults.E_NOTIMPL; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/NotSupportedException.cs b/external/corert/src/System.Private.CoreLib/shared/System/NotSupportedException.cs index 3180bc2837..e3191ea13e 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/NotSupportedException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/NotSupportedException.cs @@ -25,13 +25,13 @@ namespace System HResult = HResults.COR_E_NOTSUPPORTED; } - public NotSupportedException(String message) + public NotSupportedException(string message) : base(message) { HResult = HResults.COR_E_NOTSUPPORTED; } - public NotSupportedException(String message, Exception innerException) + public NotSupportedException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_NOTSUPPORTED; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/NullReferenceException.cs b/external/corert/src/System.Private.CoreLib/shared/System/NullReferenceException.cs index c2e722470c..cfbc0fb78e 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/NullReferenceException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/NullReferenceException.cs @@ -25,13 +25,13 @@ namespace System HResult = HResults.COR_E_NULLREFERENCE; } - public NullReferenceException(String message) + public NullReferenceException(string message) : base(message) { HResult = HResults.COR_E_NULLREFERENCE; } - public NullReferenceException(String message, Exception innerException) + public NullReferenceException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_NULLREFERENCE; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Nullable.cs b/external/corert/src/System.Private.CoreLib/shared/System/Nullable.cs index 73ad6056c2..3c1cbd5101 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Nullable.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Nullable.cs @@ -141,7 +141,7 @@ namespace System { // instantiated generic type only Type genericType = nullableType.GetGenericTypeDefinition(); - if (Object.ReferenceEquals(genericType, typeof(Nullable<>))) + if (object.ReferenceEquals(genericType, typeof(Nullable<>))) { return nullableType.GetGenericArguments()[0]; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Number.Formatting.cs b/external/corert/src/System.Private.CoreLib/shared/System/Number.Formatting.cs index 24d5db1da9..3d3c15bf73 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Number.Formatting.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Number.Formatting.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Buffers.Text; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; @@ -246,12 +247,12 @@ namespace System private const int DoublePrecision = 15; private const int ScaleNAN = unchecked((int)0x80000000); private const int ScaleINF = 0x7FFFFFFF; - private const int MaxUInt32HexDigits = 8; private const int MaxUInt32DecDigits = 10; - private const int MaxUInt64DecDigits = 20; private const int CharStackBufferSize = 32; private const string PosNumberFormat = "#"; + private static readonly string[] s_singleDigitStringCache = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; + private static readonly string[] s_posCurrencyFormats = { "$#", "#$", "$ #", "# $" @@ -289,7 +290,7 @@ namespace System char fmt = ParseFormatSpecifier(format, out int digits); NumberBuffer number = default; - DecimalToNumber(value, ref number); + DecimalToNumber(ref value, ref number); ValueStringBuilder sb; unsafe @@ -300,7 +301,7 @@ namespace System if (fmt != 0) { - NumberToString(ref sb, ref number, fmt, digits, info, isDecimal:true); + NumberToString(ref sb, ref number, fmt, digits, info); } else { @@ -315,7 +316,7 @@ namespace System char fmt = ParseFormatSpecifier(format, out int digits); NumberBuffer number = default; - DecimalToNumber(value, ref number); + DecimalToNumber(ref value, ref number); ValueStringBuilder sb; unsafe @@ -326,7 +327,7 @@ namespace System if (fmt != 0) { - NumberToString(ref sb, ref number, fmt, digits, info, isDecimal: true); + NumberToString(ref sb, ref number, fmt, digits, info); } else { @@ -336,13 +337,12 @@ namespace System return sb.TryCopyTo(destination, out charsWritten); } - private static unsafe void DecimalToNumber(decimal value, ref NumberBuffer number) + private static unsafe void DecimalToNumber(ref decimal d, ref NumberBuffer number) { - decimal d = value; - char* buffer = number.digits; number.precision = DecimalPrecision; number.sign = d.IsNegative; + number.kind = NumberBufferKind.Decimal; char* p = buffer + DecimalPrecision; while ((d.Mid | d.High) != 0) @@ -351,7 +351,7 @@ namespace System } p = UInt32ToDecChars(p, d.Low, 0); - int i = (int)(buffer + DecimalPrecision - p); + int i = (int)((byte*)(buffer + DecimalPrecision) - (byte*)p) >> 1; number.scale = i - d.Scale; char* dst = number.digits; @@ -389,6 +389,7 @@ namespace System char fmt = ParseFormatSpecifier(format, out int digits); int precision = DoublePrecision; NumberBuffer number = default; + number.kind = NumberBufferKind.Double; switch (fmt) { @@ -410,12 +411,12 @@ namespace System if (NumberToDouble(ref number) == value) { - NumberToString(ref sb, ref number, 'G', DoublePrecision, info, isDecimal: false); + NumberToString(ref sb, ref number, 'G', DoublePrecision, info); } else { DoubleToNumber(value, 17, ref number); - NumberToString(ref sb, ref number, 'G', 17, info, isDecimal: false); + NumberToString(ref sb, ref number, 'G', 17, info); } return null; @@ -452,7 +453,7 @@ namespace System if (fmt != 0) { - NumberToString(ref sb, ref number, fmt, digits, info, isDecimal: false); + NumberToString(ref sb, ref number, fmt, digits, info); } else { @@ -489,6 +490,7 @@ namespace System char fmt = ParseFormatSpecifier(format, out int digits); int precision = FloatPrecision; NumberBuffer number = default; + number.kind = NumberBufferKind.Double; switch (fmt) { @@ -510,12 +512,12 @@ namespace System if ((float)NumberToDouble(ref number) == value) { - NumberToString(ref sb, ref number, 'G', FloatPrecision, info, isDecimal: false); + NumberToString(ref sb, ref number, 'G', FloatPrecision, info); } else { DoubleToNumber(value, 9, ref number); - NumberToString(ref sb, ref number, 'G', 9, info, isDecimal: false); + NumberToString(ref sb, ref number, 'G', 9, info); } return null; } @@ -551,7 +553,7 @@ namespace System if (fmt != 0) { - NumberToString(ref sb, ref number, fmt, digits, info, false); + NumberToString(ref sb, ref number, fmt, digits, info); } else { @@ -583,14 +585,12 @@ namespace System } char fmt = ParseFormatSpecifier(format, out int digits); - NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); - char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D') { return value >= 0 ? UInt32ToDecStr((uint)value, digits) : - NegativeInt32ToDecStr(value, digits, info.NegativeSign); + NegativeInt32ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign); } else if (fmtUpper == 'X') { @@ -600,6 +600,7 @@ namespace System } else { + NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); NumberBuffer number = default; Int32ToNumber(value, ref number); ValueStringBuilder sb; @@ -610,7 +611,7 @@ namespace System } if (fmt != 0) { - NumberToString(ref sb, ref number, fmt, digits, info, false); + NumberToString(ref sb, ref number, fmt, digits, info); } else { @@ -629,14 +630,12 @@ namespace System } char fmt = ParseFormatSpecifier(format, out int digits); - NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); - char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D') { return value >= 0 ? TryUInt32ToDecStr((uint)value, digits, destination, out charsWritten) : - TryNegativeInt32ToDecStr(value, digits, info.NegativeSign, destination, out charsWritten); + TryNegativeInt32ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign, destination, out charsWritten); } else if (fmtUpper == 'X') { @@ -646,6 +645,7 @@ namespace System } else { + NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); NumberBuffer number = default; Int32ToNumber(value, ref number); ValueStringBuilder sb; @@ -656,7 +656,7 @@ namespace System } if (fmt != 0) { - NumberToString(ref sb, ref number, fmt, digits, info, false); + NumberToString(ref sb, ref number, fmt, digits, info); } else { @@ -675,8 +675,6 @@ namespace System } char fmt = ParseFormatSpecifier(format, out int digits); - NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); - char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D') { @@ -690,6 +688,7 @@ namespace System } else { + NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); NumberBuffer number = default; UInt32ToNumber(value, ref number); ValueStringBuilder sb; @@ -700,7 +699,7 @@ namespace System } if (fmt != 0) { - NumberToString(ref sb, ref number, fmt, digits, info, false); + NumberToString(ref sb, ref number, fmt, digits, info); } else { @@ -719,8 +718,6 @@ namespace System } char fmt = ParseFormatSpecifier(format, out int digits); - NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); - char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D') { @@ -734,6 +731,7 @@ namespace System } else { + NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); NumberBuffer number = default; UInt32ToNumber(value, ref number); ValueStringBuilder sb; @@ -744,7 +742,7 @@ namespace System } if (fmt != 0) { - NumberToString(ref sb, ref number, fmt, digits, info, false); + NumberToString(ref sb, ref number, fmt, digits, info); } else { @@ -763,14 +761,12 @@ namespace System } char fmt = ParseFormatSpecifier(format, out int digits); - NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); - char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D') { return value >= 0 ? UInt64ToDecStr((ulong)value, digits) : - NegativeInt64ToDecStr(value, digits, info.NegativeSign); + NegativeInt64ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign); } else if (fmtUpper == 'X') { @@ -781,6 +777,7 @@ namespace System } else { + NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); NumberBuffer number = default; Int64ToNumber(value, ref number); ValueStringBuilder sb; @@ -791,7 +788,7 @@ namespace System } if (fmt != 0) { - NumberToString(ref sb, ref number, fmt, digits, info, false); + NumberToString(ref sb, ref number, fmt, digits, info); } else { @@ -810,14 +807,12 @@ namespace System } char fmt = ParseFormatSpecifier(format, out int digits); - NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); - char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D') { return value >= 0 ? TryUInt64ToDecStr((ulong)value, digits, destination, out charsWritten) : - TryNegativeInt64ToDecStr(value, digits, info.NegativeSign, destination, out charsWritten); + TryNegativeInt64ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign, destination, out charsWritten); } else if (fmtUpper == 'X') { @@ -828,6 +823,7 @@ namespace System } else { + NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); NumberBuffer number = default; Int64ToNumber(value, ref number); ValueStringBuilder sb; @@ -838,7 +834,7 @@ namespace System } if (fmt != 0) { - NumberToString(ref sb, ref number, fmt, digits, info, false); + NumberToString(ref sb, ref number, fmt, digits, info); } else { @@ -857,8 +853,6 @@ namespace System } char fmt = ParseFormatSpecifier(format, out int digits); - NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); - char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D') { @@ -873,6 +867,7 @@ namespace System } else { + NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); NumberBuffer number = default; UInt64ToNumber(value, ref number); ValueStringBuilder sb; @@ -883,7 +878,7 @@ namespace System } if (fmt != 0) { - NumberToString(ref sb, ref number, fmt, digits, info, false); + NumberToString(ref sb, ref number, fmt, digits, info); } else { @@ -902,8 +897,6 @@ namespace System } char fmt = ParseFormatSpecifier(format, out int digits); - NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); - char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D') { @@ -918,6 +911,7 @@ namespace System } else { + NumberFormatInfo info = NumberFormatInfo.GetInstance(provider); NumberBuffer number = default; UInt64ToNumber(value, ref number); ValueStringBuilder sb; @@ -928,7 +922,7 @@ namespace System } if (fmt != 0) { - NumberToString(ref sb, ref number, fmt, digits, info, false); + NumberToString(ref sb, ref number, fmt, digits, info); } else { @@ -958,6 +952,7 @@ namespace System int i = (int)(buffer + Int32Precision - p); number.scale = i; + number.kind = NumberBufferKind.Integer; char* dst = number.digits; while (--i >= 0) @@ -972,18 +967,20 @@ namespace System if (digits < 1) digits = 1; - int bufferLength = Math.Max(digits, MaxUInt32DecDigits) + sNegative.Length; - int index = bufferLength; - - char* buffer = stackalloc char[bufferLength]; - char* p = UInt32ToDecChars(buffer + bufferLength, (uint)(-value), digits); - for (int i = sNegative.Length - 1; i >= 0; i--) + int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits((uint)(-value))) + sNegative.Length; + string result = string.FastAllocateString(bufferLength); + fixed (char* buffer = result) { - *(--p) = sNegative[i]; - } + char* p = UInt32ToDecChars(buffer + bufferLength, (uint)(-value), digits); + Debug.Assert(p == buffer + sNegative.Length); - Debug.Assert(buffer + bufferLength - p >= 0 && buffer <= p); - return new string(p, 0, (int)(buffer + bufferLength - p)); + for (int i = sNegative.Length - 1; i >= 0; i--) + { + *(--p) = sNegative[i]; + } + Debug.Assert(p == buffer); + } + return result; } private static unsafe bool TryNegativeInt32ToDecStr(int value, int digits, string sNegative, Span destination, out int charsWritten) @@ -993,18 +990,26 @@ namespace System if (digits < 1) digits = 1; - int bufferLength = Math.Max(digits, MaxUInt32DecDigits) + sNegative.Length; - int index = bufferLength; - - char* buffer = stackalloc char[bufferLength]; - char* p = UInt32ToDecChars(buffer + bufferLength, (uint)(-value), digits); - for (int i = sNegative.Length - 1; i >= 0; i--) + int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits((uint)(-value))) + sNegative.Length; + if (bufferLength > destination.Length) { - *(--p) = sNegative[i]; + charsWritten = 0; + return false; } - Debug.Assert(buffer + bufferLength - p >= 0 && buffer <= p); - return TryCopyTo(p, (int)(buffer + bufferLength - p), destination, out charsWritten); + charsWritten = bufferLength; + fixed (char* buffer = &MemoryMarshal.GetReference(destination)) + { + char* p = UInt32ToDecChars(buffer + bufferLength, (uint)(-value), digits); + Debug.Assert(p == buffer + sNegative.Length); + + for (int i = sNegative.Length - 1; i >= 0; i--) + { + *(--p) = sNegative[i]; + } + Debug.Assert(p == buffer); + } + return true; } private static unsafe string Int32ToHexStr(int value, char hexBase, int digits) @@ -1012,11 +1017,14 @@ namespace System if (digits < 1) digits = 1; - int bufferLength = Math.Max(digits, MaxUInt32HexDigits); - char* buffer = stackalloc char[bufferLength]; - - char* p = Int32ToHexChars(buffer + bufferLength, (uint)value, hexBase, digits); - return new string(p, 0, (int)(buffer + bufferLength - p)); + int bufferLength = Math.Max(digits, FormattingHelpers.CountHexDigits((uint)value)); + string result = string.FastAllocateString(bufferLength); + fixed (char* buffer = result) + { + char* p = Int32ToHexChars(buffer + bufferLength, (uint)value, hexBase, digits); + Debug.Assert(p == buffer); + } + return result; } private static unsafe bool TryInt32ToHexStr(int value, char hexBase, int digits, Span destination, out int charsWritten) @@ -1024,11 +1032,20 @@ namespace System if (digits < 1) digits = 1; - int bufferLength = Math.Max(digits, MaxUInt32HexDigits); - char* buffer = stackalloc char[bufferLength]; + int bufferLength = Math.Max(digits, FormattingHelpers.CountHexDigits((uint)value)); + if (bufferLength > destination.Length) + { + charsWritten = 0; + return false; + } - char* p = Int32ToHexChars(buffer + bufferLength, (uint)value, hexBase, digits); - return TryCopyTo(p, (int)(buffer + bufferLength - p), destination, out charsWritten); + charsWritten = bufferLength; + fixed (char* buffer = &MemoryMarshal.GetReference(destination)) + { + char* p = Int32ToHexChars(buffer + bufferLength, (uint)value, hexBase, digits); + Debug.Assert(p == buffer); + } + return true; } private static unsafe char* Int32ToHexChars(char* buffer, uint value, int hexBase, int digits) @@ -1052,6 +1069,7 @@ namespace System char* p = UInt32ToDecChars(buffer + UInt32Precision, value, 0); int i = (int)(buffer + UInt32Precision - p); number.scale = i; + number.kind = NumberBufferKind.Integer; char* dst = number.digits; while (--i >= 0) @@ -1073,56 +1091,69 @@ namespace System private static unsafe string UInt32ToDecStr(uint value, int digits) { - if (digits <= 1) - { - char* buffer = stackalloc char[MaxUInt32DecDigits]; + int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value)); - char* start = buffer + MaxUInt32DecDigits; - char* p = start; - do + // For single-digit values that are very common, especially 0 and 1, just return cached strings. + if (bufferLength == 1) + { + return s_singleDigitStringCache[value]; + } + + string result = string.FastAllocateString(bufferLength); + fixed (char* buffer = result) + { + char* p = buffer + bufferLength; + if (digits <= 1) { - // TODO https://github.com/dotnet/coreclr/issues/3439 - uint div = value / 10; - *(--p) = (char)('0' + value - (div * 10)); - value = div; + do + { + // TODO https://github.com/dotnet/coreclr/issues/3439 + uint div = value / 10; + *(--p) = (char)('0' + value - (div * 10)); + value = div; + } + while (value != 0); } - while (value != 0); - - return new string(p, 0, (int)(start - p)); - } - else - { - int bufferSize = Math.Max(digits, MaxUInt32DecDigits); - char* buffer = stackalloc char[bufferSize]; - char* p = UInt32ToDecChars(buffer + bufferSize, value, digits); - return new string(p, 0, (int)(buffer + bufferSize - p)); + else + { + p = UInt32ToDecChars(p, value, digits); + } + Debug.Assert(p == buffer); } + return result; } private static unsafe bool TryUInt32ToDecStr(uint value, int digits, Span destination, out int charsWritten) { - if (digits <= 1) + int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value)); + if (bufferLength > destination.Length) { - char* buffer = stackalloc char[MaxUInt32DecDigits]; - char* start = buffer + MaxUInt32DecDigits; - char* p = start; - do + charsWritten = 0; + return false; + } + + charsWritten = bufferLength; + fixed (char* buffer = &MemoryMarshal.GetReference(destination)) + { + char* p = buffer + bufferLength; + if (digits <= 1) { - // TODO https://github.com/dotnet/coreclr/issues/3439 - uint div = value / 10; - *(--p) = (char)('0' + value - (div * 10)); - value = div; + do + { + // TODO https://github.com/dotnet/coreclr/issues/3439 + uint div = value / 10; + *(--p) = (char)('0' + value - (div * 10)); + value = div; + } + while (value != 0); } - while (value != 0); - return TryCopyTo(p, (int)(start - p), destination, out charsWritten); - } - else - { - int bufferSize = Math.Max(digits, MaxUInt32DecDigits); - char* buffer = stackalloc char[bufferSize]; - char* p = UInt32ToDecChars(buffer + bufferSize, value, digits); - return TryCopyTo(p, (int)(buffer + bufferSize - p), destination, out charsWritten); + else + { + p = UInt32ToDecChars(p, value, digits); + } + Debug.Assert(p == buffer); } + return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -1158,6 +1189,7 @@ namespace System int i = (int)(buffer + Int64Precision - p); number.scale = i; + number.kind = NumberBufferKind.Integer; char* dst = number.digits; while (--i >= 0) @@ -1176,24 +1208,26 @@ namespace System ulong value = (ulong)(-input); - int bufferLength = Math.Max(digits, MaxUInt64DecDigits) + sNegative.Length; - int index = bufferLength; - - char* buffer = stackalloc char[bufferLength]; - char* p = buffer + bufferLength; - while (High32(value) != 0) + int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value)) + sNegative.Length; + string result = string.FastAllocateString(bufferLength); + fixed (char* buffer = result) { - p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9); - digits -= 9; - } - p = UInt32ToDecChars(p, Low32(value), digits); + char* p = buffer + bufferLength; + while (High32(value) != 0) + { + p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9); + digits -= 9; + } + p = UInt32ToDecChars(p, Low32(value), digits); + Debug.Assert(p == buffer + sNegative.Length); - for (int i = sNegative.Length - 1; i >= 0; i--) - { - *(--p) = sNegative[i]; + for (int i = sNegative.Length - 1; i >= 0; i--) + { + *(--p) = sNegative[i]; + } + Debug.Assert(p == buffer); } - - return new string(p, 0, (int)(buffer + bufferLength - p)); + return result; } private static unsafe bool TryNegativeInt64ToDecStr(long input, int digits, string sNegative, Span destination, out int charsWritten) @@ -1207,64 +1241,80 @@ namespace System ulong value = (ulong)(-input); - int bufferLength = Math.Max(digits, MaxUInt64DecDigits) + sNegative.Length; - int index = bufferLength; - - char* buffer = stackalloc char[bufferLength]; - char* p = buffer + bufferLength; - while (High32(value) != 0) + int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits((ulong)(-input))) + sNegative.Length; + if (bufferLength > destination.Length) { - p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9); - digits -= 9; - } - p = UInt32ToDecChars(p, Low32(value), digits); - - for (int i = sNegative.Length - 1; i >= 0; i--) - { - *(--p) = sNegative[i]; + charsWritten = 0; + return false; } - return TryCopyTo(p, (int)(buffer + bufferLength - p), destination, out charsWritten); + charsWritten = bufferLength; + fixed (char* buffer = &MemoryMarshal.GetReference(destination)) + { + char* p = buffer + bufferLength; + while (High32(value) != 0) + { + p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9); + digits -= 9; + } + p = UInt32ToDecChars(p, Low32(value), digits); + Debug.Assert(p == buffer + sNegative.Length); + + for (int i = sNegative.Length - 1; i >= 0; i--) + { + *(--p) = sNegative[i]; + } + Debug.Assert(p == buffer); + } + return true; } private static unsafe string Int64ToHexStr(long value, char hexBase, int digits) { - int bufferLength = Math.Max(digits, MaxUInt32HexDigits * 2); - char* buffer = stackalloc char[bufferLength]; - int index = bufferLength; - - char* p; - if (High32((ulong)value) != 0) + int bufferLength = Math.Max(digits, FormattingHelpers.CountHexDigits((ulong)value)); + string result = string.FastAllocateString(bufferLength); + fixed (char* buffer = result) { - p = Int32ToHexChars(buffer + index, Low32((ulong)value), hexBase, 8); - p = Int32ToHexChars(p, High32((ulong)value), hexBase, digits - 8); + char* p = buffer + bufferLength; + if (High32((ulong)value) != 0) + { + p = Int32ToHexChars(p, Low32((ulong)value), hexBase, 8); + p = Int32ToHexChars(p, High32((ulong)value), hexBase, digits - 8); + } + else + { + p = Int32ToHexChars(p, Low32((ulong)value), hexBase, Math.Max(digits, 1)); + } + Debug.Assert(p == buffer); } - else - { - p = Int32ToHexChars(buffer + index, Low32((ulong)value), hexBase, Math.Max(digits, 1)); - } - - return new string(p, 0, (int)(buffer + bufferLength - p)); + return result; } private static unsafe bool TryInt64ToHexStr(long value, char hexBase, int digits, Span destination, out int charsWritten) { - int bufferLength = Math.Max(digits, MaxUInt32HexDigits * 2); - char* buffer = stackalloc char[bufferLength]; - int index = bufferLength; - - char* p; - if (High32((ulong)value) != 0) + int bufferLength = Math.Max(digits, FormattingHelpers.CountHexDigits((ulong)value)); + if (bufferLength > destination.Length) { - p = Int32ToHexChars(buffer + index, Low32((ulong)value), hexBase, 8); - p = Int32ToHexChars(p, High32((ulong)value), hexBase, digits - 8); - } - else - { - p = Int32ToHexChars(buffer + index, Low32((ulong)value), hexBase, Math.Max(digits, 1)); + charsWritten = 0; + return false; } - return TryCopyTo(p, (int)(buffer + bufferLength - p), destination, out charsWritten); + charsWritten = bufferLength; + fixed (char* buffer = &MemoryMarshal.GetReference(destination)) + { + char* p = buffer + bufferLength; + if (High32((ulong)value) != 0) + { + p = Int32ToHexChars(p, Low32((ulong)value), hexBase, 8); + p = Int32ToHexChars(p, High32((ulong)value), hexBase, digits - 8); + } + else + { + p = Int32ToHexChars(p, Low32((ulong)value), hexBase, Math.Max(digits, 1)); + } + Debug.Assert(p == buffer); + } + return true; } private static unsafe void UInt64ToNumber(ulong value, ref NumberBuffer number) @@ -1281,6 +1331,7 @@ namespace System int i = (int)(buffer + UInt64Precision - p); number.scale = i; + number.kind = NumberBufferKind.Integer; char* dst = number.digits; while (--i >= 0) @@ -1293,17 +1344,27 @@ namespace System if (digits < 1) digits = 1; - int bufferSize = Math.Max(digits, MaxUInt64DecDigits); - char* buffer = stackalloc char[bufferSize]; - char* p = buffer + bufferSize; - while (High32(value) != 0) - { - p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9); - digits -= 9; - } - p = UInt32ToDecChars(p, Low32(value), digits); + int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value)); - return new string(p, 0, (int)(buffer + bufferSize - p)); + // For single-digit values that are very common, especially 0 and 1, just return cached strings. + if (bufferLength == 1) + { + return s_singleDigitStringCache[value]; + } + + string result = string.FastAllocateString(bufferLength); + fixed (char* buffer = result) + { + char* p = buffer + bufferLength; + while (High32(value) != 0) + { + p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9); + digits -= 9; + } + p = UInt32ToDecChars(p, Low32(value), digits); + Debug.Assert(p == buffer); + } + return result; } private static unsafe bool TryUInt64ToDecStr(ulong value, int digits, Span destination, out int charsWritten) @@ -1311,17 +1372,26 @@ namespace System if (digits < 1) digits = 1; - int bufferSize = Math.Max(digits, MaxUInt64DecDigits); - char* buffer = stackalloc char[bufferSize]; - char* p = buffer + bufferSize; - while (High32(value) != 0) + int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value)); + if (bufferLength > destination.Length) { - p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9); - digits -= 9; + charsWritten = 0; + return false; } - p = UInt32ToDecChars(p, Low32(value), digits); - return TryCopyTo(p, (int)(buffer + bufferSize - p), destination, out charsWritten); + charsWritten = bufferLength; + fixed (char* buffer = &MemoryMarshal.GetReference(destination)) + { + char* p = buffer + bufferLength; + while (High32(value) != 0) + { + p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9); + digits -= 9; + } + p = UInt32ToDecChars(p, Low32(value), digits); + Debug.Assert(p == buffer); + } + return true; } internal static unsafe char ParseFormatSpecifier(ReadOnlySpan format, out int digits) @@ -1390,22 +1460,21 @@ namespace System '\0'; } - internal static unsafe void NumberToString(ref ValueStringBuilder sb, ref NumberBuffer number, char format, int nMaxDigits, NumberFormatInfo info, bool isDecimal) + internal static unsafe void NumberToString(ref ValueStringBuilder sb, ref NumberBuffer number, char format, int nMaxDigits, NumberFormatInfo info) { - int nMinDigits = -1; + Debug.Assert(number.kind != NumberBufferKind.Unknown); switch (format) { case 'C': case 'c': { - nMinDigits = nMaxDigits >= 0 ? nMaxDigits : info.CurrencyDecimalDigits; if (nMaxDigits < 0) nMaxDigits = info.CurrencyDecimalDigits; RoundNumber(ref number, number.scale + nMaxDigits); // Don't change this line to use digPos since digCount could have its sign changed. - FormatCurrency(ref sb, ref number, nMinDigits, nMaxDigits, info); + FormatCurrency(ref sb, ref number, nMaxDigits, info); break; } @@ -1414,16 +1483,14 @@ namespace System case 'f': { if (nMaxDigits < 0) - nMaxDigits = nMinDigits = info.NumberDecimalDigits; - else - nMinDigits = nMaxDigits; + nMaxDigits = info.NumberDecimalDigits; RoundNumber(ref number, number.scale + nMaxDigits); if (number.sign) sb.Append(info.NegativeSign); - FormatFixed(ref sb, ref number, nMinDigits, nMaxDigits, info, null, info.NumberDecimalSeparator, null); + FormatFixed(ref sb, ref number, nMaxDigits, info, null, info.NumberDecimalSeparator, null); break; } @@ -1432,13 +1499,11 @@ namespace System case 'n': { if (nMaxDigits < 0) - nMaxDigits = nMinDigits = info.NumberDecimalDigits; // Since we are using digits in our calculation - else - nMinDigits = nMaxDigits; + nMaxDigits = info.NumberDecimalDigits; // Since we are using digits in our calculation RoundNumber(ref number, number.scale + nMaxDigits); - FormatNumber(ref sb, ref number, nMinDigits, nMaxDigits, info); + FormatNumber(ref sb, ref number, nMaxDigits, info); break; } @@ -1447,9 +1512,7 @@ namespace System case 'e': { if (nMaxDigits < 0) - nMaxDigits = nMinDigits = 6; - else - nMinDigits = nMaxDigits; + nMaxDigits = 6; nMaxDigits++; RoundNumber(ref number, nMaxDigits); @@ -1457,7 +1520,7 @@ namespace System if (number.sign) sb.Append(info.NegativeSign); - FormatScientific(ref sb, ref number, nMinDigits, nMaxDigits, info, format); + FormatScientific(ref sb, ref number, nMaxDigits, info, format); break; } @@ -1465,40 +1528,28 @@ namespace System case 'G': case 'g': { - bool enableRounding = true; + bool noRounding = false; if (nMaxDigits < 1) { - if (isDecimal && (nMaxDigits == -1)) + if ((number.kind == NumberBufferKind.Decimal) && (nMaxDigits == -1)) { - // Default to 29 digits precision only for G formatting without a precision specifier - // This ensures that the PAL code pads out to the correct place even when we use the default precision - nMaxDigits = nMinDigits = DecimalPrecision; - enableRounding = false; // Turn off rounding for ECMA compliance to output trailing 0's after decimal as significant + noRounding = true; // Turn off rounding for ECMA compliance to output trailing 0's after decimal as significant + goto SkipRounding; } else { // This ensures that the PAL code pads out to the correct place even when we use the default precision - nMaxDigits = nMinDigits = number.precision; - } - } - else - nMinDigits = nMaxDigits; - - if (enableRounding) // Don't round for G formatting without precision - RoundNumber(ref number, nMaxDigits); // This also fixes up the minus zero case - else - { - if (isDecimal && (number.digits[0] == 0)) - { - // Minus zero should be formatted as 0 - number.sign = false; + nMaxDigits = number.precision; } } + RoundNumber(ref number, nMaxDigits); + +SkipRounding: if (number.sign) sb.Append(info.NegativeSign); - FormatGeneral(ref sb, ref number, nMinDigits, nMaxDigits, info, (char)(format - ('G' - 'E')), !enableRounding); + FormatGeneral(ref sb, ref number, nMaxDigits, info, (char)(format - ('G' - 'E')), noRounding); break; } @@ -1507,14 +1558,12 @@ namespace System case 'p': { if (nMaxDigits < 0) - nMaxDigits = nMinDigits = info.PercentDecimalDigits; - else - nMinDigits = nMaxDigits; + nMaxDigits = info.PercentDecimalDigits; number.scale += 2; RoundNumber(ref number, number.scale + nMaxDigits); - FormatPercent(ref sb, ref number, nMinDigits, nMaxDigits, info); + FormatPercent(ref sb, ref number, nMaxDigits, info); break; } @@ -1526,6 +1575,8 @@ namespace System internal static unsafe void NumberToStringFormat(ref ValueStringBuilder sb, ref NumberBuffer number, ReadOnlySpan format, NumberFormatInfo info) { + Debug.Assert(number.kind != NumberBufferKind.Unknown); + int digitCount; int decimalPos; int firstDigit; @@ -1648,7 +1699,6 @@ namespace System } else { - number.sign = false; // We need to format -0 without the sign set. number.scale = 0; // Decimals with scale ('0.00') should be rounded. } @@ -1881,7 +1931,7 @@ namespace System } } - private static void FormatCurrency(ref ValueStringBuilder sb, ref NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info) + private static void FormatCurrency(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info) { string fmt = number.sign ? s_negCurrencyFormats[info.CurrencyNegativePattern] : @@ -1892,7 +1942,7 @@ namespace System switch (ch) { case '#': - FormatFixed(ref sb, ref number, nMinDigits, nMaxDigits, info, info.currencyGroupSizes, info.CurrencyDecimalSeparator, info.CurrencyGroupSeparator); + FormatFixed(ref sb, ref number, nMaxDigits, info, info.currencyGroupSizes, info.CurrencyDecimalSeparator, info.CurrencyGroupSeparator); break; case '-': sb.Append(info.NegativeSign); @@ -1907,7 +1957,7 @@ namespace System } } - private static unsafe void FormatFixed(ref ValueStringBuilder sb, ref NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info, int[] groupDigits, string sDecimal, string sGroup) + private static unsafe void FormatFixed(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info, int[] groupDigits, string sDecimal, string sGroup) { int digPos = number.scale; char* dig = number.digits; @@ -1917,13 +1967,14 @@ namespace System if (groupDigits != null) { int groupSizeIndex = 0; // Index into the groupDigits array. - int groupSizeCount = groupDigits[groupSizeIndex]; // The current total of group size. int bufferSize = digPos; // The length of the result buffer string. int groupSize = 0; // The current group size. // Find out the size of the string buffer for the result. if (groupDigits.Length != 0) // You can pass in 0 length arrays { + int groupSizeCount = groupDigits[groupSizeIndex]; // The current total of group size. + while (digPos > groupSizeCount) { groupSize = groupDigits[groupSizeIndex]; @@ -2008,7 +2059,7 @@ namespace System } } - private static void FormatNumber(ref ValueStringBuilder sb, ref NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info) + private static void FormatNumber(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info) { string fmt = number.sign ? s_negNumberFormats[info.NumberNegativePattern] : @@ -2019,7 +2070,7 @@ namespace System switch (ch) { case '#': - FormatFixed(ref sb, ref number, nMinDigits, nMaxDigits, info, info.numberGroupSizes, info.NumberDecimalSeparator, info.NumberGroupSeparator); + FormatFixed(ref sb, ref number, nMaxDigits, info, info.numberGroupSizes, info.NumberDecimalSeparator, info.NumberGroupSeparator); break; case '-': sb.Append(info.NegativeSign); @@ -2031,7 +2082,7 @@ namespace System } } - private static unsafe void FormatScientific(ref ValueStringBuilder sb, ref NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info, char expChar) + private static unsafe void FormatScientific(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info, char expChar) { char* dig = number.digits; @@ -2068,7 +2119,7 @@ namespace System sb.Append(p, (int)(digits + MaxUInt32DecDigits - p)); } - private static unsafe void FormatGeneral(ref ValueStringBuilder sb, ref NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info, char expChar, bool bSuppressScientific) + private static unsafe void FormatGeneral(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info, char expChar, bool bSuppressScientific) { int digPos = number.scale; bool scientific = false; @@ -2115,7 +2166,7 @@ namespace System FormatExponent(ref sb, info, number.scale - 1, expChar, 2, true); } - private static void FormatPercent(ref ValueStringBuilder sb, ref NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info) + private static void FormatPercent(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info) { string fmt = number.sign ? s_negPercentFormats[info.PercentNegativePattern] : @@ -2126,7 +2177,7 @@ namespace System switch (ch) { case '#': - FormatFixed(ref sb, ref number, nMinDigits, nMaxDigits, info, info.percentGroupSizes, info.PercentDecimalSeparator, info.PercentGroupSeparator); + FormatFixed(ref sb, ref number, nMaxDigits, info, info.percentGroupSizes, info.PercentDecimalSeparator, info.PercentGroupSeparator); break; case '-': sb.Append(info.NegativeSign); @@ -2173,7 +2224,11 @@ namespace System if (i == 0) { number.scale = 0; - number.sign = false; + + if (number.kind == NumberBufferKind.Integer) + { + number.sign = false; + } } dig[i] = '\0'; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Number.NumberBuffer.cs b/external/corert/src/System.Private.CoreLib/shared/System/Number.NumberBuffer.cs index 2316f99bd3..1730cf18fa 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Number.NumberBuffer.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Number.NumberBuffer.cs @@ -15,17 +15,27 @@ namespace System [StructLayout(LayoutKind.Sequential, Pack = 1)] internal unsafe ref struct NumberBuffer // needs to match layout of NUMBER in coreclr's src/classlibnative/bcltype/number.h { - public int precision; - public int scale; - private int _sign; - private DigitsAndNullTerminator _digits; - private char* _allDigits; + public int precision; // 0 + public int scale; // 4 + private int _sign; // 8 + private NumberBufferKind _kind; // 12 + private char* _allDigits; // 16 + private DigitsAndNullTerminator _digits; // 20 or 24 public bool sign { get => _sign != 0; set => _sign = value ? 1 : 0; } public char* digits => (char*)Unsafe.AsPointer(ref _digits); + public NumberBufferKind kind { get => _kind; set => _kind = value; } [StructLayout(LayoutKind.Sequential, Size = (NumberMaxDigits + 1) * sizeof(char))] private struct DigitsAndNullTerminator { } } + + internal enum NumberBufferKind // needs to match NUMBER_KIND in coreclr's src/classlibnative/bcltype/number.h + { + Unknown = 0, + Integer = 1, + Decimal = 2, + Double = 3 + } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Number.Parsing.cs b/external/corert/src/System.Private.CoreLib/shared/System/Number.Parsing.cs index 46951094eb..7c7866a901 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Number.Parsing.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Number.Parsing.cs @@ -5,6 +5,11 @@ using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; +#if MONO +using System.Runtime.CompilerServices; +#else +using Internal.Runtime.CompilerServices; +#endif namespace System { @@ -30,129 +35,26 @@ namespace System private const int Int64Precision = 19; private const int UInt64Precision = 20; - private static bool HexNumberToInt32(ref NumberBuffer number, ref int value) + /// 256-element map from an ASCII char to its hex value, e.g. arr['b'] == 11. 0xFF means it's not a hex digit. + private static readonly int[] s_charToHexLookup = { - uint passedValue = 0; - bool returnValue = HexNumberToUInt32(ref number, ref passedValue); - value = (int)passedValue; - return returnValue; - } - - private static bool HexNumberToInt64(ref NumberBuffer number, ref long value) - { - ulong passedValue = 0; - bool returnValue = HexNumberToUInt64(ref number, ref passedValue); - value = (long)passedValue; - return returnValue; - } - - private static unsafe bool HexNumberToUInt32(ref NumberBuffer number, ref uint value) - { - int i = number.scale; - if (i > UInt32Precision || i < number.precision) - { - return false; - } - char* p = number.digits; - Debug.Assert(p != null); - - uint n = 0; - while (--i >= 0) - { - if (n > ((uint)0xFFFFFFFF / 16)) - { - return false; - } - n *= 16; - if (*p != '\0') - { - uint newN = n; - if (*p != '\0') - { - if (*p >= '0' && *p <= '9') - { - newN += (uint)(*p - '0'); - } - else - { - if (*p >= 'A' && *p <= 'F') - { - newN += (uint)((*p - 'A') + 10); - } - else - { - Debug.Assert(*p >= 'a' && *p <= 'f'); - newN += (uint)((*p - 'a') + 10); - } - } - p++; - } - - // Detect an overflow here... - if (newN < n) - { - return false; - } - n = newN; - } - } - value = n; - return true; - } - - private static unsafe bool HexNumberToUInt64(ref NumberBuffer number, ref ulong value) - { - int i = number.scale; - if (i > UInt64Precision || i < number.precision) - { - return false; - } - char* p = number.digits; - Debug.Assert(p != null); - - ulong n = 0; - while (--i >= 0) - { - if (n > (0xFFFFFFFFFFFFFFFF / 16)) - { - return false; - } - n *= 16; - if (*p != '\0') - { - ulong newN = n; - if (*p != '\0') - { - if (*p >= '0' && *p <= '9') - { - newN += (ulong)(*p - '0'); - } - else - { - if (*p >= 'A' && *p <= 'F') - { - newN += (ulong)((*p - 'A') + 10); - } - else - { - Debug.Assert(*p >= 'a' && *p <= 'f'); - newN += (ulong)((*p - 'a') + 10); - } - } - p++; - } - - // Detect an overflow here... - if (newN < n) - { - return false; - } - n = newN; - } - } - value = n; - return true; - } + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 15 + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 31 + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 47 + 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 63 + 0xFF, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 79 + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 95 + 0xFF, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 111 + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 127 + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 143 + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 159 + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 175 + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 191 + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 207 + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 223 + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 239 + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // 255 + }; private static unsafe bool NumberToInt32(ref NumberBuffer number, ref int value) { @@ -173,7 +75,7 @@ namespace System n *= 10; if (*p != '\0') { - n += (int)(*p++ - '0'); + n += (*p++ - '0'); } } if (number.sign) @@ -214,7 +116,7 @@ namespace System n *= 10; if (*p != '\0') { - n += (int)(*p++ - '0'); + n += (*p++ - '0'); } } if (number.sign) @@ -300,104 +202,147 @@ namespace System return true; } - internal unsafe static int ParseInt32(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info) + internal static int ParseInt32(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { + if ((styles & ~NumberStyles.Integer) == 0) + { + // Optimized path for the common case of anything that's allowed for integer style. + bool overflow = false; + if (!TryParseInt32IntegerStyle(value, styles, info, out int intResult, ref overflow)) + { + ThrowOverflowOrFormatException(overflow, nameof(SR.Overflow_Int32)); + } + return intResult; + } + + if ((styles & NumberStyles.AllowHexSpecifier) != 0) + { + bool overflow = false; + if (!TryParseUInt32HexNumberStyle(value, styles, info, out uint hexResult, ref overflow)) + { + ThrowOverflowOrFormatException(overflow, nameof(SR.Overflow_Int32)); + } + return (int)hexResult; + } + NumberBuffer number = default; - int i = 0; - - StringToNumber(s, style, ref number, info, false); - - if ((style & NumberStyles.AllowHexSpecifier) != 0) + int result = 0; + StringToNumber(value, styles, ref number, info, false); + if (!NumberToInt32(ref number, ref result)) { - if (!HexNumberToInt32(ref number, ref i)) - { - throw new OverflowException(SR.Overflow_Int32); - } + ThrowOverflowOrFormatException(overflow: true, nameof(SR.Overflow_Int32)); } - else - { - if (!NumberToInt32(ref number, ref i)) - { - throw new OverflowException(SR.Overflow_Int32); - } - } - return i; + return result; } - internal unsafe static long ParseInt64(ReadOnlySpan value, NumberStyles options, NumberFormatInfo numfmt) + internal static long ParseInt64(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { + if ((styles & ~NumberStyles.Integer) == 0) + { + // Optimized path for the common case of anything that's allowed for integer style. + bool overflow = false; + if (!TryParseInt64IntegerStyle(value, styles, info, out long intResult, ref overflow)) + { + ThrowOverflowOrFormatException(overflow, nameof(SR.Overflow_Int64)); + } + return intResult; + } + + if ((styles & NumberStyles.AllowHexSpecifier) != 0) + { + bool overflow = false; + if (!TryParseUInt64HexNumberStyle(value, styles, info, out ulong hexResult, ref overflow)) + { + ThrowOverflowOrFormatException(overflow, nameof(SR.Overflow_Int64)); + } + return (long)hexResult; + } + NumberBuffer number = default; - long i = 0; - - StringToNumber(value, options, ref number, numfmt, false); - - if ((options & NumberStyles.AllowHexSpecifier) != 0) + long result = 0; + StringToNumber(value, styles, ref number, info, false); + if (!NumberToInt64(ref number, ref result)) { - if (!HexNumberToInt64(ref number, ref i)) - { - throw new OverflowException(SR.Overflow_Int64); - } + ThrowOverflowOrFormatException(overflow: true, nameof(SR.Overflow_Int64)); } - else - { - if (!NumberToInt64(ref number, ref i)) - { - throw new OverflowException(SR.Overflow_Int64); - } - } - return i; + return result; } - internal unsafe static uint ParseUInt32(ReadOnlySpan value, NumberStyles options, NumberFormatInfo numfmt) + internal static uint ParseUInt32(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { + uint result = 0; + + if ((styles & ~NumberStyles.Integer) == 0) + { + // Optimized path for the common case of anything that's allowed for integer style. + bool overflow = false; + if (!TryParseUInt32IntegerStyle(value, styles, info, out result, ref overflow)) + { + ThrowOverflowOrFormatException(overflow, nameof(SR.Overflow_UInt32)); + } + return result; + } + + if ((styles & NumberStyles.AllowHexSpecifier) != 0) + { + bool overflow = false; + if (!TryParseUInt32HexNumberStyle(value, styles, info, out result, ref overflow)) + { + ThrowOverflowOrFormatException(overflow, nameof(SR.Overflow_UInt32)); + } + return result; + } + NumberBuffer number = default; - uint i = 0; - - StringToNumber(value, options, ref number, numfmt, false); - - if ((options & NumberStyles.AllowHexSpecifier) != 0) + StringToNumber(value, styles, ref number, info, false); + if (!NumberToUInt32(ref number, ref result)) { - if (!HexNumberToUInt32(ref number, ref i)) - { - throw new OverflowException(SR.Overflow_UInt32); - } + ThrowOverflowOrFormatException(overflow: true, nameof(SR.Overflow_UInt32)); } - else - { - if (!NumberToUInt32(ref number, ref i)) - { - throw new OverflowException(SR.Overflow_UInt32); - } - } - - return i; + return result; } - internal unsafe static ulong ParseUInt64(ReadOnlySpan value, NumberStyles options, NumberFormatInfo numfmt) + internal static ulong ParseUInt64(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { - NumberBuffer number = default; - ulong i = 0; + ulong result = 0; - StringToNumber(value, options, ref number, numfmt, false); - if ((options & NumberStyles.AllowHexSpecifier) != 0) + if ((styles & ~NumberStyles.Integer) == 0) { - if (!HexNumberToUInt64(ref number, ref i)) + // Optimized path for the common case of anything that's allowed for integer style. + bool overflow = false; + if (!TryParseUInt64IntegerStyle(value, styles, info, out result, ref overflow)) { - throw new OverflowException(SR.Overflow_UInt64); + ThrowOverflowOrFormatException(overflow, nameof(SR.Overflow_UInt64)); } + return result; } - else + + if ((styles & NumberStyles.AllowHexSpecifier) != 0) { - if (!NumberToUInt64(ref number, ref i)) + bool overflow = false; + if (!TryParseUInt64HexNumberStyle(value, styles, info, out result, ref overflow)) { - throw new OverflowException(SR.Overflow_UInt64); + ThrowOverflowOrFormatException(overflow, nameof(SR.Overflow_UInt64)); } + return result; } - return i; + + NumberBuffer number = default; + StringToNumber(value, styles, ref number, info, false); + if (!NumberToUInt64(ref number, ref result)) + { + ThrowOverflowOrFormatException(overflow: true, nameof(SR.Overflow_UInt64)); + } + return result; } - private unsafe static bool ParseNumber(ref char* str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo numfmt, bool parseDecimal) + private static unsafe bool ParseNumber(ref char* str, char* strEnd, NumberStyles styles, ref NumberBuffer number, NumberFormatInfo info, bool parseDecimal) { + Debug.Assert(str != null); + Debug.Assert(strEnd != null); + Debug.Assert(str <= strEnd); + Debug.Assert((styles & NumberStyles.AllowHexSpecifier) == 0); + const int StateSign = 0x0001; const int StateParens = 0x0002; const int StateDigits = 0x0004; @@ -412,44 +357,44 @@ namespace System string currSymbol = null; // currency symbol from NumberFormatInfo. bool parsingCurrency = false; - if ((options & NumberStyles.AllowCurrencySymbol) != 0) + if ((styles & NumberStyles.AllowCurrencySymbol) != 0) { - currSymbol = numfmt.CurrencySymbol; + currSymbol = info.CurrencySymbol; // The idea here is to match the currency separators and on failure match the number separators to keep the perf of VB's IsNumeric fast. // The values of decSep are setup to use the correct relevant separator (currency in the if part and decimal in the else part). - decSep = numfmt.CurrencyDecimalSeparator; - groupSep = numfmt.CurrencyGroupSeparator; + decSep = info.CurrencyDecimalSeparator; + groupSep = info.CurrencyGroupSeparator; parsingCurrency = true; } else { - decSep = numfmt.NumberDecimalSeparator; - groupSep = numfmt.NumberGroupSeparator; + decSep = info.NumberDecimalSeparator; + groupSep = info.NumberGroupSeparator; } int state = 0; char* p = str; - char ch = *p; + char ch = p < strEnd ? *p : '\0'; char* next; while (true) { // Eat whitespace unless we've found a sign which isn't followed by a currency symbol. // "-Kr 1231.47" is legal but "- 1231.47" is not. - if (!IsWhite(ch) || (options & NumberStyles.AllowLeadingWhite) == 0 || ((state & StateSign) != 0 && ((state & StateCurrency) == 0 && numfmt.NumberNegativePattern != 2))) + if (!IsWhite(ch) || (styles & NumberStyles.AllowLeadingWhite) == 0 || ((state & StateSign) != 0 && ((state & StateCurrency) == 0 && info.NumberNegativePattern != 2))) { - if ((((options & NumberStyles.AllowLeadingSign) != 0) && (state & StateSign) == 0) && ((next = MatchChars(p, numfmt.PositiveSign)) != null || ((next = MatchChars(p, numfmt.NegativeSign)) != null && (number.sign = true)))) + if ((((styles & NumberStyles.AllowLeadingSign) != 0) && (state & StateSign) == 0) && ((next = MatchChars(p, strEnd, info.PositiveSign)) != null || ((next = MatchChars(p, strEnd, info.NegativeSign)) != null && (number.sign = true)))) { state |= StateSign; p = next - 1; } - else if (ch == '(' && ((options & NumberStyles.AllowParentheses) != 0) && ((state & StateSign) == 0)) + else if (ch == '(' && ((styles & NumberStyles.AllowParentheses) != 0) && ((state & StateSign) == 0)) { state |= StateSign | StateParens; number.sign = true; } - else if (currSymbol != null && (next = MatchChars(p, currSymbol)) != null) + else if (currSymbol != null && (next = MatchChars(p, strEnd, currSymbol)) != null) { state |= StateCurrency; currSymbol = null; @@ -462,13 +407,13 @@ namespace System break; } } - ch = *++p; + ch = ++p < strEnd ? *p : '\0'; } int digCount = 0; int digEnd = 0; while (true) { - if ((ch >= '0' && ch <= '9') || (((options & NumberStyles.AllowHexSpecifier) != 0) && ((ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')))) + if (IsDigit(ch)) { state |= StateDigits; @@ -493,12 +438,12 @@ namespace System number.scale--; } } - else if (((options & NumberStyles.AllowDecimalPoint) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars(p, decSep)) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars(p, numfmt.NumberDecimalSeparator)) != null)) + else if (((styles & NumberStyles.AllowDecimalPoint) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars(p, strEnd, decSep)) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars(p, strEnd, info.NumberDecimalSeparator)) != null)) { state |= StateDecimal; p = next - 1; } - else if (((options & NumberStyles.AllowThousands) != 0) && ((state & StateDigits) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars(p, groupSep)) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars(p, numfmt.NumberGroupSeparator)) != null)) + else if (((styles & NumberStyles.AllowThousands) != 0) && ((state & StateDigits) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars(p, strEnd, groupSep)) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars(p, strEnd, info.NumberGroupSeparator)) != null)) { p = next - 1; } @@ -506,7 +451,7 @@ namespace System { break; } - ch = *++p; + ch = ++p < strEnd ? *p : '\0'; } bool negExp = false; @@ -514,35 +459,35 @@ namespace System number.digits[digEnd] = '\0'; if ((state & StateDigits) != 0) { - if ((ch == 'E' || ch == 'e') && ((options & NumberStyles.AllowExponent) != 0)) + if ((ch == 'E' || ch == 'e') && ((styles & NumberStyles.AllowExponent) != 0)) { char* temp = p; - ch = *++p; - if ((next = MatchChars(p, numfmt.positiveSign)) != null) + ch = ++p < strEnd ? *p : '\0'; + if ((next = MatchChars(p, strEnd, info.positiveSign)) != null) { - ch = *(p = next); + ch = (p = next) < strEnd ? *p : '\0'; } - else if ((next = MatchChars(p, numfmt.negativeSign)) != null) + else if ((next = MatchChars(p, strEnd, info.negativeSign)) != null) { - ch = *(p = next); + ch = (p = next) < strEnd ? *p : '\0'; negExp = true; } - if (ch >= '0' && ch <= '9') + if (IsDigit(ch)) { int exp = 0; do { exp = exp * 10 + (ch - '0'); - ch = *++p; + ch = ++p < strEnd ? *p : '\0'; if (exp > 1000) { exp = 9999; - while (ch >= '0' && ch <= '9') + while (IsDigit(ch)) { - ch = *++p; + ch = ++p < strEnd ? *p : '\0'; } } - } while (ch >= '0' && ch <= '9'); + } while (IsDigit(ch)); if (negExp) { exp = -exp; @@ -552,14 +497,14 @@ namespace System else { p = temp; - ch = *p; + ch = p < strEnd ? *p : '\0'; } } while (true) { - if (!IsWhite(ch) || (options & NumberStyles.AllowTrailingWhite) == 0) + if (!IsWhite(ch) || (styles & NumberStyles.AllowTrailingWhite) == 0) { - if (((options & NumberStyles.AllowTrailingSign) != 0 && ((state & StateSign) == 0)) && ((next = MatchChars(p, numfmt.PositiveSign)) != null || (((next = MatchChars(p, numfmt.NegativeSign)) != null) && (number.sign = true)))) + if (((styles & NumberStyles.AllowTrailingSign) != 0 && ((state & StateSign) == 0)) && ((next = MatchChars(p, strEnd, info.PositiveSign)) != null || (((next = MatchChars(p, strEnd, info.NegativeSign)) != null) && (number.sign = true)))) { state |= StateSign; p = next - 1; @@ -568,7 +513,7 @@ namespace System { state &= ~StateParens; } - else if (currSymbol != null && (next = MatchChars(p, currSymbol)) != null) + else if (currSymbol != null && (next = MatchChars(p, strEnd, currSymbol)) != null) { currSymbol = null; p = next - 1; @@ -578,7 +523,7 @@ namespace System break; } } - ch = *++p; + ch = ++p < strEnd ? *p : '\0'; } if ((state & StateParens) == 0) { @@ -601,206 +546,1109 @@ namespace System return false; } - internal unsafe static bool TryParseInt32(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out int result) + internal static bool TryParseInt32(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out int result) { - NumberBuffer number = default; + if ((styles & ~NumberStyles.Integer) == 0) + { + // Optimized path for the common case of anything that's allowed for integer style. + bool overflow = false; + return TryParseInt32IntegerStyle(value, styles, info, out result, ref overflow); + } + result = 0; - if (!TryStringToNumber(s, style, ref number, info, false)) + if ((styles & NumberStyles.AllowHexSpecifier) != 0) { - return false; + bool overflow = false; + return TryParseUInt32HexNumberStyle(value, styles, info, out Unsafe.As(ref result), ref overflow); } - if ((style & NumberStyles.AllowHexSpecifier) != 0) - { - if (!HexNumberToInt32(ref number, ref result)) - { - return false; - } - } - else - { - if (!NumberToInt32(ref number, ref result)) - { - return false; - } - } - return true; + NumberBuffer number = default; + return + TryStringToNumber(value, styles, ref number, info, false) && + NumberToInt32(ref number, ref result); } - internal unsafe static bool TryParseInt64(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out long result) + /// Parses int limited to styles that make up NumberStyles.Integer. + private static bool TryParseInt32IntegerStyle(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out int result, ref bool failureIsOverflow) { - NumberBuffer number = default; + Debug.Assert((styles & ~NumberStyles.Integer) == 0, "Only handles subsets of Integer format"); + Debug.Assert(!failureIsOverflow, $"failureIsOverflow should have been initialized to false"); + + if ((uint)value.Length < 1) goto FalseExit; + + bool overflow = false; + int sign = 1; + int index = 0; + int num = value[0]; + + // Skip past any whitespace at the beginning. + if ((styles & NumberStyles.AllowLeadingWhite) != 0 && IsWhite(num)) + { + do + { + index++; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + while (IsWhite(num)); + } + + // Parse leading sign. + if ((styles & NumberStyles.AllowLeadingSign) != 0) + { + string positiveSign = info.PositiveSign, negativeSign = info.NegativeSign; + + if (positiveSign == "+" && negativeSign == "-") + { + if (num == '-') + { + sign = -1; + index++; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + else if (num == '+') + { + index++; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + } + else + { + value = value.Slice(index); + index = 0; + if (!string.IsNullOrEmpty(positiveSign) && value.StartsWith(positiveSign)) + { + index += positiveSign.Length; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + else if (!string.IsNullOrEmpty(negativeSign) && value.StartsWith(negativeSign)) + { + sign = -1; + index += negativeSign.Length; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + } + } + + int answer = 0; + + if (IsDigit(num)) + { + // Skip past leading zeros. + if (num == '0') + { + do + { + index++; + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + } while (num == '0'); + if (!IsDigit(num)) goto HasTrailingChars; + } + + // Parse most digits, up to the potential for overflow, which can't happen until after 9 digits. + answer = num - '0'; // first digit + index++; + for (int i = 0; i < 8; i++) // next 8 digits can't overflow + { + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + if (!IsDigit(num)) goto HasTrailingChars; + index++; + answer = 10 * answer + num - '0'; + } + + // Potential overflow now processing the 10th digit. + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + if (!IsDigit(num)) goto HasTrailingChars; + index++; + if (answer > int.MaxValue / 10) + { + overflow = true; + } + answer = answer * 10 + num - '0'; + if ((uint)answer > (uint)int.MaxValue + (-1 * sign + 1) / 2) + { + overflow = true; + } + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + + // At this point, we're either overflowing or hitting a formatting error. + // Format errors take precedence for compatibility. + num = value[index]; + while (IsDigit(num)) + { + overflow = true; + index++; + if ((uint)index >= (uint)value.Length) + goto DoneAtEndButPotentialOverflow; + num = value[index]; + } + goto HasTrailingChars; + } + + FalseExit: // parsing failed + result = 0; + return false; + + DoneAtEndButPotentialOverflow: + if (overflow) + { + failureIsOverflow = true; + goto FalseExit; + } + result = answer * sign; + return true; + + HasTrailingChars: // we've successfully parsed, but there are still remaining characters in the span + // Skip past trailing whitespace, then past trailing zeros, and if anything else remains, fail. + if (IsWhite(num)) + { + if ((styles & NumberStyles.AllowTrailingWhite) == 0) goto FalseExit; + for (index++; index < value.Length; index++) + { + if (!IsWhite(value[index])) break; + } + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + } + + if (!TrailingZeros(value, index)) goto FalseExit; + + goto DoneAtEndButPotentialOverflow; + } + + /// Parses long inputs limited to styles that make up NumberStyles.Integer. + private static bool TryParseInt64IntegerStyle( + ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out long result, ref bool failureIsOverflow) + { + Debug.Assert((styles & ~NumberStyles.Integer) == 0, "Only handles subsets of Integer format"); + Debug.Assert(!failureIsOverflow, $"failureIsOverflow should have been initialized to false"); + + if ((uint)value.Length < 1) goto FalseExit; + + bool overflow = false; + int sign = 1; + int index = 0; + int num = value[0]; + + // Skip past any whitespace at the beginning. + if ((styles & NumberStyles.AllowLeadingWhite) != 0 && IsWhite(num)) + { + do + { + index++; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + while (IsWhite(num)); + } + + // Parse leading sign. + if ((styles & NumberStyles.AllowLeadingSign) != 0) + { + string positiveSign = info.PositiveSign, negativeSign = info.NegativeSign; + + if (positiveSign == "+" && negativeSign == "-") + { + if (num == '-') + { + sign = -1; + index++; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + else if (num == '+') + { + index++; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + } + else + { + value = value.Slice(index); + index = 0; + if (!string.IsNullOrEmpty(positiveSign) && value.StartsWith(positiveSign)) + { + index += positiveSign.Length; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + else if (!string.IsNullOrEmpty(negativeSign) && value.StartsWith(negativeSign)) + { + sign = -1; + index += negativeSign.Length; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + } + } + + long answer = 0; + + if (IsDigit(num)) + { + // Skip past leading zeros. + if (num == '0') + { + do + { + index++; + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + } while (num == '0'); + if (!IsDigit(num)) goto HasTrailingChars; + } + + // Parse most digits, up to the potential for overflow, which can't happen until after 18 digits. + answer = num - '0'; // first digit + index++; + for (int i = 0; i < 17; i++) // next 17 digits can't overflow + { + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + if (!IsDigit(num)) goto HasTrailingChars; + index++; + answer = 10 * answer + num - '0'; + } + + // Potential overflow now processing the 19th digit. + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + if (!IsDigit(num)) goto HasTrailingChars; + index++; + if (answer > long.MaxValue / 10) + { + overflow = true; + } + answer = answer * 10 + num - '0'; + if ((ulong)answer > (ulong)long.MaxValue + (ulong)((-1 * sign + 1) / 2)) // + sign => 0, - sign => 1 + { + overflow = true; + } + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + + // At this point, we're either overflowing or hitting a formatting error. + // Format errors take precedence for compatibility. + num = value[index]; + while (IsDigit(num)) + { + overflow = true; + index++; + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + } + goto HasTrailingChars; + } + + FalseExit: // parsing failed + result = 0; + return false; + + DoneAtEndButPotentialOverflow: + if (overflow) + { + failureIsOverflow = true; + goto FalseExit; + } + result = answer * sign; + return true; + + HasTrailingChars: // we've successfully parsed, but there are still remaining characters in the span + // Skip past trailing whitespace, then past trailing zeros, and if anything else remains, fail. + if (IsWhite(num)) + { + if ((styles & NumberStyles.AllowTrailingWhite) == 0) goto FalseExit; + for (index++; index < value.Length; index++) + { + if (!IsWhite(value[index])) break; + } + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + } + + if (!TrailingZeros(value, index)) goto FalseExit; + + goto DoneAtEndButPotentialOverflow; + } + + internal static bool TryParseInt64(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out long result) + { + if ((styles & ~NumberStyles.Integer) == 0) + { + // Optimized path for the common case of anything that's allowed for integer style. + bool overflow = false; + return TryParseInt64IntegerStyle(value, styles, info, out result, ref overflow); + } + result = 0; - if (!TryStringToNumber(s, style, ref number, info, false)) + if ((styles & NumberStyles.AllowHexSpecifier) != 0) { - return false; + bool overflow = false; + return TryParseUInt64HexNumberStyle(value, styles, info, out Unsafe.As(ref result), ref overflow); } - if ((style & NumberStyles.AllowHexSpecifier) != 0) - { - if (!HexNumberToInt64(ref number, ref result)) - { - return false; - } - } - else - { - if (!NumberToInt64(ref number, ref result)) - { - return false; - } - } - return true; + NumberBuffer number = default; + return + TryStringToNumber(value, styles, ref number, info, false) && + NumberToInt64(ref number, ref result); } - internal unsafe static bool TryParseUInt32(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out uint result) + internal static bool TryParseUInt32(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out uint result) { + if ((styles & ~NumberStyles.Integer) == 0) + { + // Optimized path for the common case of anything that's allowed for integer style. + bool overflow = false; + return TryParseUInt32IntegerStyle(value, styles, info, out result, ref overflow); + } + + if ((styles & NumberStyles.AllowHexSpecifier) != 0) + { + bool overflow = false; + return TryParseUInt32HexNumberStyle(value, styles, info, out result, ref overflow); + } + NumberBuffer number = default; result = 0; - - if (!TryStringToNumber(s, style, ref number, info, false)) - { - return false; - } - - if ((style & NumberStyles.AllowHexSpecifier) != 0) - { - if (!HexNumberToUInt32(ref number, ref result)) - { - return false; - } - } - else - { - if (!NumberToUInt32(ref number, ref result)) - { - return false; - } - } - return true; + return + TryStringToNumber(value, styles, ref number, info, false) && + NumberToUInt32(ref number, ref result); } - internal unsafe static bool TryParseUInt64(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out ulong result) + /// Parses uint limited to styles that make up NumberStyles.Integer. + private static bool TryParseUInt32IntegerStyle( + ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out uint result, ref bool failureIsOverflow) { + Debug.Assert((styles & ~NumberStyles.Integer) == 0, "Only handles subsets of Integer format"); + Debug.Assert(!failureIsOverflow, $"failureIsOverflow should have been initialized to false"); + + if ((uint)value.Length < 1) goto FalseExit; + + bool overflow = false; + bool hasNegativeSign = false; + int index = 0; + int num = value[0]; + + // Skip past any whitespace at the beginning. + if ((styles & NumberStyles.AllowLeadingWhite) != 0 && IsWhite(num)) + { + do + { + index++; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + while (IsWhite(num)); + } + + // Parse leading sign. + if ((styles & NumberStyles.AllowLeadingSign) != 0) + { + string positiveSign = info.PositiveSign, negativeSign = info.NegativeSign; + + if (positiveSign == "+" && negativeSign == "-") + { + if (num == '+') + { + index++; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + else if (num == '-') + { + hasNegativeSign = true; + index++; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + } + else + { + value = value.Slice(index); + index = 0; + if (!string.IsNullOrEmpty(positiveSign) && value.StartsWith(positiveSign)) + { + index += positiveSign.Length; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + else if (!string.IsNullOrEmpty(negativeSign) && value.StartsWith(negativeSign)) + { + hasNegativeSign = true; + index += negativeSign.Length; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + } + } + + int answer = 0; + + if (IsDigit(num)) + { + // Skip past leading zeros. + if (num == '0') + { + do + { + index++; + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + } while (num == '0'); + if (!IsDigit(num)) goto HasTrailingChars; + } + + // Parse most digits, up to the potential for overflow, which can't happen until after 9 digits. + answer = num - '0'; // first digit + index++; + for (int i = 0; i < 8; i++) // next 8 digits can't overflow + { + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + if (!IsDigit(num)) goto HasTrailingChars; + index++; + answer = 10 * answer + num - '0'; + } + + // Potential overflow now processing the 10th digit. + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + if (!IsDigit(num)) goto HasTrailingChars; + index++; + if ((uint)answer > uint.MaxValue / 10 || ((uint)answer == uint.MaxValue / 10 && num > '5')) + { + overflow = true; + } + answer = answer * 10 + num - '0'; + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + + // At this point, we're either overflowing or hitting a formatting error. + // Format errors take precedence for compatibility. + num = value[index]; + while (IsDigit(num)) + { + overflow = true; + index++; + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + } + goto HasTrailingChars; + } + + FalseExit: // parsing failed + result = 0; + return false; + + DoneAtEndButPotentialOverflow: + if (overflow || (hasNegativeSign && answer != 0)) + { + failureIsOverflow = true; + goto FalseExit; + } + result = (uint)answer; + return true; + + HasTrailingChars: // we've successfully parsed, but there are still remaining characters in the span + // Skip past trailing whitespace, then past trailing zeros, and if anything else remains, fail. + if (IsWhite(num)) + { + if ((styles & NumberStyles.AllowTrailingWhite) == 0) goto FalseExit; + for (index++; index < value.Length; index++) + { + if (!IsWhite(value[index])) break; + } + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + } + + if (!TrailingZeros(value, index)) goto FalseExit; + + goto DoneAtEndButPotentialOverflow; + } + + /// Parses uint limited to styles that make up NumberStyles.HexNumber. + private static bool TryParseUInt32HexNumberStyle( + ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out uint result, ref bool failureIsOverflow) + { + Debug.Assert((styles & ~NumberStyles.HexNumber) == 0, "Only handles subsets of HexNumber format"); + Debug.Assert(!failureIsOverflow, $"failureIsOverflow should have been initialized to false"); + + if ((uint)value.Length < 1) goto FalseExit; + + bool overflow = false; + int index = 0; + int num = value[0]; + int numValue = 0; + + // Skip past any whitespace at the beginning. + if ((styles & NumberStyles.AllowLeadingWhite) != 0 && IsWhite(num)) + { + do + { + index++; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + while (IsWhite(num)); + } + + int answer = 0; + int[] charToHexLookup = s_charToHexLookup; + + if ((uint)num < (uint)charToHexLookup.Length && charToHexLookup[num] != 0xFF) + { + // Skip past leading zeros. + if (num == '0') + { + do + { + index++; + if ((uint)index >= (uint)value.Length) goto DoneAtEnd; + num = value[index]; + } while (num == '0'); + if ((uint)num >= (uint)charToHexLookup.Length || charToHexLookup[num] == 0xFF) goto HasTrailingChars; + } + + // Parse up through 8 digits, as no overflow is possible + answer = charToHexLookup[num]; // first digit + index++; + for (int i = 0; i < 7; i++) // next 7 digits can't overflow + { + if ((uint)index >= (uint)value.Length) goto DoneAtEnd; + num = value[index]; + if ((uint)num >= (uint)charToHexLookup.Length || (numValue = charToHexLookup[num]) == 0xFF) goto HasTrailingChars; + index++; + answer = 16 * answer + numValue; + } + + // If there's another digit, it's an overflow. + if ((uint)index >= (uint)value.Length) goto DoneAtEnd; + num = value[index]; + if ((uint)num >= (uint)charToHexLookup.Length || (numValue = charToHexLookup[num]) == 0xFF) goto HasTrailingChars; + index++; + overflow = true; + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + + // At this point, we're either overflowing or hitting a formatting error. + // Format errors take precedence for compatibility. Read through any remaining digits. + num = value[index]; + while ((uint)num < (uint)charToHexLookup.Length && charToHexLookup[num] != 0xFF) + { + index++; + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + } + goto HasTrailingChars; + } + + FalseExit: // parsing failed + result = 0; + return false; + + DoneAtEndButPotentialOverflow: + if (overflow) + { + failureIsOverflow = true; + goto FalseExit; + } + DoneAtEnd: + result = (uint)answer; + return true; + + HasTrailingChars: // we've successfully parsed, but there are still remaining characters in the span + // Skip past trailing whitespace, then past trailing zeros, and if anything else remains, fail. + if (IsWhite(num)) + { + if ((styles & NumberStyles.AllowTrailingWhite) == 0) goto FalseExit; + for (index++; index < value.Length; index++) + { + if (!IsWhite(value[index])) break; + } + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + } + + if (!TrailingZeros(value, index)) goto FalseExit; + + goto DoneAtEndButPotentialOverflow; + } + + internal static bool TryParseUInt64(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out ulong result) + { + if ((styles & ~NumberStyles.Integer) == 0) + { + // Optimized path for the common case of anything that's allowed for integer style. + bool overflow = false; + return TryParseUInt64IntegerStyle(value, styles, info, out result, ref overflow); + } + + if ((styles & NumberStyles.AllowHexSpecifier) != 0) + { + bool overflow = false; + return TryParseUInt64HexNumberStyle(value, styles, info, out result, ref overflow); + } + NumberBuffer number = default; result = 0; - - if (!TryStringToNumber(s, style, ref number, info, false)) - { - return false; - } - - if ((style & NumberStyles.AllowHexSpecifier) != 0) - { - if (!HexNumberToUInt64(ref number, ref result)) - { - return false; - } - } - else - { - if (!NumberToUInt64(ref number, ref result)) - { - return false; - } - } - return true; + return + TryStringToNumber(value, styles, ref number, info, false) && + NumberToUInt64(ref number, ref result); } - internal unsafe static decimal ParseDecimal(ReadOnlySpan value, NumberStyles options, NumberFormatInfo numfmt) + /// Parses ulong limited to styles that make up NumberStyles.Integer. + private static bool TryParseUInt64IntegerStyle( + ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out ulong result, ref bool failureIsOverflow) + { + Debug.Assert((styles & ~NumberStyles.Integer) == 0, "Only handles subsets of Integer format"); + Debug.Assert(!failureIsOverflow, $"failureIsOverflow should have been initialized to false"); + + if ((uint)value.Length < 1) goto FalseExit; + + bool overflow = false; + bool hasNegativeSign = false; + int index = 0; + int num = value[0]; + + // Skip past any whitespace at the beginning. + if ((styles & NumberStyles.AllowLeadingWhite) != 0 && IsWhite(num)) + { + do + { + index++; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + while (IsWhite(num)); + } + + // Parse leading sign. + if ((styles & NumberStyles.AllowLeadingSign) != 0) + { + string positiveSign = info.PositiveSign, negativeSign = info.NegativeSign; + + if (positiveSign == "+" && negativeSign == "-") + { + if (num == '+') + { + index++; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + else if (num == '-') + { + hasNegativeSign = true; + index++; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + } + else + { + value = value.Slice(index); + index = 0; + if (!string.IsNullOrEmpty(positiveSign) && value.StartsWith(positiveSign)) + { + index += positiveSign.Length; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + else if (!string.IsNullOrEmpty(negativeSign) && value.StartsWith(negativeSign)) + { + hasNegativeSign = true; + index += negativeSign.Length; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + } + } + + long answer = 0; + + if (IsDigit(num)) + { + // Skip past leading zeros. + if (num == '0') + { + do + { + index++; + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + } while (num == '0'); + if (!IsDigit(num)) goto HasTrailingChars; + } + + // Parse most digits, up to the potential for overflow, which can't happen until after 19 digits. + answer = num - '0'; // first digit + index++; + for (int i = 0; i < 18; i++) // next 18 digits can't overflow + { + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + if (!IsDigit(num)) goto HasTrailingChars; + index++; + answer = 10 * answer + num - '0'; + } + + // Potential overflow now processing the 20th digit. + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + if (!IsDigit(num)) goto HasTrailingChars; + index++; + if ((ulong)answer > ulong.MaxValue / 10 || ((ulong)answer == ulong.MaxValue / 10 && num > '5')) + { + overflow = true; + } + answer = answer * 10 + num - '0'; + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + + // At this point, we're either overflowing or hitting a formatting error. + // Format errors take precedence for compatibility. + num = value[index]; + while (IsDigit(num)) + { + overflow = true; + index++; + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + } + goto HasTrailingChars; + } + + FalseExit: // parsing failed + result = 0; + return false; + + DoneAtEndButPotentialOverflow: + if (overflow || (hasNegativeSign && answer != 0)) + { + failureIsOverflow = true; + goto FalseExit; + } + result = (ulong)answer; + return true; + + HasTrailingChars: // we've successfully parsed, but there are still remaining characters in the span + // Skip past trailing whitespace, then past trailing zeros, and if anything else remains, fail. + if (IsWhite(num)) + { + if ((styles & NumberStyles.AllowTrailingWhite) == 0) goto FalseExit; + for (index++; index < value.Length; index++) + { + if (!IsWhite(value[index])) break; + } + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + } + + if (!TrailingZeros(value, index)) goto FalseExit; + + goto DoneAtEndButPotentialOverflow; + } + + /// Parses ulong limited to styles that make up NumberStyles.HexNumber. + private static bool TryParseUInt64HexNumberStyle( + ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out ulong result, ref bool failureIsOverflow) + { + Debug.Assert((styles & ~NumberStyles.HexNumber) == 0, "Only handles subsets of HexNumber format"); + Debug.Assert(!failureIsOverflow, $"failureIsOverflow should have been initialized to false"); + + if ((uint)value.Length < 1) goto FalseExit; + + bool overflow = false; + int index = 0; + int num = value[0]; + int numValue = 0; + + // Skip past any whitespace at the beginning. + if ((styles & NumberStyles.AllowLeadingWhite) != 0 && IsWhite(num)) + { + do + { + index++; + if ((uint)index >= (uint)value.Length) goto FalseExit; + num = value[index]; + } + while (IsWhite(num)); + } + + long answer = 0; + int[] charToHexLookup = s_charToHexLookup; + + if ((uint)num < (uint)charToHexLookup.Length && charToHexLookup[num] != 0xFF) + { + // Skip past leading zeros. + if (num == '0') + { + do + { + index++; + if ((uint)index >= (uint)value.Length) goto DoneAtEnd; + num = value[index]; + } while (num == '0'); + if ((uint)num >= (uint)charToHexLookup.Length || charToHexLookup[num] == 0xFF) goto HasTrailingChars; + } + + // Parse up through 16 digits, as no overflow is possible + answer = charToHexLookup[num]; // first digit + index++; + for (int i = 0; i < 15; i++) // next 15 digits can't overflow + { + if ((uint)index >= (uint)value.Length) goto DoneAtEnd; + num = value[index]; + if ((uint)num >= (uint)charToHexLookup.Length || (numValue = charToHexLookup[num]) == 0xFF) goto HasTrailingChars; + index++; + answer = 16 * answer + numValue; + } + + // If there's another digit, it's an overflow. + if ((uint)index >= (uint)value.Length) goto DoneAtEnd; + num = value[index]; + if ((uint)num >= (uint)charToHexLookup.Length || (numValue = charToHexLookup[num]) == 0xFF) goto HasTrailingChars; + index++; + overflow = true; + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + + // At this point, we're either overflowing or hitting a formatting error. + // Format errors take precedence for compatibility. Read through any remaining digits. + num = value[index]; + while ((uint)num < (uint)charToHexLookup.Length && charToHexLookup[num] != 0xFF) + { + index++; + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + num = value[index]; + } + goto HasTrailingChars; + } + + FalseExit: // parsing failed + result = 0; + return false; + + DoneAtEndButPotentialOverflow: + if (overflow) + { + failureIsOverflow = true; + goto FalseExit; + } + DoneAtEnd: + result = (ulong)answer; + return true; + + HasTrailingChars: // we've successfully parsed, but there are still remaining characters in the span + // Skip past trailing whitespace, then past trailing zeros, and if anything else remains, fail. + if (IsWhite(num)) + { + if ((styles & NumberStyles.AllowTrailingWhite) == 0) goto FalseExit; + for (index++; index < value.Length; index++) + { + if (!IsWhite(value[index])) break; + } + if ((uint)index >= (uint)value.Length) goto DoneAtEndButPotentialOverflow; + } + + if (!TrailingZeros(value, index)) goto FalseExit; + + goto DoneAtEndButPotentialOverflow; + } + + internal static decimal ParseDecimal(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { NumberBuffer number = default; decimal result = 0; - StringToNumber(value, options, ref number, numfmt, true); + StringToNumber(value, styles, ref number, info, true); if (!NumberBufferToDecimal(ref number, ref result)) { - throw new OverflowException(SR.Overflow_Decimal); + ThrowOverflowOrFormatException(overflow: true, nameof(SR.Overflow_Decimal)); } return result; } - internal unsafe static double ParseDouble(ReadOnlySpan value, NumberStyles options, NumberFormatInfo numfmt) + private static unsafe bool NumberBufferToDecimal(ref NumberBuffer number, ref decimal value) + { + char* p = number.digits; + int e = number.scale; + bool sign = number.sign; + uint c = *p; + if (c == 0) + { + // To avoid risking an app-compat issue with pre 4.5 (where some app was illegally using Reflection to examine the internal scale bits), we'll only force + // the scale to 0 if the scale was previously positive (previously, such cases were unparsable to a bug.) + value = new decimal(0, 0, 0, sign, (byte)Math.Clamp(-e, 0, 28)); + return true; + } + + if (e > DecimalPrecision) + return false; + + ulong low64 = 0; + while (e > -28) + { + e--; + low64 *= 10; + low64 += c - '0'; + c = *++p; + if (low64 >= ulong.MaxValue / 10) + break; + if (c == 0) + { + while (e > 0) + { + e--; + low64 *= 10; + if (low64 >= ulong.MaxValue / 10) + break; + } + break; + } + } + + uint high = 0; + while ((e > 0 || (c != 0 && e > -28)) && + (high < uint.MaxValue / 10 || (high == uint.MaxValue / 10 && (low64 < 0x99999999_99999999 || (low64 == 0x99999999_99999999 && c <= '5'))))) + { + // multiply by 10 + ulong tmpLow = (uint)low64 * 10UL; + ulong tmp64 = (uint)(low64 >> 32) * 10UL + (tmpLow >> 32); + low64 = (uint)tmpLow + (tmp64 << 32); + high = (uint)(tmp64 >> 32) + high * 10; + + if (c != 0) + { + c -= '0'; + low64 += c; + if (low64 < c) + high++; + c = *++p; + } + e--; + } + + if (c >= '5') + { + // If the next digit is 5, round up if the number is odd or any following digit is non-zero + if (c == '5' && (low64 & 1) == 0) + { + c = *++p; + int count = 20; // Look at the next 20 digits to check to round + while (c == '0' && count != 0) + { + c = *++p; + count--; + } + if (c == 0 || count == 0) + goto NoRounding;// Do nothing + } + + if (++low64 == 0 && ++high == 0) + { + low64 = 0x99999999_9999999A; + high = uint.MaxValue / 10; + e++; + } + } + NoRounding: + + if (e > 0) + return false; + + if (e <= -DecimalPrecision) + { + // Parsing a large scale zero can give you more precision than fits in the decimal. + // This should only happen for actual zeros or very small numbers that round to zero. + value = new decimal(0, 0, 0, sign, DecimalPrecision - 1); + } + else + { + value = new decimal((int)low64, (int)(low64 >> 32), (int)high, sign, (byte)-e); + } + return true; + } + + internal static double ParseDouble(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { NumberBuffer number = default; double d = 0; - if (!TryStringToNumber(value, options, ref number, numfmt, false)) + if (!TryStringToNumber(value, styles, ref number, info, false)) { //If we failed TryStringToNumber, it may be from one of our special strings. //Check the three with which we're concerned and rethrow if it's not one of //those strings. ReadOnlySpan sTrim = value.Trim(); - if (StringSpanHelpers.Equals(sTrim, numfmt.PositiveInfinitySymbol)) + if (sTrim.EqualsOrdinal(info.PositiveInfinitySymbol)) { return double.PositiveInfinity; } - if (StringSpanHelpers.Equals(sTrim, numfmt.NegativeInfinitySymbol)) + if (sTrim.EqualsOrdinal(info.NegativeInfinitySymbol)) { return double.NegativeInfinity; } - if (StringSpanHelpers.Equals(sTrim, numfmt.NaNSymbol)) + if (sTrim.EqualsOrdinal(info.NaNSymbol)) { return double.NaN; } - throw new FormatException(SR.Format_InvalidString); + ThrowOverflowOrFormatException(overflow: false, null); } if (!NumberBufferToDouble(ref number, ref d)) { - throw new OverflowException(SR.Overflow_Double); + ThrowOverflowOrFormatException(overflow: true, nameof(SR.Overflow_Double)); } return d; } - internal unsafe static float ParseSingle(ReadOnlySpan value, NumberStyles options, NumberFormatInfo numfmt) + internal static float ParseSingle(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { NumberBuffer number = default; double d = 0; - if (!TryStringToNumber(value, options, ref number, numfmt, false)) + if (!TryStringToNumber(value, styles, ref number, info, false)) { //If we failed TryStringToNumber, it may be from one of our special strings. //Check the three with which we're concerned and rethrow if it's not one of //those strings. ReadOnlySpan sTrim = value.Trim(); - if (StringSpanHelpers.Equals(sTrim, numfmt.PositiveInfinitySymbol)) + if (sTrim.EqualsOrdinal(info.PositiveInfinitySymbol)) { return float.PositiveInfinity; } - if (StringSpanHelpers.Equals(sTrim, numfmt.NegativeInfinitySymbol)) + if (sTrim.EqualsOrdinal(info.NegativeInfinitySymbol)) { return float.NegativeInfinity; } - if (StringSpanHelpers.Equals(sTrim, numfmt.NaNSymbol)) + if (sTrim.EqualsOrdinal(info.NaNSymbol)) { return float.NaN; } - throw new FormatException(SR.Format_InvalidString); + ThrowOverflowOrFormatException(overflow: false, null); } if (!NumberBufferToDouble(ref number, ref d)) { - throw new OverflowException(SR.Overflow_Single); + ThrowOverflowOrFormatException(overflow: true, nameof(SR.Overflow_Single)); } float castSingle = (float)d; if (float.IsInfinity(castSingle)) { - throw new OverflowException(SR.Overflow_Single); + ThrowOverflowOrFormatException(overflow: true, nameof(SR.Overflow_Single)); } return castSingle; } - internal unsafe static bool TryParseDecimal(ReadOnlySpan value, NumberStyles options, NumberFormatInfo numfmt, out decimal result) + internal static bool TryParseDecimal(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out decimal result) { NumberBuffer number = default; result = 0; - if (!TryStringToNumber(value, options, ref number, numfmt, true)) + if (!TryStringToNumber(value, styles, ref number, info, true)) { return false; } @@ -812,13 +1660,12 @@ namespace System return true; } - internal unsafe static bool TryParseDouble(ReadOnlySpan value, NumberStyles options, NumberFormatInfo numfmt, out double result) + internal static bool TryParseDouble(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out double result) { NumberBuffer number = default; result = 0; - - if (!TryStringToNumber(value, options, ref number, numfmt, false)) + if (!TryStringToNumber(value, styles, ref number, info, false)) { return false; } @@ -829,13 +1676,13 @@ namespace System return true; } - internal unsafe static bool TryParseSingle(ReadOnlySpan value, NumberStyles options, NumberFormatInfo numfmt, out float result) + internal static bool TryParseSingle(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out float result) { NumberBuffer number = default; result = 0; double d = 0; - if (!TryStringToNumber(value, options, ref number, numfmt, false)) + if (!TryStringToNumber(value, styles, ref number, info, false)) { return false; } @@ -853,28 +1700,28 @@ namespace System return true; } - private static unsafe void StringToNumber(ReadOnlySpan str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo info, bool parseDecimal) + private static unsafe void StringToNumber(ReadOnlySpan value, NumberStyles styles, ref NumberBuffer number, NumberFormatInfo info, bool parseDecimal) { Debug.Assert(info != null); - fixed (char* stringPointer = &MemoryMarshal.GetReference(str)) + fixed (char* stringPointer = &MemoryMarshal.GetReference(value)) { char* p = stringPointer; - if (!ParseNumber(ref p, options, ref number, info, parseDecimal) - || (p - stringPointer < str.Length && !TrailingZeros(str, (int)(p - stringPointer)))) + if (!ParseNumber(ref p, p + value.Length, styles, ref number, info, parseDecimal) + || (p - stringPointer < value.Length && !TrailingZeros(value, (int)(p - stringPointer)))) { - throw new FormatException(SR.Format_InvalidString); + ThrowOverflowOrFormatException(overflow: false, null); } } } - internal static unsafe bool TryStringToNumber(ReadOnlySpan str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo numfmt, bool parseDecimal) + internal static unsafe bool TryStringToNumber(ReadOnlySpan value, NumberStyles styles, ref NumberBuffer number, NumberFormatInfo info, bool parseDecimal) { - Debug.Assert(numfmt != null); - fixed (char* stringPointer = &MemoryMarshal.GetReference(str)) + Debug.Assert(info != null); + fixed (char* stringPointer = &MemoryMarshal.GetReference(value)) { char* p = stringPointer; - if (!ParseNumber(ref p, options, ref number, numfmt, parseDecimal) - || (p - stringPointer < str.Length && !TrailingZeros(str, (int)(p - stringPointer)))) + if (!ParseNumber(ref p, p + value.Length, styles, ref number, info, parseDecimal) + || (p - stringPointer < value.Length && !TrailingZeros(value, (int)(p - stringPointer)))) { return false; } @@ -883,12 +1730,12 @@ namespace System return true; } - private static bool TrailingZeros(ReadOnlySpan s, int index) + private static bool TrailingZeros(ReadOnlySpan value, int index) { // For compatibility, we need to allow trailing zeros at the end of a number string - for (int i = index; i < s.Length; i++) + for (int i = index; i < value.Length; i++) { - if (s[i] != '\0') + if (value[i] != '\0') { return false; } @@ -897,68 +1744,62 @@ namespace System return true; } - private unsafe static char* MatchChars(char* p, string str) + private static unsafe char* MatchChars(char* p, char* pEnd, string value) { - fixed (char* stringPointer = str) + Debug.Assert(p != null && pEnd != null && p <= pEnd && value != null); + fixed (char* stringPointer = value) { - return MatchChars(p, stringPointer); - } - } - - private unsafe static char* MatchChars(char* p, char* str) - { - Debug.Assert(p != null && str != null); - - if (*str == '\0') - { - return null; - } - - // We only hurt the failure case - // This fix is for French or Kazakh cultures. Since a user cannot type 0xA0 as a - // space character we use 0x20 space character instead to mean the same. - while (*p == *str || (*str == '\u00a0' && *p == '\u0020')) - { - p++; - str++; - if (*str == '\0') return p; + char* str = stringPointer; + if (*str != '\0') + { + // We only hurt the failure case + // This fix is for French or Kazakh cultures. Since a user cannot type 0xA0 as a + // space character we use 0x20 space character instead to mean the same. + while (true) + { + char cp = p < pEnd ? *p : '\0'; + if (cp != *str && !(*str == '\u00a0' && cp == '\u0020')) + { + break; + } + p++; + str++; + if (*str == '\0') return p; + } + } } return null; } - private static bool IsWhite(char ch) => ch == 0x20 || (ch >= 0x09 && ch <= 0x0D); + private static bool IsWhite(int ch) => ch == 0x20 || ((uint)(ch - 0x09) <= (0x0D - 0x09)); + + private static bool IsDigit(int ch) => ((uint)ch - '0') <= 9; + + private static void ThrowOverflowOrFormatException(bool overflow, string overflowResourceKey) + { + throw overflow ? + new OverflowException(SR.GetResourceString(overflowResourceKey)) : + (Exception)new FormatException(SR.Format_InvalidString); + } private static bool NumberBufferToDouble(ref NumberBuffer number, ref double value) { double d = NumberToDouble(ref number); - uint e = DoubleHelper.Exponent(d); - ulong m = DoubleHelper.Mantissa(d); - - if (e == 0x7FF) + if (!double.IsFinite(d)) { + value = default; return false; } - if (e == 0 && m == 0) + if (d == 0.0) { - d = 0; + // normalize -0.0 to 0.0 + d = 0.0; } value = d; return true; } - - private static class DoubleHelper - { - public static unsafe uint Exponent(double d) => - (*((uint*)&d + 1) >> 20) & 0x000007ff; - - public static unsafe ulong Mantissa(double d) => - *((ulong*)&d) & 0x000fffffffffffff; - - public static unsafe bool Sign(double d) => - (*((uint*)&d + 1) >> 31) != 0; - } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.cs b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.cs index ea32ed3803..3fb3086b2d 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.cs @@ -9,131 +9,131 @@ namespace System.Numerics internal class ConstantHelper { [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Byte GetByteWithAllBitsSet() + public static byte GetByteWithAllBitsSet() { - Byte value = 0; + byte value = 0; unsafe { unchecked { - *((Byte*)&value) = (Byte)0xff; + *((byte*)&value) = (byte)0xff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static SByte GetSByteWithAllBitsSet() + public static sbyte GetSByteWithAllBitsSet() { - SByte value = 0; + sbyte value = 0; unsafe { unchecked { - *((SByte*)&value) = (SByte)0xff; + *((sbyte*)&value) = (sbyte)0xff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static UInt16 GetUInt16WithAllBitsSet() + public static ushort GetUInt16WithAllBitsSet() { - UInt16 value = 0; + ushort value = 0; unsafe { unchecked { - *((UInt16*)&value) = (UInt16)0xffff; + *((ushort*)&value) = (ushort)0xffff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Int16 GetInt16WithAllBitsSet() + public static short GetInt16WithAllBitsSet() { - Int16 value = 0; + short value = 0; unsafe { unchecked { - *((Int16*)&value) = (Int16)0xffff; + *((short*)&value) = (short)0xffff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static UInt32 GetUInt32WithAllBitsSet() + public static uint GetUInt32WithAllBitsSet() { - UInt32 value = 0; + uint value = 0; unsafe { unchecked { - *((UInt32*)&value) = (UInt32)0xffffffff; + *((uint*)&value) = (uint)0xffffffff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Int32 GetInt32WithAllBitsSet() + public static int GetInt32WithAllBitsSet() { - Int32 value = 0; + int value = 0; unsafe { unchecked { - *((Int32*)&value) = (Int32)0xffffffff; + *((int*)&value) = (int)0xffffffff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static UInt64 GetUInt64WithAllBitsSet() + public static ulong GetUInt64WithAllBitsSet() { - UInt64 value = 0; + ulong value = 0; unsafe { unchecked { - *((UInt64*)&value) = (UInt64)0xffffffffffffffff; + *((ulong*)&value) = (ulong)0xffffffffffffffff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Int64 GetInt64WithAllBitsSet() + public static long GetInt64WithAllBitsSet() { - Int64 value = 0; + long value = 0; unsafe { unchecked { - *((Int64*)&value) = (Int64)0xffffffffffffffff; + *((long*)&value) = (long)0xffffffffffffffff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Single GetSingleWithAllBitsSet() + public static float GetSingleWithAllBitsSet() { - Single value = 0; + float value = 0; unsafe { unchecked { - *((Int32*)&value) = (Int32)0xffffffff; + *((int*)&value) = (int)0xffffffff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Double GetDoubleWithAllBitsSet() + public static double GetDoubleWithAllBitsSet() { - Double value = 0; + double value = 0; unsafe { unchecked { - *((Int64*)&value) = (Int64)0xffffffffffffffff; + *((long*)&value) = (long)0xffffffffffffffff; } } return value; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.tt b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.tt index 4b1c677574..dd823abc0a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.tt +++ b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.tt @@ -20,19 +20,20 @@ namespace System.Numerics { internal class ConstantHelper { -<# foreach (var type in supportedTypes) +<# + foreach (var type in supportedTypes) { string hexValue = "0x" + new string('f', Marshal.SizeOf(type) * 2); #> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static <#= type.Name #> Get<#= type.Name #>WithAllBitsSet() + public static <#= typeAliases[type] #> Get<#= type.Name #>WithAllBitsSet() { - <#= type.Name #> value = 0; + <#= typeAliases[type] #> value = 0; unsafe { unchecked { - *((<#= GetIntegralEquivalent(type).Name #>*)&value) = (<#=GetIntegralEquivalent(type).Name#>)<#= hexValue #>; + *((<#= typeAliases[GetIntegralEquivalent(type)] #>*)&value) = (<#= typeAliases[GetIntegralEquivalent(type)] #>)<#= hexValue #>; } } return value; @@ -44,17 +45,17 @@ namespace System.Numerics }<#+ public Type GetIntegralEquivalent(Type type) { - if (type == typeof(Single)) + if (type == typeof(float)) { - return typeof(Int32); + return typeof(int); } else if (type == typeof(double)) { - return typeof(Int64); + return typeof(long); } else { return type; } } -#> \ No newline at end of file +#> diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/GenerationConfig.ttinclude b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/GenerationConfig.ttinclude index cdd9c95213..a4466e1a86 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/GenerationConfig.ttinclude +++ b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/GenerationConfig.ttinclude @@ -1,5 +1,6 @@ <#@ import namespace="System.Linq" #> <#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.Text" #> <#+ /* This file includes static data used as compilation configuration for the rest of the code generation. It is shared here to ensure that all generated code compiles with the same constants and configurations. */ @@ -7,27 +8,40 @@ // The set of supported numeric types to compile public static Type[] supportedTypes = new[] { - typeof(Byte), typeof(SByte), typeof(UInt16), typeof(Int16), - typeof(UInt32), typeof(Int32), typeof(UInt64), typeof(Int64), - typeof(Single), typeof(Double) + typeof(byte), typeof(sbyte), typeof(ushort), typeof(short), + typeof(uint), typeof(int), typeof(ulong), typeof(long), + typeof(float), typeof(double) }; // The set of unsigned types, a subset of the above. Used for excluding from certain methods, i.e. Abs and Negate public static Type[] unsignedTypes = new[] { - typeof(Byte), typeof(UInt16), typeof(UInt32), typeof(UInt64) + typeof(byte), typeof(ushort), typeof(uint), typeof(ulong) }; public static Type[] integralTypes = new[] { - typeof(Byte), typeof(SByte), typeof(UInt16), typeof(Int16), - typeof(UInt32), typeof(Int32), typeof(UInt64), typeof(Int64) + typeof(byte), typeof(sbyte), typeof(ushort), typeof(short), + typeof(uint), typeof(int), typeof(ulong), typeof(long) }; public static Type[] nonClsCompliantTypes = new[] { - typeof(SByte), typeof(UInt16), - typeof(UInt32), typeof(UInt64) + typeof(sbyte), typeof(ushort), typeof(uint), typeof(ulong) + }; + + public static Dictionary typeAliases = new Dictionary() + { + { typeof(byte), "byte" }, + { typeof(sbyte), "sbyte" }, + { typeof(ushort), "ushort" }, + { typeof(short), "short" }, + { typeof(uint), "uint" }, + { typeof(int), "int" }, + { typeof(ulong), "ulong" }, + { typeof(long), "long" }, + { typeof(float), "float" }, + { typeof(double), "double" } }; // The total register size, in bytes. 16 for SSE2, 32 for AVX, 64 for AVX512 @@ -136,12 +150,37 @@ public string GenerateIfStatementHeader(Type type) { string keyword = (type == supportedTypes[0]) ? "if" : "else if"; - return string.Format("{0} (typeof(T) == typeof({1}))", keyword, type.Name); + return string.Format("{0} (typeof(T) == typeof({1}))", keyword, typeAliases[type]); } public string GenerateIfStatementHeader(Type type, IEnumerable allTypes) { string keyword = (type == allTypes.ToArray()[0]) ? "if" : "else if"; - return string.Format("{0} (typeof(T) == typeof({1}))", keyword, type.Name); + return string.Format("{0} (typeof(T) == typeof({1}))", keyword, typeAliases[type]); } -#> \ No newline at end of file + + public string MakeTypeComparisonCondition(Type type) + { + return string.Format("(typeof(T) == typeof({0}))", typeAliases[type]); + } + + public string GenerateIfConditionAllTypes(IEnumerable allTypes) + { + StringBuilder sbuilder = new StringBuilder(); + bool firstTime = true; + foreach (var type in allTypes) + { + if (firstTime) + { + sbuilder.Append("if (").Append(MakeTypeComparisonCondition(type)); + firstTime = false; + } + else + { + sbuilder.AppendLine().Append(" || ").Append(MakeTypeComparisonCondition(type)); + } + } + sbuilder.Append(")"); + return sbuilder.ToString(); + } +#> diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Register.cs b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Register.cs index a27e922b9d..8efa85b199 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Register.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Register.cs @@ -17,155 +17,155 @@ namespace System.Numerics #region Internal Storage Fields // Internal System.Byte Fields [FieldOffset(0)] - internal Byte byte_0; + internal byte byte_0; [FieldOffset(1)] - internal Byte byte_1; + internal byte byte_1; [FieldOffset(2)] - internal Byte byte_2; + internal byte byte_2; [FieldOffset(3)] - internal Byte byte_3; + internal byte byte_3; [FieldOffset(4)] - internal Byte byte_4; + internal byte byte_4; [FieldOffset(5)] - internal Byte byte_5; + internal byte byte_5; [FieldOffset(6)] - internal Byte byte_6; + internal byte byte_6; [FieldOffset(7)] - internal Byte byte_7; + internal byte byte_7; [FieldOffset(8)] - internal Byte byte_8; + internal byte byte_8; [FieldOffset(9)] - internal Byte byte_9; + internal byte byte_9; [FieldOffset(10)] - internal Byte byte_10; + internal byte byte_10; [FieldOffset(11)] - internal Byte byte_11; + internal byte byte_11; [FieldOffset(12)] - internal Byte byte_12; + internal byte byte_12; [FieldOffset(13)] - internal Byte byte_13; + internal byte byte_13; [FieldOffset(14)] - internal Byte byte_14; + internal byte byte_14; [FieldOffset(15)] - internal Byte byte_15; + internal byte byte_15; // Internal System.SByte Fields [FieldOffset(0)] - internal SByte sbyte_0; + internal sbyte sbyte_0; [FieldOffset(1)] - internal SByte sbyte_1; + internal sbyte sbyte_1; [FieldOffset(2)] - internal SByte sbyte_2; + internal sbyte sbyte_2; [FieldOffset(3)] - internal SByte sbyte_3; + internal sbyte sbyte_3; [FieldOffset(4)] - internal SByte sbyte_4; + internal sbyte sbyte_4; [FieldOffset(5)] - internal SByte sbyte_5; + internal sbyte sbyte_5; [FieldOffset(6)] - internal SByte sbyte_6; + internal sbyte sbyte_6; [FieldOffset(7)] - internal SByte sbyte_7; + internal sbyte sbyte_7; [FieldOffset(8)] - internal SByte sbyte_8; + internal sbyte sbyte_8; [FieldOffset(9)] - internal SByte sbyte_9; + internal sbyte sbyte_9; [FieldOffset(10)] - internal SByte sbyte_10; + internal sbyte sbyte_10; [FieldOffset(11)] - internal SByte sbyte_11; + internal sbyte sbyte_11; [FieldOffset(12)] - internal SByte sbyte_12; + internal sbyte sbyte_12; [FieldOffset(13)] - internal SByte sbyte_13; + internal sbyte sbyte_13; [FieldOffset(14)] - internal SByte sbyte_14; + internal sbyte sbyte_14; [FieldOffset(15)] - internal SByte sbyte_15; + internal sbyte sbyte_15; // Internal System.UInt16 Fields [FieldOffset(0)] - internal UInt16 uint16_0; + internal ushort uint16_0; [FieldOffset(2)] - internal UInt16 uint16_1; + internal ushort uint16_1; [FieldOffset(4)] - internal UInt16 uint16_2; + internal ushort uint16_2; [FieldOffset(6)] - internal UInt16 uint16_3; + internal ushort uint16_3; [FieldOffset(8)] - internal UInt16 uint16_4; + internal ushort uint16_4; [FieldOffset(10)] - internal UInt16 uint16_5; + internal ushort uint16_5; [FieldOffset(12)] - internal UInt16 uint16_6; + internal ushort uint16_6; [FieldOffset(14)] - internal UInt16 uint16_7; + internal ushort uint16_7; // Internal System.Int16 Fields [FieldOffset(0)] - internal Int16 int16_0; + internal short int16_0; [FieldOffset(2)] - internal Int16 int16_1; + internal short int16_1; [FieldOffset(4)] - internal Int16 int16_2; + internal short int16_2; [FieldOffset(6)] - internal Int16 int16_3; + internal short int16_3; [FieldOffset(8)] - internal Int16 int16_4; + internal short int16_4; [FieldOffset(10)] - internal Int16 int16_5; + internal short int16_5; [FieldOffset(12)] - internal Int16 int16_6; + internal short int16_6; [FieldOffset(14)] - internal Int16 int16_7; + internal short int16_7; // Internal System.UInt32 Fields [FieldOffset(0)] - internal UInt32 uint32_0; + internal uint uint32_0; [FieldOffset(4)] - internal UInt32 uint32_1; + internal uint uint32_1; [FieldOffset(8)] - internal UInt32 uint32_2; + internal uint uint32_2; [FieldOffset(12)] - internal UInt32 uint32_3; + internal uint uint32_3; // Internal System.Int32 Fields [FieldOffset(0)] - internal Int32 int32_0; + internal int int32_0; [FieldOffset(4)] - internal Int32 int32_1; + internal int int32_1; [FieldOffset(8)] - internal Int32 int32_2; + internal int int32_2; [FieldOffset(12)] - internal Int32 int32_3; + internal int int32_3; // Internal System.UInt64 Fields [FieldOffset(0)] - internal UInt64 uint64_0; + internal ulong uint64_0; [FieldOffset(8)] - internal UInt64 uint64_1; + internal ulong uint64_1; // Internal System.Int64 Fields [FieldOffset(0)] - internal Int64 int64_0; + internal long int64_0; [FieldOffset(8)] - internal Int64 int64_1; + internal long int64_1; // Internal System.Single Fields [FieldOffset(0)] - internal Single single_0; + internal float single_0; [FieldOffset(4)] - internal Single single_1; + internal float single_1; [FieldOffset(8)] - internal Single single_2; + internal float single_2; [FieldOffset(12)] - internal Single single_3; + internal float single_3; // Internal System.Double Fields [FieldOffset(0)] - internal Double double_0; + internal double double_0; [FieldOffset(8)] - internal Double double_1; + internal double double_1; #endregion Internal Storage Fields } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Register.tt b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Register.tt index a9de3b9748..676b89f547 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Register.tt +++ b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Register.tt @@ -34,7 +34,7 @@ namespace System.Numerics { #> [FieldOffset(<#=Marshal.SizeOf(type) * g#>)] - internal <#=type.Name#> <#= type.Name.ToLowerInvariant() + "_" + g #>; + internal <#= typeAliases[type] #> <#= type.Name.ToLowerInvariant() + "_" + g #>; <# } #> diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Vector.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Vector.cs.REMOVED.git-id index 130808fa2a..426aa09160 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Vector.cs.REMOVED.git-id +++ b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Vector.cs.REMOVED.git-id @@ -1 +1 @@ -5fd286732ee606b078187d0f1e85b14cb7d677fa \ No newline at end of file +31a9114e33f7da3286a94872082a740ddfb77287 \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Vector.tt b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Vector.tt index 275f47350d..9eda34d046 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Vector.tt +++ b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Vector.tt @@ -7,9 +7,13 @@ <#@ import namespace="System.Runtime.InteropServices" #> <#@ include file="GenerationConfig.ttinclude" #><# GenerateCopyrightHeader(); #> +#if netcoreapp +using Internal.Runtime.CompilerServices; +#endif using System.Globalization; using System.Numerics.Hashing; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using System.Text; namespace System.Numerics @@ -17,8 +21,8 @@ namespace System.Numerics /* Note: The following patterns are used throughout the code here and are described here * * PATTERN: - * if (typeof(T) == typeof(Int32)) { ... } - * else if (typeof(T) == typeof(Single)) { ... } + * if (typeof(T) == typeof(int)) { ... } + * else if (typeof(T) == typeof(float)) { ... } * EXPLANATION: * At runtime, each instantiation of Vector will be type-specific, and each of these typeof blocks will be eliminated, * as typeof(T) is a (JIT) compile-time constant for each instantiation. This design was chosen to eliminate any overhead from @@ -101,7 +105,7 @@ namespace System.Numerics internal byte _byte; } - // Calculates the size of this struct in bytes, by computing the offset of a field in a structure + // Calculates the size of this struct in bytes, by computing the offset of a field in a structure private static unsafe int InitializeCount() { VectorSizeHelper vsh; @@ -110,15 +114,16 @@ namespace System.Numerics int vectorSizeInBytes = (int)(byteBase - vectorBase); int typeSizeInBytes = -1; -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - typeSizeInBytes = sizeof(<#=type.Name#>); + typeSizeInBytes = sizeof(<#=typeAliases[type]#>); } <# - } + } #> else { @@ -139,41 +144,43 @@ namespace System.Numerics { if (Vector.IsHardwareAccelerated) { -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { - fixed (<#=type.Name#>* basePtr = &this.<#=GetRegisterFieldName(type, 0)#>) + fixed (<#=typeAliases[type]#>* basePtr = &this.<#=GetRegisterFieldName(type, 0)#>) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (<#=type.Name#>)(object)value; + *(basePtr + g) = (<#=typeAliases[type]#>)(object)value; } } } <# - } + } #> } else { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { <# - for (int g = 0; g < totalSize / Marshal.SizeOf(type); g++) - { + for (int g = 0; g < totalSize / Marshal.SizeOf(type); g++) + { #> - <#=GetRegisterFieldName(type, g)#> = (<#=type.Name#>)(object)value; + <#=GetRegisterFieldName(type, g)#> = (<#=typeAliases[type]#>)(object)value; <# - } + } #> } <# - } + } #> } } @@ -198,49 +205,51 @@ namespace System.Numerics } if (index < 0 || (values.Length - index) < Count) { - throw new IndexOutOfRangeException(); + throw new IndexOutOfRangeException(SR.Format(SR.Arg_InsufficientNumberOfElements, Vector.Count, nameof(values))); } if (Vector.IsHardwareAccelerated) { -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { - fixed (<#=type.Name#>* basePtr = &this.<#=GetRegisterFieldName(type, 0)#>) + fixed (<#=typeAliases[type]#>* basePtr = &this.<#=GetRegisterFieldName(type, 0)#>) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (<#=type.Name#>)(object)values[g + index]; + *(basePtr + g) = (<#=typeAliases[type]#>)(object)values[g + index]; } } } <# - } + } #> } else { -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { - fixed (<#=type.Name#>* basePtr = &this.<#=GetRegisterFieldName(type, 0)#>) + fixed (<#=typeAliases[type]#>* basePtr = &this.<#=GetRegisterFieldName(type, 0)#>) { <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> - *(basePtr + <#=g#>) = (<#=type.Name#>)(object)values[<#=g#> + index]; + *(basePtr + <#=g#>) = (<#=typeAliases[type]#>)(object)values[<#=g#> + index]; <# - } + } #> } } <# - } + } #> } } @@ -254,14 +263,15 @@ namespace System.Numerics internal unsafe Vector(void* dataPointer, int offset) : this() { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#>* castedPtr = (<#=type.Name#>*)dataPointer; + <#=typeAliases[type]#>* castedPtr = (<#=typeAliases[type]#>*)dataPointer; castedPtr += offset; - fixed (<#=type.Name#>* registerBase = &this.<#=GetRegisterFieldName(type, 0)#>) + fixed (<#=typeAliases[type]#>* registerBase = &this.<#=GetRegisterFieldName(type, 0)#>) { for (int g = 0; g < Count; g++) { @@ -270,7 +280,7 @@ namespace System.Numerics } } <# - } + } #> else { @@ -283,6 +293,28 @@ namespace System.Numerics { this.register = existingRegister; } + +#if netcoreapp + /// + /// Constructs a vector from the given span. The span must contain at least Vector'T.Count elements. + /// + public Vector(Span values) + : this() + { + <#=GenerateIfConditionAllTypes(supportedTypes)#> + { + if (values.Length < Count) + { + throw new IndexOutOfRangeException(SR.Format(SR.Arg_InsufficientNumberOfElements, Vector.Count, nameof(values))); + } + this = Unsafe.ReadUnaligned>(ref Unsafe.As(ref MemoryMarshal.GetReference(values))); + } + else + { + throw new NotSupportedException(SR.Arg_TypeNotSupported); + } + } +#endif #endregion Constructors #region Public Instance Methods @@ -325,46 +357,48 @@ namespace System.Numerics if (Vector.IsHardwareAccelerated) { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#>[] <#=type.Name.ToLowerInvariant()#>Array = (<#=type.Name#>[])(object)destination; - fixed (<#=type.Name#>* destinationBase = <#=type.Name.ToLowerInvariant()#>Array) + <#=typeAliases[type]#>[] <#=type.Name.ToLowerInvariant()#>Array = (<#=typeAliases[type]#>[])(object)destination; + fixed (<#=typeAliases[type]#>* destinationBase = <#=type.Name.ToLowerInvariant()#>Array) { for (int g = 0; g < Count; g++) { - destinationBase[startIndex + g] = (<#=type.Name#>)(object)this[g]; + destinationBase[startIndex + g] = (<#=typeAliases[type]#>)(object)this[g]; } } } <# - } + } #> } else { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#>[] <#=type.Name.ToLowerInvariant()#>Array = (<#=type.Name#>[])(object)destination; - fixed (<#=type.Name#>* destinationBase = <#=type.Name.ToLowerInvariant()#>Array) + <#=typeAliases[type]#>[] <#=type.Name.ToLowerInvariant()#>Array = (<#=typeAliases[type]#>[])(object)destination; + fixed (<#=typeAliases[type]#>* destinationBase = <#=type.Name.ToLowerInvariant()#>Array) { <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> destinationBase[startIndex + <#=g#>] = this.<#=GetRegisterFieldName(type, g)#>; <# - } + } #> } } <# - } + } #> } } @@ -381,12 +415,13 @@ namespace System.Numerics { throw new IndexOutOfRangeException(SR.Format(SR.Arg_ArgumentOutOfRangeException, index)); } -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { - fixed (<#=type.Name#>* basePtr = &this.<#=GetRegisterFieldName(type, 0)#>) + fixed (<#=typeAliases[type]#>* basePtr = &this.<#=GetRegisterFieldName(type, 0)#>) { return (T)(object)*(basePtr + index); } @@ -437,36 +472,37 @@ namespace System.Numerics } else { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { return <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> <# - if (g == 0) - { + if (g == 0) + { #> this.<#=GetRegisterFieldName(type, g)#> == other.<#=GetRegisterFieldName(type, g)#> <# - } - else - { + } + else + { #> && this.<#=GetRegisterFieldName(type, g)#> == other.<#=GetRegisterFieldName(type, g)#><#=(g == (GetNumFields(type, totalSize) -1)) ? ";" : ""#> -<# - } -#> <# } #> - } <# } +#> + } +<# + } #> else { @@ -485,19 +521,20 @@ namespace System.Numerics if (Vector.IsHardwareAccelerated) { -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { for (int g = 0; g < Count; g++) { - hash = HashHelpers.Combine(hash, ((<#=type.Name#>)(object)this[g]).GetHashCode()); + hash = HashHelpers.Combine(hash, ((<#=typeAliases[type]#>)(object)this[g]).GetHashCode()); } return hash; } <# - } + } #> else { @@ -506,23 +543,24 @@ namespace System.Numerics } else { -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> hash = HashHelpers.Combine(hash, this.<#=GetRegisterFieldName(type, g)#>.GetHashCode()); <# - } + } #> return hash; } <# - } + } #> else { @@ -588,20 +626,21 @@ namespace System.Numerics { if (Vector.IsHardwareAccelerated) { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#>* dataPtr = stackalloc <#=type.Name#>[Count]; + <#=typeAliases[type]#>* dataPtr = stackalloc <#=typeAliases[type]#>[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (<#=type.Name#>)(object)ScalarAdd(left[g], right[g]); + dataPtr[g] = (<#=typeAliases[type]#>)(object)ScalarAdd(left[g], right[g]); } return new Vector(dataPtr); } <# - } + } #> else { @@ -611,8 +650,9 @@ namespace System.Numerics else { Vector sum = new Vector(); -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { @@ -620,13 +660,13 @@ namespace System.Numerics for (int g = 0; g < GetNumFields(type, totalSize); g++) { #> - sum.<#= GetRegisterFieldName(type, g) #> = (<#=type.Name#>)(left.<#= GetRegisterFieldName(type, g) #> + right.<#= GetRegisterFieldName(type, g) #>); + sum.<#= GetRegisterFieldName(type, g) #> = (<#=typeAliases[type]#>)(left.<#= GetRegisterFieldName(type, g) #> + right.<#= GetRegisterFieldName(type, g) #>); <# } #> } <# - } + } #> return sum; } @@ -645,20 +685,21 @@ namespace System.Numerics { if (Vector.IsHardwareAccelerated) { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#>* dataPtr = stackalloc <#=type.Name#>[Count]; + <#=typeAliases[type]#>* dataPtr = stackalloc <#=typeAliases[type]#>[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (<#=type.Name#>)(object)ScalarSubtract(left[g], right[g]); + dataPtr[g] = (<#=typeAliases[type]#>)(object)ScalarSubtract(left[g], right[g]); } return new Vector(dataPtr); } <# - } + } #> else { @@ -668,22 +709,23 @@ namespace System.Numerics else { Vector difference = new Vector(); -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> - difference.<#= GetRegisterFieldName(type, g) #> = (<#=type.Name#>)(left.<#= GetRegisterFieldName(type, g) #> - right.<#= GetRegisterFieldName(type, g) #>); + difference.<#= GetRegisterFieldName(type, g) #> = (<#=typeAliases[type]#>)(left.<#= GetRegisterFieldName(type, g) #> - right.<#= GetRegisterFieldName(type, g) #>); <# - } + } #> } <# - } + } #> return difference; } @@ -703,20 +745,21 @@ namespace System.Numerics { if (Vector.IsHardwareAccelerated) { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#>* dataPtr = stackalloc <#=type.Name#>[Count]; + <#=typeAliases[type]#>* dataPtr = stackalloc <#=typeAliases[type]#>[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (<#=type.Name#>)(object)ScalarMultiply(left[g], right[g]); + dataPtr[g] = (<#=typeAliases[type]#>)(object)ScalarMultiply(left[g], right[g]); } return new Vector(dataPtr); } <# - } + } #> else { @@ -726,18 +769,19 @@ namespace System.Numerics else { Vector product = new Vector(); -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> - product.<#= GetRegisterFieldName(type, g) #> = (<#=type.Name#>)(left.<#= GetRegisterFieldName(type, g) #> * right.<#= GetRegisterFieldName(type, g) #>); + product.<#= GetRegisterFieldName(type, g) #> = (<#=typeAliases[type]#>)(left.<#= GetRegisterFieldName(type, g) #> * right.<#= GetRegisterFieldName(type, g) #>); <# - } + } #> } <# @@ -766,18 +810,19 @@ namespace System.Numerics else { Vector product = new Vector(); -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> - product.<#= GetRegisterFieldName(type, g) #> = (<#=type.Name#>)(value.<#= GetRegisterFieldName(type, g) #> * (<#=type.Name#>)(object)factor); + product.<#= GetRegisterFieldName(type, g) #> = (<#=typeAliases[type]#>)(value.<#= GetRegisterFieldName(type, g) #> * (<#=typeAliases[type]#>)(object)factor); <# - } + } #> } <# @@ -806,18 +851,19 @@ namespace System.Numerics else { Vector product = new Vector(); -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> - product.<#= GetRegisterFieldName(type, g) #> = (<#=type.Name#>)(value.<#= GetRegisterFieldName(type, g) #> * (<#=type.Name#>)(object)factor); + product.<#= GetRegisterFieldName(type, g) #> = (<#=typeAliases[type]#>)(value.<#= GetRegisterFieldName(type, g) #> * (<#=typeAliases[type]#>)(object)factor); <# - } + } #> } <# @@ -841,20 +887,21 @@ namespace System.Numerics { if (Vector.IsHardwareAccelerated) { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#>* dataPtr = stackalloc <#=type.Name#>[Count]; + <#=typeAliases[type]#>* dataPtr = stackalloc <#=typeAliases[type]#>[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (<#=type.Name#>)(object)ScalarDivide(left[g], right[g]); + dataPtr[g] = (<#=typeAliases[type]#>)(object)ScalarDivide(left[g], right[g]); } return new Vector(dataPtr); } <# - } + } #> else { @@ -864,18 +911,19 @@ namespace System.Numerics else { Vector quotient = new Vector(); -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> - quotient.<#= GetRegisterFieldName(type, g) #> = (<#=type.Name#>)(left.<#= GetRegisterFieldName(type, g) #> / right.<#= GetRegisterFieldName(type, g) #>); + quotient.<#= GetRegisterFieldName(type, g) #> = (<#=typeAliases[type]#>)(left.<#= GetRegisterFieldName(type, g) #> / right.<#= GetRegisterFieldName(type, g) #>); <# - } + } #> } <# @@ -912,18 +960,18 @@ namespace System.Numerics { if (Vector.IsHardwareAccelerated) { - Int64* resultBase = &result.register.int64_0; - Int64* leftBase = &left.register.int64_0; - Int64* rightBase = &right.register.int64_0; - for (int g = 0; g < Vector.Count; g++) + long* resultBase = &result.register.int64_0; + long* leftBase = &left.register.int64_0; + long* rightBase = &right.register.int64_0; + for (int g = 0; g < Vector.Count; g++) { resultBase[g] = leftBase[g] & rightBase[g]; } } else { - result.<#=GetRegisterFieldName(typeof(Int64), 0)#> = left.<#=GetRegisterFieldName(typeof(Int64), 0)#> & right.<#=GetRegisterFieldName(typeof(Int64), 0)#>; - result.<#=GetRegisterFieldName(typeof(Int64), 1)#> = left.<#=GetRegisterFieldName(typeof(Int64), 1)#> & right.<#=GetRegisterFieldName(typeof(Int64), 1)#>; + result.<#=GetRegisterFieldName(typeof(long), 0)#> = left.<#=GetRegisterFieldName(typeof(long), 0)#> & right.<#=GetRegisterFieldName(typeof(long), 0)#>; + result.<#=GetRegisterFieldName(typeof(long), 1)#> = left.<#=GetRegisterFieldName(typeof(long), 1)#> & right.<#=GetRegisterFieldName(typeof(long), 1)#>; } } return result; @@ -943,18 +991,18 @@ namespace System.Numerics { if (Vector.IsHardwareAccelerated) { - Int64* resultBase = &result.register.int64_0; - Int64* leftBase = &left.register.int64_0; - Int64* rightBase = &right.register.int64_0; - for (int g = 0; g < Vector.Count; g++) + long* resultBase = &result.register.int64_0; + long* leftBase = &left.register.int64_0; + long* rightBase = &right.register.int64_0; + for (int g = 0; g < Vector.Count; g++) { resultBase[g] = leftBase[g] | rightBase[g]; } } else { - result.<#=GetRegisterFieldName(typeof(Int64), 0)#> = left.<#=GetRegisterFieldName(typeof(Int64), 0)#> | right.<#=GetRegisterFieldName(typeof(Int64), 0)#>; - result.<#=GetRegisterFieldName(typeof(Int64), 1)#> = left.<#=GetRegisterFieldName(typeof(Int64), 1)#> | right.<#=GetRegisterFieldName(typeof(Int64), 1)#>; + result.<#=GetRegisterFieldName(typeof(long), 0)#> = left.<#=GetRegisterFieldName(typeof(long), 0)#> | right.<#=GetRegisterFieldName(typeof(long), 0)#>; + result.<#=GetRegisterFieldName(typeof(long), 1)#> = left.<#=GetRegisterFieldName(typeof(long), 1)#> | right.<#=GetRegisterFieldName(typeof(long), 1)#>; } } return result; @@ -974,18 +1022,18 @@ namespace System.Numerics { if (Vector.IsHardwareAccelerated) { - Int64* resultBase = &result.register.int64_0; - Int64* leftBase = &left.register.int64_0; - Int64* rightBase = &right.register.int64_0; - for (int g = 0; g < Vector.Count; g++) + long* resultBase = &result.register.int64_0; + long* leftBase = &left.register.int64_0; + long* rightBase = &right.register.int64_0; + for (int g = 0; g < Vector.Count; g++) { resultBase[g] = leftBase[g] ^ rightBase[g]; } } else { - result.<#=GetRegisterFieldName(typeof(Int64), 0)#> = left.<#=GetRegisterFieldName(typeof(Int64), 0)#> ^ right.<#=GetRegisterFieldName(typeof(Int64), 0)#>; - result.<#=GetRegisterFieldName(typeof(Int64), 1)#> = left.<#=GetRegisterFieldName(typeof(Int64), 1)#> ^ right.<#=GetRegisterFieldName(typeof(Int64), 1)#>; + result.<#=GetRegisterFieldName(typeof(long), 0)#> = left.<#=GetRegisterFieldName(typeof(long), 0)#> ^ right.<#=GetRegisterFieldName(typeof(long), 0)#>; + result.<#=GetRegisterFieldName(typeof(long), 1)#> = left.<#=GetRegisterFieldName(typeof(long), 1)#> ^ right.<#=GetRegisterFieldName(typeof(long), 1)#>; } } return result; @@ -1030,7 +1078,8 @@ namespace System.Numerics #endregion Logical Operators #region Conversions -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> /// @@ -1047,9 +1096,9 @@ namespace System.Numerics } #> [Intrinsic] - public static explicit operator Vector<<#=type.Name#>>(Vector value) + public static explicit operator Vector<<#=typeAliases[type]#>>(Vector value) { - return new Vector<<#=type.Name#>>(ref value.register); + return new Vector<<#=typeAliases[type]#>>(ref value.register); } <# @@ -1064,15 +1113,16 @@ namespace System.Numerics { if (Vector.IsHardwareAccelerated) { -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#>* dataPtr = stackalloc <#=type.Name#>[Count]; + <#=typeAliases[type]#>* dataPtr = stackalloc <#=typeAliases[type]#>[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.Get<#=type.Name#>WithAllBitsSet() : (<#=type.Name#>)0; + dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.Get<#=type.Name#>WithAllBitsSet() : (<#=typeAliases[type]#>)0; } return new Vector(dataPtr); } @@ -1087,23 +1137,24 @@ namespace System.Numerics else { Register register = new Register(); -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> - <#= GetRegisterFieldName(type, g) #> = left.<#= GetRegisterFieldName(type, g) #> == right.<#= GetRegisterFieldName(type, g) #> ? ConstantHelper.Get<#=type.Name#>WithAllBitsSet() : (<#=type.Name#>)0; + <#= GetRegisterFieldName(type, g) #> = left.<#= GetRegisterFieldName(type, g) #> == right.<#= GetRegisterFieldName(type, g) #> ? ConstantHelper.Get<#=type.Name#>WithAllBitsSet() : (<#=typeAliases[type]#>)0; <# - } + } #> return new Vector(ref register); } <# - } + } #> else { @@ -1118,15 +1169,16 @@ namespace System.Numerics { if (Vector.IsHardwareAccelerated) { -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#>* dataPtr = stackalloc <#=type.Name#>[Count]; + <#=typeAliases[type]#>* dataPtr = stackalloc <#=typeAliases[type]#>[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.Get<#=type.Name#>WithAllBitsSet() : (<#=type.Name#>)0; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.Get<#=type.Name#>WithAllBitsSet() : (<#=typeAliases[type]#>)0; } return new Vector(dataPtr); } @@ -1141,8 +1193,9 @@ namespace System.Numerics else { Register register = new Register(); -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { @@ -1150,14 +1203,14 @@ namespace System.Numerics for (int g = 0; g < GetNumFields(type, totalSize); g++) { #> - <#= GetRegisterFieldName(type, g) #> = left.<#= GetRegisterFieldName(type, g) #> < right.<#= GetRegisterFieldName(type, g) #> ? ConstantHelper.Get<#=type.Name#>WithAllBitsSet() : (<#=type.Name#>)0; + <#= GetRegisterFieldName(type, g) #> = left.<#= GetRegisterFieldName(type, g) #> < right.<#= GetRegisterFieldName(type, g) #> ? ConstantHelper.Get<#=type.Name#>WithAllBitsSet() : (<#=typeAliases[type]#>)0; <# } #> return new Vector(ref register); } <# - } + } #> else { @@ -1172,15 +1225,16 @@ namespace System.Numerics { if (Vector.IsHardwareAccelerated) { -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#>* dataPtr = stackalloc <#=type.Name#>[Count]; + <#=typeAliases[type]#>* dataPtr = stackalloc <#=typeAliases[type]#>[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.Get<#=type.Name#>WithAllBitsSet() : (<#=type.Name#>)0; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.Get<#=type.Name#>WithAllBitsSet() : (<#=typeAliases[type]#>)0; } return new Vector(dataPtr); } @@ -1195,23 +1249,24 @@ namespace System.Numerics else { Register register = new Register(); -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> - <#= GetRegisterFieldName(type, g) #> = left.<#= GetRegisterFieldName(type, g) #> > right.<#= GetRegisterFieldName(type, g) #> ? ConstantHelper.Get<#=type.Name#>WithAllBitsSet() : (<#=type.Name#>)0; + <#= GetRegisterFieldName(type, g) #> = left.<#= GetRegisterFieldName(type, g) #> > right.<#= GetRegisterFieldName(type, g) #> ? ConstantHelper.Get<#=type.Name#>WithAllBitsSet() : (<#=typeAliases[type]#>)0; <# - } + } #> return new Vector(ref register); } <# - } + } #> else { @@ -1265,10 +1320,10 @@ namespace System.Numerics #> <#=GenerateIfStatementHeader(type, supportedTypes.Except(unsignedTypes))#> { - <#=type.Name#>* dataPtr = stackalloc <#=type.Name#>[Count]; + <#=typeAliases[type]#>* dataPtr = stackalloc <#=typeAliases[type]#>[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (<#=type.Name#>)(object)(Math.Abs((<#=type.Name#>)(object)value[g])); + dataPtr[g] = (<#=typeAliases[type]#>)(object)(Math.Abs((<#=typeAliases[type]#>)(object)value[g])); } return new Vector(dataPtr); } @@ -1292,7 +1347,7 @@ namespace System.Numerics for (int g = 0; g < GetNumFields(type, totalSize); g++) { #> - value.<#=GetRegisterFieldName(type, g)#> = (<#=type.Name#>)(Math.Abs(value.<#=GetRegisterFieldName(type, g)#>)); + value.<#=GetRegisterFieldName(type, g)#> = (<#=typeAliases[type]#>)(Math.Abs(value.<#=GetRegisterFieldName(type, g)#>)); <# } #> @@ -1313,15 +1368,16 @@ namespace System.Numerics { if (Vector.IsHardwareAccelerated) { -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#>* dataPtr = stackalloc <#=type.Name#>[Count]; + <#=typeAliases[type]#>* dataPtr = stackalloc <#=typeAliases[type]#>[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (<#=type.Name#>)(object)left[g] : (<#=type.Name#>)(object)right[g]; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (<#=typeAliases[type]#>)(object)left[g] : (<#=typeAliases[type]#>)(object)right[g]; } return new Vector(dataPtr); } @@ -1336,23 +1392,24 @@ namespace System.Numerics else { Vector vec = new Vector(); -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> vec.<#=GetRegisterFieldName(type, g)#> = left.<#=GetRegisterFieldName(type, g)#> < right.<#=GetRegisterFieldName(type, g)#> ? left.<#=GetRegisterFieldName(type, g)#> : right.<#=GetRegisterFieldName(type, g)#>; <# - } + } #> return vec; } <# - } + } #> else { @@ -1366,15 +1423,16 @@ namespace System.Numerics { if (Vector.IsHardwareAccelerated) { -<# foreach (Type type in supportedTypes) +<# + foreach (Type type in supportedTypes) { #> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#>* dataPtr = stackalloc <#=type.Name#>[Count]; + <#=typeAliases[type]#>* dataPtr = stackalloc <#=typeAliases[type]#>[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (<#=type.Name#>)(object)left[g] : (<#=type.Name#>)(object)right[g]; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (<#=typeAliases[type]#>)(object)left[g] : (<#=typeAliases[type]#>)(object)right[g]; } return new Vector(dataPtr); } @@ -1389,23 +1447,24 @@ namespace System.Numerics else { Vector vec = new Vector(); -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> vec.<#=GetRegisterFieldName(type, g)#> = left.<#=GetRegisterFieldName(type, g)#> > right.<#=GetRegisterFieldName(type, g)#> ? left.<#=GetRegisterFieldName(type, g)#> : right.<#=GetRegisterFieldName(type, g)#>; <# - } + } #> return vec; } <# - } + } #> else { @@ -1428,24 +1487,25 @@ namespace System.Numerics } else { -<# foreach (Type type in supportedTypes) - { - #> +<# + foreach (Type type in supportedTypes) + { +#> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#> product = 0; + <#=typeAliases[type]#> product = 0; <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> - product += (<#=type.Name#>)(left.<#=GetRegisterFieldName(type, g)#> * right.<#=GetRegisterFieldName(type, g)#>); + product += (<#=typeAliases[type]#>)(left.<#=GetRegisterFieldName(type, g)#> * right.<#=GetRegisterFieldName(type, g)#>); <# - } + } #> return (T)(object)product; } <# - } + } #> else { @@ -1459,20 +1519,21 @@ namespace System.Numerics { if (Vector.IsHardwareAccelerated) { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#>* dataPtr = stackalloc <#=type.Name#>[Count]; + <#=typeAliases[type]#>* dataPtr = stackalloc <#=typeAliases[type]#>[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = unchecked((<#=type.Name#>)Math.Sqrt((<#=type.Name#>)(object)value[g])); + dataPtr[g] = unchecked((<#=typeAliases[type]#>)Math.Sqrt((<#=typeAliases[type]#>)(object)value[g])); } return new Vector(dataPtr); } <# - } + } #> else { @@ -1481,23 +1542,24 @@ namespace System.Numerics } else { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { <# - for (int g = 0; g < GetNumFields(type, totalSize); g++) - { + for (int g = 0; g < GetNumFields(type, totalSize); g++) + { #> - value.<#=GetRegisterFieldName(type, g)#> = (<#=type.Name#>)Math.Sqrt(value.<#=GetRegisterFieldName(type, g)#>); + value.<#=GetRegisterFieldName(type, g)#> = (<#=typeAliases[type]#>)Math.Sqrt(value.<#=GetRegisterFieldName(type, g)#>); <# - } + } #> return value; } <# - } + } #> else { @@ -1511,15 +1573,16 @@ namespace System.Numerics [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static bool ScalarEquals(T left, T right) { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - return (<#=type.Name#>)(object)left == (<#=type.Name#>)(object)right; + return (<#=typeAliases[type]#>)(object)left == (<#=typeAliases[type]#>)(object)right; } <# - } + } #> else { @@ -1530,15 +1593,16 @@ namespace System.Numerics [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static bool ScalarLessThan(T left, T right) { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - return (<#=type.Name#>)(object)left < (<#=type.Name#>)(object)right; + return (<#=typeAliases[type]#>)(object)left < (<#=typeAliases[type]#>)(object)right; } <# - } + } #> else { @@ -1549,15 +1613,16 @@ namespace System.Numerics [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static bool ScalarGreaterThan(T left, T right) { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - return (<#=type.Name#>)(object)left > (<#=type.Name#>)(object)right; + return (<#=typeAliases[type]#>)(object)left > (<#=typeAliases[type]#>)(object)right; } <# - } + } #> else { @@ -1568,15 +1633,16 @@ namespace System.Numerics [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static T ScalarAdd(T left, T right) { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - return (T)(object)unchecked((<#=type.Name#>)((<#=type.Name#>)(object)left + (<#=type.Name#>)(object)right)); + return (T)(object)unchecked((<#=typeAliases[type]#>)((<#=typeAliases[type]#>)(object)left + (<#=typeAliases[type]#>)(object)right)); } <# - } + } #> else { @@ -1587,15 +1653,16 @@ namespace System.Numerics [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static T ScalarSubtract(T left, T right) { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - return (T)(object)(<#=type.Name#>)((<#=type.Name#>)(object)left - (<#=type.Name#>)(object)right); + return (T)(object)(<#=typeAliases[type]#>)((<#=typeAliases[type]#>)(object)left - (<#=typeAliases[type]#>)(object)right); } <# - } + } #> else { @@ -1606,15 +1673,16 @@ namespace System.Numerics [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static T ScalarMultiply(T left, T right) { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - return (T)(object)unchecked((<#=type.Name#>)((<#=type.Name#>)(object)left * (<#=type.Name#>)(object)right)); + return (T)(object)unchecked((<#=typeAliases[type]#>)((<#=typeAliases[type]#>)(object)left * (<#=typeAliases[type]#>)(object)right)); } <# - } + } #> else { @@ -1625,15 +1693,16 @@ namespace System.Numerics [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static T ScalarDivide(T left, T right) { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - return (T)(object)(<#=type.Name#>)((<#=type.Name#>)(object)left / (<#=type.Name#>)(object)right); + return (T)(object)(<#=typeAliases[type]#>)((<#=typeAliases[type]#>)(object)left / (<#=typeAliases[type]#>)(object)right); } <# - } + } #> else { @@ -1644,16 +1713,17 @@ namespace System.Numerics [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static T GetOneValue() { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { - <#=type.Name#> value = 1; + <#=typeAliases[type]#> value = 1; return (T)(object)value; } <# - } + } #> else { @@ -1664,15 +1734,16 @@ namespace System.Numerics [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static T GetAllBitsSetValue() { -<# foreach (Type type in supportedTypes) - { +<# + foreach (Type type in supportedTypes) + { #> <#=GenerateIfStatementHeader(type)#> { return (T)(object)ConstantHelper.Get<#=type.Name#>WithAllBitsSet(); } <# - } + } #> else { @@ -1686,7 +1757,8 @@ namespace System.Numerics public static partial class Vector { #region Widen/Narrow -<# foreach (Type type in WidenableTypes) +<# + foreach (Type type in WidenableTypes) { Type widenTarget = GetWidenTarget(type); #> @@ -1705,28 +1777,28 @@ namespace System.Numerics } #> [Intrinsic] - public static unsafe void Widen(Vector<<#=type.Name#>> source, out Vector<<#=widenTarget.Name#>> low, out Vector<<#=widenTarget.Name#>> high) + public static unsafe void Widen(Vector<<#=typeAliases[type]#>> source, out Vector<<#=typeAliases[widenTarget]#>> low, out Vector<<#=typeAliases[widenTarget]#>> high) { - int elements = Vector<<#=type.Name#>>.Count; - <#=widenTarget.Name#>* lowPtr = stackalloc <#=widenTarget.Name#>[elements / 2]; + int elements = Vector<<#=typeAliases[type]#>>.Count; + <#=typeAliases[widenTarget]#>* lowPtr = stackalloc <#=typeAliases[widenTarget]#>[elements / 2]; for (int i = 0; i < elements / 2; i++) { - lowPtr[i] = (<#=widenTarget.Name#>)source[i]; + lowPtr[i] = (<#=typeAliases[widenTarget]#>)source[i]; } - <#=widenTarget.Name#>* highPtr = stackalloc <#=widenTarget.Name#>[elements / 2]; + <#=typeAliases[widenTarget]#>* highPtr = stackalloc <#=typeAliases[widenTarget]#>[elements / 2]; for (int i = 0; i < elements / 2; i++) { - highPtr[i] = (<#=widenTarget.Name#>)source[i + (elements / 2)]; + highPtr[i] = (<#=typeAliases[widenTarget]#>)source[i + (elements / 2)]; } - low = new Vector<<#=widenTarget.Name#>>(lowPtr); - high = new Vector<<#=widenTarget.Name#>>(highPtr); + low = new Vector<<#=typeAliases[widenTarget]#>>(lowPtr); + high = new Vector<<#=typeAliases[widenTarget]#>>(highPtr); } <# } -#> -<# foreach (Type narrowSource in NarrowableTypes) + + foreach (Type narrowSource in NarrowableTypes) { Type narrowTarget = GetNarrowTarget(narrowSource); #> @@ -1745,23 +1817,23 @@ namespace System.Numerics } #> [Intrinsic] - public static unsafe Vector<<#=narrowTarget.Name#>> Narrow(Vector<<#=narrowSource.Name#>> low, Vector<<#=narrowSource.Name#>> high) + public static unsafe Vector<<#=typeAliases[narrowTarget]#>> Narrow(Vector<<#=typeAliases[narrowSource]#>> low, Vector<<#=typeAliases[narrowSource]#>> high) { - unchecked - { - int elements = Vector<<#=narrowTarget.Name#>>.Count; - <#=narrowTarget.Name#>* retPtr = stackalloc <#=narrowTarget.Name#>[elements]; - for (int i = 0; i < elements / 2; i++) - { - retPtr[i] = (<#=narrowTarget.Name#>)low[i]; - } - for (int i = 0; i < elements / 2; i++) - { - retPtr[i + (elements / 2)] = (<#=narrowTarget.Name#>)high[i]; - } + unchecked + { + int elements = Vector<<#=typeAliases[narrowTarget]#>>.Count; + <#=typeAliases[narrowTarget]#>* retPtr = stackalloc <#=typeAliases[narrowTarget]#>[elements]; + for (int i = 0; i < elements / 2; i++) + { + retPtr[i] = (<#=typeAliases[narrowTarget]#>)low[i]; + } + for (int i = 0; i < elements / 2; i++) + { + retPtr[i + (elements / 2)] = (<#=typeAliases[narrowTarget]#>)high[i]; + } - return new Vector<<#=narrowTarget.Name#>>(retPtr); - } + return new Vector<<#=typeAliases[narrowTarget]#>>(retPtr); + } } <# @@ -1770,7 +1842,8 @@ namespace System.Numerics #endregion Widen/Narrow #region Same-Size Conversion -<# foreach (var pair in SameSizeConversionPairs) +<# + foreach (var pair in SameSizeConversionPairs) { #> /// @@ -1787,22 +1860,24 @@ namespace System.Numerics } #> [Intrinsic] - public static unsafe Vector<<#=pair.Value.Name#>> ConvertTo<#=pair.Value.Name#>(Vector<<#=pair.Key.Name#>> value) + public static unsafe Vector<<#=typeAliases[pair.Value]#>> ConvertTo<#=pair.Value.Name#>(Vector<<#=typeAliases[pair.Key]#>> value) { - unchecked - { - int elements = Vector<<#=pair.Value.Name#>>.Count; - <#=pair.Value.Name#>* retPtr = stackalloc <#=pair.Value.Name#>[elements]; - for (int i = 0; i < elements; i++) - { - retPtr[i] = (<#=pair.Value.Name#>)value[i]; - } + unchecked + { + int elements = Vector<<#=typeAliases[pair.Value]#>>.Count; + <#=typeAliases[pair.Value]#>* retPtr = stackalloc <#=typeAliases[pair.Value]#>[elements]; + for (int i = 0; i < elements; i++) + { + retPtr[i] = (<#=typeAliases[pair.Value]#>)value[i]; + } - return new Vector<<#=pair.Value.Name#>>(retPtr); - } + return new Vector<<#=typeAliases[pair.Value]#>>(retPtr); + } } -<# } #> +<# + } +#> #endregion Same-Size Conversion } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Vector_Operations.cs b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Vector_Operations.cs index b69b058be9..d3ed2509d8 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Vector_Operations.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Numerics/Vector_Operations.cs @@ -22,9 +22,9 @@ namespace System.Numerics /// The second source vector. /// The new vector with elements selected based on the mask. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector ConditionalSelect(Vector condition, Vector left, Vector right) + public static Vector ConditionalSelect(Vector condition, Vector left, Vector right) { - return (Vector)Vector.ConditionalSelect((Vector)condition, left, right); + return (Vector)Vector.ConditionalSelect((Vector)condition, left, right); } /// @@ -75,9 +75,9 @@ namespace System.Numerics /// The second vector to compare. /// The resultant vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector Equals(Vector left, Vector right) + public static Vector Equals(Vector left, Vector right) { - return (Vector)Vector.Equals(left, right); + return (Vector)Vector.Equals(left, right); } /// @@ -163,9 +163,9 @@ namespace System.Numerics /// The second vector to compare. /// The resultant integral vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector LessThan(Vector left, Vector right) + public static Vector LessThan(Vector left, Vector right) { - return (Vector)Vector.LessThan(left, right); + return (Vector)Vector.LessThan(left, right); } /// @@ -256,9 +256,9 @@ namespace System.Numerics /// The second vector to compare. /// The resultant integral vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector LessThanOrEqual(Vector left, Vector right) + public static Vector LessThanOrEqual(Vector left, Vector right) { - return (Vector)Vector.LessThanOrEqual(left, right); + return (Vector)Vector.LessThanOrEqual(left, right); } /// @@ -349,9 +349,9 @@ namespace System.Numerics /// The second vector to compare. /// The resultant integral vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector GreaterThan(Vector left, Vector right) + public static Vector GreaterThan(Vector left, Vector right) { - return (Vector)Vector.GreaterThan(left, right); + return (Vector)Vector.GreaterThan(left, right); } /// @@ -443,9 +443,9 @@ namespace System.Numerics /// The second vector to compare. /// The resultant integral vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector GreaterThanOrEqual(Vector left, Vector right) + public static Vector GreaterThanOrEqual(Vector left, Vector right) { - return (Vector)Vector.GreaterThanOrEqual(left, right); + return (Vector)Vector.GreaterThanOrEqual(left, right); } /// @@ -752,9 +752,9 @@ namespace System.Numerics /// The source vector /// The reinterpreted vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorByte(Vector value) where T : struct + public static Vector AsVectorByte(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -764,9 +764,9 @@ namespace System.Numerics /// The reinterpreted vector. [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorSByte(Vector value) where T : struct + public static Vector AsVectorSByte(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -776,9 +776,9 @@ namespace System.Numerics /// The reinterpreted vector. [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorUInt16(Vector value) where T : struct + public static Vector AsVectorUInt16(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -787,9 +787,9 @@ namespace System.Numerics /// The source vector /// The reinterpreted vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorInt16(Vector value) where T : struct + public static Vector AsVectorInt16(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -799,9 +799,9 @@ namespace System.Numerics /// The reinterpreted vector. [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorUInt32(Vector value) where T : struct + public static Vector AsVectorUInt32(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -810,9 +810,9 @@ namespace System.Numerics /// The source vector /// The reinterpreted vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorInt32(Vector value) where T : struct + public static Vector AsVectorInt32(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -822,9 +822,9 @@ namespace System.Numerics /// The reinterpreted vector. [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorUInt64(Vector value) where T : struct + public static Vector AsVectorUInt64(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } @@ -834,9 +834,9 @@ namespace System.Numerics /// The source vector /// The reinterpreted vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorInt64(Vector value) where T : struct + public static Vector AsVectorInt64(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -845,9 +845,9 @@ namespace System.Numerics /// The source vector /// The reinterpreted vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorSingle(Vector value) where T : struct + public static Vector AsVectorSingle(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -856,9 +856,9 @@ namespace System.Numerics /// The source vector /// The reinterpreted vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorDouble(Vector value) where T : struct + public static Vector AsVectorDouble(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } #endregion Conversion Methods } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ObjectDisposedException.cs b/external/corert/src/System.Private.CoreLib/shared/System/ObjectDisposedException.cs index 3daed13bb6..8f13055b94 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ObjectDisposedException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ObjectDisposedException.cs @@ -15,7 +15,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ObjectDisposedException : InvalidOperationException { - private String _objectName; + private string _objectName; // This constructor should only be called by the EE (COMPlusThrow) private ObjectDisposedException() : @@ -23,18 +23,18 @@ namespace System { } - public ObjectDisposedException(String objectName) : + public ObjectDisposedException(string objectName) : this(objectName, SR.ObjectDisposed_Generic) { } - public ObjectDisposedException(String objectName, String message) : base(message) + public ObjectDisposedException(string objectName, string message) : base(message) { HResult = HResults.COR_E_OBJECTDISPOSED; _objectName = objectName; } - public ObjectDisposedException(String message, Exception innerException) + public ObjectDisposedException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_OBJECTDISPOSED; @@ -55,26 +55,26 @@ namespace System /// /// Gets the text for the message for this exception. /// - public override String Message + public override string Message { get { - String name = ObjectName; + string name = ObjectName; if (name == null || name.Length == 0) return base.Message; - String objectDisposed = SR.Format(SR.ObjectDisposed_ObjectName_Name, name); + string objectDisposed = SR.Format(SR.ObjectDisposed_ObjectName_Name, name); return base.Message + Environment.NewLine + objectDisposed; } } - public String ObjectName + public string ObjectName { get { if (_objectName == null) { - return String.Empty; + return string.Empty; } return _objectName; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs b/external/corert/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs index a63db137f8..748681756d 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs @@ -26,7 +26,7 @@ namespace System , Inherited = false)] public sealed class ObsoleteAttribute : Attribute { - private String _message; + private string _message; private bool _error; public ObsoleteAttribute() @@ -35,19 +35,19 @@ namespace System _error = false; } - public ObsoleteAttribute(String message) + public ObsoleteAttribute(string message) { _message = message; _error = false; } - public ObsoleteAttribute(String message, bool error) + public ObsoleteAttribute(string message, bool error) { _message = message; _error = error; } - public String Message + public string Message { get { return _message; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/OperationCanceledException.cs b/external/corert/src/System.Private.CoreLib/shared/System/OperationCanceledException.cs index 8a472c9ff0..0c311afd7d 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/OperationCanceledException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/OperationCanceledException.cs @@ -36,13 +36,13 @@ namespace System HResult = HResults.COR_E_OPERATIONCANCELED; } - public OperationCanceledException(String message) + public OperationCanceledException(string message) : base(message) { HResult = HResults.COR_E_OPERATIONCANCELED; } - public OperationCanceledException(String message, Exception innerException) + public OperationCanceledException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_OPERATIONCANCELED; @@ -55,13 +55,13 @@ namespace System CancellationToken = token; } - public OperationCanceledException(String message, CancellationToken token) + public OperationCanceledException(string message, CancellationToken token) : this(message) { CancellationToken = token; } - public OperationCanceledException(String message, Exception innerException, CancellationToken token) + public OperationCanceledException(string message, Exception innerException, CancellationToken token) : this(message, innerException) { CancellationToken = token; diff --git a/external/corert/src/System.Private.CoreLib/src/System/OutOfMemoryException.cs b/external/corert/src/System.Private.CoreLib/shared/System/OutOfMemoryException.cs similarity index 68% rename from external/corert/src/System.Private.CoreLib/src/System/OutOfMemoryException.cs rename to external/corert/src/System.Private.CoreLib/shared/System/OutOfMemoryException.cs index 5bd4f21e81..c59852f785 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/OutOfMemoryException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/OutOfMemoryException.cs @@ -2,38 +2,37 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: The exception class for OOM. -** -** -=============================================================================*/ - using System.Runtime.Serialization; namespace System { + /// + /// The exception class for OOM. + /// [Serializable] #if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] #endif public class OutOfMemoryException : SystemException { - public OutOfMemoryException() - : base(SR.Arg_OutOfMemoryException) + public OutOfMemoryException() : base( +#if CORECLR + GetMessageFromNativeResources(ExceptionMessageKind.OutOfMemory) +#else + SR.Arg_OutOfMemoryException +#endif + ) { HResult = HResults.COR_E_OUTOFMEMORY; } - public OutOfMemoryException(String message) + public OutOfMemoryException(string message) : base(message) { HResult = HResults.COR_E_OUTOFMEMORY; } - public OutOfMemoryException(String message, Exception innerException) + public OutOfMemoryException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_OUTOFMEMORY; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/OverflowException.cs b/external/corert/src/System.Private.CoreLib/shared/System/OverflowException.cs index e28dcb87ed..c18fe3f7b3 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/OverflowException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/OverflowException.cs @@ -25,13 +25,13 @@ namespace System HResult = HResults.COR_E_OVERFLOW; } - public OverflowException(String message) + public OverflowException(string message) : base(message) { HResult = HResults.COR_E_OVERFLOW; } - public OverflowException(String message, Exception innerException) + public OverflowException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_OVERFLOW; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/PlatformNotSupportedException.cs b/external/corert/src/System.Private.CoreLib/shared/System/PlatformNotSupportedException.cs index 5039f3f441..f9e461ed0a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/PlatformNotSupportedException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/PlatformNotSupportedException.cs @@ -25,13 +25,13 @@ namespace System HResult = HResults.COR_E_PLATFORMNOTSUPPORTED; } - public PlatformNotSupportedException(String message) + public PlatformNotSupportedException(string message) : base(message) { HResult = HResults.COR_E_PLATFORMNOTSUPPORTED; } - public PlatformNotSupportedException(String message, Exception inner) + public PlatformNotSupportedException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_PLATFORMNOTSUPPORTED; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Random.cs b/external/corert/src/System.Private.CoreLib/shared/System/Random.cs index 20f035e2e8..ed79732c25 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Random.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Random.cs @@ -156,7 +156,7 @@ namespace System /*=====================================Next===================================== - **Returns: An int [0..Int32.MaxValue) + **Returns: An int [0..int.MaxValue) **Arguments: None **Exceptions: None. ==============================================================================*/ @@ -169,7 +169,7 @@ namespace System { // The distribution of double value returned by Sample // is not distributed well enough for a large range. - // If we use Sample for a range [Int32.MinValue..Int32.MaxValue) + // If we use Sample for a range [int.MinValue..int.MaxValue) // We will end up getting even numbers only. int result = InternalSample(); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/RankException.cs b/external/corert/src/System.Private.CoreLib/shared/System/RankException.cs index bdd2cd51f1..e1e7d169b8 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/RankException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/RankException.cs @@ -26,13 +26,13 @@ namespace System HResult = HResults.COR_E_RANK; } - public RankException(String message) + public RankException(string message) : base(message) { HResult = HResults.COR_E_RANK; } - public RankException(String message, Exception innerException) + public RankException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_RANK; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ReadOnlyMemory.cs b/external/corert/src/System.Private.CoreLib/shared/System/ReadOnlyMemory.cs index 166a204edb..02445ec5c6 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ReadOnlyMemory.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ReadOnlyMemory.cs @@ -8,9 +8,8 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; -#if !FEATURE_PORTABLE_SPAN + using Internal.Runtime.CompilerServices; -#endif // FEATURE_PORTABLE_SPAN namespace System { @@ -18,21 +17,23 @@ namespace System /// Represents a contiguous region of memory, similar to . /// Unlike , it is not a byref-like type. /// - [DebuggerDisplay("{DebuggerDisplay,nq}")] [DebuggerTypeProxy(typeof(MemoryDebugView<>))] + [DebuggerDisplay("{ToString(),raw}")] public readonly struct ReadOnlyMemory { // NOTE: With the current implementation, Memory and ReadOnlyMemory must have the same layout, // as code uses Unsafe.As to cast between them. // The highest order bit of _index is used to discern whether _object is an array/string or an owned memory - // if (_index >> 31) == 1, _object is an OwnedMemory - // else, _object is a T[] or string + // if (_index >> 31) == 1, _object is an MemoryManager + // else, _object is a T[] or string. + // if (_length >> 31) == 1, _object is a pre-pinned array, so Pin() will not allocate a new GCHandle + // else, Pin() needs to allocate a new GCHandle to pin the object. private readonly object _object; private readonly int _index; private readonly int _length; - internal const int RemoveOwnedFlagBitMask = 0x7FFFFFFF; + internal const int RemoveFlagsBitMask = 0x7FFFFFFF; /// /// Creates a new memory over the entirety of the target array. @@ -97,9 +98,6 @@ namespace System _length = length; } - //Debugger Display = {T[length]} - private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length); - /// /// Defines an implicit conversion of an array to a /// @@ -108,7 +106,7 @@ namespace System /// /// Defines an implicit conversion of a to a /// - public static implicit operator ReadOnlyMemory(ArraySegment arraySegment) => new ReadOnlyMemory(arraySegment.Array, arraySegment.Offset, arraySegment.Count); + public static implicit operator ReadOnlyMemory(ArraySegment segment) => new ReadOnlyMemory(segment.Array, segment.Offset, segment.Count); /// /// Returns an empty @@ -118,12 +116,25 @@ namespace System /// /// The number of items in the memory. /// - public int Length => _length; + public int Length => _length & RemoveFlagsBitMask; /// /// Returns true if Length is 0. /// - public bool IsEmpty => _length == 0; + public bool IsEmpty => (_length & RemoveFlagsBitMask) == 0; + + /// + /// For , returns a new instance of string that represents the characters pointed to by the memory. + /// Otherwise, returns a with the name of the type and the number of elements. + /// + public override string ToString() + { + if (typeof(T) == typeof(char)) + { + return (_object is string str) ? str.Substring(_index, _length & RemoveFlagsBitMask) : Span.ToString(); + } + return string.Format("System.ReadOnlyMemory<{0}>[{1}]", typeof(T).Name, _length & RemoveFlagsBitMask); + } /// /// Forms a slice out of the given memory, beginning at 'start'. @@ -135,12 +146,16 @@ namespace System [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory Slice(int start) { - if ((uint)start > (uint)_length) + // Used to maintain the high-bit which indicates whether the Memory has been pre-pinned or not. + int capturedLength = _length; + int actualLength = capturedLength & RemoveFlagsBitMask; + if ((uint)start > (uint)actualLength) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } - return new ReadOnlyMemory(_object, _index + start, _length - start); + // It is expected for (capturedLength - start) to be negative if the memory is already pre-pinned. + return new ReadOnlyMemory(_object, _index + start, capturedLength - start); } /// @@ -154,12 +169,16 @@ namespace System [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory Slice(int start, int length) { - if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) + // Used to maintain the high-bit which indicates whether the Memory has been pre-pinned or not. + int capturedLength = _length; + int actualLength = _length & RemoveFlagsBitMask; + if ((uint)start > (uint)actualLength || (uint)length > (uint)(actualLength - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } - return new ReadOnlyMemory(_object, _index + start, length); + // Set the high-bit to match the this._length high bit (1 for pre-pinned, 0 for unpinned). + return new ReadOnlyMemory(_object, _index + start, length | (capturedLength & ~RemoveFlagsBitMask)); } /// @@ -172,19 +191,18 @@ namespace System { if (_index < 0) { - return ((OwnedMemory)_object).Span.Slice(_index & RemoveOwnedFlagBitMask, _length); + Debug.Assert(_length >= 0); + Debug.Assert(_object != null); + return ((MemoryManager)_object).GetSpan().Slice(_index & RemoveFlagsBitMask, _length); } else if (typeof(T) == typeof(char) && _object is string s) { -#if FEATURE_PORTABLE_SPAN - return new ReadOnlySpan(Unsafe.As>(s), MemoryExtensions.StringAdjustment, s.Length).Slice(_index, _length); -#else + Debug.Assert(_length >= 0); return new ReadOnlySpan(ref Unsafe.As(ref s.GetRawStringData()), s.Length).Slice(_index, _length); -#endif // FEATURE_PORTABLE_SPAN } else if (_object != null) { - return new ReadOnlySpan((T[])_object, _index, _length); + return new ReadOnlySpan((T[])_object, _index, _length & RemoveFlagsBitMask); } else { @@ -216,50 +234,43 @@ namespace System /// The span to copy items into. public bool TryCopyTo(Memory destination) => Span.TryCopyTo(destination.Span); - /// Creates a handle for the memory. - /// - /// If pin is true, the GC will not move the array until the returned - /// is disposed, enabling the memory's address can be taken and used. - /// - public unsafe MemoryHandle Retain(bool pin = false) + /// + /// Creates a handle for the memory. + /// The GC will not move the memory until the returned + /// is disposed, enabling taking and using the memory's address. + /// + /// An instance with nonprimitive (non-blittable) members cannot be pinned. + /// + /// + public unsafe MemoryHandle Pin() { - MemoryHandle memoryHandle = default; - if (pin) + if (_index < 0) { - if (_index < 0) + Debug.Assert(_object != null); + return ((MemoryManager)_object).Pin((_index & RemoveFlagsBitMask)); + } + else if (typeof(T) == typeof(char) && _object is string s) + { + GCHandle handle = GCHandle.Alloc(s, GCHandleType.Pinned); + void* pointer = Unsafe.Add(Unsafe.AsPointer(ref s.GetRawStringData()), _index); + return new MemoryHandle(pointer, handle); + } + else if (_object is T[] array) + { + // Array is already pre-pinned + if (_length < 0) { - memoryHandle = ((OwnedMemory)_object).Pin((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf()); - } - else if (typeof(T) == typeof(char) && _object is string s) - { - GCHandle handle = GCHandle.Alloc(s, GCHandleType.Pinned); -#if FEATURE_PORTABLE_SPAN - void* pointer = Unsafe.Add((void*)handle.AddrOfPinnedObject(), _index); -#else - void* pointer = Unsafe.Add(Unsafe.AsPointer(ref s.GetRawStringData()), _index); -#endif // FEATURE_PORTABLE_SPAN - memoryHandle = new MemoryHandle(null, pointer, handle); - } - else if (_object is T[] array) - { - var handle = GCHandle.Alloc(array, GCHandleType.Pinned); -#if FEATURE_PORTABLE_SPAN - void* pointer = Unsafe.Add((void*)handle.AddrOfPinnedObject(), _index); -#else void* pointer = Unsafe.Add(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index); -#endif // FEATURE_PORTABLE_SPAN - memoryHandle = new MemoryHandle(null, pointer, handle); + return new MemoryHandle(pointer); } - } - else - { - if (_index < 0) + else { - ((OwnedMemory)_object).Retain(); - memoryHandle = new MemoryHandle((OwnedMemory)_object); + GCHandle handle = GCHandle.Alloc(array, GCHandleType.Pinned); + void* pointer = Unsafe.Add(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index); + return new MemoryHandle(pointer, handle); } } - return memoryHandle; + return default; } /// diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs b/external/corert/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs index 9bf3f211a8..4fb039a0fc 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs @@ -2,10 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Versioning; +using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; +using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using Internal.Runtime.CompilerServices; #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span.Equals(object)' overrides non-obsolete member 'object.Equals(object)' @@ -22,8 +23,6 @@ namespace System /// ReadOnlySpan represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed /// or native memory, or to memory allocated on the stack. It is type- and memory-safe. /// - [DebuggerTypeProxy(typeof(SpanDebugView<>))] - [DebuggerDisplay("{ToString(),raw}")] [NonVersionable] public readonly ref partial struct ReadOnlySpan { @@ -149,6 +148,13 @@ namespace System #endif } + /// + /// Returns a reference to the 0th element of the Span. If the Span is empty, returns null reference. + /// It can be used for pinning and is required to support the use of span within a fixed statement. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe ref readonly T GetPinnableReference() => ref (_length != 0) ? ref _pointer.Value : ref Unsafe.AsRef(null); + /// /// Copies the contents of this read-only span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in @@ -159,6 +165,7 @@ namespace System /// Thrown when the destination Span is shorter than the source Span. /// /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(Span destination) { // Using "if (!TryCopyTo(...))" results in two branches: one for the length @@ -204,7 +211,7 @@ namespace System /// /// For , returns a new instance of string that represents the characters pointed to by the span. - /// Otherwise, returns a with the name of the type and the number of elements. + /// Otherwise, returns a with the name of the type and the number of elements. /// public override string ToString() { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ReadOnlySpan.cs b/external/corert/src/System.Private.CoreLib/shared/System/ReadOnlySpan.cs index 906a3c4317..17b7134e27 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ReadOnlySpan.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/ReadOnlySpan.cs @@ -5,9 +5,8 @@ using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; -#if !FEATURE_PORTABLE_SPAN + using System.Runtime.Versioning; -#endif // !FEATURE_PORTABLE_SPAN #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span.Equals(object)' overrides non-obsolete member 'object.Equals(object)' @@ -26,9 +25,7 @@ namespace System /// public int Length { -#if !FEATURE_PORTABLE_SPAN [NonVersionable] -#endif // !FEATURE_PORTABLE_SPAN get { return _length; @@ -40,12 +37,11 @@ namespace System /// public bool IsEmpty { -#if !FEATURE_PORTABLE_SPAN [NonVersionable] -#endif // !FEATURE_PORTABLE_SPAN get { - return _length == 0; + // Workaround for https://github.com/dotnet/coreclr/issues/19620 + return 0 >= (uint)_length; } } /// @@ -88,13 +84,13 @@ namespace System /// /// Defines an implicit conversion of a to a /// - public static implicit operator ReadOnlySpan(ArraySegment arraySegment) - => new ReadOnlySpan(arraySegment.Array, arraySegment.Offset, arraySegment.Count); + public static implicit operator ReadOnlySpan(ArraySegment segment) + => new ReadOnlySpan(segment.Array, segment.Offset, segment.Count); /// /// Returns a 0-length read-only span whose base is the null pointer. /// - public static ReadOnlySpan Empty => default(ReadOnlySpan); + public static ReadOnlySpan Empty => default; /// Gets an enumerator for this span. public Enumerator GetEnumerator() => new Enumerator(this); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Assembly.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Assembly.cs index 7280869c02..f22c8c40ef 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Assembly.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Assembly.cs @@ -141,7 +141,7 @@ namespace System.Reflection Returns true if the assembly was loaded from the global assembly cache. */ public virtual bool GlobalAssemblyCache { get { throw NotImplemented.ByDesign; } } - public virtual Int64 HostContext { get { throw NotImplemented.ByDesign; } } + public virtual long HostContext { get { throw NotImplemented.ByDesign; } } public override bool Equals(object o) => base.Equals(o); public override int GetHashCode() => base.GetHashCode(); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/AssemblyNameFormatter.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/AssemblyNameFormatter.cs index 716afb045c..90ccd1fe54 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/AssemblyNameFormatter.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/AssemblyNameFormatter.cs @@ -111,8 +111,7 @@ namespace System.Reflection continue; if ((s.Length - i) < escapeReplacement.Length) continue; - string prefix = s.Substring(i, escapeReplacement.Length); - if (prefix == escapeReplacement) + if (s.AsSpan(i, escapeReplacement.Length).SequenceEqual(escapeReplacement)) { sb.Append('\\'); sb.Append(kv.Key); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/AssemblyBuilderAccess.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/AssemblyBuilderAccess.cs new file mode 100644 index 0000000000..b096960406 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/AssemblyBuilderAccess.cs @@ -0,0 +1,18 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +// This enumeration defines the access modes for a dynamic assembly. +// EE uses these enum values..look for m_dwDynamicAssemblyAccess in Assembly.hpp + +namespace System.Reflection.Emit +{ + [Flags] + public enum AssemblyBuilderAccess + { + Run = 1, + RunAndCollect = 8 | Run + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/FlowControl.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/FlowControl.cs new file mode 100644 index 0000000000..8905a7f1d9 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/FlowControl.cs @@ -0,0 +1,32 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/*============================================================ +** +** Enumeration: FlowControl +** +** Purpose: Exposes FlowControl Attribute of IL. +** +** THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT BY HAND! +** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.** +==============================================================*/ + +using System; + +namespace System.Reflection.Emit +{ + public enum FlowControl + { + Branch = 0, + Break = 1, + Call = 2, + Cond_Branch = 3, + Meta = 4, + Next = 5, + [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] + Phi = 6, + Return = 7, + Throw = 8, + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/Label.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/Label.cs new file mode 100644 index 0000000000..e49d471a99 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/Label.cs @@ -0,0 +1,75 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/*============================================================ +** +** +** +** +** +** +** Purpose: Represents a Label to the ILGenerator class. +** +** +===========================================================*/ + +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace System.Reflection.Emit +{ + // The Label class is an opaque representation of a label used by the + // ILGenerator class. The token is used to mark where labels occur in the IL + // stream and then the necessary offsets are put back in the code when the ILGenerator + // is passed to the MethodWriter. + // Labels are created by using ILGenerator.CreateLabel and their position is set + // by using ILGenerator.MarkLabel. + public struct Label + { + internal int m_label; + + //public Label() { + // m_label=0; + //} + + internal Label(int label) + { + m_label = label; + } + + internal int GetLabelValue() + { + return m_label; + } + + public override int GetHashCode() + { + return m_label; + } + + public override bool Equals(object obj) + { + if (obj is Label) + return Equals((Label)obj); + else + return false; + } + + public bool Equals(Label obj) + { + return obj.m_label == m_label; + } + + public static bool operator ==(Label a, Label b) + { + return a.Equals(b); + } + + public static bool operator !=(Label a, Label b) + { + return !(a == b); + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodeType.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodeType.cs new file mode 100644 index 0000000000..17435c5768 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodeType.cs @@ -0,0 +1,29 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/*============================================================ +** +** Enumeration: OpCodeType +** +** Purpose: Exposes OpCodeType Attribute of IL. +** +** THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT BY HAND! +** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.** +==============================================================*/ + +using System; + +namespace System.Reflection.Emit +{ + public enum OpCodeType + { + [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] + Annotation = 0, + Macro = 1, + Nternal = 2, + Objmodel = 3, + Prefix = 4, + Primitive = 5, + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodes.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodes.cs.REMOVED.git-id new file mode 100644 index 0000000000..b73066156b --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodes.cs.REMOVED.git-id @@ -0,0 +1 @@ +7690005e2f18e08a550816969bd51fe4b16e9b03 \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/Opcode.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/Opcode.cs new file mode 100644 index 0000000000..1a144fcf44 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/Opcode.cs @@ -0,0 +1,191 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Threading; + +namespace System.Reflection.Emit +{ + public struct OpCode + { + // + // Use packed bitfield for flags to avoid code bloat + // + + internal const int OperandTypeMask = 0x1F; // 000000000000000000000000000XXXXX + + internal const int FlowControlShift = 5; // 00000000000000000000000XXXX00000 + internal const int FlowControlMask = 0x0F; + + internal const int OpCodeTypeShift = 9; // 00000000000000000000XXX000000000 + internal const int OpCodeTypeMask = 0x07; + + internal const int StackBehaviourPopShift = 12; // 000000000000000XXXXX000000000000 + internal const int StackBehaviourPushShift = 17; // 0000000000XXXXX00000000000000000 + internal const int StackBehaviourMask = 0x1F; + + internal const int SizeShift = 22; // 00000000XX0000000000000000000000 + internal const int SizeMask = 0x03; + + internal const int EndsUncondJmpBlkFlag = 0x01000000; // 0000000X000000000000000000000000 + + // unused // 0000XXX0000000000000000000000000 + + internal const int StackChangeShift = 28; // XXXX0000000000000000000000000000 + + private OpCodeValues m_value; + private int m_flags; + + internal OpCode(OpCodeValues value, int flags) + { + m_value = value; + m_flags = flags; + } + + internal bool EndsUncondJmpBlk() + { + return (m_flags & EndsUncondJmpBlkFlag) != 0; + } + + internal int StackChange() + { + return (m_flags >> StackChangeShift); + } + + public OperandType OperandType + { + get + { + return (OperandType)(m_flags & OperandTypeMask); + } + } + + public FlowControl FlowControl + { + get + { + return (FlowControl)((m_flags >> FlowControlShift) & FlowControlMask); + } + } + + public OpCodeType OpCodeType + { + get + { + return (OpCodeType)((m_flags >> OpCodeTypeShift) & OpCodeTypeMask); + } + } + + public StackBehaviour StackBehaviourPop + { + get + { + return (StackBehaviour)((m_flags >> StackBehaviourPopShift) & StackBehaviourMask); + } + } + + public StackBehaviour StackBehaviourPush + { + get + { + return (StackBehaviour)((m_flags >> StackBehaviourPushShift) & StackBehaviourMask); + } + } + + public int Size + { + get + { + return (m_flags >> SizeShift) & SizeMask; + } + } + + public short Value + { + get + { + return (short)m_value; + } + } + + private static volatile string[] g_nameCache; + + public string Name + { + get + { + if (Size == 0) + return null; + + // Create and cache the opcode names lazily. They should be rarely used (only for logging, etc.) + // Note that we do not any locks here because of we always get the same names. The last one wins. + string[] nameCache = g_nameCache; + if (nameCache == null) + { + nameCache = new string[0x11f]; + g_nameCache = nameCache; + } + + OpCodeValues opCodeValue = (OpCodeValues)(ushort)Value; + + int idx = (int)opCodeValue; + if (idx > 0xFF) + { + if (idx >= 0xfe00 && idx <= 0xfe1e) + { + // Transform two byte opcode value to lower range that's suitable + // for array index + idx = 0x100 + (idx - 0xfe00); + } + else + { + // Unknown opcode + return null; + } + } + + string name = Volatile.Read(ref nameCache[idx]); + if (name != null) + return name; + + // Create ilasm style name from the enum value name. + name = Enum.GetName(typeof(OpCodeValues), opCodeValue).ToLowerInvariant().Replace("_", "."); + Volatile.Write(ref nameCache[idx], name); + return name; + } + } + + public override bool Equals(object obj) + { + if (obj is OpCode) + return Equals((OpCode)obj); + else + return false; + } + + public bool Equals(OpCode obj) + { + return obj.Value == Value; + } + + public static bool operator ==(OpCode a, OpCode b) + { + return a.Equals(b); + } + + public static bool operator !=(OpCode a, OpCode b) + { + return !(a == b); + } + + public override int GetHashCode() + { + return Value; + } + + public override string ToString() + { + return Name; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/OperandType.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/OperandType.cs new file mode 100644 index 0000000000..6257c56745 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/OperandType.cs @@ -0,0 +1,41 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/*============================================================ +** +** Enumeration: OperandType +** +** Purpose: Exposes OperandType Attribute of IL. +** +** THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT BY HAND! +** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.** +==============================================================*/ + +using System; + +namespace System.Reflection.Emit +{ + public enum OperandType + { + InlineBrTarget = 0, + InlineField = 1, + InlineI = 2, + InlineI8 = 3, + InlineMethod = 4, + InlineNone = 5, + [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] + InlinePhi = 6, + InlineR = 7, + InlineSig = 9, + InlineString = 10, + InlineSwitch = 11, + InlineTok = 12, + InlineType = 13, + InlineVar = 14, + ShortInlineBrTarget = 15, + ShortInlineI = 16, + ShortInlineR = 17, + ShortInlineVar = 18, + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/PEFileKinds.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/PEFileKinds.cs new file mode 100644 index 0000000000..f6606c477a --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/PEFileKinds.cs @@ -0,0 +1,17 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + + +using System; + +namespace System.Reflection.Emit +{ + // This Enum matchs the CorFieldAttr defined in CorHdr.h + public enum PEFileKinds + { + Dll = 0x0001, + ConsoleApplication = 0x0002, + WindowApplication = 0x0003, + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/PackingSize.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/PackingSize.cs new file mode 100644 index 0000000000..f734e1a342 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/PackingSize.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection.Emit +{ + public enum PackingSize + { + Unspecified = 0, + Size1 = 1, + Size2 = 2, + Size4 = 4, + Size8 = 8, + Size16 = 16, + Size32 = 32, + Size64 = 64, + Size128 = 128, + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/StackBehaviour.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/StackBehaviour.cs new file mode 100644 index 0000000000..3e64b48798 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Emit/StackBehaviour.cs @@ -0,0 +1,51 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/*============================================================ +** +** Enumeration: StackBehaviour +** +** Purpose: Exposes StackBehaviour Attribute of IL. +** +** THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT BY HAND! +** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.** +==============================================================*/ + +using System; + +namespace System.Reflection.Emit +{ + public enum StackBehaviour + { + Pop0 = 0, + Pop1 = 1, + Pop1_pop1 = 2, + Popi = 3, + Popi_pop1 = 4, + Popi_popi = 5, + Popi_popi8 = 6, + Popi_popi_popi = 7, + Popi_popr4 = 8, + Popi_popr8 = 9, + Popref = 10, + Popref_pop1 = 11, + Popref_popi = 12, + Popref_popi_popi = 13, + Popref_popi_popi8 = 14, + Popref_popi_popr4 = 15, + Popref_popi_popr8 = 16, + Popref_popi_popref = 17, + Push0 = 18, + Push1 = 19, + Push1_push1 = 20, + Pushi = 21, + Pushi8 = 22, + Pushr4 = 23, + Pushr8 = 24, + Pushref = 25, + Varpop = 26, + Varpush = 27, + Popref_popi_pop1 = 28, + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/ExceptionHandlingClause.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/ExceptionHandlingClause.cs similarity index 75% rename from external/corert/src/System.Private.CoreLib/src/System/Reflection/ExceptionHandlingClause.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Reflection/ExceptionHandlingClause.cs index 8598256b3d..15780f11cf 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Reflection/ExceptionHandlingClause.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/ExceptionHandlingClause.cs @@ -9,17 +9,13 @@ namespace System.Reflection public class ExceptionHandlingClause { protected ExceptionHandlingClause() { } - - // Desktop compat: These default implementations behave strangely because this class was originally - // creatable only from the native runtime, not through subclass inheritance. - - public virtual Type CatchType => null; - public virtual int FilterOffset { get { throw new InvalidOperationException(); } } - public virtual ExceptionHandlingClauseOptions Flags => default(ExceptionHandlingClauseOptions); - public virtual int HandlerLength => 0; - public virtual int HandlerOffset => 0; - public virtual int TryLength => 0; + public virtual ExceptionHandlingClauseOptions Flags => default; public virtual int TryOffset => 0; + public virtual int TryLength => 0; + public virtual int HandlerOffset => 0; + public virtual int HandlerLength => 0; + public virtual int FilterOffset => throw new InvalidOperationException(SR.Arg_EHClauseNotFilter); + public virtual Type CatchType => null; public override string ToString() { @@ -29,3 +25,4 @@ namespace System.Reflection } } } + diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/LocalVariableInfo.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/LocalVariableInfo.cs new file mode 100644 index 0000000000..1540bde531 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/LocalVariableInfo.cs @@ -0,0 +1,26 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; + +namespace System.Reflection +{ + public class LocalVariableInfo + { + public virtual Type LocalType { get { Debug.Fail("type must be set!"); return null; } } + public virtual int LocalIndex => 0; + public virtual bool IsPinned => false; + protected LocalVariableInfo() { } + public override string ToString() + { + string toString = LocalType.ToString() + " (" + LocalIndex + ")"; + + if (IsPinned) + toString += " (pinned)"; + + return toString; + } + } +} + diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/MethodBody.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/MethodBody.cs similarity index 62% rename from external/corert/src/System.Private.CoreLib/src/System/Reflection/MethodBody.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Reflection/MethodBody.cs index b87558573a..bdf53ad12f 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Reflection/MethodBody.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/MethodBody.cs @@ -9,14 +9,12 @@ namespace System.Reflection public class MethodBody { protected MethodBody() { } - - // Desktop compat: These default implementations behave strangely because this class was originally - // creatable only from the native runtime, not through subclass inheritance. public virtual int LocalSignatureMetadataToken => 0; - public virtual IList LocalVariables { get { throw new ArgumentNullException("array"); } } + public virtual IList LocalVariables => throw new ArgumentNullException("array"); public virtual int MaxStackSize => 0; public virtual bool InitLocals => false; public virtual byte[] GetILAsByteArray() => null; - public virtual IList ExceptionHandlingClauses { get { throw new ArgumentNullException("array"); } } + public virtual IList ExceptionHandlingClauses => throw new ArgumentNullException("array"); } } + diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Module.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Module.cs index 56f83c40d9..d290f78033 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Module.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/Module.cs @@ -130,53 +130,29 @@ namespace System.Reflection public override string ToString() => ScopeName; - public static readonly TypeFilter FilterTypeName = FilterTypeNameImpl; - public static readonly TypeFilter FilterTypeNameIgnoreCase = FilterTypeNameIgnoreCaseImpl; + public static readonly TypeFilter FilterTypeName = (m, c) => FilterTypeNameImpl(m, c, StringComparison.Ordinal); + public static readonly TypeFilter FilterTypeNameIgnoreCase = (m, c) => FilterTypeNameImpl(m, c, StringComparison.OrdinalIgnoreCase); private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; // FilterTypeName // This method will filter the class based upon the name. It supports // a trailing wild card. - private static bool FilterTypeNameImpl(Type cls, object filterCriteria) + private static bool FilterTypeNameImpl(Type cls, object filterCriteria, StringComparison comparison) { // Check that the criteria object is a String object - if (filterCriteria == null || !(filterCriteria is string)) + if (!(filterCriteria is string str)) + { throw new InvalidFilterCriteriaException(SR.InvalidFilterCriteriaException_CritString); - - string str = (string)filterCriteria; - + } // Check to see if this is a prefix or exact match requirement if (str.Length > 0 && str[str.Length - 1] == '*') { - str = str.Substring(0, str.Length - 1); - return cls.Name.StartsWith(str, StringComparison.Ordinal); + ReadOnlySpan slice = str.AsSpan(0, str.Length - 1); + return cls.Name.AsSpan().StartsWith(slice, comparison); } - return cls.Name.Equals(str); - } - - // FilterFieldNameIgnoreCase - // This method filter the Type based upon name, it ignores case. - private static bool FilterTypeNameIgnoreCaseImpl(Type cls, object filterCriteria) - { - // Check that the criteria object is a String object - if (filterCriteria == null || !(filterCriteria is string)) - throw new InvalidFilterCriteriaException(SR.InvalidFilterCriteriaException_CritString); - - string str = (string)filterCriteria; - - // Check to see if this is a prefix or exact match requirement - if (str.Length > 0 && str[str.Length - 1] == '*') - { - str = str.Substring(0, str.Length - 1); - string name = cls.Name; - if (name.Length >= str.Length) - return (string.Compare(name, 0, str, 0, str.Length, StringComparison.OrdinalIgnoreCase) == 0); - else - return false; - } - return (string.Compare(str, cls.Name, StringComparison.OrdinalIgnoreCase) == 0); + return cls.Name.Equals(str, comparison); } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/SignatureConstructedGenericType.cs b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/SignatureConstructedGenericType.cs index cd97ffa21b..d3d88520fc 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Reflection/SignatureConstructedGenericType.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Reflection/SignatureConstructedGenericType.cs @@ -10,11 +10,25 @@ namespace System.Reflection { internal sealed class SignatureConstructedGenericType : SignatureType { - internal SignatureConstructedGenericType(Type genericTypeDefinition, Type[] genericTypeArguments) + // The exception-visible name "typeArguments" is chosen to match the parameter name to Type.MakeGenericType() since that's the + // intended user of this constructor. + internal SignatureConstructedGenericType(Type genericTypeDefinition, Type[] typeArguments) { - Debug.Assert(genericTypeDefinition != null && genericTypeArguments != null); + if (genericTypeDefinition == null) + throw new ArgumentNullException(nameof(genericTypeDefinition)); + + if (typeArguments == null) + throw new ArgumentNullException(nameof(typeArguments)); + + typeArguments = (Type[])(typeArguments.Clone()); + for (int i = 0; i < typeArguments.Length; i++) + { + if (typeArguments[i] == null) + throw new ArgumentNullException(nameof(typeArguments)); + } + _genericTypeDefinition = genericTypeDefinition; - _genericTypeArguments = (Type[])(genericTypeArguments.Clone()); + _genericTypeArguments = typeArguments; } public sealed override bool IsTypeDefinition => false; diff --git a/external/corert/src/System.Private.CoreLib/src/System/Resources/FastResourceComparer.cs b/external/corert/src/System.Private.CoreLib/shared/System/Resources/FastResourceComparer.cs similarity index 81% rename from external/corert/src/System.Private.CoreLib/src/System/Resources/FastResourceComparer.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Resources/FastResourceComparer.cs index 3af7a1546c..6b813a0cec 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Resources/FastResourceComparer.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Resources/FastResourceComparer.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. @@ -21,18 +21,18 @@ using System.Diagnostics; namespace System.Resources { - internal sealed class FastResourceComparer : IComparer, IEqualityComparer, IComparer, IEqualityComparer + internal sealed class FastResourceComparer : IComparer, IEqualityComparer, IComparer, IEqualityComparer { internal static readonly FastResourceComparer Default = new FastResourceComparer(); // Implements IHashCodeProvider too, due to Hashtable requirements. - public int GetHashCode(Object key) + public int GetHashCode(object key) { - String s = (String)key; + string s = (string)key; return FastResourceComparer.HashFunction(s); } - public int GetHashCode(String key) + public int GetHashCode(string key) { return FastResourceComparer.HashFunction(key); } @@ -40,7 +40,7 @@ namespace System.Resources // This hash function MUST be publically documented with the resource // file format, AND we may NEVER change this hash function's return // value (without changing the file format). - internal static int HashFunction(String key) + internal static int HashFunction(string key) { // Never change this hash function. We must standardize it so that // others can read & write our .resources files. Additionally, we @@ -52,35 +52,35 @@ namespace System.Resources } // Compares Strings quickly in a case-sensitive way - public int Compare(Object a, Object b) + public int Compare(object a, object b) { if (a == b) return 0; - String sa = (String)a; - String sb = (String)b; - return String.CompareOrdinal(sa, sb); + string sa = (string)a; + string sb = (string)b; + return string.CompareOrdinal(sa, sb); } - public int Compare(String a, String b) + public int Compare(string a, string b) { - return String.CompareOrdinal(a, b); + return string.CompareOrdinal(a, b); } - public bool Equals(String a, String b) + public bool Equals(string a, string b) { - return String.Equals(a, b); + return string.Equals(a, b); } - public new bool Equals(Object a, Object b) + public new bool Equals(object a, object b) { if (a == b) return true; - String sa = (String)a; - String sb = (String)b; - return String.Equals(sa, sb); + string sa = (string)a; + string sb = (string)b; + return string.Equals(sa, sb); } // Input is one string to compare with, and a byte[] containing chars in // little endian unicode. Pass in the number of valid chars. - public unsafe static int CompareOrdinal(String a, byte[] bytes, int bCharLength) + public static unsafe int CompareOrdinal(string a, byte[] bytes, int bCharLength) { Debug.Assert(a != null && bytes != null, "FastResourceComparer::CompareOrdinal must have non-null params"); Debug.Assert(bCharLength * 2 <= bytes.Length, "FastResourceComparer::CompareOrdinal - numChars is too big!"); @@ -109,14 +109,14 @@ namespace System.Resources return a.Length - bCharLength; } - public static int CompareOrdinal(byte[] bytes, int aCharLength, String b) + public static int CompareOrdinal(byte[] bytes, int aCharLength, string b) { return -CompareOrdinal(b, bytes, aCharLength); } // This method is to handle potentially misaligned data accesses. // The byte* must point to little endian Unicode characters. - internal unsafe static int CompareOrdinal(byte* a, int byteLen, String b) + internal static unsafe int CompareOrdinal(byte* a, int byteLen, string b) { Debug.Assert((byteLen & 1) == 0, "CompareOrdinal is expecting a UTF-16 string length, which must be even!"); Debug.Assert(a != null && b != null, "Null args not allowed."); @@ -139,3 +139,4 @@ namespace System.Resources } } } + diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Resources/MissingSatelliteAssemblyException.cs b/external/corert/src/System.Private.CoreLib/shared/System/Resources/MissingSatelliteAssemblyException.cs index af547b21f1..0bbc626734 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Resources/MissingSatelliteAssemblyException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Resources/MissingSatelliteAssemblyException.cs @@ -24,7 +24,7 @@ namespace System.Resources [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class MissingSatelliteAssemblyException : SystemException { - private String _cultureName; + private string _cultureName; public MissingSatelliteAssemblyException() : base(SR.MissingSatelliteAssembly_Default) @@ -38,7 +38,7 @@ namespace System.Resources HResult = System.HResults.COR_E_MISSINGSATELLITEASSEMBLY; } - public MissingSatelliteAssemblyException(string message, String cultureName) + public MissingSatelliteAssemblyException(string message, string cultureName) : base(message) { HResult = System.HResults.COR_E_MISSINGSATELLITEASSEMBLY; @@ -56,7 +56,7 @@ namespace System.Resources { } - public String CultureName + public string CultureName { get { return _cultureName; } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Resources/ResourceReader.cs b/external/corert/src/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs similarity index 90% rename from external/corert/src/System.Private.CoreLib/src/System/Resources/ResourceReader.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs index 96fea18f60..cd2b0d0804 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Resources/ResourceReader.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. @@ -15,18 +15,21 @@ ** ===========================================================*/ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Reflection; -using System.Runtime.Versioning; -using System.Text; - namespace System.Resources { + using System; + using System.IO; + using System.Text; + using System.Collections; + using System.Collections.Generic; + using System.Reflection; + using System.Security; + using System.Globalization; + using System.Configuration.Assemblies; + using System.Runtime.Versioning; + using System.Diagnostics; + using System.Diagnostics.Contracts; + // Provides the default implementation of IResourceReader, reading // .resources file from the system default binary format. This class // can be treated as an enumerator once. @@ -37,10 +40,10 @@ namespace System.Resources internal struct ResourceLocator { - internal Object _value; // Can be null. Consider WeakReference instead? + internal object _value; // Can be null. Consider WeakReference instead? internal int _dataPos; - internal ResourceLocator(int dataPos, Object value) + internal ResourceLocator(int dataPos, object value) { _dataPos = dataPos; _value = value; @@ -54,7 +57,7 @@ namespace System.Resources // Allows adding in profiling data in a future version, or a special // resource profiling build. We could also use WeakReference. - internal Object Value + internal object Value { get { return _value; } set { _value = value; } @@ -78,7 +81,7 @@ namespace System.Resources // Used by RuntimeResourceSet and this class's enumerator. Maps // resource name to a value, a ResourceLocator, or a // LooselyLinkedManifestResource. - internal Dictionary _resCache; + internal Dictionary _resCache; private long _nameSectionOffset; // Offset to name section of file. private long _dataSectionOffset; // Offset to Data section of file. @@ -102,13 +105,10 @@ namespace System.Resources // Version number of .resources file, for compatibility private int _version; -#if RESOURCE_FILE_FORMAT_DEBUG - private bool _debug; // Whether this file has debugging stuff in it. -#endif - public ResourceReader(String fileName) + public ResourceReader(string fileName) { - _resCache = new Dictionary(FastResourceComparer.Default); + _resCache = new Dictionary(FastResourceComparer.Default); _store = new BinaryReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.RandomAccess), Encoding.UTF8); try @@ -117,7 +117,7 @@ namespace System.Resources } catch { - _store.Dispose(); // If we threw an exception, close the file. + _store.Close(); // If we threw an exception, close the file. throw; } } @@ -129,7 +129,7 @@ namespace System.Resources if (!stream.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable); - _resCache = new Dictionary(FastResourceComparer.Default); + _resCache = new Dictionary(FastResourceComparer.Default); _store = new BinaryReader(stream, Encoding.UTF8); // We have a faster code path for reading resource files from an assembly. _ums = stream as UnmanagedMemoryStream; @@ -141,7 +141,7 @@ namespace System.Resources // passing in the stream to read from and the RuntimeResourceSet's // internal hash table (hash table of names with file offsets // and values, coupled to this ResourceReader). - internal ResourceReader(Stream stream, Dictionary resCache) + internal ResourceReader(Stream stream, Dictionary resCache) { Debug.Assert(stream != null, "Need a stream!"); Debug.Assert(stream.CanRead, "Stream should be readable!"); @@ -178,7 +178,7 @@ namespace System.Resources BinaryReader copyOfStore = _store; _store = null; if (copyOfStore != null) - copyOfStore.Dispose(); + copyOfStore.Close(); } _store = null; _namePositions = null; @@ -196,38 +196,10 @@ namespace System.Resources return buffer[0] | (buffer[1] << 8) | (buffer[2] << 16) | (buffer[3] << 24); } - internal int Read7BitEncodedInt() - { - // Read out an Int32 7 bits at a time. The high bit - // of the byte when on means to continue reading more bytes. - int count = 0; - int shift = 0; - byte b; - do - { - // Check for a corrupted stream. Read a max of 5 bytes. - // In a future version, add a DataFormatException. - if (shift == 5 * 7) // 5 bytes max per Int32, shift += 7 - throw new FormatException(SR.Format_Bad7BitInt32); - - // ReadByte handles end of stream cases for us. - b = _store.ReadByte(); - count |= (b & 0x7F) << shift; - shift += 7; - } while ((b & 0x80) != 0); - return count; - } - - - private void SkipInt32() - { - _store.BaseStream.Seek(4, SeekOrigin.Current); - } - private void SkipString() { - int stringLength = Read7BitEncodedInt(); + int stringLength = _store.Read7BitEncodedInt(); if (stringLength < 0) { throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength); @@ -284,10 +256,11 @@ namespace System.Resources // To read the data, seek to _dataSectionOffset + dataPos, then // read the resource type & data. // This does a binary search through the names. - internal int FindPosForResource(String name) + internal int FindPosForResource(string name) { Debug.Assert(_store != null, "ResourceReader is closed!"); int hash = FastResourceComparer.HashFunction(name); + // Binary search over the hashes. Use the _namePositions array to // determine where they exist in the underlying stream. int lo = 0; @@ -307,7 +280,7 @@ namespace System.Resources c = -1; else c = 1; - //BCLDebug.Log("RESMGRFILEFORMAT", " Probing index "+index+" lo: "+lo+" hi: "+hi+" c: "+c); + if (c == 0) { success = true; @@ -364,10 +337,10 @@ namespace System.Resources // with the string you pass in. // Whoever calls this method should make sure that they take a lock // so no one else can cause us to seek in the stream. - private unsafe bool CompareStringEqualsName(String name) + private unsafe bool CompareStringEqualsName(string name) { Debug.Assert(_store != null, "ResourceReader is closed!"); - int byteLen = Read7BitEncodedInt(); + int byteLen = _store.Read7BitEncodedInt(); if (byteLen < 0) { throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength); @@ -406,7 +379,7 @@ namespace System.Resources // This is used in the enumerator. The enumerator iterates from 0 to n // of our resources and this returns the resource name for a particular // index. The parameter is NOT a virtual offset. - private unsafe String AllocateStringForNameIndex(int index, out int dataOffset) + private unsafe string AllocateStringForNameIndex(int index, out int dataOffset) { Debug.Assert(_store != null, "ResourceReader is closed!"); byte[] bytes; @@ -416,7 +389,7 @@ namespace System.Resources { _store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin); // Can't use _store.ReadString, since it's using UTF-8! - byteLen = Read7BitEncodedInt(); + byteLen = _store.Read7BitEncodedInt(); if (byteLen < 0) { throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength); @@ -427,9 +400,10 @@ namespace System.Resources if (_ums.Position > _ums.Length - byteLen) throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourcesIndexTooLong, index)); - String s = null; + string s = null; char* charPtr = (char*)_ums.PositionPointer; - s = new String(charPtr, 0, byteLen / 2); + + s = new string(charPtr, 0, byteLen / 2); _ums.Position += byteLen; dataOffset = _store.ReadInt32(); @@ -464,7 +438,7 @@ namespace System.Resources // This is used in the enumerator. The enumerator iterates from 0 to n // of our resources and this returns the resource value for a particular // index. The parameter is NOT a virtual offset. - private Object GetValueForNameIndex(int index) + private object GetValueForNameIndex(int index) { Debug.Assert(_store != null, "ResourceReader is closed!"); long nameVA = GetNamePosition(index); @@ -472,7 +446,7 @@ namespace System.Resources { _store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin); SkipString(); - //BCLDebug.Log("RESMGRFILEFORMAT", "GetValueForNameIndex for index: "+index+" skip (name length): "+skip); + int dataPos = _store.ReadInt32(); if (dataPos < 0 || dataPos >= _store.BaseStream.Length - _dataSectionOffset) { @@ -490,17 +464,17 @@ namespace System.Resources // from that location. // Anyone who calls LoadObject should make sure they take a lock so // no one can cause us to do a seek in here. - internal String LoadString(int pos) + internal string LoadString(int pos) { Debug.Assert(_store != null, "ResourceReader is closed!"); _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); - String s = null; - int typeIndex = Read7BitEncodedInt(); + string s = null; + int typeIndex = _store.Read7BitEncodedInt(); if (_version == 1) { if (typeIndex == -1) return null; - if (FindType(typeIndex) != typeof(String)) + if (FindType(typeIndex) != typeof(string)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Type, FindType(typeIndex).FullName)); s = _store.ReadString(); } @@ -509,7 +483,7 @@ namespace System.Resources ResourceTypeCode typeCode = (ResourceTypeCode)typeIndex; if (typeCode != ResourceTypeCode.String && typeCode != ResourceTypeCode.Null) { - String typeString; + string typeString; if (typeCode < ResourceTypeCode.StartOfUserTypes) typeString = typeCode.ToString(); else @@ -523,7 +497,7 @@ namespace System.Resources } // Called from RuntimeResourceSet - internal Object LoadObject(int pos) + internal object LoadObject(int pos) { if (_version == 1) return LoadObjectV1(pos); @@ -531,12 +505,12 @@ namespace System.Resources return LoadObjectV2(pos, out typeCode); } - internal Object LoadObject(int pos, out ResourceTypeCode typeCode) + internal object LoadObject(int pos, out ResourceTypeCode typeCode) { if (_version == 1) { - Object o = LoadObjectV1(pos); - typeCode = (o is String) ? ResourceTypeCode.String : ResourceTypeCode.StartOfUserTypes; + object o = LoadObjectV1(pos); + typeCode = (o is string) ? ResourceTypeCode.String : ResourceTypeCode.StartOfUserTypes; return o; } return LoadObjectV2(pos, out typeCode); @@ -546,7 +520,7 @@ namespace System.Resources // from that location. // Anyone who calls LoadObject should make sure they take a lock so // no one can cause us to do a seek in here. - internal Object LoadObjectV1(int pos) + internal object LoadObjectV1(int pos) { Debug.Assert(_store != null, "ResourceReader is closed!"); Debug.Assert(_version == 1, ".resources file was not a V1 .resources file!"); @@ -567,10 +541,10 @@ namespace System.Resources } } - private Object _LoadObjectV1(int pos) + private object _LoadObjectV1(int pos) { _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); - int typeIndex = Read7BitEncodedInt(); + int typeIndex = _store.Read7BitEncodedInt(); if (typeIndex == -1) return null; Type type = FindType(typeIndex); @@ -578,27 +552,27 @@ namespace System.Resources // primitive or a value type first, so we can reach the // deserialization code faster for arbitrary objects. - if (type == typeof(String)) + if (type == typeof(string)) return _store.ReadString(); - else if (type == typeof(Int32)) + else if (type == typeof(int)) return _store.ReadInt32(); - else if (type == typeof(Byte)) + else if (type == typeof(byte)) return _store.ReadByte(); - else if (type == typeof(SByte)) + else if (type == typeof(sbyte)) return _store.ReadSByte(); - else if (type == typeof(Int16)) + else if (type == typeof(short)) return _store.ReadInt16(); - else if (type == typeof(Int64)) + else if (type == typeof(long)) return _store.ReadInt64(); - else if (type == typeof(UInt16)) + else if (type == typeof(ushort)) return _store.ReadUInt16(); - else if (type == typeof(UInt32)) + else if (type == typeof(uint)) return _store.ReadUInt32(); - else if (type == typeof(UInt64)) + else if (type == typeof(ulong)) return _store.ReadUInt64(); - else if (type == typeof(Single)) + else if (type == typeof(float)) return _store.ReadSingle(); - else if (type == typeof(Double)) + else if (type == typeof(double)) return _store.ReadDouble(); else if (type == typeof(DateTime)) { @@ -608,12 +582,12 @@ namespace System.Resources } else if (type == typeof(TimeSpan)) return new TimeSpan(_store.ReadInt64()); - else if (type == typeof(Decimal)) + else if (type == typeof(decimal)) { int[] bits = new int[4]; for (int i = 0; i < bits.Length; i++) bits[i] = _store.ReadInt32(); - return new Decimal(bits); + return new decimal(bits); } else { @@ -621,7 +595,7 @@ namespace System.Resources } } - internal Object LoadObjectV2(int pos, out ResourceTypeCode typeCode) + internal object LoadObjectV2(int pos, out ResourceTypeCode typeCode) { Debug.Assert(_store != null, "ResourceReader is closed!"); Debug.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!"); @@ -642,10 +616,10 @@ namespace System.Resources } } - private Object _LoadObjectV2(int pos, out ResourceTypeCode typeCode) + private object _LoadObjectV2(int pos, out ResourceTypeCode typeCode) { _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); - typeCode = (ResourceTypeCode)Read7BitEncodedInt(); + typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt(); switch (typeCode) { @@ -696,11 +670,11 @@ namespace System.Resources case ResourceTypeCode.DateTime: // Use DateTime's ToBinary & FromBinary. - Int64 data = _store.ReadInt64(); + long data = _store.ReadInt64(); return DateTime.FromBinary(data); case ResourceTypeCode.TimeSpan: - Int64 ticks = _store.ReadInt64(); + long ticks = _store.ReadInt64(); return new TimeSpan(ticks); // Special types @@ -822,7 +796,7 @@ namespace System.Resources // Read in type name for a suitable ResourceReader // Note ResourceWriter & InternalResGen use different Strings. - String readerType = _store.ReadString(); + string readerType = _store.ReadString(); readerType = System.CoreLib.FixupCoreLibName(readerType); AssemblyName mscorlib = new AssemblyName(ResourceManager.MscorlibName); @@ -969,7 +943,7 @@ namespace System.Resources try { _store.BaseStream.Position = _typeNamePositions[typeIndex]; - String typeName = _store.ReadString(); + string typeName = _store.ReadString(); _typeTable[typeIndex] = Type.GetType(typeName, true); } // If serialization isn't supported, we convert FileNotFoundException to @@ -995,7 +969,7 @@ namespace System.Resources return _typeTable[typeIndex]; } - public void GetResourceData(String resourceName, out String resourceType, out byte[] resourceData) + public void GetResourceData(string resourceName, out string resourceType, out byte[] resourceData) { if (resourceName == null) throw new ArgumentNullException(nameof(resourceName)); @@ -1020,7 +994,7 @@ namespace System.Resources { _store.BaseStream.Position = _nameSectionOffset + GetNamePosition(i); // Skip over name of resource - int numBytesToSkip = Read7BitEncodedInt(); + int numBytesToSkip = _store.Read7BitEncodedInt(); if (numBytesToSkip < 0) { throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesNameInvalidOffset, numBytesToSkip)); @@ -1044,7 +1018,7 @@ namespace System.Resources // Read type code then byte[] _store.BaseStream.Position = _dataSectionOffset + dataPos; - ResourceTypeCode typeCode = (ResourceTypeCode)Read7BitEncodedInt(); + ResourceTypeCode typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt(); if (typeCode < 0 || typeCode >= ResourceTypeCode.StartOfUserTypes + _typeTable.Length) { throw new BadImageFormatException(SR.BadImageFormat_InvalidType); @@ -1061,12 +1035,12 @@ namespace System.Resources } } - private String TypeNameFromTypeCode(ResourceTypeCode typeCode) + private string TypeNameFromTypeCode(ResourceTypeCode typeCode) { Debug.Assert(typeCode >= 0, "can't be negative"); if (typeCode < ResourceTypeCode.StartOfUserTypes) { - Debug.Assert(!String.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers."); + Debug.Assert(!string.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers."); return "ResourceTypeCode." + typeCode.ToString(); } else @@ -1088,7 +1062,7 @@ namespace System.Resources internal sealed class ResourceEnumerator : IDictionaryEnumerator { - private const int ENUM_DONE = Int32.MinValue; + private const int ENUM_DONE = int.MinValue; private const int ENUM_NOT_STARTED = -1; private ResourceReader _reader; @@ -1116,7 +1090,7 @@ namespace System.Resources return true; } - public Object Key + public object Key { get { @@ -1128,7 +1102,7 @@ namespace System.Resources } } - public Object Current + public object Current { get { @@ -1153,8 +1127,8 @@ namespace System.Resources if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); if (_reader._resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed); - String key; - Object value = null; + string key; + object value = null; lock (_reader) { // locks should be taken in the same order as in RuntimeResourceSet.GetObject to avoid deadlock lock (_reader._resCache) @@ -1183,7 +1157,7 @@ namespace System.Resources } } - public Object Value + public object Value { get { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Resources/ResourceSet.cs b/external/corert/src/System.Private.CoreLib/shared/System/Resources/ResourceSet.cs similarity index 72% rename from external/corert/src/System.Private.CoreLib/src/System/Resources/ResourceSet.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Resources/ResourceSet.cs index 5b1fd99a7a..2d33f3a8b0 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Resources/ResourceSet.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Resources/ResourceSet.cs @@ -13,15 +13,9 @@ ** ===========================================================*/ -using System; using System.Collections; using System.IO; -using System.Globalization; -using System.Runtime.InteropServices; using System.Reflection; -using System.Runtime.Serialization; -using System.Runtime.Versioning; -using System.Collections.Generic; namespace System.Resources { @@ -33,11 +27,10 @@ namespace System.Resources // public class ResourceSet : IDisposable, IEnumerable { - [NonSerialized] protected IResourceReader Reader; + internal Hashtable Table; - private Dictionary _table; - private Dictionary _caseInsensitiveTable; // For case-insensitive lookups. + private Hashtable _caseInsensitiveTable; // For case-insensitive lookups. protected ResourceSet() { @@ -56,7 +49,7 @@ namespace System.Resources // implementation. Use this constructor to open & read from a file // on disk. // - public ResourceSet(String fileName) + public ResourceSet(string fileName) { Reader = new ResourceReader(fileName); CommonInit(); @@ -85,7 +78,7 @@ namespace System.Resources private void CommonInit() { - _table = new Dictionary(); + Table = new Hashtable(); } // Closes and releases any resources used by this ResourceSet, if any. @@ -109,7 +102,7 @@ namespace System.Resources } Reader = null; _caseInsensitiveTable = null; - _table = null; + Table = null; } public void Dispose() @@ -146,7 +139,7 @@ namespace System.Resources private IDictionaryEnumerator GetEnumeratorHelper() { - Dictionary copyOfTable = _table; // Avoid a race with Dispose + Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); return copyOfTable.GetEnumerator(); @@ -154,12 +147,12 @@ namespace System.Resources // Look up a string value for a resource given its name. // - public virtual String GetString(String name) + public virtual string GetString(string name) { - Object obj = GetObjectInternal(name); + object obj = GetObjectInternal(name); try { - return (String)obj; + return (string)obj; } catch (InvalidCastException) { @@ -167,16 +160,16 @@ namespace System.Resources } } - public virtual String GetString(String name, bool ignoreCase) + public virtual string GetString(string name, bool ignoreCase) { - Object obj; - String s; + object obj; + string s; // Case-sensitive lookup obj = GetObjectInternal(name); try { - s = (String)obj; + s = (string)obj; } catch (InvalidCastException) { @@ -193,7 +186,7 @@ namespace System.Resources obj = GetCaseInsensitiveObjectInternal(name); try { - return (String)obj; + return (string)obj; } catch (InvalidCastException) { @@ -203,14 +196,14 @@ namespace System.Resources // Look up an object value for a resource given its name. // - public virtual Object GetObject(String name) + public virtual object GetObject(string name) { return GetObjectInternal(name); } - public virtual Object GetObject(String name, bool ignoreCase) + public virtual object GetObject(string name, bool ignoreCase) { - Object obj = GetObjectInternal(name); + object obj = GetObjectInternal(name); if (obj != null || !ignoreCase) return obj; @@ -223,38 +216,37 @@ namespace System.Resources IDictionaryEnumerator en = Reader.GetEnumerator(); while (en.MoveNext()) { - Object value = en.Value; - _table.Add(en.Key, value); + object value = en.Value; + Table.Add(en.Key, value); } // While technically possible to close the Reader here, don't close it // to help with some WinRes lifetime issues. } - private Object GetObjectInternal(String name) + private object GetObjectInternal(string name) { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); - Dictionary copyOfTable = _table; // Avoid a race with Dispose + Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); - object value; - copyOfTable.TryGetValue(name, out value); - return value; + + return copyOfTable[name]; } - private Object GetCaseInsensitiveObjectInternal(String name) + private object GetCaseInsensitiveObjectInternal(string name) { - Dictionary copyOfTable = _table; // Avoid a race with Dispose + Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); - Dictionary caseTable = _caseInsensitiveTable; // Avoid a race condition with Close + Hashtable caseTable = _caseInsensitiveTable; // Avoid a race condition with Close if (caseTable == null) { - caseTable = new Dictionary(CaseInsensitiveStringObjectComparer.Instance); + caseTable = new Hashtable(StringComparer.OrdinalIgnoreCase); IDictionaryEnumerator en = copyOfTable.GetEnumerator(); while (en.MoveNext()) @@ -263,29 +255,8 @@ namespace System.Resources } _caseInsensitiveTable = caseTable; } - object value; - caseTable.TryGetValue(name, out value); - return value; - } - /// - /// Adapter for StringComparer.OrdinalIgnoreCase to allow it to be used with Dictionary - /// - private class CaseInsensitiveStringObjectComparer : IEqualityComparer - { - public static CaseInsensitiveStringObjectComparer Instance { get; } = new CaseInsensitiveStringObjectComparer(); - - private CaseInsensitiveStringObjectComparer() { } - - public new bool Equals(object x, object y) - { - return ((IEqualityComparer)StringComparer.OrdinalIgnoreCase).Equals(x, y); - } - - public int GetHashCode(object obj) - { - return ((IEqualityComparer)StringComparer.OrdinalIgnoreCase).GetHashCode(obj); - } + return caseTable[name]; } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Resources/RuntimeResourceSet.cs b/external/corert/src/System.Private.CoreLib/shared/System/Resources/RuntimeResourceSet.cs index a63e68c19d..426e17bdba 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Resources/RuntimeResourceSet.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Resources/RuntimeResourceSet.cs @@ -173,7 +173,7 @@ namespace System.Resources // for arbitrarily long times, since the object is usually a string // literal that will live for the lifetime of the appdomain. The // value is a ResourceLocator instance, which might cache the object. - private Dictionary _resCache; + private Dictionary _resCache; // For our special load-on-demand reader, cache the cast. The @@ -185,15 +185,15 @@ namespace System.Resources // want to fill this out if we can avoid it. The problem is resource // fallback will somewhat regularly cause us to look up resources that // don't exist. - private Dictionary _caseInsensitiveTable; + private Dictionary _caseInsensitiveTable; // If we're not using our custom reader, then enumerate through all // the resources once, adding them into the table. private bool _haveReadFromReader; - internal RuntimeResourceSet(String fileName) : base(false) + internal RuntimeResourceSet(string fileName) : base(false) { - _resCache = new Dictionary(FastResourceComparer.Default); + _resCache = new Dictionary(FastResourceComparer.Default); Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); _defaultReader = new ResourceReader(stream, _resCache); Reader = _defaultReader; @@ -201,7 +201,7 @@ namespace System.Resources internal RuntimeResourceSet(Stream stream) : base(false) { - _resCache = new Dictionary(FastResourceComparer.Default); + _resCache = new Dictionary(FastResourceComparer.Default); _defaultReader = new ResourceReader(stream, _resCache); Reader = _defaultReader; } @@ -256,36 +256,36 @@ namespace System.Resources } - public override String GetString(String key) + public override string GetString(string key) { - Object o = GetObject(key, false, true); - return (String)o; + object o = GetObject(key, false, true); + return (string)o; } - public override String GetString(String key, bool ignoreCase) + public override string GetString(string key, bool ignoreCase) { - Object o = GetObject(key, ignoreCase, true); - return (String)o; + object o = GetObject(key, ignoreCase, true); + return (string)o; } - public override Object GetObject(String key) + public override object GetObject(string key) { return GetObject(key, false, false); } - public override Object GetObject(String key, bool ignoreCase) + public override object GetObject(string key, bool ignoreCase) { return GetObject(key, ignoreCase, false); } - private Object GetObject(String key, bool ignoreCase, bool isString) + private object GetObject(string key, bool ignoreCase, bool isString) { if (key == null) throw new ArgumentNullException(nameof(key)); if (Reader == null || _resCache == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); - Object value = null; + object value = null; ResourceLocator resLocation; lock (Reader) @@ -348,7 +348,7 @@ namespace System.Resources // If necessary, init our case insensitive hash table. if (ignoreCase && _caseInsensitiveTable == null) { - _caseInsensitiveTable = new Dictionary(StringComparer.OrdinalIgnoreCase); + _caseInsensitiveTable = new Dictionary(StringComparer.OrdinalIgnoreCase); } if (_defaultReader == null) @@ -357,7 +357,7 @@ namespace System.Resources while (en.MoveNext()) { DictionaryEntry entry = en.Entry; - String readKey = (String)entry.Key; + string readKey = (string)entry.Key; ResourceLocator resLoc = new ResourceLocator(-1, entry.Value); _resCache.Add(readKey, resLoc); if (ignoreCase) @@ -375,7 +375,7 @@ namespace System.Resources while (en.MoveNext()) { // Note: Always ask for the resource key before the data position. - String currentKey = (String)en.Key; + string currentKey = (string)en.Key; int dataPos = en.DataPosition; ResourceLocator resLoc = new ResourceLocator(dataPos, null); _caseInsensitiveTable.Add(currentKey, resLoc); @@ -383,7 +383,7 @@ namespace System.Resources } _haveReadFromReader = true; } - Object obj = null; + object obj = null; bool found = false; bool keyInWrongCase = false; if (_defaultReader != null) @@ -410,11 +410,11 @@ namespace System.Resources // The last parameter indicates whether the lookup required a // case-insensitive lookup to succeed, indicating we shouldn't add // the ResourceLocation to our case-sensitive cache. - private Object ResolveResourceLocator(ResourceLocator resLocation, String key, Dictionary copyOfCache, bool keyInWrongCase) + private object ResolveResourceLocator(ResourceLocator resLocation, string key, Dictionary copyOfCache, bool keyInWrongCase) { // We need to explicitly resolve loosely linked manifest // resources, and we need to resolve ResourceLocators with null objects. - Object value = resLocation.Value; + object value = resLocation.Value; if (value == null) { ResourceTypeCode typeCode; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Resources/SatelliteContractVersionAttribute.cs b/external/corert/src/System.Private.CoreLib/shared/System/Resources/SatelliteContractVersionAttribute.cs index 0707447677..aeccadca99 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Resources/SatelliteContractVersionAttribute.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Resources/SatelliteContractVersionAttribute.cs @@ -19,13 +19,13 @@ namespace System.Resources [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public sealed class SatelliteContractVersionAttribute : Attribute { - public SatelliteContractVersionAttribute(String version) + public SatelliteContractVersionAttribute(string version) { if (version == null) throw new ArgumentNullException(nameof(version)); Version = version; } - public String Version { get; } + public string Version { get; } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.cs new file mode 100644 index 0000000000..6e1c4c56cd --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.cs @@ -0,0 +1,17 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Runtime.CompilerServices +{ + [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] + public sealed class CallerArgumentExpressionAttribute : Attribute + { + public CallerArgumentExpressionAttribute(string parameterName) + { + ParameterName = parameterName; + } + + public string ParameterName { get; } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs index b6f12299bf..8f7b0c809c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs @@ -33,7 +33,7 @@ namespace System.Runtime.CompilerServices [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion #if CORECLR - , IValueTaskAwaiter + , IStateMachineBoxAwareAwaiter #endif { /// The value being awaited. @@ -59,55 +59,64 @@ namespace System.Runtime.CompilerServices /// Schedules the continuation action for the . public void OnCompleted(Action continuation) { - if (_value.ObjectIsTask) + object obj = _value._obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj is Task t) { - _value.UnsafeGetTask().ConfigureAwait(_value.ContinueOnCapturedContext).GetAwaiter().OnCompleted(continuation); + t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } - else if (_value._obj != null) + else if (obj != null) { - _value.UnsafeGetValueTaskSource().OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, + Unsafe.As(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | - (_value.ContinueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None)); + (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None)); } else { - ValueTask.CompletedTask.ConfigureAwait(_value.ContinueOnCapturedContext).GetAwaiter().OnCompleted(continuation); + ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } } /// Schedules the continuation action for the . public void UnsafeOnCompleted(Action continuation) { - if (_value.ObjectIsTask) + object obj = _value._obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj is Task t) { - _value.UnsafeGetTask().ConfigureAwait(_value.ContinueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); + t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } - else if (_value._obj != null) + else if (obj != null) { - _value.UnsafeGetValueTaskSource().OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, - _value.ContinueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); + Unsafe.As(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, + _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { - ValueTask.CompletedTask.ConfigureAwait(_value.ContinueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); + ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } } #if CORECLR - void IValueTaskAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) + void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { - if (_value.ObjectIsTask) + object obj = _value._obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj is Task t) { - TaskAwaiter.UnsafeOnCompletedInternal(_value.UnsafeGetTask(), box, _value.ContinueOnCapturedContext); + TaskAwaiter.UnsafeOnCompletedInternal(t, box, _value._continueOnCapturedContext); } - else if (_value._obj != null) + else if (obj != null) { - _value.UnsafeGetValueTaskSource().OnCompleted(ValueTaskAwaiter.s_invokeAsyncStateMachineBox, box, _value._token, - _value.ContinueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); + Unsafe.As(obj).OnCompleted(ValueTaskAwaiter.s_invokeAsyncStateMachineBox, box, _value._token, + _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { - TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, _value.ContinueOnCapturedContext); + TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, _value._continueOnCapturedContext); } } #endif @@ -135,7 +144,7 @@ namespace System.Runtime.CompilerServices [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion #if CORECLR - , IValueTaskAwaiter + , IStateMachineBoxAwareAwaiter #endif { /// The value being awaited. @@ -161,58 +170,67 @@ namespace System.Runtime.CompilerServices /// Schedules the continuation action for the . public void OnCompleted(Action continuation) { - if (_value.ObjectIsTask) + object obj = _value._obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj is Task t) { - _value.UnsafeGetTask().ConfigureAwait(_value.ContinueOnCapturedContext).GetAwaiter().OnCompleted(continuation); + t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } - else if (_value._obj != null) + else if (obj != null) { - _value.UnsafeGetValueTaskSource().OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, + Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | - (_value.ContinueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None)); + (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None)); } else { - ValueTask.CompletedTask.ConfigureAwait(_value.ContinueOnCapturedContext).GetAwaiter().OnCompleted(continuation); + ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } } /// Schedules the continuation action for the . public void UnsafeOnCompleted(Action continuation) { - if (_value.ObjectIsTask) + object obj = _value._obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj is Task t) { - _value.UnsafeGetTask().ConfigureAwait(_value.ContinueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); + t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } - else if (_value._obj != null) + else if (obj != null) { - _value.UnsafeGetValueTaskSource().OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, - _value.ContinueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); + Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, + _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { - ValueTask.CompletedTask.ConfigureAwait(_value.ContinueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); + ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } } #if CORECLR - void IValueTaskAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) + void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { - if (_value.ObjectIsTask) + object obj = _value._obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj is Task t) { - TaskAwaiter.UnsafeOnCompletedInternal(_value.UnsafeGetTask(), box, _value.ContinueOnCapturedContext); + TaskAwaiter.UnsafeOnCompletedInternal(t, box, _value._continueOnCapturedContext); } - else if (_value._obj != null) + else if (obj != null) { - _value.UnsafeGetValueTaskSource().OnCompleted(ValueTaskAwaiter.s_invokeAsyncStateMachineBox, box, _value._token, - _value.ContinueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); + Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeAsyncStateMachineBox, box, _value._token, + _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { - TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, _value.ContinueOnCapturedContext); + TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, _value._continueOnCapturedContext); } } #endif } } -} \ No newline at end of file +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs index f75693eb40..d3116cc8ad 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs @@ -7,6 +7,6 @@ namespace System.Runtime.CompilerServices [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public abstract class CustomConstantAttribute : Attribute { - public abstract Object Value { get; } + public abstract object Value { get; } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs index 813e6803bf..44c497706e 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs @@ -14,6 +14,6 @@ namespace System.Runtime.CompilerServices _date = new DateTime(ticks); } - public override Object Value => _date; + public override object Value => _date; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs index 19db84eb43..521a3abe9c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs @@ -9,7 +9,7 @@ namespace System.Runtime.CompilerServices [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public sealed class DecimalConstantAttribute : Attribute { - private Decimal _dec; + private decimal _dec; [CLSCompliant(false)] public DecimalConstantAttribute( @@ -20,7 +20,7 @@ namespace System.Runtime.CompilerServices uint low ) { - _dec = new Decimal((int)low, (int)mid, (int)hi, (sign != 0), scale); + _dec = new decimal((int)low, (int)mid, (int)hi, (sign != 0), scale); } public DecimalConstantAttribute( @@ -31,9 +31,9 @@ namespace System.Runtime.CompilerServices int low ) { - _dec = new Decimal(low, mid, hi, (sign != 0), scale); + _dec = new decimal(low, mid, hi, (sign != 0), scale); } - public Decimal Value => _dec; + public decimal Value => _dec; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs index 0fe07edc9e..7bb7acec41 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs @@ -7,13 +7,13 @@ namespace System.Runtime.CompilerServices [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class DependencyAttribute : Attribute { - public DependencyAttribute(String dependentAssemblyArgument, LoadHint loadHintArgument) + public DependencyAttribute(string dependentAssemblyArgument, LoadHint loadHintArgument) { DependentAssembly = dependentAssemblyArgument; LoadHint = loadHintArgument; } - public String DependentAssembly { get; } + public string DependentAssembly { get; } public LoadHint LoadHint { get; } } } \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ICastable.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ICastable.cs similarity index 92% rename from external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ICastable.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ICastable.cs index aac87b8a80..37e77358ad 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ICastable.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ICastable.cs @@ -2,16 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// -// Support for dynamic interface casting. Specifically implementing this interface on a type will allow the -// type to support interfaces (for the purposes of casting and interface dispatch) that do not appear in its -// interface map. -// - using System; namespace System.Runtime.CompilerServices { + /// + /// Support for dynamic interface casting. Specifically implementing this interface on a type will allow the + /// type to support interfaces (for the purposes of casting and interface dispatch) that do not appear in its + /// interface map. + /// public interface ICastable { // This is called if casting this object to the given interface type would otherwise fail. Casting diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs index ea843b3daa..bc76250adc 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs @@ -7,7 +7,7 @@ namespace System.Runtime.CompilerServices [AttributeUsage(AttributeTargets.Property, Inherited = true)] public sealed class IndexerNameAttribute : Attribute { - public IndexerNameAttribute(String indexerName) + public IndexerNameAttribute(string indexerName) { } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs index f3842ec562..6c6fe9e258 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs @@ -22,11 +22,11 @@ namespace System.Runtime.CompilerServices { } - public ReferenceAssemblyAttribute(String description) + public ReferenceAssemblyAttribute(string description) { Description = description; } - public String Description { get; } + public string Description { get; } } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TaskAwaiter.cs similarity index 81% rename from external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TaskAwaiter.cs index 33b5b0b26b..030278dcf5 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TaskAwaiter.cs @@ -5,7 +5,6 @@ // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // - // // Types for awaiting Task and Task. These types are emitted from Task{}.GetAwaiter // and Task{}.ConfigureAwait. They are meant to be used only by the compiler, e.g. @@ -39,10 +38,12 @@ // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; +using System.Diagnostics.Tracing; using System.Threading; using System.Threading.Tasks; - +#if !CORECLR using Internal.Threading.Tasks.Tracing; +#endif // NOTE: For performance reasons, initialization is not verified. If a developer // incorrectly initializes a task awaiter, which should only be done by the compiler, @@ -54,10 +55,13 @@ namespace System.Runtime.CompilerServices { /// Provides an awaiter for awaiting a . /// This type is intended for compiler use only. - public readonly struct TaskAwaiter : ICriticalNotifyCompletion + public readonly struct TaskAwaiter : ICriticalNotifyCompletion, ITaskAwaiter { + // WARNING: Unsafe.As is used to access the generic TaskAwaiter<> as TaskAwaiter. + // Its layout must remain the same. + /// The task being awaited. - private readonly Task m_task; + internal readonly Task m_task; /// Initializes the . /// The to be awaited. @@ -99,7 +103,7 @@ namespace System.Runtime.CompilerServices /// The awaiter was not properly initialized. /// The task was canceled. /// The task completed in a Faulted state. - [StackTraceHidden] + [StackTraceHidden] public void GetResult() { ValidateEnd(m_task); @@ -110,7 +114,7 @@ namespace System.Runtime.CompilerServices /// prior to completing the await. /// /// The awaited task. - [StackTraceHidden] + [StackTraceHidden] internal static void ValidateEnd(Task task) { // Fast checks that can be inlined. @@ -139,7 +143,7 @@ namespace System.Runtime.CompilerServices // but where for one reason or another synchronous rather than asynchronous waiting is needed. if (!task.IsCompleted) { - bool taskCompleted = task.InternalWait(Timeout.Infinite, default(CancellationToken)); + bool taskCompleted = task.InternalWait(Timeout.Infinite, default); Debug.Assert(taskCompleted, "With an infinite timeout, the task should have always completed."); } @@ -195,6 +199,7 @@ namespace System.Runtime.CompilerServices /// The task being awaited. /// The action to invoke when the await operation completes. /// Whether to capture and marshal back to the current context. + /// Whether to flow ExecutionContext across the await. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. /// This method is intended for compiler user rather than use directly in code. @@ -204,7 +209,13 @@ namespace System.Runtime.CompilerServices // If TaskWait* ETW events are enabled, trace a beginning event for this await // and set up an ending event to be traced when the asynchronous await completes. - if (TaskTrace.Enabled) + if ( +#if CORECLR + TplEtwProvider.Log.IsEnabled() || Task.s_asyncDebuggingEnabled +#else + TaskTrace.Enabled +#endif + ) { continuation = OutputWaitEtwEvents(task, continuation); } @@ -213,6 +224,31 @@ namespace System.Runtime.CompilerServices task.SetContinuationForAwait(continuation, continueOnCapturedContext, flowExecutionContext); } +#if CORECLR + /// Schedules the continuation onto the associated with this . + /// The task being awaited. + /// The action to invoke when the await operation completes. + /// Whether to capture and marshal back to the current context. + /// Whether to flow ExecutionContext across the await. + /// The argument is null (Nothing in Visual Basic). + /// The awaiter was not properly initialized. + /// This method is intended for compiler user rather than use directly in code. + internal static void UnsafeOnCompletedInternal(Task task, IAsyncStateMachineBox stateMachineBox, bool continueOnCapturedContext) + { + Debug.Assert(stateMachineBox != null); + + // If TaskWait* ETW events are enabled, trace a beginning event for this await + // and set up an ending event to be traced when the asynchronous await completes. + if (TplEtwProvider.Log.IsEnabled() || Task.s_asyncDebuggingEnabled) + { + task.SetContinuationForAwait(OutputWaitEtwEvents(task, stateMachineBox.MoveNextAction), continueOnCapturedContext, flowExecutionContext: false); + } + else + { + task.UnsafeSetContinuationForAwait(stateMachineBox, continueOnCapturedContext); + } + } +#endif /// /// Outputs a WaitBegin ETW event, and augments the continuation action to output a WaitEnd ETW event. /// @@ -223,6 +259,28 @@ namespace System.Runtime.CompilerServices { Debug.Assert(task != null, "Need a task to wait on"); Debug.Assert(continuation != null, "Need a continuation to invoke when the wait completes"); +#if CORECLR + if (Task.s_asyncDebuggingEnabled) + { + Task.AddToActiveTasks(task); + } + + var etwLog = TplEtwProvider.Log; + + if (etwLog.IsEnabled()) + { + // ETW event for Task Wait Begin + var currentTaskAtBegin = Task.InternalCurrent; + + // If this task's continuation is another task, get it. + var continuationTask = AsyncMethodBuilderCore.TryGetContinuationTask(continuation); + etwLog.TaskWaitBegin( + (currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler.Id : TaskScheduler.Default.Id), + (currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0), + task.Id, TplEtwProvider.TaskWaitBehavior.Asynchronous, + (continuationTask != null ? continuationTask.Id : 0)); + } +#else Debug.Assert(TaskTrace.Enabled, "Should only be used when ETW tracing is enabled"); // ETW event for Task Wait Begin @@ -231,12 +289,51 @@ namespace System.Runtime.CompilerServices (currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler.Id : TaskScheduler.Default.Id), (currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0), task.Id); +#endif // Create a continuation action that outputs the end event and then invokes the user // provided delegate. This incurs the allocations for the closure/delegate, but only if the event // is enabled, and in doing so it allows us to pass the awaited task's information into the end event // in a purely pay-for-play manner (the alternatively would be to increase the size of TaskAwaiter // just for this ETW purpose, not pay-for-play, since GetResult would need to know whether a real yield occurred). +#if CORECLR + return AsyncMethodBuilderCore.CreateContinuationWrapper(continuation, (innerContinuation,innerTask) => + { + if (Task.s_asyncDebuggingEnabled) + { + Task.RemoveFromActiveTasks(innerTask.Id); + } + + TplEtwProvider innerEtwLog = TplEtwProvider.Log; + + // ETW event for Task Wait End. + Guid prevActivityId = new Guid(); + bool bEtwLogEnabled = innerEtwLog.IsEnabled(); + if (bEtwLogEnabled) + { + var currentTaskAtEnd = Task.InternalCurrent; + innerEtwLog.TaskWaitEnd( + (currentTaskAtEnd != null ? currentTaskAtEnd.m_taskScheduler.Id : TaskScheduler.Default.Id), + (currentTaskAtEnd != null ? currentTaskAtEnd.Id : 0), + innerTask.Id); + + // Ensure the continuation runs under the activity ID of the task that completed for the + // case the antecedent is a promise (in the other cases this is already the case). + if (innerEtwLog.TasksSetActivityIds && (innerTask.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0) + EventSource.SetCurrentThreadActivityId(TplEtwProvider.CreateGuidForTaskID(innerTask.Id), out prevActivityId); + } + + // Invoke the original continuation provided to OnCompleted. + innerContinuation(); + + if (bEtwLogEnabled) + { + innerEtwLog.TaskWaitContinuationComplete(innerTask.Id); + if (innerEtwLog.TasksSetActivityIds && (innerTask.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0) + EventSource.SetCurrentThreadActivityId(prevActivityId); + } + }, task); +#else return () => { // ETW event for Task Wait End. @@ -252,13 +349,17 @@ namespace System.Runtime.CompilerServices // Invoke the original continuation provided to OnCompleted. continuation(); }; +#endif } } /// Provides an awaiter for awaiting a . /// This type is intended for compiler use only. - public readonly struct TaskAwaiter : ICriticalNotifyCompletion + public readonly struct TaskAwaiter : ICriticalNotifyCompletion, ITaskAwaiter { + // WARNING: Unsafe.As is used to access TaskAwaiter<> as the non-generic TaskAwaiter. + // Its layout must remain the same. + /// The task being awaited. private readonly Task m_task; @@ -311,6 +412,20 @@ namespace System.Runtime.CompilerServices } } + /// + /// Marker interface used to know whether a particular awaiter is either a + /// TaskAwaiter or a TaskAwaiter`1. It must not be implemented by any other + /// awaiters. + /// + internal interface ITaskAwaiter { } + + /// + /// Marker interface used to know whether a particular awaiter is either a + /// CTA.ConfiguredTaskAwaiter or a CTA`1.ConfiguredTaskAwaiter. It must not + /// be implemented by any other awaiters. + /// + internal interface IConfiguredTaskAwaiter { } + /// Provides an awaitable object that allows for configured awaits on . /// This type is intended for compiler use only. public readonly struct ConfiguredTaskAwaitable @@ -338,12 +453,15 @@ namespace System.Runtime.CompilerServices /// Provides an awaiter for a . /// This type is intended for compiler use only. - public readonly struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion + public readonly struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion, IConfiguredTaskAwaiter { + // WARNING: Unsafe.As is used to access the generic ConfiguredTaskAwaiter as this. + // Its layout must remain the same. + /// The task being awaited. - private readonly Task m_task; + internal readonly Task m_task; /// Whether to attempt marshaling back to the original context. - private readonly bool m_continueOnCapturedContext; + internal readonly bool m_continueOnCapturedContext; /// Initializes the . /// The to await. @@ -425,8 +543,11 @@ namespace System.Runtime.CompilerServices /// Provides an awaiter for a . /// This type is intended for compiler use only. - public readonly struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion + public readonly struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion, IConfiguredTaskAwaiter { + // WARNING: Unsafe.As is used to access this as the non-generic ConfiguredTaskAwaiter. + // Its layout must remain the same. + /// The task being awaited. private readonly Task m_task; /// Whether to attempt marshaling back to the original context. diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ValueTaskAwaiter.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ValueTaskAwaiter.cs index 221a1a437d..02b5910b77 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ValueTaskAwaiter.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ValueTaskAwaiter.cs @@ -6,12 +6,16 @@ using System.Diagnostics; using System.Threading.Tasks; using System.Threading.Tasks.Sources; +#if !netstandard +using Internal.Runtime.CompilerServices; +#endif + namespace System.Runtime.CompilerServices { /// Provides an awaiter for a . public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion #if CORECLR - , IValueTaskAwaiter + , IStateMachineBoxAwareAwaiter #endif { /// Shim used to invoke an passed as the state argument to a . @@ -48,13 +52,16 @@ namespace System.Runtime.CompilerServices /// Schedules the continuation action for this ValueTask. public void OnCompleted(Action continuation) { - if (_value.ObjectIsTask) + object obj = _value._obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj is Task t) { - _value.UnsafeGetTask().GetAwaiter().OnCompleted(continuation); + t.GetAwaiter().OnCompleted(continuation); } - else if (_value._obj != null) + else if (obj != null) { - _value.UnsafeGetValueTaskSource().OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext); + Unsafe.As(obj).OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext); } else { @@ -65,13 +72,16 @@ namespace System.Runtime.CompilerServices /// Schedules the continuation action for this ValueTask. public void UnsafeOnCompleted(Action continuation) { - if (_value.ObjectIsTask) + object obj = _value._obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj is Task t) { - _value.UnsafeGetTask().GetAwaiter().UnsafeOnCompleted(continuation); + t.GetAwaiter().UnsafeOnCompleted(continuation); } - else if (_value._obj != null) + else if (obj != null) { - _value.UnsafeGetValueTaskSource().OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); + Unsafe.As(obj).OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); } else { @@ -80,15 +90,18 @@ namespace System.Runtime.CompilerServices } #if CORECLR - void IValueTaskAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) + void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { - if (_value.ObjectIsTask) + object obj = _value._obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj is Task t) { - TaskAwaiter.UnsafeOnCompletedInternal(_value.UnsafeGetTask(), box, continueOnCapturedContext: true); + TaskAwaiter.UnsafeOnCompletedInternal(t, box, continueOnCapturedContext: true); } - else if (_value._obj != null) + else if (obj != null) { - _value.UnsafeGetValueTaskSource().OnCompleted(s_invokeAsyncStateMachineBox, box, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); + Unsafe.As(obj).OnCompleted(s_invokeAsyncStateMachineBox, box, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); } else { @@ -105,7 +118,7 @@ namespace System.Runtime.CompilerServices return; } - box.Invoke(null); + box.MoveNext(); }; #endif } @@ -113,7 +126,7 @@ namespace System.Runtime.CompilerServices /// Provides an awaiter for a . public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion #if CORECLR - , IValueTaskAwaiter + , IStateMachineBoxAwareAwaiter #endif { /// The value being awaited. @@ -139,13 +152,16 @@ namespace System.Runtime.CompilerServices /// Schedules the continuation action for this ValueTask. public void OnCompleted(Action continuation) { - if (_value.ObjectIsTask) + object obj = _value._obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj is Task t) { - _value.UnsafeGetTask().GetAwaiter().OnCompleted(continuation); + t.GetAwaiter().OnCompleted(continuation); } - else if (_value._obj != null) + else if (obj != null) { - _value.UnsafeGetValueTaskSource().OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext); + Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext); } else { @@ -156,13 +172,16 @@ namespace System.Runtime.CompilerServices /// Schedules the continuation action for this ValueTask. public void UnsafeOnCompleted(Action continuation) { - if (_value.ObjectIsTask) + object obj = _value._obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj is Task t) { - _value.UnsafeGetTask().GetAwaiter().UnsafeOnCompleted(continuation); + t.GetAwaiter().UnsafeOnCompleted(continuation); } - else if (_value._obj != null) + else if (obj != null) { - _value.UnsafeGetValueTaskSource().OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); + Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); } else { @@ -171,15 +190,18 @@ namespace System.Runtime.CompilerServices } #if CORECLR - void IValueTaskAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) + void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { - if (_value.ObjectIsTask) + object obj = _value._obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj is Task t) { - TaskAwaiter.UnsafeOnCompletedInternal(_value.UnsafeGetTask(), box, continueOnCapturedContext: true); + TaskAwaiter.UnsafeOnCompletedInternal(t, box, continueOnCapturedContext: true); } - else if (_value._obj != null) + else if (obj != null) { - _value.UnsafeGetValueTaskSource().OnCompleted(ValueTaskAwaiter.s_invokeAsyncStateMachineBox, box, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); + Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeAsyncStateMachineBox, box, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); } else { @@ -190,12 +212,12 @@ namespace System.Runtime.CompilerServices } #if CORECLR - /// Internal interface used to enable optimizations from on .> - internal interface IValueTaskAwaiter + /// Internal interface used to enable optimizations from .> + internal interface IStateMachineBoxAwareAwaiter { /// Invoked to set of the as the awaiter's continuation. /// The box object. void AwaitUnsafeOnCompleted(IAsyncStateMachineBox box); } #endif -} \ No newline at end of file +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/YieldAwaitable.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/YieldAwaitable.cs index c45ef2484c..68fd5ab8d6 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/YieldAwaitable.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/YieldAwaitable.cs @@ -47,6 +47,9 @@ namespace System.Runtime.CompilerServices /// Provides an awaiter that switches into a target environment. /// This type is intended for compiler use only. public readonly struct YieldAwaiter : ICriticalNotifyCompletion +#if CORECLR + , IStateMachineBoxAwareAwaiter +#endif { /// Gets whether a yield is not required. /// This property is intended for compiler user rather than use directly in code. @@ -110,11 +113,46 @@ namespace System.Runtime.CompilerServices // We're targeting a custom scheduler, so queue a task. else { - Task.Factory.StartNew(continuation, default(CancellationToken), TaskCreationOptions.PreferFairness, scheduler); + Task.Factory.StartNew(continuation, default, TaskCreationOptions.PreferFairness, scheduler); } } } +#if CORECLR + void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) + { + Debug.Assert(box != null); + + // If tracing is enabled, delegate the Action-based implementation. + if (TplEtwProvider.Log.IsEnabled()) + { + QueueContinuation(box.MoveNextAction, flowContext: false); + return; + } + + // Otherwise, this is the same logic as in QueueContinuation, except using + // an IAsyncStateMachineBox instead of an Action, and only for flowContext:false. + + SynchronizationContext syncCtx = SynchronizationContext.Current; + if (syncCtx != null && syncCtx.GetType() != typeof(SynchronizationContext)) + { + syncCtx.Post(s => ((IAsyncStateMachineBox)s).MoveNext(), box); + } + else + { + TaskScheduler scheduler = TaskScheduler.Current; + if (scheduler == TaskScheduler.Default) + { + ThreadPool.UnsafeQueueUserWorkItem(s => ((IAsyncStateMachineBox)s).MoveNext(), box); + } + else + { + Task.Factory.StartNew(s => ((IAsyncStateMachineBox)s).MoveNext(), box, default, TaskCreationOptions.PreferFairness, scheduler); + } + } + } +#endif + private static Action OutputCorrelationEtwEvent(Action continuation) { #if CORERT @@ -153,7 +191,6 @@ namespace System.Runtime.CompilerServices private static readonly WaitCallback s_waitCallbackRunAction = RunAction; /// SendOrPostCallback that invokes the Action supplied as object state. private static readonly SendOrPostCallback s_sendOrPostCallbackRunAction = RunAction; - /// Runs an Action delegate provided as state. /// The Action delegate to invoke. private static void RunAction(object state) { ((Action)state)(); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/ConstrainedExecution/CriticalFinalizerObject.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/ConstrainedExecution/CriticalFinalizerObject.cs similarity index 100% rename from external/corert/src/System.Private.CoreLib/src/System/Runtime/ConstrainedExecution/CriticalFinalizerObject.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Runtime/ConstrainedExecution/CriticalFinalizerObject.cs diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ExternalException.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ExternalException.cs index 160fe301e8..ab5a84c08a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ExternalException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ExternalException.cs @@ -68,7 +68,7 @@ namespace System.Runtime.InteropServices string s = className + " (0x" + HResult.ToString("X8", CultureInfo.InvariantCulture) + ")"; - if (!(String.IsNullOrEmpty(message))) + if (!(string.IsNullOrEmpty(message))) { s = s + ": " + message; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/HandleRef.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/HandleRef.cs index 64d0553130..c81a701996 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/HandleRef.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/HandleRef.cs @@ -4,12 +4,12 @@ namespace System.Runtime.InteropServices { - public struct HandleRef + public readonly struct HandleRef { // ! Do not add or rearrange fields as the EE depends on this layout. //------------------------------------------------------------------ - private object _wrapper; - private IntPtr _handle; + private readonly object _wrapper; + private readonly IntPtr _handle; //------------------------------------------------------------------ public HandleRef(object wrapper, IntPtr handle) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MarshalDirectiveException.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MarshalDirectiveException.cs index 1d0d59fab6..3bb1140f5e 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MarshalDirectiveException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MarshalDirectiveException.cs @@ -27,13 +27,13 @@ namespace System.Runtime.InteropServices HResult = HResults.COR_E_MARSHALDIRECTIVE; } - public MarshalDirectiveException(String message) + public MarshalDirectiveException(string message) : base(message) { HResult = HResults.COR_E_MARSHALDIRECTIVE; } - public MarshalDirectiveException(String message, Exception inner) + public MarshalDirectiveException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_MARSHALDIRECTIVE; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.Fast.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.Fast.cs index 8a5bb75394..e3cf0a84e2 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.Fast.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.Fast.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Buffers; using System.Runtime.CompilerServices; -using System.Collections.Generic; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices @@ -15,8 +13,54 @@ namespace System.Runtime.InteropServices /// public static partial class MemoryMarshal { + /// + /// Casts a Span of one primitive type to Span of bytes. + /// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety. + /// + /// The source slice, of type . + /// + /// Thrown when contains pointers. + /// + /// + /// Thrown if the Length property of the new Span would exceed int.MaxValue. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span AsBytes(Span span) + where T : struct + { + if (RuntimeHelpers.IsReferenceOrContainsReferences()) + ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); + + return new Span( + ref Unsafe.As(ref GetReference(span)), + checked(span.Length * Unsafe.SizeOf())); + } + + /// + /// Casts a ReadOnlySpan of one primitive type to ReadOnlySpan of bytes. + /// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety. + /// + /// The source slice, of type . + /// + /// Thrown when contains pointers. + /// + /// + /// Thrown if the Length property of the new Span would exceed int.MaxValue. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ReadOnlySpan AsBytes(ReadOnlySpan span) + where T : struct + { + if (RuntimeHelpers.IsReferenceOrContainsReferences()) + ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); + + return new ReadOnlySpan( + ref Unsafe.As(ref GetReference(span)), + checked(span.Length * Unsafe.SizeOf())); + } + /// Creates a from a . - /// The . + /// The . /// A representing the same memory as the , but writable. /// /// must be used with extreme caution. is used @@ -24,33 +68,48 @@ namespace System.Runtime.InteropServices /// by should not be written to. The method exists to enable variables typed /// as but only used for reading to store a . /// - public static Memory AsMemory(ReadOnlyMemory readOnlyMemory) => - Unsafe.As, Memory>(ref readOnlyMemory); + public static Memory AsMemory(ReadOnlyMemory memory) => + Unsafe.As, Memory>(ref memory); /// /// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element - /// would have been stored. Such a reference can be used for pinning but must never be dereferenced. + /// would have been stored. Such a reference may or may not be null. It can be used for pinning but must never be dereferenced. /// public static ref T GetReference(Span span) => ref span._pointer.Value; /// - /// Returns a reference to the 0th element of the ReadOnlySpan. If the Span is empty, returns a reference to the location where the 0th element - /// would have been stored. Such a reference can be used for pinning but must never be dereferenced. + /// Returns a reference to the 0th element of the ReadOnlySpan. If the ReadOnlySpan is empty, returns a reference to the location where the 0th element + /// would have been stored. Such a reference may or may not be null. It can be used for pinning but must never be dereferenced. /// public static ref T GetReference(ReadOnlySpan span) => ref span._pointer.Value; + /// + /// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to fake non-null pointer. Such a reference can be used + /// for pinning but must never be dereferenced. This is useful for interop with methods that do not accept null pointers for zero-sized buffers. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static unsafe ref T GetNonNullPinnableReference(Span span) => ref (span.Length != 0) ? ref span._pointer.Value : ref Unsafe.AsRef((void*)1); + + /// + /// Returns a reference to the 0th element of the ReadOnlySpan. If the ReadOnlySpan is empty, returns a reference to fake non-null pointer. Such a reference + /// can be used for pinning but must never be dereferenced. This is useful for interop with methods that do not accept null pointers for zero-sized buffers. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static unsafe ref T GetNonNullPinnableReference(ReadOnlySpan span) => ref (span.Length != 0) ? ref span._pointer.Value : ref Unsafe.AsRef((void*)1); + /// /// Casts a Span of one primitive type to another primitive type . /// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// /// - /// Supported only for platforms that support misaligned memory access. + /// Supported only for platforms that support misaligned memory access or when the memory block is aligned by other means. /// - /// The source slice, of type . + /// The source slice, of type . /// /// Thrown when or contains pointers. /// - public static Span Cast(Span source) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span Cast(Span span) where TFrom : struct where TTo : struct { @@ -63,7 +122,7 @@ namespace System.Runtime.InteropServices // and checked casts are faster and smaller. uint fromSize = (uint)Unsafe.SizeOf(); uint toSize = (uint)Unsafe.SizeOf(); - uint fromLength = (uint)source.Length; + uint fromLength = (uint)span.Length; int toLength; if (fromSize == toSize) { @@ -89,7 +148,7 @@ namespace System.Runtime.InteropServices } return new Span( - ref Unsafe.As(ref source._pointer.Value), + ref Unsafe.As(ref span._pointer.Value), toLength); } @@ -98,13 +157,14 @@ namespace System.Runtime.InteropServices /// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// /// - /// Supported only for platforms that support misaligned memory access. + /// Supported only for platforms that support misaligned memory access or when the memory block is aligned by other means. /// - /// The source slice, of type . + /// The source slice, of type . /// /// Thrown when or contains pointers. /// - public static ReadOnlySpan Cast(ReadOnlySpan source) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ReadOnlySpan Cast(ReadOnlySpan span) where TFrom : struct where TTo : struct { @@ -117,7 +177,7 @@ namespace System.Runtime.InteropServices // and checked casts are faster and smaller. uint fromSize = (uint)Unsafe.SizeOf(); uint toSize = (uint)Unsafe.SizeOf(); - uint fromLength = (uint)source.Length; + uint fromLength = (uint)span.Length; int toLength; if (fromSize == toSize) { @@ -143,7 +203,7 @@ namespace System.Runtime.InteropServices } return new ReadOnlySpan( - ref Unsafe.As(ref MemoryMarshal.GetReference(source)), + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), toLength); } @@ -154,6 +214,7 @@ namespace System.Runtime.InteropServices /// /// A reference to data. /// The number of elements the memory contains. + /// The lifetime of the returned span will not be validated for safety by span-aware languages. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span CreateSpan(ref T reference, int length) => new Span(ref reference, length); @@ -164,6 +225,7 @@ namespace System.Runtime.InteropServices /// /// A reference to data. /// The number of elements the memory contains. + /// The lifetime of the returned span will not be validated for safety by span-aware languages. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan CreateReadOnlySpan(ref T reference, int length) => new ReadOnlySpan(ref reference, length); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.cs index 316ce12aab..fcc9c4f41a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.cs @@ -5,6 +5,9 @@ using System.Buffers; using System.Runtime.CompilerServices; using System.Collections.Generic; +using System.Diagnostics; + +using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices { @@ -18,72 +21,78 @@ namespace System.Runtime.InteropServices /// Get an array segment from the underlying memory. /// If unable to get the array segment, return false with a default array segment. /// - public static bool TryGetArray(ReadOnlyMemory readOnlyMemory, out ArraySegment arraySegment) + public static bool TryGetArray(ReadOnlyMemory memory, out ArraySegment segment) { - object obj = readOnlyMemory.GetObjectStartLength(out int index, out int length); + object obj = memory.GetObjectStartLength(out int index, out int length); if (index < 0) { - if (((OwnedMemory)obj).TryGetArray(out var segment)) + Debug.Assert(length >= 0); + if (((MemoryManager)obj).TryGetArray(out ArraySegment arraySegment)) { - arraySegment = new ArraySegment(segment.Array, segment.Offset + (index & ReadOnlyMemory.RemoveOwnedFlagBitMask), length); + segment = new ArraySegment(arraySegment.Array, arraySegment.Offset + (index & ReadOnlyMemory.RemoveFlagsBitMask), length); return true; } } else if (obj is T[] arr) { - arraySegment = new ArraySegment(arr, index, length); + segment = new ArraySegment(arr, index, length & ReadOnlyMemory.RemoveFlagsBitMask); return true; } - if (length == 0) + if ((length & ReadOnlyMemory.RemoveFlagsBitMask) == 0) { -#if FEATURE_PORTABLE_SPAN - arraySegment = new ArraySegment(SpanHelpers.PerTypeValues.EmptyArray); -#else - arraySegment = ArraySegment.Empty; -#endif // FEATURE_PORTABLE_SPAN + segment = ArraySegment.Empty; return true; } - arraySegment = default; + segment = default; return false; } /// - /// Gets an from the underlying readOnlyMemory. - /// If unable to get the type, returns false. + /// Gets an from the underlying read-only memory. + /// If unable to get the type, returns false. /// - /// The element type of the . - /// The type of to try and retrive. - /// The memory to get the owner for. - /// The returned owner of the . + /// The element type of the . + /// The type of to try and retrive. + /// The memory to get the manager for. + /// The returned manager of the . /// A indicating if it was successful. - public static bool TryGetOwnedMemory(ReadOnlyMemory readOnlyMemory, out TOwner ownedMemory) - where TOwner : OwnedMemory + public static bool TryGetMemoryManager(ReadOnlyMemory memory, out TManager manager) + where TManager : MemoryManager { - TOwner owner; // Use register for null comparison rather than byref - ownedMemory = owner = readOnlyMemory.GetObjectStartLength(out int index, out int length) as TOwner; - return !ReferenceEquals(owner, null); + TManager localManager; // Use register for null comparison rather than byref + manager = localManager = memory.GetObjectStartLength(out _, out _) as TManager; + return manager != null; } /// - /// Gets an and , from the underlying memory. - /// If unable to get the type, returns false. + /// Gets an and , from the underlying read-only memory. + /// If unable to get the type, returns false. /// - /// The element type of the . - /// The type of to try and retrive. - /// The memory to get the owner for. - /// The returned owner of the . - /// The offset from the start of the that the represents. - /// The length of the that the represents. + /// The element type of the . + /// The type of to try and retrive. + /// The memory to get the manager for. + /// The returned manager of the . + /// The offset from the start of the that the represents. + /// The length of the that the represents. /// A indicating if it was successful. - public static bool TryGetOwnedMemory(ReadOnlyMemory readOnlyMemory, out TOwner ownedMemory, out int index, out int length) - where TOwner : OwnedMemory + public static bool TryGetMemoryManager(ReadOnlyMemory memory, out TManager manager, out int start, out int length) + where TManager : MemoryManager { - TOwner owner; // Use register for null comparison rather than byref - ownedMemory = owner = readOnlyMemory.GetObjectStartLength(out index, out length) as TOwner; - index &= ReadOnlyMemory.RemoveOwnedFlagBitMask; - return !ReferenceEquals(owner, null); + TManager localManager; // Use register for null comparison rather than byref + manager = localManager = memory.GetObjectStartLength(out start, out length) as TManager; + start &= ReadOnlyMemory.RemoveFlagsBitMask; + + Debug.Assert(length >= 0); + + if (manager == null) + { + start = default; + length = default; + return false; + } + return true; } /// @@ -100,15 +109,17 @@ namespace System.Runtime.InteropServices } /// Attempts to get the underlying from a . - /// The memory that may be wrapping a object. + /// The memory that may be wrapping a object. /// The string. /// The starting location in . /// The number of items in . /// - public static bool TryGetString(ReadOnlyMemory readOnlyMemory, out string text, out int start, out int length) + public static bool TryGetString(ReadOnlyMemory memory, out string text, out int start, out int length) { - if (readOnlyMemory.GetObjectStartLength(out int offset, out int count) is string s) + if (memory.GetObjectStartLength(out int offset, out int count) is string s) { + Debug.Assert(offset >= 0); + Debug.Assert(count >= 0); text = s; start = offset; length = count; @@ -122,5 +133,159 @@ namespace System.Runtime.InteropServices return false; } } + + /// + /// Reads a structure of type T out of a read-only span of bytes. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T Read(ReadOnlySpan source) + where T : struct + { + if (RuntimeHelpers.IsReferenceOrContainsReferences()) + { + ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); + } + if (Unsafe.SizeOf() > source.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); + } + return Unsafe.ReadUnaligned(ref GetReference(source)); + } + + /// + /// Reads a structure of type T out of a span of bytes. + /// If the span is too small to contain the type T, return false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryRead(ReadOnlySpan source, out T value) + where T : struct + { + if (RuntimeHelpers.IsReferenceOrContainsReferences()) + { + ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); + } + if (Unsafe.SizeOf() > (uint)source.Length) + { + value = default; + return false; + } + value = Unsafe.ReadUnaligned(ref GetReference(source)); + return true; + } + + /// + /// Writes a structure of type T into a span of bytes. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Write(Span destination, ref T value) + where T : struct + { + if (RuntimeHelpers.IsReferenceOrContainsReferences()) + { + ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); + } + if ((uint)Unsafe.SizeOf() > (uint)destination.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); + } + Unsafe.WriteUnaligned(ref GetReference(destination), value); + } + + /// + /// Writes a structure of type T into a span of bytes. + /// If the span is too small to contain the type T, return false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryWrite(Span destination, ref T value) + where T : struct + { + if (RuntimeHelpers.IsReferenceOrContainsReferences()) + { + ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); + } + if (Unsafe.SizeOf() > (uint)destination.Length) + { + return false; + } + Unsafe.WriteUnaligned(ref GetReference(destination), value); + return true; + } + + /// + /// Re-interprets a span of bytes as a reference to structure of type T. + /// The type may not contain pointers or references. This is checked at runtime in order to preserve type safety. + /// + /// + /// Supported only for platforms that support misaligned memory access or when the memory block is aligned by other means. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref T AsRef(Span span) + where T : struct + { + if (RuntimeHelpers.IsReferenceOrContainsReferences()) + { + ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); + } + if (Unsafe.SizeOf() > (uint)span.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); + } + return ref Unsafe.As(ref GetReference(span)); + } + + /// + /// Re-interprets a span of bytes as a reference to structure of type T. + /// The type may not contain pointers or references. This is checked at runtime in order to preserve type safety. + /// + /// + /// Supported only for platforms that support misaligned memory access or when the memory block is aligned by other means. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref readonly T AsRef(ReadOnlySpan span) + where T : struct + { + if (RuntimeHelpers.IsReferenceOrContainsReferences()) + { + ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); + } + if (Unsafe.SizeOf() > (uint)span.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); + } + return ref Unsafe.As(ref GetReference(span)); + } + + /// + /// Creates a new memory over the portion of the pre-pinned target array beginning + /// at 'start' index and ending at 'end' index (exclusive). + /// + /// The pre-pinned target array. + /// The index at which to begin the memory. + /// The number of items in the memory. + /// This method should only be called on an array that is already pinned and + /// that array should not be unpinned while the returned Memory is still in use. + /// Calling this method on an unpinned array could result in memory corruption. + /// Returns default when is null. + /// Thrown when is covariant and array's type is not exactly T[]. + /// + /// Thrown when the specified or end index is not in the range (<0 or >=Length). + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Memory CreateFromPinnedArray(T[] array, int start, int length) + { + if (array == null) + { + if (start != 0 || length != 0) + ThrowHelper.ThrowArgumentOutOfRangeException(); + return default; + } + if (default(T) == null && array.GetType() != typeof(T[])) + ThrowHelper.ThrowArrayTypeMismatchException(); + if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + // Before using _length, check if _length < 0, then 'and' it with RemoveFlagsBitMask + return new Memory((object)array, start, length | (1 << 31)); + } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/NativeCallableAttribute.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/NativeCallableAttribute.cs new file mode 100644 index 0000000000..bad4d7f6ad --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/NativeCallableAttribute.cs @@ -0,0 +1,29 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Runtime.InteropServices +{ + /// + /// Any method marked with NativeCallableAttribute can be directly called from + /// native code. The function token can be loaded to a local variable using LDFTN + /// and passed as a callback to native method. + /// + [AttributeUsage(AttributeTargets.Method)] + public sealed class NativeCallableAttribute : Attribute + { + public NativeCallableAttribute() + { + } + + /// + /// Optional. If omitted, compiler will choose one for you. + /// + public CallingConvention CallingConvention; + + /// + /// Optional. If omitted, then the method is native callable, but no EAT is emitted. + /// + public string EntryPoint; + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeBuffer.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeBuffer.cs index 455e413928..661a7edcea 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeBuffer.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeBuffer.cs @@ -77,7 +77,7 @@ namespace System.Runtime.InteropServices { // Steal UIntPtr.MaxValue as our uninitialized value. private static readonly UIntPtr Uninitialized = (UIntPtr.Size == 4) ? - ((UIntPtr)UInt32.MaxValue) : ((UIntPtr)UInt64.MaxValue); + ((UIntPtr)uint.MaxValue) : ((UIntPtr)ulong.MaxValue); private UIntPtr _numBytes; @@ -94,7 +94,7 @@ namespace System.Runtime.InteropServices [CLSCompliant(false)] public void Initialize(ulong numBytes) { - if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue) + if (IntPtr.Size == 4 && numBytes > uint.MaxValue) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_AddressSpace); if (numBytes >= (ulong)Uninitialized) @@ -110,7 +110,7 @@ namespace System.Runtime.InteropServices [CLSCompliant(false)] public void Initialize(uint numElements, uint sizeOfEachElement) { - if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue) + if (IntPtr.Size == 4 && numElements * sizeOfEachElement > uint.MaxValue) throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace); if (numElements * sizeOfEachElement >= (ulong)Uninitialized) @@ -198,7 +198,7 @@ namespace System.Runtime.InteropServices SpaceCheck(ptr, sizeofT); // return *(T*) (_ptr + byteOffset); - T value = default(T); + T value = default; bool mustCallRelease = false; try { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Aes.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Aes.PlatformNotSupported.cs new file mode 100644 index 0000000000..0ad9634d19 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Aes.PlatformNotSupported.cs @@ -0,0 +1,40 @@ +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.Arm.Arm64 +{ + /// + /// This class provides access to the Arm64 AES Crypto intrinsics + /// + /// Arm64 CPU indicate support for this feature by setting + /// ID_AA64ISAR0_EL1.AES is 1 or better + /// + [CLSCompliant(false)] + public static class Aes + { + public static bool IsSupported { get { return false; } } + // + /// Performs AES single round decryption + /// vaesdq_u8 (uint8x16_t data, uint8x16_t key) + /// + public static Vector128 Decrypt(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } + + // + /// Performs AES single round encryption + /// vaeseq_u8 (uint8x16_t data, uint8x16_t key) + /// + public static Vector128 Encrypt(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } + + // + /// Performs AES Mix Columns + /// vaesmcq_u8 (uint8x16_t data) + /// + public static Vector128 MixColumns(Vector128 value) { throw new PlatformNotSupportedException(); } + + // + /// Performs AES inverse mix columns + /// vaesimcq_u8 (uint8x16_t data) + /// + public static Vector128 InverseMixColumns(Vector128 value) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Aes.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Aes.cs new file mode 100644 index 0000000000..24c9342d91 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Aes.cs @@ -0,0 +1,40 @@ +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.Arm.Arm64 +{ + /// + /// This class provides access to the Arm64 AES Crypto intrinsics + /// + /// Arm64 CPU indicate support for this feature by setting + /// ID_AA64ISAR0_EL1.AES is 1 or better + /// + [CLSCompliant(false)] + public static class Aes + { + public static bool IsSupported { get => IsSupported; } + // + /// Performs AES single round decryption + /// vaesdq_u8 (uint8x16_t data, uint8x16_t key) + /// + public static Vector128 Decrypt(Vector128 value, Vector128 roundKey) => Decrypt(value, roundKey); + + // + /// Performs AES single round encryption + /// vaeseq_u8 (uint8x16_t data, uint8x16_t key) + /// + public static Vector128 Encrypt(Vector128 value, Vector128 roundKey) => Encrypt(value, roundKey); + + // + /// Performs AES Mix Columns + /// vaesmcq_u8 (uint8x16_t data) + /// + public static Vector128 MixColumns(Vector128 value) => MixColumns(value); + + // + /// Performs AES inverse mix columns + /// vaesimcq_u8 (uint8x16_t data) + /// + public static Vector128 InverseMixColumns(Vector128 value) => InverseMixColumns(value); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Base.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Base.PlatformNotSupported.cs new file mode 100644 index 0000000000..0a13828ee0 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Base.PlatformNotSupported.cs @@ -0,0 +1,33 @@ +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + + +namespace System.Runtime.Intrinsics.Arm.Arm64 +{ + /// + /// This class provides access to the Arm64 Base intrinsics + /// + /// These intrinsics are supported by all Arm64 CPUs + /// + [CLSCompliant(false)] + public static class Base + { + public static bool IsSupported { get { return false; }} + + /// + /// Vector LeadingSignCount + /// Corresponds to integer forms of ARM64 CLS + /// + public static int LeadingSignCount(int value) { throw new PlatformNotSupportedException(); } + public static int LeadingSignCount(long value) { throw new PlatformNotSupportedException(); } + + /// + /// Vector LeadingZeroCount + /// Corresponds to integer forms of ARM64 CLZ + /// + public static int LeadingZeroCount(int value) { throw new PlatformNotSupportedException(); } + public static int LeadingZeroCount(uint value) { throw new PlatformNotSupportedException(); } + public static int LeadingZeroCount(long value) { throw new PlatformNotSupportedException(); } + public static int LeadingZeroCount(ulong value) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Base.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Base.cs new file mode 100644 index 0000000000..fc0a19055e --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Base.cs @@ -0,0 +1,33 @@ +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + + +namespace System.Runtime.Intrinsics.Arm.Arm64 +{ + /// + /// This class provides access to the Arm64 Base intrinsics + /// + /// These intrinsics are supported by all Arm64 CPUs + /// + [CLSCompliant(false)] + public static class Base + { + public static bool IsSupported { get { return false; }} + + /// + /// Vector LeadingSignCount + /// Corresponds to integer forms of ARM64 CLS + /// + public static int LeadingSignCount(int value) => LeadingSignCount(value); + public static int LeadingSignCount(long value) => LeadingSignCount(value); + + /// + /// Vector LeadingZeroCount + /// Corresponds to integer forms of ARM64 CLZ + /// + public static int LeadingZeroCount(int value) => LeadingZeroCount(value); + public static int LeadingZeroCount(uint value) => LeadingZeroCount(value); + public static int LeadingZeroCount(long value) => LeadingZeroCount(value); + public static int LeadingZeroCount(ulong value) => LeadingZeroCount(value); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Sha1.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Sha1.PlatformNotSupported.cs new file mode 100644 index 0000000000..9b6c5aac63 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Sha1.PlatformNotSupported.cs @@ -0,0 +1,54 @@ +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.Arm.Arm64 +{ + /// + /// This class provides access to the Arm64 SHA1 Crypto intrinsics + /// + /// Arm64 CPU indicate support for this feature by setting + /// ID_AA64ISAR0_EL1.SHA1 is 1 or better + /// + [CLSCompliant(false)] + public static class Sha1 + { + + public static bool IsSupported { get { return false; } } + + // + /// Performs SHA1 hash update choose form. + /// vsha1cq_u32 (uint32x4_t hash_abcd, uint32_t hash_e, uint32x4_t wk) + /// + public static Vector128 HashChoose(Vector128 hash_abcd, uint hash_e, Vector128wk) { throw new PlatformNotSupportedException(); } + + // + /// Performs SHA1 hash update majority form. + /// vsha1mq_u32 (uint32x4_t hash_abcd, uint32_t hash_e, uint32x4_t wk) + /// + public static Vector128 HashMajority(Vector128 hash_abcd, uint hash_e, Vector128wk) { throw new PlatformNotSupportedException(); } + + // + /// Performs SHA1 hash update parity form. + /// vsha1pq_u32 (uint32x4_t hash_abcd, uint32_t hash_e, uint32x4_t wk) + /// + public static Vector128 HashParity(Vector128 hash_abcd, uint hash_e, Vector128wk) { throw new PlatformNotSupportedException(); } + + // + /// Performs SHA1 fixed rotate + /// vsha1h_u32 (uint32_t hash_e) + /// + public static uint FixedRotate(uint hash_e) { throw new PlatformNotSupportedException(); } + + // + /// Performs SHA1 schedule update 0 + /// vsha1su0q_u32 (uint32x4_t w0_3, uint32x4_t w4_7, uint32x4_t w8_11) + /// + public static Vector128 SchedulePart1(Vector128 w0_3, Vector128 w4_7, Vector128 w8_11) { throw new PlatformNotSupportedException(); } + + // + /// Performs SHA1 schedule update 1 + /// vsha1su1q_u32 (uint32x4_t tw0_3, uint32x4_t w12_15) + /// + public static Vector128 SchedulePart2(Vector128 tw0_3, Vector128 w12_15) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Sha1.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Sha1.cs new file mode 100644 index 0000000000..28cc397ceb --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Sha1.cs @@ -0,0 +1,53 @@ +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.Arm.Arm64 +{ + /// + /// This class provides access to the Arm64 SHA1 Crypto intrinsics + /// + /// Arm64 CPU indicate support for this feature by setting + /// ID_AA64ISAR0_EL1.SHA1 is 1 or better + /// + [CLSCompliant(false)] + public static class Sha1 + { + public static bool IsSupported { get => IsSupported; } + + // + /// Performs SHA1 hash update choose form. + /// vsha1cq_u32 (uint32x4_t hash_abcd, uint32_t hash_e, uint32x4_t wk) + /// + public static Vector128 HashChoose(Vector128 hash_abcd, uint hash_e, Vector128wk) => HashChoose(hash_abcd, hash_e, wk); + + // + /// Performs SHA1 hash update majority form. + /// vsha1mq_u32 (uint32x4_t hash_abcd, uint32_t hash_e, uint32x4_t wk) + /// + public static Vector128 HashMajority(Vector128 hash_abcd, uint hash_e, Vector128wk) => HashMajority(hash_abcd, hash_e, wk); + + // + /// Performs SHA1 hash update parity form. + /// vsha1pq_u32 (uint32x4_t hash_abcd, uint32_t hash_e, uint32x4_t wk) + /// + public static Vector128 HashParity(Vector128 hash_abcd, uint hash_e, Vector128wk) => HashParity(hash_abcd, hash_e, wk); + + // + /// Performs SHA1 fixed rotate + /// vsha1h_u32 (uint32_t hash_e) + /// + public static uint FixedRotate(uint hash_e) => FixedRotate(hash_e); + + // + /// Performs SHA1 schedule update 0 + /// vsha1su0q_u32 (uint32x4_t w0_3, uint32x4_t w4_7, uint32x4_t w8_11) + /// + public static Vector128 SchedulePart1(Vector128 w0_3, Vector128 w4_7, Vector128 w8_11) => SchedulePart1(w0_3, w4_7, w8_11); + + // + /// Performs SHA1 schedule update 1 + /// vsha1su1q_u32 (uint32x4_t tw0_3, uint32x4_t w12_15) + /// + public static Vector128 SchedulePart2(Vector128 tw0_3, Vector128 w12_15) => SchedulePart2(tw0_3, w12_15); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Sha256.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Sha256.PlatformNotSupported.cs new file mode 100644 index 0000000000..052a1d236b --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Sha256.PlatformNotSupported.cs @@ -0,0 +1,41 @@ +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.Arm.Arm64 +{ + /// + /// This class provides access to the Arm64 SHA256 Crypto intrinsics + /// + /// Arm64 CPU indicate support for this feature by setting + /// ID_AA64ISAR0_EL1.SHA2 is 1 or better + /// + [CLSCompliant(false)] + public static class Sha256 + { + public static bool IsSupported { get { return false; } } + + // + /// Performs SHA256 hash update (part 1). + /// vsha256hq_u32 (uint32x4_t hash_abcd, uint32x4_t hash_efgh, uint32x4_t wk) + /// + public static Vector128 HashLower(Vector128 hash_abcd, Vector128 hash_efgh, Vector128 wk) { throw new PlatformNotSupportedException(); } + + // + /// Performs SHA256 hash update (part 2). + /// vsha256h2q_u32 (uint32x4_t hash_efgh, uint32x4_t hash_abcd, uint32x4_t wk) + /// + public static Vector128 HashUpper(Vector128 hash_efgh, Vector128 hash_abcd, Vector128 wk) { throw new PlatformNotSupportedException(); } + + // + /// Performs SHA256 schedule update 0 + /// vsha256su0q_u32 (uint32x4_t w0_3, uint32x4_t w4_7) + /// + public static Vector128 SchedulePart1(Vector128 w0_3, Vector128 w4_7) { throw new PlatformNotSupportedException(); } + + // + /// Performs SHA256 schedule update 1 + /// vsha256su1q_u32 (uint32x4_t w0_3, uint32x4_t w8_11, uint32x4_t w12_15) + /// + public static Vector128 SchedulePart2(Vector128 w0_3, Vector128 w8_11, Vector128 w12_15) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Sha256.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Sha256.cs new file mode 100644 index 0000000000..4e7e51db30 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Sha256.cs @@ -0,0 +1,41 @@ +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.Arm.Arm64 +{ + /// + /// This class provides access to the Arm64 SHA256 Crypto intrinsics + /// + /// Arm64 CPU indicate support for this feature by setting + /// ID_AA64ISAR0_EL1.SHA2 is 1 or better + /// + [CLSCompliant(false)] + public static class Sha256 + { + public static bool IsSupported { get => IsSupported; } + + // + /// Performs SHA256 hash update (part 1). + /// vsha256hq_u32 (uint32x4_t hash_abcd, uint32x4_t hash_efgh, uint32x4_t wk) + /// + public static Vector128 HashLower(Vector128 hash_abcd, Vector128 hash_efgh, Vector128 wk) => HashLower(hash_abcd, hash_efgh, wk); + + // + /// Performs SHA256 hash update (part 2). + /// vsha256h2q_u32 (uint32x4_t hash_efgh, uint32x4_t hash_abcd, uint32x4_t wk) + /// + public static Vector128 HashUpper(Vector128 hash_efgh, Vector128 hash_abcd, Vector128 wk) => HashUpper(hash_efgh, hash_abcd, wk); + + // + /// Performs SHA256 schedule update 0 + /// vsha256su0q_u32 (uint32x4_t w0_3, uint32x4_t w4_7) + /// + public static Vector128 SchedulePart1(Vector128 w0_3, Vector128 w4_7) => SchedulePart1(w0_3, w4_7); + + // + /// Performs SHA256 schedule update 1 + /// vsha256su1q_u32 (uint32x4_t tw0_3, uint32x4_t w8_11, uint32x4_t w12_15) + /// + public static Vector128 SchedulePart2(Vector128 w0_3, Vector128 w8_11, Vector128 w12_15) => SchedulePart2(w0_3, w8_11, w12_15); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Simd.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Simd.PlatformNotSupported.cs new file mode 100644 index 0000000000..4b377902c7 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Simd.PlatformNotSupported.cs @@ -0,0 +1,344 @@ +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + + +namespace System.Runtime.Intrinsics.Arm.Arm64 +{ + /// + /// This class provides access to the Arm64 AdvSIMD intrinsics + /// + /// Arm64 CPU indicate support for this feature by setting + /// ID_AA64PFR0_EL1.AdvSIMD == 0 or better. + /// + [CLSCompliant(false)] + public static class Simd + { + /// + /// IsSupported property indicates whether any method provided + /// by this class is supported by the current runtime. + /// + public static bool IsSupported { get { return false; }} + + /// + /// Vector abs + /// Corresponds to vector forms of ARM64 ABS & FABS + /// + public static Vector64 Abs(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector64 Abs(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector64 Abs(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector64 Abs(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// Vector add + /// Corresponds to vector forms of ARM64 ADD & FADD + /// + public static Vector64 Add(Vector64 left, Vector64 right) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 Add(Vector128 left, Vector128 right) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector and + /// Corresponds to vector forms of ARM64 AND + /// + public static Vector64 And(Vector64 left, Vector64 right) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 And(Vector128 left, Vector128 right) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector and not + /// Corresponds to vector forms of ARM64 BIC + /// + public static Vector64 AndNot(Vector64 left, Vector64 right) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 AndNot(Vector128 left, Vector128 right) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector BitwiseSelect + /// For each bit in the vector result[bit] = sel[bit] ? left[bit] : right[bit] + /// Corresponds to vector forms of ARM64 BSL (Also BIF & BIT) + /// + public static Vector64 BitwiseSelect(Vector64 sel, Vector64 left, Vector64 right) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 BitwiseSelect(Vector128 sel, Vector128 left, Vector128 right) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector CompareEqual + /// For each element result[elem] = (left[elem] == right[elem]) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMEQ & FCMEQ + /// + public static Vector64 CompareEqual(Vector64 left, Vector64 right) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 CompareEqual(Vector128 left, Vector128 right) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector CompareEqualZero + /// For each element result[elem] = (left[elem] == 0) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMEQ & FCMEQ + /// + public static Vector64 CompareEqualZero(Vector64 value) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 CompareEqualZero(Vector128 value) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector CompareGreaterThan + /// For each element result[elem] = (left[elem] > right[elem]) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMGT/CMHI & FCMGT + /// + public static Vector64 CompareGreaterThan(Vector64 left, Vector64 right) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector CompareGreaterThanZero + /// For each element result[elem] = (left[elem] > 0) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMGT & FCMGT + /// + public static Vector64 CompareGreaterThanZero(Vector64 value) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 CompareGreaterThanZero(Vector128 value) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector CompareGreaterThanOrEqual + /// For each element result[elem] = (left[elem] >= right[elem]) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMGE/CMHS & FCMGE + /// + public static Vector64 CompareGreaterThanOrEqual(Vector64 left, Vector64 right) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector CompareGreaterThanOrEqualZero + /// For each element result[elem] = (left[elem] >= 0) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMGE & FCMGE + /// + public static Vector64 CompareGreaterThanOrEqualZero(Vector64 value) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 CompareGreaterThanOrEqualZero(Vector128 value) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector CompareLessThanZero + /// For each element result[elem] = (left[elem] < 0) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMGT & FCMGT + /// + public static Vector64 CompareLessThanZero(Vector64 value) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 CompareLessThanZero(Vector128 value) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector CompareLessThanOrEqualZero + /// For each element result[elem] = (left[elem] < 0) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMGT & FCMGT + /// + public static Vector64 CompareLessThanOrEqualZero(Vector64 value) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 CompareLessThanOrEqualZero(Vector128 value) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector CompareTest + /// For each element result[elem] = (left[elem] & right[elem]) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMTST + /// + public static Vector64 CompareTest(Vector64 left, Vector64 right) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 CompareTest(Vector128 left, Vector128 right) where T : struct { throw new PlatformNotSupportedException(); } + + /// TBD Convert... + + /// + /// Vector Divide + /// Corresponds to vector forms of ARM64 FDIV + /// + public static Vector64 Divide(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Divide(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Divide(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// Vector extract item + /// + /// result = vector[index] + /// + /// Note: In order to be inlined, index must be a JIT time const expression which can be used to + /// populate the literal immediate field. Use of a non constant will result in generation of a switch table + /// + /// Corresponds to vector forms of ARM64 MOV + /// + public static T Extract(Vector64 vector, byte index) where T : struct { throw new PlatformNotSupportedException(); } + public static T Extract(Vector128 vector, byte index) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector insert item + /// + /// result = vector; + /// result[index] = data; + /// + /// Note: In order to be inlined, index must be a JIT time const expression which can be used to + /// populate the literal immediate field. Use of a non constant will result in generation of a switch table + /// + /// Corresponds to vector forms of ARM64 INS + /// + public static Vector64 Insert(Vector64 vector, byte index, T data) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 Insert(Vector128 vector, byte index, T data) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector LeadingSignCount + /// Corresponds to vector forms of ARM64 CLS + /// + public static Vector64 LeadingSignCount(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector64 LeadingSignCount(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector64 LeadingSignCount(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector128 LeadingSignCount(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 LeadingSignCount(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 LeadingSignCount(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// Vector LeadingZeroCount + /// Corresponds to vector forms of ARM64 CLZ + /// + public static Vector64 LeadingZeroCount(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector64 LeadingZeroCount(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector64 LeadingZeroCount(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector64 LeadingZeroCount(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector64 LeadingZeroCount(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector64 LeadingZeroCount(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector128 LeadingZeroCount(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 LeadingZeroCount(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 LeadingZeroCount(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 LeadingZeroCount(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 LeadingZeroCount(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 LeadingZeroCount(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// Vector max + /// Corresponds to vector forms of ARM64 SMAX, UMAX & FMAX + /// + public static Vector64 Max(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Max(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Max(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Max(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Max(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Max(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Max(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// Vector min + /// Corresponds to vector forms of ARM64 SMIN, UMIN & FMIN + /// + public static Vector64 Min(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Min(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Min(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Min(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Min(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Min(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Min(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// TBD MOV, FMOV + + /// + /// Vector multiply + /// + /// For each element result[elem] = left[elem] * right[elem] + /// + /// Corresponds to vector forms of ARM64 MUL & FMUL + /// + public static Vector64 Multiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Multiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Multiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Multiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Multiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Multiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector64 Multiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// Vector negate + /// Corresponds to vector forms of ARM64 NEG & FNEG + /// + public static Vector64 Negate(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector64 Negate(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector64 Negate(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector64 Negate(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector128 Negate(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 Negate(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 Negate(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 Negate(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 Negate(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 Negate(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// Vector not + /// Corresponds to vector forms of ARM64 NOT + /// + public static Vector64 Not(Vector64 value) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 Not(Vector128 value) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector or + /// Corresponds to vector forms of ARM64 ORR + /// + public static Vector64 Or(Vector64 left, Vector64 right) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 Or(Vector128 left, Vector128 right) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector or not + /// Corresponds to vector forms of ARM64 ORN + /// + public static Vector64 OrNot(Vector64 left, Vector64 right) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 OrNot(Vector128 left, Vector128 right) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector PopCount + /// Corresponds to vector forms of ARM64 CNT + /// + public static Vector64 PopCount(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector64 PopCount(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector128 PopCount(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 PopCount(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// SetVector* Fill vector elements by replicating element value + /// + /// Corresponds to vector forms of ARM64 DUP (general), DUP (element 0), FMOV (vector, immediate) + /// + public static Vector64 SetAllVector64(T value) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 SetAllVector128(T value) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// Vector square root + /// Corresponds to vector forms of ARM64 FRSQRT + /// + public static Vector64 Sqrt(Vector64 value) { throw new PlatformNotSupportedException(); } + public static Vector128 Sqrt(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 Sqrt(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// Vector subtract + /// Corresponds to vector forms of ARM64 SUB & FSUB + /// + public static Vector64 Subtract(Vector64 left, Vector64 right) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 Subtract(Vector128 left, Vector128 right) where T : struct { throw new PlatformNotSupportedException(); } + + + /// + /// Vector exclusive or + /// Corresponds to vector forms of ARM64 EOR + /// + public static Vector64 Xor(Vector64 left, Vector64 right) where T : struct { throw new PlatformNotSupportedException(); } + public static Vector128 Xor(Vector128 left, Vector128 right) where T : struct { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Simd.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Simd.cs new file mode 100644 index 0000000000..f162483daf --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Arm/Arm64/Simd.cs @@ -0,0 +1,344 @@ +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + + +namespace System.Runtime.Intrinsics.Arm.Arm64 +{ + /// + /// This class provides access to the Arm64 AdvSIMD intrinsics + /// + /// Arm64 CPU indicate support for this feature by setting + /// ID_AA64PFR0_EL1.AdvSIMD == 0 or better. + /// + [CLSCompliant(false)] + public static class Simd + { + /// + /// IsSupported property indicates whether any method provided + /// by this class is supported by the current runtime. + /// + public static bool IsSupported { get => IsSupported; } + + /// + /// Vector abs + /// Corresponds to vector forms of ARM64 ABS & FABS + /// + public static Vector64 Abs(Vector64 value) => Abs(value); + public static Vector64 Abs(Vector64 value) => Abs(value); + public static Vector64 Abs(Vector64 value) => Abs(value); + public static Vector64 Abs(Vector64 value) => Abs(value); + public static Vector128 Abs(Vector128 value) => Abs(value); + public static Vector128 Abs(Vector128 value) => Abs(value); + public static Vector128 Abs(Vector128 value) => Abs(value); + public static Vector128 Abs(Vector128 value) => Abs(value); + public static Vector128 Abs(Vector128 value) => Abs(value); + public static Vector128 Abs(Vector128 value) => Abs(value); + + /// + /// Vector add + /// Corresponds to vector forms of ARM64 ADD & FADD + /// + public static Vector64 Add(Vector64 left, Vector64 right) where T : struct => Add(left, right); + public static Vector128 Add(Vector128 left, Vector128 right) where T : struct => Add(left, right); + + /// + /// Vector and + /// Corresponds to vector forms of ARM64 AND + /// + public static Vector64 And(Vector64 left, Vector64 right) where T : struct => And(left, right); + public static Vector128 And(Vector128 left, Vector128 right) where T : struct => And(left, right); + + /// + /// Vector and not + /// Corresponds to vector forms of ARM64 BIC + /// + public static Vector64 AndNot(Vector64 left, Vector64 right) where T : struct => AndNot(left, right); + public static Vector128 AndNot(Vector128 left, Vector128 right) where T : struct => AndNot(left, right); + + /// + /// Vector BitwiseSelect + /// For each bit in the vector result[bit] = sel[bit] ? left[bit] : right[bit] + /// Corresponds to vector forms of ARM64 BSL (Also BIF & BIT) + /// + public static Vector64 BitwiseSelect(Vector64 sel, Vector64 left, Vector64 right) where T : struct => BitwiseSelect(sel, left, right); + public static Vector128 BitwiseSelect(Vector128 sel, Vector128 left, Vector128 right) where T : struct => BitwiseSelect(sel, left, right); + + /// + /// Vector CompareEqual + /// For each element result[elem] = (left[elem] == right[elem]) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMEQ & FCMEQ + /// + public static Vector64 CompareEqual(Vector64 left, Vector64 right) where T : struct => CompareEqual(left, right); + public static Vector128 CompareEqual(Vector128 left, Vector128 right) where T : struct => CompareEqual(left, right); + + /// + /// Vector CompareEqualZero + /// For each element result[elem] = (left[elem] == 0) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMEQ & FCMEQ + /// + public static Vector64 CompareEqualZero(Vector64 value) where T : struct => CompareEqualZero(value); + public static Vector128 CompareEqualZero(Vector128 value) where T : struct => CompareEqualZero(value); + + /// + /// Vector CompareGreaterThan + /// For each element result[elem] = (left[elem] > right[elem]) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMGT/CMHI & FCMGT + /// + public static Vector64 CompareGreaterThan(Vector64 left, Vector64 right) where T : struct => CompareGreaterThan(left, right); + public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) where T : struct => CompareGreaterThan(left, right); + + /// + /// Vector CompareGreaterThanZero + /// For each element result[elem] = (left[elem] > 0) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMGT & FCMGT + /// + public static Vector64 CompareGreaterThanZero(Vector64 value) where T : struct => CompareGreaterThanZero(value); + public static Vector128 CompareGreaterThanZero(Vector128 value) where T : struct => CompareGreaterThanZero(value); + + /// + /// Vector CompareGreaterThanOrEqual + /// For each element result[elem] = (left[elem] >= right[elem]) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMGE/CMHS & FCMGE + /// + public static Vector64 CompareGreaterThanOrEqual(Vector64 left, Vector64 right) where T : struct => CompareGreaterThanOrEqual(left, right); + public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) where T : struct => CompareGreaterThanOrEqual(left, right); + + /// + /// Vector CompareGreaterThanOrEqualZero + /// For each element result[elem] = (left[elem] >= 0) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMGE & FCMGE + /// + public static Vector64 CompareGreaterThanOrEqualZero(Vector64 value) where T : struct => CompareGreaterThanOrEqualZero(value); + public static Vector128 CompareGreaterThanOrEqualZero(Vector128 value) where T : struct => CompareGreaterThanOrEqualZero(value); + + /// + /// Vector CompareLessThanZero + /// For each element result[elem] = (left[elem] < 0) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMGT & FCMGT + /// + public static Vector64 CompareLessThanZero(Vector64 value) where T : struct => CompareLessThanZero(value); + public static Vector128 CompareLessThanZero(Vector128 value) where T : struct => CompareLessThanZero(value); + + /// + /// Vector CompareLessThanOrEqualZero + /// For each element result[elem] = (left[elem] < 0) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMGT & FCMGT + /// + public static Vector64 CompareLessThanOrEqualZero(Vector64 value) where T : struct => CompareLessThanOrEqualZero(value); + public static Vector128 CompareLessThanOrEqualZero(Vector128 value) where T : struct => CompareLessThanOrEqualZero(value); + + /// + /// Vector CompareTest + /// For each element result[elem] = (left[elem] & right[elem]) ? ~0 : 0 + /// Corresponds to vector forms of ARM64 CMTST + /// + public static Vector64 CompareTest(Vector64 left, Vector64 right) where T : struct => CompareTest(left, right); + public static Vector128 CompareTest(Vector128 left, Vector128 right) where T : struct => CompareTest(left, right); + + /// TBD Convert... + + /// + /// Vector Divide + /// Corresponds to vector forms of ARM64 FDIV + /// + public static Vector64 Divide(Vector64 left, Vector64 right) => Divide(left, right); + public static Vector128 Divide(Vector128 left, Vector128 right) => Divide(left, right); + public static Vector128 Divide(Vector128 left, Vector128 right) => Divide(left, right); + + /// + /// Vector extract item + /// + /// result = vector[index] + /// + /// Note: In order to be inlined, index must be a JIT time const expression which can be used to + /// populate the literal immediate field. Use of a non constant will result in generation of a switch table + /// + /// Corresponds to vector forms of ARM64 MOV + /// + public static T Extract(Vector64 vector, byte index) where T : struct => Extract(vector, index); + public static T Extract(Vector128 vector, byte index) where T : struct => Extract(vector, index); + + /// + /// Vector insert item + /// + /// result = vector; + /// result[index] = data; + /// + /// Note: In order to be inlined, index must be a JIT time const expression which can be used to + /// populate the literal immediate field. Use of a non constant will result in generation of a switch table + /// + /// Corresponds to vector forms of ARM64 INS + /// + public static Vector64 Insert(Vector64 vector, byte index, T data) where T : struct => Insert(vector, index, data); + public static Vector128 Insert(Vector128 vector, byte index, T data) where T : struct => Insert(vector, index, data); + + /// + /// Vector LeadingSignCount + /// Corresponds to vector forms of ARM64 CLS + /// + public static Vector64 LeadingSignCount(Vector64 value) => LeadingSignCount(value); + public static Vector64 LeadingSignCount(Vector64 value) => LeadingSignCount(value); + public static Vector64 LeadingSignCount(Vector64 value) => LeadingSignCount(value); + public static Vector128 LeadingSignCount(Vector128 value) => LeadingSignCount(value); + public static Vector128 LeadingSignCount(Vector128 value) => LeadingSignCount(value); + public static Vector128 LeadingSignCount(Vector128 value) => LeadingSignCount(value); + + /// + /// Vector LeadingZeroCount + /// Corresponds to vector forms of ARM64 CLZ + /// + public static Vector64 LeadingZeroCount(Vector64 value) => LeadingZeroCount(value); + public static Vector64 LeadingZeroCount(Vector64 value) => LeadingZeroCount(value); + public static Vector64 LeadingZeroCount(Vector64 value) => LeadingZeroCount(value); + public static Vector64 LeadingZeroCount(Vector64 value) => LeadingZeroCount(value); + public static Vector64 LeadingZeroCount(Vector64 value) => LeadingZeroCount(value); + public static Vector64 LeadingZeroCount(Vector64 value) => LeadingZeroCount(value); + public static Vector128 LeadingZeroCount(Vector128 value) => LeadingZeroCount(value); + public static Vector128 LeadingZeroCount(Vector128 value) => LeadingZeroCount(value); + public static Vector128 LeadingZeroCount(Vector128 value) => LeadingZeroCount(value); + public static Vector128 LeadingZeroCount(Vector128 value) => LeadingZeroCount(value); + public static Vector128 LeadingZeroCount(Vector128 value) => LeadingZeroCount(value); + public static Vector128 LeadingZeroCount(Vector128 value) => LeadingZeroCount(value); + + /// + /// Vector max + /// Corresponds to vector forms of ARM64 SMAX, UMAX & FMAX + /// + public static Vector64 Max(Vector64 left, Vector64 right) => Max(left, right); + public static Vector64 Max(Vector64 left, Vector64 right) => Max(left, right); + public static Vector64 Max(Vector64 left, Vector64 right) => Max(left, right); + public static Vector64 Max(Vector64 left, Vector64 right) => Max(left, right); + public static Vector64 Max(Vector64 left, Vector64 right) => Max(left, right); + public static Vector64 Max(Vector64 left, Vector64 right) => Max(left, right); + public static Vector64 Max(Vector64 left, Vector64 right) => Max(left, right); + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + + /// + /// Vector min + /// Corresponds to vector forms of ARM64 SMIN, UMIN & FMIN + /// + public static Vector64 Min(Vector64 left, Vector64 right) => Min(left, right); + public static Vector64 Min(Vector64 left, Vector64 right) => Min(left, right); + public static Vector64 Min(Vector64 left, Vector64 right) => Min(left, right); + public static Vector64 Min(Vector64 left, Vector64 right) => Min(left, right); + public static Vector64 Min(Vector64 left, Vector64 right) => Min(left, right); + public static Vector64 Min(Vector64 left, Vector64 right) => Min(left, right); + public static Vector64 Min(Vector64 left, Vector64 right) => Min(left, right); + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + + /// TBD MOV, FMOV + + /// + /// Vector multiply + /// + /// For each element result[elem] = left[elem] * right[elem] + /// + /// Corresponds to vector forms of ARM64 MUL & FMUL + /// + public static Vector64 Multiply(Vector64 left, Vector64 right) => Multiply(left, right); + public static Vector64 Multiply(Vector64 left, Vector64 right) => Multiply(left, right); + public static Vector64 Multiply(Vector64 left, Vector64 right) => Multiply(left, right); + public static Vector64 Multiply(Vector64 left, Vector64 right) => Multiply(left, right); + public static Vector64 Multiply(Vector64 left, Vector64 right) => Multiply(left, right); + public static Vector64 Multiply(Vector64 left, Vector64 right) => Multiply(left, right); + public static Vector64 Multiply(Vector64 left, Vector64 right) => Multiply(left, right); + public static Vector128 Multiply(Vector128 left, Vector128 right) => Multiply(left, right); + public static Vector128 Multiply(Vector128 left, Vector128 right) => Multiply(left, right); + public static Vector128 Multiply(Vector128 left, Vector128 right) => Multiply(left, right); + public static Vector128 Multiply(Vector128 left, Vector128 right) => Multiply(left, right); + public static Vector128 Multiply(Vector128 left, Vector128 right) => Multiply(left, right); + public static Vector128 Multiply(Vector128 left, Vector128 right) => Multiply(left, right); + public static Vector128 Multiply(Vector128 left, Vector128 right) => Multiply(left, right); + public static Vector128 Multiply(Vector128 left, Vector128 right) => Multiply(left, right); + + /// + /// Vector negate + /// Corresponds to vector forms of ARM64 NEG & FNEG + /// + public static Vector64 Negate(Vector64 value) => Negate(value); + public static Vector64 Negate(Vector64 value) => Negate(value); + public static Vector64 Negate(Vector64 value) => Negate(value); + public static Vector64 Negate(Vector64 value) => Negate(value); + public static Vector128 Negate(Vector128 value) => Negate(value); + public static Vector128 Negate(Vector128 value) => Negate(value); + public static Vector128 Negate(Vector128 value) => Negate(value); + public static Vector128 Negate(Vector128 value) => Negate(value); + public static Vector128 Negate(Vector128 value) => Negate(value); + public static Vector128 Negate(Vector128 value) => Negate(value); + + /// + /// Vector not + /// Corresponds to vector forms of ARM64 NOT + /// + public static Vector64 Not(Vector64 value) where T : struct => Not(value); + public static Vector128 Not(Vector128 value) where T : struct => Not(value); + + /// + /// Vector or + /// Corresponds to vector forms of ARM64 ORR + /// + public static Vector64 Or(Vector64 left, Vector64 right) where T : struct => Or(left, right); + public static Vector128 Or(Vector128 left, Vector128 right) where T : struct => Or(left, right); + + /// + /// Vector or not + /// Corresponds to vector forms of ARM64 ORN + /// + public static Vector64 OrNot(Vector64 left, Vector64 right) where T : struct => OrNot(left, right); + public static Vector128 OrNot(Vector128 left, Vector128 right) where T : struct => OrNot(left, right); + + /// + /// Vector PopCount + /// Corresponds to vector forms of ARM64 CNT + /// + public static Vector64 PopCount(Vector64 value) => PopCount(value); + public static Vector64 PopCount(Vector64 value) => PopCount(value); + public static Vector128 PopCount(Vector128 value) => PopCount(value); + public static Vector128 PopCount(Vector128 value) => PopCount(value); + + /// + /// SetVector* Fill vector elements by replicating element value + /// + /// Corresponds to vector forms of ARM64 DUP (general), DUP (element 0), FMOV (vector, immediate) + /// + public static Vector64 SetAllVector64(T value) where T : struct => SetAllVector64(value); + public static Vector128 SetAllVector128(T value) where T : struct => SetAllVector128(value); + + /// + /// Vector square root + /// Corresponds to vector forms of ARM64 FRSQRT + /// + public static Vector64 Sqrt(Vector64 value) => Sqrt(value); + public static Vector128 Sqrt(Vector128 value) => Sqrt(value); + public static Vector128 Sqrt(Vector128 value) => Sqrt(value); + + /// + /// Vector subtract + /// Corresponds to vector forms of ARM64 SUB & FSUB + /// + public static Vector64 Subtract(Vector64 left, Vector64 right) where T : struct => Subtract(left, right); + public static Vector128 Subtract(Vector128 left, Vector128 right) where T : struct => Subtract(left, right); + + + /// + /// Vector exclusive or + /// Corresponds to vector forms of ARM64 EOR + /// + public static Vector64 Xor(Vector64 left, Vector64 right) where T : struct => Xor(left, right); + public static Vector128 Xor(Vector128 left, Vector128 right) where T : struct => Xor(left, right); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector128.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector128.cs new file mode 100644 index 0000000000..b2e72ddf89 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector128.cs @@ -0,0 +1,44 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Internal.Runtime.CompilerServices; + +namespace System.Runtime.Intrinsics +{ + [Intrinsic] + [DebuggerDisplay("{DisplayString,nq}")] + [DebuggerTypeProxy(typeof(Vector128DebugView<>))] + [StructLayout(LayoutKind.Sequential, Size = 16)] + public readonly struct Vector128 where T : struct + { + // These fields exist to ensure the alignment is 8, rather than 1. + // This also allows the debug view to work https://github.com/dotnet/coreclr/issues/15694) + private readonly ulong _00; + private readonly ulong _01; + + private unsafe string DisplayString + { + get + { + // The IsPrimitive check ends up working for `bool`, `char`, `IntPtr`, and `UIntPtr` + // which are not actually supported by any current architecture. This shouldn't be + // an issue however and greatly simplifies the check + + if (typeof(T).IsPrimitive) + { + var items = new T[16 / Unsafe.SizeOf()]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), this); + return $"({string.Join(", ", items)})"; + } + else + { + return SR.NotSupported_Type; + } + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector128DebugView.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector128DebugView.cs new file mode 100644 index 0000000000..ccdc655949 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector128DebugView.cs @@ -0,0 +1,118 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.Runtime.CompilerServices; + +namespace System.Runtime.Intrinsics +{ + internal readonly struct Vector128DebugView where T : struct + { + private readonly Vector128 _value; + + public Vector128DebugView(Vector128 value) + { + _value = value; + } + + public byte[] ByteView + { + get + { + var items = new byte[16]; + Unsafe.WriteUnaligned(ref items[0], _value); + return items; + } + } + + public double[] DoubleView + { + get + { + var items = new double[2]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public short[] Int16View + { + get + { + var items = new short[8]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public int[] Int32View + { + get + { + var items = new int[4]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public long[] Int64View + { + get + { + var items = new long[2]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public sbyte[] SByteView + { + get + { + var items = new sbyte[16]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public float[] SingleView + { + get + { + var items = new float[4]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public ushort[] UInt16View + { + get + { + var items = new ushort[8]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public uint[] UInt32View + { + get + { + var items = new uint[4]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public ulong[] UInt64View + { + get + { + var items = new ulong[2]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector256.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector256.cs new file mode 100644 index 0000000000..48744bb5ea --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector256.cs @@ -0,0 +1,46 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Internal.Runtime.CompilerServices; + +namespace System.Runtime.Intrinsics +{ + [Intrinsic] + [DebuggerDisplay("{DisplayString,nq}")] + [DebuggerTypeProxy(typeof(Vector256DebugView<>))] + [StructLayout(LayoutKind.Sequential, Size = 32)] + public readonly struct Vector256 where T : struct + { + // These fields exist to ensure the alignment is 8, rather than 1. + // This also allows the debug view to work https://github.com/dotnet/coreclr/issues/15694) + private readonly ulong _00; + private readonly ulong _01; + private readonly ulong _02; + private readonly ulong _03; + + private unsafe string DisplayString + { + get + { + // The IsPrimitive check ends up working for `bool`, `char`, `IntPtr`, and `UIntPtr` + // which are not actually supported by any current architecture. This shouldn't be + // an issue however and greatly simplifies the check + + if (typeof(T).IsPrimitive) + { + var items = new T[32 / Unsafe.SizeOf()]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), this); + return $"({string.Join(", ", items)})"; + } + else + { + return SR.NotSupported_Type; + } + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector256DebugView.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector256DebugView.cs new file mode 100644 index 0000000000..5131341ad8 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector256DebugView.cs @@ -0,0 +1,118 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.Runtime.CompilerServices; + +namespace System.Runtime.Intrinsics +{ + internal readonly struct Vector256DebugView where T : struct + { + private readonly Vector256 _value; + + public Vector256DebugView(Vector256 value) + { + _value = value; + } + + public byte[] ByteView + { + get + { + var items = new byte[32]; + Unsafe.WriteUnaligned(ref items[0], _value); + return items; + } + } + + public double[] DoubleView + { + get + { + var items = new double[4]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public short[] Int16View + { + get + { + var items = new short[16]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public int[] Int32View + { + get + { + var items = new int[8]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public long[] Int64View + { + get + { + var items = new long[4]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public sbyte[] SByteView + { + get + { + var items = new sbyte[32]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public float[] SingleView + { + get + { + var items = new float[8]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public ushort[] UInt16View + { + get + { + var items = new ushort[16]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public uint[] UInt32View + { + get + { + var items = new uint[8]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public ulong[] UInt64View + { + get + { + var items = new ulong[4]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector64.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector64.cs new file mode 100644 index 0000000000..8ce90b9d0f --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector64.cs @@ -0,0 +1,43 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Internal.Runtime.CompilerServices; + +namespace System.Runtime.Intrinsics +{ + [Intrinsic] + [DebuggerDisplay("{DisplayString,nq}")] + [DebuggerTypeProxy(typeof(Vector64DebugView<>))] + [StructLayout(LayoutKind.Sequential, Size = 8)] + public readonly struct Vector64 where T : struct + { + // These fields exist to ensure the alignment is 8, rather than 1. + // This also allows the debug view to work https://github.com/dotnet/coreclr/issues/15694) + private readonly ulong _00; + + private unsafe string DisplayString + { + get + { + // The IsPrimitive check ends up working for `bool`, `char`, `IntPtr`, and `UIntPtr` + // which are not actually supported by any current architecture. This shouldn't be + // an issue however and greatly simplifies the check + + if (typeof(T).IsPrimitive) + { + var items = new T[8 / Unsafe.SizeOf()]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), this); + return $"({string.Join(", ", items)})"; + } + else + { + return SR.NotSupported_Type; + } + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector64DebugView.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector64DebugView.cs new file mode 100644 index 0000000000..878e29949e --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/Vector64DebugView.cs @@ -0,0 +1,118 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.Runtime.CompilerServices; + +namespace System.Runtime.Intrinsics +{ + internal readonly struct Vector64DebugView where T : struct + { + private readonly Vector64 _value; + + public Vector64DebugView(Vector64 value) + { + _value = value; + } + + public byte[] ByteView + { + get + { + var items = new byte[8]; + Unsafe.WriteUnaligned(ref items[0], _value); + return items; + } + } + + public double[] DoubleView + { + get + { + var items = new double[1]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public short[] Int16View + { + get + { + var items = new short[4]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public int[] Int32View + { + get + { + var items = new int[2]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public long[] Int64View + { + get + { + var items = new long[1]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public sbyte[] SByteView + { + get + { + var items = new sbyte[8]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public float[] SingleView + { + get + { + var items = new float[2]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public ushort[] UInt16View + { + get + { + var items = new ushort[4]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public uint[] UInt32View + { + get + { + var items = new uint[2]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + + public ulong[] UInt64View + { + get + { + var items = new ulong[1]; + Unsafe.WriteUnaligned(ref Unsafe.As(ref items[0]), _value); + return items; + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Aes.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Aes.PlatformNotSupported.cs new file mode 100644 index 0000000000..d439defd71 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Aes.PlatformNotSupported.cs @@ -0,0 +1,58 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel AES hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Aes : Sse2 + { + internal Aes() { } + + public new static bool IsSupported { get { return false; } } + + /// + /// __m128i _mm_aesdec_si128 (__m128i a, __m128i RoundKey) + /// AESDEC xmm, xmm/m128 + /// + public static Vector128 Decrypt(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_aesdeclast_si128 (__m128i a, __m128i RoundKey) + /// AESDECLAST xmm, xmm/m128 + /// + public static Vector128 DecryptLast(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_aesenc_si128 (__m128i a, __m128i RoundKey) + /// AESENC xmm, xmm/m128 + /// + public static Vector128 Encrypt(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_aesenclast_si128 (__m128i a, __m128i RoundKey) + /// AESENCLAST xmm, xmm/m128 + /// + public static Vector128 EncryptLast(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_aesimc_si128 (__m128i a) + /// AESIMC xmm, xmm/m128 + /// + public static Vector128 InverseMixColumns(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_aeskeygenassist_si128 (__m128i a, const int imm8) + /// AESKEYGENASSIST xmm, xmm/m128, imm8 + /// + public static Vector128 KeygenAssist(Vector128 value, byte control) { throw new PlatformNotSupportedException(); } + + } + +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Aes.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Aes.cs new file mode 100644 index 0000000000..412a0c2f14 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Aes.cs @@ -0,0 +1,58 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel AES hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Aes : Sse2 + { + internal Aes() { } + + public new static bool IsSupported { get => IsSupported; } + + /// + /// __m128i _mm_aesdec_si128 (__m128i a, __m128i RoundKey) + /// AESDEC xmm, xmm/m128 + /// + public static Vector128 Decrypt(Vector128 value, Vector128 roundKey) => Decrypt(value, roundKey); + + /// + /// __m128i _mm_aesdeclast_si128 (__m128i a, __m128i RoundKey) + /// AESDECLAST xmm, xmm/m128 + /// + public static Vector128 DecryptLast(Vector128 value, Vector128 roundKey) => DecryptLast(value, roundKey); + + /// + /// __m128i _mm_aesenc_si128 (__m128i a, __m128i RoundKey) + /// AESENC xmm, xmm/m128 + /// + public static Vector128 Encrypt(Vector128 value, Vector128 roundKey) => Encrypt(value, roundKey); + + /// + /// __m128i _mm_aesenclast_si128 (__m128i a, __m128i RoundKey) + /// AESENCLAST xmm, xmm/m128 + /// + public static Vector128 EncryptLast(Vector128 value, Vector128 roundKey) => EncryptLast(value, roundKey); + + /// + /// __m128i _mm_aesimc_si128 (__m128i a) + /// AESIMC xmm, xmm/m128 + /// + public static Vector128 InverseMixColumns(Vector128 value) => InverseMixColumns(value); + + /// + /// __m128i _mm_aeskeygenassist_si128 (__m128i a, const int imm8) + /// AESKEYGENASSIST xmm, xmm/m128, imm8 + /// + public static Vector128 KeygenAssist(Vector128 value, byte control) => KeygenAssist(value, control); + + } + +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx.PlatformNotSupported.cs new file mode 100644 index 0000000000..d6597cfb56 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx.PlatformNotSupported.cs @@ -0,0 +1,1230 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel AVX hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Avx : Sse42 + { + internal Avx() { } + + public new static bool IsSupported { get { return false; } } + + /// + /// __m256 _mm256_add_ps (__m256 a, __m256 b) + /// VADDPS ymm, ymm, ymm/m256 + /// + public static Vector256 Add(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_add_pd (__m256d a, __m256d b) + /// VADDPD ymm, ymm, ymm/m256 + /// + public static Vector256 Add(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_addsub_ps (__m256 a, __m256 b) + /// VADDSUBPS ymm, ymm, ymm/m256 + /// + public static Vector256 AddSubtract(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_addsub_pd (__m256d a, __m256d b) + /// VADDSUBPD ymm, ymm, ymm/m256 + /// + public static Vector256 AddSubtract(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_and_ps (__m256 a, __m256 b) + /// VANDPS ymm, ymm, ymm/m256 + /// + public static Vector256 And(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_and_pd (__m256d a, __m256d b) + /// VANDPD ymm, ymm, ymm/m256 + /// + public static Vector256 And(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_andnot_ps (__m256 a, __m256 b) + /// VANDNPS ymm, ymm, ymm/m256 + /// + public static Vector256 AndNot(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_andnot_pd (__m256d a, __m256d b) + /// VANDNPD ymm, ymm, ymm/m256 + /// + public static Vector256 AndNot(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_blend_ps (__m256 a, __m256 b, const int imm8) + /// VBLENDPS ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 Blend(Vector256 left, Vector256 right, byte control) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_blend_pd (__m256d a, __m256d b, const int imm8) + /// VBLENDPD ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 Blend(Vector256 left, Vector256 right, byte control) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_blendv_ps (__m256 a, __m256 b, __m256 mask) + /// VBLENDVPS ymm, ymm, ymm/m256, ymm + /// + public static Vector256 BlendVariable(Vector256 left, Vector256 right, Vector256 mask) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_blendv_pd (__m256d a, __m256d b, __m256d mask) + /// VBLENDVPD ymm, ymm, ymm/m256, ymm + /// + public static Vector256 BlendVariable(Vector256 left, Vector256 right, Vector256 mask) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_broadcast_ss (float const * mem_addr) + /// VBROADCASTSS xmm, m32 + /// + public static unsafe Vector128 BroadcastScalarToVector128(float* source) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_broadcast_ss (float const * mem_addr) + /// VBROADCASTSS ymm, m32 + /// + public static unsafe Vector256 BroadcastScalarToVector256(float* source) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_broadcast_sd (double const * mem_addr) + /// VBROADCASTSD ymm, m64 + /// + public static unsafe Vector256 BroadcastScalarToVector256(double* source) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_broadcast_ps (__m128 const * mem_addr) + /// VBROADCASTF128, ymm, m128 + /// + public static unsafe Vector256 BroadcastVector128ToVector256(float* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_broadcast_pd (__m128d const * mem_addr) + /// VBROADCASTF128, ymm, m128 + /// + public static unsafe Vector256 BroadcastVector128ToVector256(double* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_ceil_ps (__m256 a) + /// VROUNDPS ymm, ymm/m256, imm8(10) + /// + public static Vector256 Ceiling(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_ceil_pd (__m256d a) + /// VROUNDPD ymm, ymm/m256, imm8(10) + /// + public static Vector256 Ceiling(Vector256 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmp_ps (__m128 a, __m128 b, const int imm8) + /// VCMPPS xmm, xmm, xmm/m128, imm8 + /// + public static Vector128 Compare(Vector128 left, Vector128 right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_cmp_pd (__m128d a, __m128d b, const int imm8) + /// VCMPPD xmm, xmm, xmm/m128, imm8 + /// + public static Vector128 Compare(Vector128 left, Vector128 right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_cmp_ps (__m256 a, __m256 b, const int imm8) + /// VCMPPS ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 Compare(Vector256 left, Vector256 right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_cmp_pd (__m256d a, __m256d b, const int imm8) + /// VCMPPD ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 Compare(Vector256 left, Vector256 right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmp_sd (__m128d a, __m128d b, const int imm8) + /// VCMPSS xmm, xmm, xmm/m32, imm8 + /// + public static Vector128 CompareScalar(Vector128 left, Vector128 right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_cmp_ss (__m128 a, __m128 b, const int imm8) + /// VCMPSD xmm, xmm, xmm/m64, imm8 + /// + public static Vector128 CompareScalar(Vector128 left, Vector128 right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// float _mm256_cvtss_f32 (__m256 a) + /// HELPER: VMOVSS + /// + public static float ConvertToSingle(Vector256 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm256_cvtpd_epi32 (__m256d a) + /// VCVTPD2DQ xmm, ymm/m256 + /// + public static Vector128 ConvertToVector128Int32(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm256_cvtpd_ps (__m256d a) + /// VCVTPD2PS xmm, ymm/m256 + /// + public static Vector128 ConvertToVector128Single(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_cvtps_epi32 (__m256 a) + /// VCVTPS2DQ ymm, ymm/m256 + /// + public static Vector256 ConvertToVector256Int32(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_cvtepi32_ps (__m256i a) + /// VCVTDQ2PS ymm, ymm/m256 + /// + public static Vector256 ConvertToVector256Single(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_cvtps_pd (__m128 a) + /// VCVTPS2PD ymm, xmm/m128 + /// + public static Vector256 ConvertToVector256Double(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_cvtepi32_pd (__m128i a) + /// VCVTDQ2PD ymm, xmm/m128 + /// + public static Vector256 ConvertToVector256Double(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm256_cvttpd_epi32 (__m256d a) + /// VCVTTPD2DQ xmm, ymm/m256 + /// + public static Vector128 ConvertToVector128Int32WithTruncation(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_cvttps_epi32 (__m256 a) + /// VCVTTPS2DQ ymm, ymm/m256 + /// + public static Vector256 ConvertToVector256Int32WithTruncation(Vector256 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_div_ps (__m256 a, __m256 b) + /// VDIVPS ymm, ymm, ymm/m256 + /// + public static Vector256 Divide(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_div_pd (__m256d a, __m256d b) + /// VDIVPD ymm, ymm, ymm/m256 + /// + public static Vector256 Divide(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_dp_ps (__m256 a, __m256 b, const int imm8) + /// VDPPS ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 DotProduct(Vector256 left, Vector256 right, byte control) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_moveldup_ps (__m256 a) + /// VMOVSLDUP ymm, ymm/m256 + /// + public static Vector256 DuplicateEvenIndexed(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_movedup_pd (__m256d a) + /// VMOVDDUP ymm, ymm/m256 + /// + public static Vector256 DuplicateEvenIndexed(Vector256 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_movehdup_ps (__m256 a) + /// VMOVSHDUP ymm, ymm/m256 + /// + public static Vector256 DuplicateOddIndexed(Vector256 value) { throw new PlatformNotSupportedException(); } + + /// + /// __int8 _mm256_extract_epi8 (__m256i a, const int index) + /// HELPER + /// + public static byte Extract(Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __int16 _mm256_extract_epi16 (__m256i a, const int index) + /// HELPER + /// + public static ushort Extract(Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __int32 _mm256_extract_epi32 (__m256i a, const int index) + /// HELPER + /// + public static int Extract(Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __int32 _mm256_extract_epi32 (__m256i a, const int index) + /// HELPER + /// + public static uint Extract(Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __int64 _mm256_extract_epi64 (__m256i a, const int index) + /// HELPER + /// + public static long Extract(Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __int64 _mm256_extract_epi64 (__m256i a, const int index) + /// HELPER + /// + public static ulong Extract(Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm256_extractf128_ps (__m256 a, const int imm8) + /// VEXTRACTF128 xmm/m128, ymm, imm8 + /// __m128d _mm256_extractf128_pd (__m256d a, const int imm8) + /// VEXTRACTF128 xmm/m128, ymm, imm8 + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 xmm/m128, ymm, imm8 + /// + public static Vector128 ExtractVector128(Vector256 value, byte index) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(byte* address, Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(sbyte* address, Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(short* address, Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(ushort* address, Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(int* address, Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(uint* address, Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(long* address, Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(ulong* address, Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm256_extractf128_ps (__m256 a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(float* address, Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm256_extractf128_pd (__m256d a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(double* address, Vector256 value, byte index) { throw new PlatformNotSupportedException(); } + + /// + /// __m256d _mm256_castpd128_pd256 (__m128d a) + /// HELPER - No Codegen + /// __m256 _mm256_castps128_ps256 (__m128 a) + /// HELPER - No Codegen + /// __m256i _mm256_castsi128_si256 (__m128i a) + /// HELPER - No Codegen + /// + public static Vector256 ExtendToVector256(Vector128 value) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_floor_ps (__m256 a) + /// VROUNDPS ymm, ymm/m256, imm8(9) + /// + public static Vector256 Floor(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_floor_pd (__m256d a) + /// VROUNDPS ymm, ymm/m256, imm8(9) + /// + public static Vector256 Floor(Vector256 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm256_castpd256_pd128 (__m256d a) + /// HELPER - No Codegen + /// __m128 _mm256_castps256_ps128 (__m256 a) + /// HELPER - No Codegen + /// __m128i _mm256_castsi256_si128 (__m256i a) + /// HELPER - No Codegen + /// + public static Vector128 GetLowerHalf(Vector256 value) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_hadd_ps (__m256 a, __m256 b) + /// VHADDPS ymm, ymm, ymm/m256 + /// + public static Vector256 HorizontalAdd(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_hadd_pd (__m256d a, __m256d b) + /// VHADDPD ymm, ymm, ymm/m256 + /// + public static Vector256 HorizontalAdd(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_hsub_ps (__m256 a, __m256 b) + /// VHSUBPS ymm, ymm, ymm/m256 + /// + public static Vector256 HorizontalSubtract(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_hsub_pd (__m256d a, __m256d b) + /// VHSUBPD ymm, ymm, ymm/m256 + /// + public static Vector256 HorizontalSubtract(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m256i _mm256_insert_epi8 (__m256i a, __int8 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, sbyte data, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_insert_epi8 (__m256i a, __int8 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, byte data, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_insert_epi16 (__m256i a, __int16 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, short data, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_insert_epi16 (__m256i a, __int16 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, ushort data, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_insert_epi32 (__m256i a, __int32 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, int data, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_insert_epi32 (__m256i a, __int32 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, uint data, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_insert_epi64 (__m256i a, __int64 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, long data, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_insert_epi64 (__m256i a, __int64 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, ulong data, byte index) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_insertf128_ps (__m256 a, __m128 b, int imm8) + /// VINSERTF128 ymm, ymm, xmm/m128, imm8 + /// __m256d _mm256_insertf128_pd (__m256d a, __m128d b, int imm8) + /// VINSERTF128 ymm, ymm, xmm/m128, imm8 + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, xmm/m128, imm8 + /// + public static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, sbyte* address, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, byte* address, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, short* address, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, ushort* address, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, int* address, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, uint* address, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, long* address, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, ulong* address, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_insertf128_ps (__m256 a, __m128 b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, float* address, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_insertf128_pd (__m256d a, __m128d b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, double* address, byte index) { throw new PlatformNotSupportedException(); } + + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(sbyte* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(byte* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(short* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(ushort* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(int* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(uint* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(long* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(ulong* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_loadu_ps (float const * mem_addr) + /// VMOVUPS ymm, ymm/m256 + /// + public static unsafe Vector256 LoadVector256(float* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_loadu_pd (double const * mem_addr) + /// VMOVUPD ymm, ymm/m256 + /// + public static unsafe Vector256 LoadVector256(double* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(sbyte* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(byte* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(short* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(ushort* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(int* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(uint* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(long* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(ulong* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_load_ps (float const * mem_addr) + /// VMOVAPS ymm, ymm/m256 + /// + public static unsafe Vector256 LoadAlignedVector256(float* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_load_pd (double const * mem_addr) + /// VMOVAPD ymm, ymm/m256 + /// + public static unsafe Vector256 LoadAlignedVector256(double* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(sbyte* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(byte* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(short* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(ushort* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(int* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(uint* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(long* address) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(ulong* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_maskload_ps (float const * mem_addr, __m128i mask) + /// VMASKMOVPS xmm, xmm, m128 + /// + public static unsafe Vector128 MaskLoad(float* address, Vector128 mask) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_maskload_pd (double const * mem_addr, __m128i mask) + /// VMASKMOVPD xmm, xmm, m128 + /// + public static unsafe Vector128 MaskLoad(double* address, Vector128 mask) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_maskload_ps (float const * mem_addr, __m256i mask) + /// VMASKMOVPS ymm, ymm, m256 + /// + public static unsafe Vector256 MaskLoad(float* address, Vector256 mask) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_maskload_pd (double const * mem_addr, __m256i mask) + /// VMASKMOVPD ymm, ymm, m256 + /// + public static unsafe Vector256 MaskLoad(double* address, Vector256 mask) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_maskstore_ps (float * mem_addr, __m128i mask, __m128 a) + /// VMASKMOVPS m128, xmm, xmm + /// + public static unsafe void MaskStore(float* address, Vector128 mask, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_maskstore_pd (double * mem_addr, __m128i mask, __m128d a) + /// VMASKMOVPD m128, xmm, xmm + /// + public static unsafe void MaskStore(double* address, Vector128 mask, Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm256_maskstore_ps (float * mem_addr, __m256i mask, __m256 a) + /// VMASKMOVPS m256, ymm, ymm + /// + public static unsafe void MaskStore(float* address, Vector256 mask, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_maskstore_pd (double * mem_addr, __m256i mask, __m256d a) + /// VMASKMOVPD m256, ymm, ymm + /// + public static unsafe void MaskStore(double* address, Vector256 mask, Vector256 source) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_max_ps (__m256 a, __m256 b) + /// VMAXPS ymm, ymm, ymm/m256 + /// + public static Vector256 Max(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_max_pd (__m256d a, __m256d b) + /// VMAXPD ymm, ymm, ymm/m256 + /// + public static Vector256 Max(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_min_ps (__m256 a, __m256 b) + /// VMINPS ymm, ymm, ymm/m256 + /// + public static Vector256 Min(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_min_pd (__m256d a, __m256d b) + /// VMINPD ymm, ymm, ymm/m256 + /// + public static Vector256 Min(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm256_movemask_ps (__m256 a) + /// VMOVMSKPS reg, ymm + /// + public static int MoveMask(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// int _mm256_movemask_pd (__m256d a) + /// VMOVMSKPD reg, ymm + /// + public static int MoveMask(Vector256 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_mul_ps (__m256 a, __m256 b) + /// VMULPS ymm, ymm, ymm/m256 + /// + public static Vector256 Multiply(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_mul_pd (__m256d a, __m256d b) + /// VMULPD ymm, ymm, ymm/m256 + /// + public static Vector256 Multiply(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_or_ps (__m256 a, __m256 b) + /// VORPS ymm, ymm, ymm/m256 + /// + public static Vector256 Or(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_or_pd (__m256d a, __m256d b) + /// VORPD ymm, ymm, ymm/m256 + /// + public static Vector256 Or(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_permute_ps (__m128 a, int imm8) + /// VPERMILPS xmm, xmm, imm8 + /// + public static Vector128 Permute(Vector128 value, byte control) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_permute_pd (__m128d a, int imm8) + /// VPERMILPD xmm, xmm, imm8 + /// + public static Vector128 Permute(Vector128 value, byte control) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_permute_ps (__m256 a, int imm8) + /// VPERMILPS ymm, ymm, imm8 + /// + public static Vector256 Permute(Vector256 value, byte control) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_permute_pd (__m256d a, int imm8) + /// VPERMILPD ymm, ymm, imm8 + /// + public static Vector256 Permute(Vector256 value, byte control) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_permute2f128_ps (__m256 a, __m256 b, int imm8) + /// VPERM2F128 ymm, ymm, ymm/m256, imm8 + /// __m256d _mm256_permute2f128_pd (__m256d a, __m256d b, int imm8) + /// VPERM2F128 ymm, ymm, ymm/m256, imm8 + /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) + /// VPERM2F128 ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_permutevar_ps (__m128 a, __m128i b) + /// VPERMILPS xmm, xmm, xmm/m128 + /// + public static Vector128 PermuteVar(Vector128 left, Vector128 control) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_permutevar_pd (__m128d a, __m128i b) + /// VPERMILPD xmm, xmm, xmm/m128 + /// + public static Vector128 PermuteVar(Vector128 left, Vector128 control) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_permutevar_ps (__m256 a, __m256i b) + /// VPERMILPS ymm, ymm, ymm/m256 + /// + public static Vector256 PermuteVar(Vector256 left, Vector256 control) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_permutevar_pd (__m256d a, __m256i b) + /// VPERMILPD ymm, ymm, ymm/m256 + /// + public static Vector256 PermuteVar(Vector256 left, Vector256 control) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_rcp_ps (__m256 a) + /// VRCPPS ymm, ymm/m256 + /// + public static Vector256 Reciprocal(Vector256 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_rsqrt_ps (__m256 a) + /// VRSQRTPS ymm, ymm/m256 + /// + public static Vector256 ReciprocalSqrt(Vector256 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) + /// VROUNDPS ymm, ymm/m256, imm8(8) + /// + public static Vector256 RoundToNearestInteger(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) + /// VROUNDPS ymm, ymm/m256, imm8(9) + /// + public static Vector256 RoundToNegativeInfinity(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) + /// VROUNDPS ymm, ymm/m256, imm8(10) + /// + public static Vector256 RoundToPositiveInfinity(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC) + /// VROUNDPS ymm, ymm/m256, imm8(11) + /// + public static Vector256 RoundToZero(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_CUR_DIRECTION) + /// VROUNDPS ymm, ymm/m256, imm8(4) + /// + public static Vector256 RoundCurrentDirection(Vector256 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) + /// VROUNDPD ymm, ymm/m256, imm8(8) + /// + public static Vector256 RoundToNearestInteger(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) + /// VROUNDPD ymm, ymm/m256, imm8(9) + /// + public static Vector256 RoundToNegativeInfinity(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) + /// VROUNDPD ymm, ymm/m256, imm8(10) + /// + public static Vector256 RoundToPositiveInfinity(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC) + /// VROUNDPD ymm, ymm/m256, imm8(11) + /// + public static Vector256 RoundToZero(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_CUR_DIRECTION) + /// VROUNDPD ymm, ymm/m256, imm8(4) + /// + public static Vector256 RoundCurrentDirection(Vector256 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m256i _mm256_set_epi8 (char e31, char e30, char e29, char e28, char e27, char e26, char e25, char e24, char e23, char e22, char e21, char e20, char e19, char e18, char e17, char e16, char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) + /// HELPER + /// + public static Vector256 SetVector256(sbyte e31, sbyte e30, sbyte e29, sbyte e28, sbyte e27, sbyte e26, sbyte e25, sbyte e24, sbyte e23, sbyte e22, sbyte e21, sbyte e20, sbyte e19, sbyte e18, sbyte e17, sbyte e16, sbyte e15, sbyte e14, sbyte e13, sbyte e12, sbyte e11, sbyte e10, sbyte e9, sbyte e8, sbyte e7, sbyte e6, sbyte e5, sbyte e4, sbyte e3, sbyte e2, sbyte e1, sbyte e0) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_set_epi8 (char e31, char e30, char e29, char e28, char e27, char e26, char e25, char e24, char e23, char e22, char e21, char e20, char e19, char e18, char e17, char e16, char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) + /// HELPER + /// + public static Vector256 SetVector256(byte e31, byte e30, byte e29, byte e28, byte e27, byte e26, byte e25, byte e24, byte e23, byte e22, byte e21, byte e20, byte e19, byte e18, byte e17, byte e16, byte e15, byte e14, byte e13, byte e12, byte e11, byte e10, byte e9, byte e8, byte e7, byte e6, byte e5, byte e4, byte e3, byte e2, byte e1, byte e0) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_set_epi16 (short e15, short e14, short e13, short e12, short e11, short e10, short e9, short e8, short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) + /// HELPER + /// + public static Vector256 SetVector256(short e15, short e14, short e13, short e12, short e11, short e10, short e9, short e8, short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_set_epi16 (short e15, short e14, short e13, short e12, short e11, short e10, short e9, short e8, short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) + /// HELPER + /// + public static Vector256 SetVector256(ushort e15, ushort e14, ushort e13, ushort e12, ushort e11, ushort e10, ushort e9, ushort e8, ushort e7, ushort e6, ushort e5, ushort e4, ushort e3, ushort e2, ushort e1, ushort e0) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_set_epi32 (int e7, int e6, int e5, int e4, int e3, int e2, int e1, int e0) + /// HELPER + /// + public static Vector256 SetVector256(int e7, int e6, int e5, int e4, int e3, int e2, int e1, int e0) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_set_epi32 (int e7, int e6, int e5, int e4, int e3, int e2, int e1, int e0) + /// HELPER + /// + public static Vector256 SetVector256(uint e7, uint e6, uint e5, uint e4, uint e3, uint e2, uint e1, uint e0) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_set_epi64x (__int64 e3, __int64 e2, __int64 e1, __int64 e0) + /// HELPER + /// + public static Vector256 SetVector256(long e3, long e2, long e1, long e0) { throw new PlatformNotSupportedException(); } + /// + /// __m256i _mm256_set_epi64x (__int64 e3, __int64 e2, __int64 e1, __int64 e0) + /// HELPER + /// + public static Vector256 SetVector256(ulong e3, ulong e2, ulong e1, ulong e0) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_set_ps (float e7, float e6, float e5, float e4, float e3, float e2, float e1, float e0) + /// HELPER + /// + public static Vector256 SetVector256(float e7, float e6, float e5, float e4, float e3, float e2, float e1, float e0) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_set_pd (double e3, double e2, double e1, double e0) + /// HELPER + /// + public static Vector256 SetVector256(double e3, double e2, double e1, double e0) { throw new PlatformNotSupportedException(); } + + /// + /// __m256i _mm256_set1_epi8 (char a) + /// HELPER + /// __m256i _mm256_set1_epi16 (short a) + /// HELPER + /// __m256i _mm256_set1_epi32 (int a) + /// HELPER + /// __m256i _mm256_set1_epi64x (long long a) + /// HELPER + /// __m256 _mm256_set1_ps (float a) + /// HELPER + /// __m256d _mm256_set1_pd (double a) + /// HELPER + /// + public static Vector256 SetAllVector256(T value) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_set_m128 (__m128 hi, __m128 lo) + /// HELPER + /// __m256d _mm256_set_m128d (__m128d hi, __m128d lo) + /// HELPER + /// __m256i _mm256_set_m128i (__m128i hi, __m128i lo) + /// HELPER + /// + public static Vector256 SetHighLow(Vector128 hi, Vector128 lo) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// __m256i _mm256_setzero_si256 (void) + /// HELPER + /// __m256 _mm256_setzero_ps (void) + /// HELPER + /// __m256d _mm256_setzero_pd (void) + /// HELPER + /// + public static Vector256 SetZeroVector256() where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_shuffle_ps (__m256 a, __m256 b, const int imm8) + /// VSHUFPS ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 Shuffle(Vector256 value, Vector256 right, byte control) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_shuffle_pd (__m256d a, __m256d b, const int imm8) + /// VSHUFPD ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 Shuffle(Vector256 value, Vector256 right, byte control) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_sqrt_ps (__m256 a) + /// VSQRTPS ymm, ymm/m256 + /// + public static Vector256 Sqrt(Vector256 value) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_sqrt_pd (__m256d a) + /// VSQRTPD ymm, ymm/m256 + /// + public static Vector256 Sqrt(Vector256 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_castpd_ps (__m256d a) + /// HELPER - No Codegen + /// __m256i _mm256_castpd_si256 (__m256d a) + /// HELPER - No Codegen + /// __m256d _mm256_castps_pd (__m256 a) + /// HELPER - No Codegen + /// __m256i _mm256_castps_si256 (__m256 a) + /// HELPER - No Codegen + /// __m256d _mm256_castsi256_pd (__m256i a) + /// HELPER - No Codegen + /// __m256 _mm256_castsi256_ps (__m256i a) + /// HELPER - No Codegen + /// + public static Vector256 StaticCast(Vector256 value) where T : struct where U : struct { throw new PlatformNotSupportedException(); } + + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(sbyte* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(byte* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(short* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(ushort* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(int* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(uint* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(long* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(ulong* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_store_ps (float * mem_addr, __m256 a) + /// VMOVAPS m256, ymm + /// + public static unsafe void StoreAligned(float* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_store_pd (double * mem_addr, __m256d a) + /// VMOVAPD m256, ymm + /// + public static unsafe void StoreAligned(double* address, Vector256 source) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(sbyte* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(byte* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(short* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(ushort* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(int* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(uint* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(long* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(ulong* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_stream_ps (float * mem_addr, __m256 a) + /// MOVNTPS m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(float* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_stream_pd (double * mem_addr, __m256d a) + /// MOVNTPD m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(double* address, Vector256 source) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(sbyte* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(byte* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(short* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(ushort* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(int* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(uint* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(long* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(ulong* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_storeu_ps (float * mem_addr, __m256 a) + /// MOVUPS m256, ymm + /// + public static unsafe void Store(float* address, Vector256 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm256_storeu_pd (double * mem_addr, __m256d a) + /// MOVUPD m256, ymm + /// + public static unsafe void Store(double* address, Vector256 source) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_sub_ps (__m256 a, __m256 b) + /// VSUBPS ymm, ymm, ymm/m256 + /// + public static Vector256 Subtract(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_sub_pd (__m256d a, __m256d b) + /// VSUBPD ymm, ymm, ymm/m256 + /// + public static Vector256 Subtract(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_testc_ps (__m128 a, __m128 b) + /// VTESTPS xmm, xmm/m128 + /// + public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testc_pd (__m128d a, __m128d b) + /// VTESTPD xmm, xmm/m128 + /// + public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm256_testc_si256 (__m256i a, __m256i b) + /// VPTEST ymm, ymm/m256 + /// int _mm256_testc_ps (__m256 a, __m256 b) + /// VTESTPS ymm, ymm/m256 + /// int _mm256_testc_pd (__m256d a, __m256d b) + /// VTESTPS ymm, ymm/m256 + /// + public static bool TestC(Vector256 left, Vector256 right) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_testnzc_ps (__m128 a, __m128 b) + /// VTESTPS xmm, xmm/m128 + /// + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testnzc_pd (__m128d a, __m128d b) + /// VTESTPD xmm, xmm/m128 + /// + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm256_testnzc_si256 (__m256i a, __m256i b) + /// VPTEST ymm, ymm/m256 + /// int _mm256_testnzc_ps (__m256 a, __m256 b) + /// VTESTPS ymm, ymm/m256 + /// int _mm256_testnzc_pd (__m256d a, __m256d b) + /// VTESTPD ymm, ymm/m256 + /// + public static bool TestNotZAndNotC(Vector256 left, Vector256 right) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_testz_ps (__m128 a, __m128 b) + /// VTESTPS xmm, xmm/m128 + /// + public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testz_pd (__m128d a, __m128d b) + /// VTESTPD xmm, xmm/m128 + /// + public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm256_testz_si256 (__m256i a, __m256i b) + /// VPTEST ymm, ymm/m256 + /// int _mm256_testz_ps (__m256 a, __m256 b) + /// VTESTPS ymm, ymm/m256 + /// int _mm256_testz_pd (__m256d a, __m256d b) + /// VTESTPD ymm, ymm/m256 + /// + public static bool TestZ(Vector256 left, Vector256 right) where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_unpackhi_ps (__m256 a, __m256 b) + /// VUNPCKHPS ymm, ymm, ymm/m256 + /// + public static Vector256 UnpackHigh(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_unpackhi_pd (__m256d a, __m256d b) + /// VUNPCKHPD ymm, ymm, ymm/m256 + /// + public static Vector256 UnpackHigh(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_unpacklo_ps (__m256 a, __m256 b) + /// VUNPCKLPS ymm, ymm, ymm/m256 + /// + public static Vector256 UnpackLow(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_unpacklo_pd (__m256d a, __m256d b) + /// VUNPCKLPD ymm, ymm, ymm/m256 + /// + public static Vector256 UnpackLow(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m256 _mm256_xor_ps (__m256 a, __m256 b) + /// VXORPS ymm, ymm, ymm/m256 + /// + public static Vector256 Xor(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_xor_pd (__m256d a, __m256d b) + /// VXORPS ymm, ymm, ymm/m256 + /// + public static Vector256 Xor(Vector256 left, Vector256 right) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx.cs new file mode 100644 index 0000000000..3cb6849a6b --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx.cs @@ -0,0 +1,1412 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; +using Internal.Runtime.CompilerServices; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel AVX hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Avx : Sse42 + { + internal Avx() { } + + public new static bool IsSupported { get => IsSupported; } + + /// + /// __m256 _mm256_add_ps (__m256 a, __m256 b) + /// VADDPS ymm, ymm, ymm/m256 + /// + public static Vector256 Add(Vector256 left, Vector256 right) => Add(left, right); + /// + /// __m256d _mm256_add_pd (__m256d a, __m256d b) + /// VADDPD ymm, ymm, ymm/m256 + /// + public static Vector256 Add(Vector256 left, Vector256 right) => Add(left, right); + + /// + /// __m256 _mm256_addsub_ps (__m256 a, __m256 b) + /// VADDSUBPS ymm, ymm, ymm/m256 + /// + public static Vector256 AddSubtract(Vector256 left, Vector256 right) => AddSubtract(left, right); + /// + /// __m256d _mm256_addsub_pd (__m256d a, __m256d b) + /// VADDSUBPD ymm, ymm, ymm/m256 + /// + public static Vector256 AddSubtract(Vector256 left, Vector256 right) => AddSubtract(left, right); + + /// + /// __m256 _mm256_and_ps (__m256 a, __m256 b) + /// VANDPS ymm, ymm, ymm/m256 + /// + public static Vector256 And(Vector256 left, Vector256 right) => And(left, right); + /// + /// __m256d _mm256_and_pd (__m256d a, __m256d b) + /// VANDPD ymm, ymm, ymm/m256 + /// + public static Vector256 And(Vector256 left, Vector256 right) => And(left, right); + + /// + /// __m256 _mm256_andnot_ps (__m256 a, __m256 b) + /// VANDNPS ymm, ymm, ymm/m256 + /// + public static Vector256 AndNot(Vector256 left, Vector256 right) => AndNot(left, right); + /// + /// __m256d _mm256_andnot_pd (__m256d a, __m256d b) + /// VANDNPD ymm, ymm, ymm/m256 + /// + public static Vector256 AndNot(Vector256 left, Vector256 right) => AndNot(left, right); + + /// + /// __m256 _mm256_blend_ps (__m256 a, __m256 b, const int imm8) + /// VBLENDPS ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 Blend(Vector256 left, Vector256 right, byte control) => Blend(left, right, control); + /// + /// __m256d _mm256_blend_pd (__m256d a, __m256d b, const int imm8) + /// VBLENDPD ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 Blend(Vector256 left, Vector256 right, byte control) => Blend(left, right, control); + + /// + /// __m256 _mm256_blendv_ps (__m256 a, __m256 b, __m256 mask) + /// VBLENDVPS ymm, ymm, ymm/m256, ymm + /// + public static Vector256 BlendVariable(Vector256 left, Vector256 right, Vector256 mask) => BlendVariable(left, right, mask); + /// + /// __m256d _mm256_blendv_pd (__m256d a, __m256d b, __m256d mask) + /// VBLENDVPD ymm, ymm, ymm/m256, ymm + /// + public static Vector256 BlendVariable(Vector256 left, Vector256 right, Vector256 mask) => BlendVariable(left, right, mask); + + /// + /// __m128 _mm_broadcast_ss (float const * mem_addr) + /// VBROADCASTSS xmm, m32 + /// + public static unsafe Vector128 BroadcastScalarToVector128(float* source) => BroadcastScalarToVector128(source); + + /// + /// __m256 _mm256_broadcast_ss (float const * mem_addr) + /// VBROADCASTSS ymm, m32 + /// + public static unsafe Vector256 BroadcastScalarToVector256(float* source) => BroadcastScalarToVector256(source); + /// + /// __m256d _mm256_broadcast_sd (double const * mem_addr) + /// VBROADCASTSD ymm, m64 + /// + public static unsafe Vector256 BroadcastScalarToVector256(double* source) => BroadcastScalarToVector256(source); + + /// + /// __m256 _mm256_broadcast_ps (__m128 const * mem_addr) + /// VBROADCASTF128, ymm, m128 + /// + public static unsafe Vector256 BroadcastVector128ToVector256(float* address) => BroadcastVector128ToVector256(address); + /// + /// __m256d _mm256_broadcast_pd (__m128d const * mem_addr) + /// VBROADCASTF128, ymm, m128 + /// + public static unsafe Vector256 BroadcastVector128ToVector256(double* address) => BroadcastVector128ToVector256(address); + + /// + /// __m256 _mm256_ceil_ps (__m256 a) + /// VROUNDPS ymm, ymm/m256, imm8(10) + /// + public static Vector256 Ceiling(Vector256 value) => Ceiling(value); + /// + /// __m256d _mm256_ceil_pd (__m256d a) + /// VROUNDPD ymm, ymm/m256, imm8(10) + /// + public static Vector256 Ceiling(Vector256 value) => Ceiling(value); + + /// + /// __m128 _mm_cmp_ps (__m128 a, __m128 b, const int imm8) + /// VCMPPS xmm, xmm, xmm/m128, imm8 + /// + public static Vector128 Compare(Vector128 left, Vector128 right, FloatComparisonMode mode) => Compare(left, right, mode); + /// + /// __m128d _mm_cmp_pd (__m128d a, __m128d b, const int imm8) + /// VCMPPD xmm, xmm, xmm/m128, imm8 + /// + public static Vector128 Compare(Vector128 left, Vector128 right, FloatComparisonMode mode) => Compare(left, right, mode); + /// + /// __m256 _mm256_cmp_ps (__m256 a, __m256 b, const int imm8) + /// VCMPPS ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 Compare(Vector256 left, Vector256 right, FloatComparisonMode mode) => Compare(left, right, mode); + /// + /// __m256d _mm256_cmp_pd (__m256d a, __m256d b, const int imm8) + /// VCMPPD ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 Compare(Vector256 left, Vector256 right, FloatComparisonMode mode) => Compare(left, right, mode); + + /// + /// __m128d _mm_cmp_sd (__m128d a, __m128d b, const int imm8) + /// VCMPSS xmm, xmm, xmm/m32, imm8 + /// + public static Vector128 CompareScalar(Vector128 left, Vector128 right, FloatComparisonMode mode) => CompareScalar(left, right, mode); + /// + /// __m128 _mm_cmp_ss (__m128 a, __m128 b, const int imm8) + /// VCMPSD xmm, xmm, xmm/m64, imm8 + /// + public static Vector128 CompareScalar(Vector128 left, Vector128 right, FloatComparisonMode mode) => CompareScalar(left, right, mode); + + /// + /// float _mm256_cvtss_f32 (__m256 a) + /// HELPER: VMOVSS + /// + public static float ConvertToSingle(Vector256 value) => ConvertToSingle(value); + + /// + /// __m128i _mm256_cvtpd_epi32 (__m256d a) + /// VCVTPD2DQ xmm, ymm/m256 + /// + public static Vector128 ConvertToVector128Int32(Vector256 value) => ConvertToVector128Int32(value); + /// + /// __m128 _mm256_cvtpd_ps (__m256d a) + /// VCVTPD2PS xmm, ymm/m256 + /// + public static Vector128 ConvertToVector128Single(Vector256 value) => ConvertToVector128Single(value); + /// + /// __m256i _mm256_cvtps_epi32 (__m256 a) + /// VCVTPS2DQ ymm, ymm/m256 + /// + public static Vector256 ConvertToVector256Int32(Vector256 value) => ConvertToVector256Int32(value); + /// + /// __m256 _mm256_cvtepi32_ps (__m256i a) + /// VCVTDQ2PS ymm, ymm/m256 + /// + public static Vector256 ConvertToVector256Single(Vector256 value) => ConvertToVector256Single(value); + /// + /// __m256d _mm256_cvtps_pd (__m128 a) + /// VCVTPS2PD ymm, xmm/m128 + /// + public static Vector256 ConvertToVector256Double(Vector128 value) => ConvertToVector256Double(value); + /// + /// __m256d _mm256_cvtepi32_pd (__m128i a) + /// VCVTDQ2PD ymm, xmm/m128 + /// + public static Vector256 ConvertToVector256Double(Vector128 value) => ConvertToVector256Double(value); + + /// + /// __m128i _mm256_cvttpd_epi32 (__m256d a) + /// VCVTTPD2DQ xmm, ymm/m256 + /// + public static Vector128 ConvertToVector128Int32WithTruncation(Vector256 value) => ConvertToVector128Int32WithTruncation(value); + /// + /// __m256i _mm256_cvttps_epi32 (__m256 a) + /// VCVTTPS2DQ ymm, ymm/m256 + /// + public static Vector256 ConvertToVector256Int32WithTruncation(Vector256 value) => ConvertToVector256Int32WithTruncation(value); + + /// + /// __m256 _mm256_div_ps (__m256 a, __m256 b) + /// VDIVPS ymm, ymm, ymm/m256 + /// + public static Vector256 Divide(Vector256 left, Vector256 right) => Divide(left, right); + /// + /// __m256d _mm256_div_pd (__m256d a, __m256d b) + /// VDIVPD ymm, ymm, ymm/m256 + /// + public static Vector256 Divide(Vector256 left, Vector256 right) => Divide(left, right); + + /// + /// __m256 _mm256_dp_ps (__m256 a, __m256 b, const int imm8) + /// VDPPS ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 DotProduct(Vector256 left, Vector256 right, byte control) => DotProduct(left, right, control); + + /// + /// __m256 _mm256_moveldup_ps (__m256 a) + /// VMOVSLDUP ymm, ymm/m256 + /// + public static Vector256 DuplicateEvenIndexed(Vector256 value) => DuplicateEvenIndexed(value); + /// + /// __m256d _mm256_movedup_pd (__m256d a) + /// VMOVDDUP ymm, ymm/m256 + /// + public static Vector256 DuplicateEvenIndexed(Vector256 value) => DuplicateEvenIndexed(value); + + /// + /// __m256 _mm256_movehdup_ps (__m256 a) + /// VMOVSHDUP ymm, ymm/m256 + /// + public static Vector256 DuplicateOddIndexed(Vector256 value) => DuplicateOddIndexed(value); + + /// + /// __int8 _mm256_extract_epi8 (__m256i a, const int index) + /// HELPER + /// + public static byte Extract(Vector256 value, byte index) + { + if (!IsSupported) + { + throw new PlatformNotSupportedException(); + } + return Unsafe.Add(ref Unsafe.As, byte>(ref value), index & 0x1F); + } + + + /// + /// __int16 _mm256_extract_epi16 (__m256i a, const int index) + /// HELPER + /// + public static ushort Extract(Vector256 value, byte index) + { + if (!IsSupported) + { + throw new PlatformNotSupportedException(); + } + return Unsafe.Add(ref Unsafe.As, ushort>(ref value), index & 0xF); + } + + /// + /// __int32 _mm256_extract_epi32 (__m256i a, const int index) + /// HELPER + /// + public static int Extract(Vector256 value, byte index) + { + if (!IsSupported) + { + throw new PlatformNotSupportedException(); + } + return Unsafe.Add(ref Unsafe.As, int>(ref value), index & 0x7); + } + + /// + /// __int32 _mm256_extract_epi32 (__m256i a, const int index) + /// HELPER + /// + public static uint Extract(Vector256 value, byte index) + { + if (!IsSupported) + { + throw new PlatformNotSupportedException(); + } + return Unsafe.Add(ref Unsafe.As, uint>(ref value), index & 0x7); + } + + /// + /// __int64 _mm256_extract_epi64 (__m256i a, const int index) + /// HELPER + /// + public static long Extract(Vector256 value, byte index) + { + if (!IsSupported || (IntPtr.Size != 8)) + { + throw new PlatformNotSupportedException(); + } + return Unsafe.Add(ref Unsafe.As, long>(ref value), index & 0x3); + } + + /// + /// __int64 _mm256_extract_epi64 (__m256i a, const int index) + /// HELPER + /// + public static ulong Extract(Vector256 value, byte index) + { + if (!IsSupported || (IntPtr.Size != 8)) + { + throw new PlatformNotSupportedException(); + } + return Unsafe.Add(ref Unsafe.As, ulong>(ref value), index & 0x3); + } + + /// + /// __m128 _mm256_extractf128_ps (__m256 a, const int imm8) + /// VEXTRACTF128 xmm/m128, ymm, imm8 + /// __m128d _mm256_extractf128_pd (__m256d a, const int imm8) + /// VEXTRACTF128 xmm/m128, ymm, imm8 + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 xmm/m128, ymm, imm8 + /// + public static Vector128 ExtractVector128(Vector256 value, byte index) where T : struct + { + return ExtractVector128(value, index); + } + + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(byte* address, Vector256 value, byte index) => ExtractVector128(address, value, index); + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(sbyte* address, Vector256 value, byte index) => ExtractVector128(address, value, index); + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(short* address, Vector256 value, byte index) => ExtractVector128(address, value, index); + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(ushort* address, Vector256 value, byte index) => ExtractVector128(address, value, index); + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(int* address, Vector256 value, byte index) => ExtractVector128(address, value, index); + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(uint* address, Vector256 value, byte index) => ExtractVector128(address, value, index); + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(long* address, Vector256 value, byte index) => ExtractVector128(address, value, index); + /// + /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(ulong* address, Vector256 value, byte index) => ExtractVector128(address, value, index); + /// + /// __m128 _mm256_extractf128_ps (__m256 a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(float* address, Vector256 value, byte index) => ExtractVector128(address, value, index); + /// + /// __m128d _mm256_extractf128_pd (__m256d a, const int imm8) + /// VEXTRACTF128 m128, ymm, imm8 + /// + public static unsafe void ExtractVector128(double* address, Vector256 value, byte index) => ExtractVector128(address, value, index); + + /// + /// __m256d _mm256_castpd128_pd256 (__m128d a) + /// HELPER - No Codegen + /// __m256 _mm256_castps128_ps256 (__m128 a) + /// HELPER - No Codegen + /// __m256i _mm256_castsi128_si256 (__m128i a) + /// HELPER - No Codegen + /// + public static Vector256 ExtendToVector256(Vector128 value) where T : struct + { + return ExtendToVector256(value); + } + + /// + /// __m256 _mm256_floor_ps (__m256 a) + /// VROUNDPS ymm, ymm/m256, imm8(9) + /// + public static Vector256 Floor(Vector256 value) => Floor(value); + /// + /// __m256d _mm256_floor_pd (__m256d a) + /// VROUNDPS ymm, ymm/m256, imm8(9) + /// + public static Vector256 Floor(Vector256 value) => Floor(value); + + /// + /// __m128d _mm256_castpd256_pd128 (__m256d a) + /// HELPER - No Codegen + /// __m128 _mm256_castps256_ps128 (__m256 a) + /// HELPER - No Codegen + /// __m128i _mm256_castsi256_si128 (__m256i a) + /// HELPER - No Codegen + /// + public static Vector128 GetLowerHalf(Vector256 value) where T : struct + { + return GetLowerHalf(value); + } + + /// + /// __m256 _mm256_hadd_ps (__m256 a, __m256 b) + /// VHADDPS ymm, ymm, ymm/m256 + /// + public static Vector256 HorizontalAdd(Vector256 left, Vector256 right) => HorizontalAdd(left, right); + /// + /// __m256d _mm256_hadd_pd (__m256d a, __m256d b) + /// VHADDPD ymm, ymm, ymm/m256 + /// + public static Vector256 HorizontalAdd(Vector256 left, Vector256 right) => HorizontalAdd(left, right); + + /// + /// __m256 _mm256_hsub_ps (__m256 a, __m256 b) + /// VHSUBPS ymm, ymm, ymm/m256 + /// + public static Vector256 HorizontalSubtract(Vector256 left, Vector256 right) => HorizontalSubtract(left, right); + /// + /// __m256d _mm256_hsub_pd (__m256d a, __m256d b) + /// VHSUBPD ymm, ymm, ymm/m256 + /// + public static Vector256 HorizontalSubtract(Vector256 left, Vector256 right) => HorizontalSubtract(left, right); + + /// + /// __m256i _mm256_insert_epi8 (__m256i a, __int8 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, sbyte data, byte index) + { + unsafe + { + index &= 0x1F; + sbyte* buffer = stackalloc sbyte[32]; + Store(buffer, value); + buffer[index] = data; + return LoadVector256(buffer); + } + } + + /// + /// __m256i _mm256_insert_epi8 (__m256i a, __int8 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, byte data, byte index) + { + unsafe + { + index &= 0x1F; + byte* buffer = stackalloc byte[32]; + Store(buffer, value); + buffer[index] = data; + return LoadVector256(buffer); + } + } + + /// + /// __m256i _mm256_insert_epi16 (__m256i a, __int16 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, short data, byte index) + { + unsafe + { + index &= 0xF; + short* buffer = stackalloc short[16]; + Store(buffer, value); + buffer[index] = data; + return LoadVector256(buffer); + } + } + + /// + /// __m256i _mm256_insert_epi16 (__m256i a, __int16 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, ushort data, byte index) + { + unsafe + { + index &= 0xF; + ushort* buffer = stackalloc ushort[16]; + Store(buffer, value); + buffer[index] = data; + return LoadVector256(buffer); + } + } + + /// + /// __m256i _mm256_insert_epi32 (__m256i a, __int32 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, int data, byte index) + { + unsafe + { + index &= 0x7; + int* buffer = stackalloc int[8]; + Store(buffer, value); + buffer[index] = data; + return LoadVector256(buffer); + } + } + + /// + /// __m256i _mm256_insert_epi32 (__m256i a, __int32 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, uint data, byte index) + { + unsafe + { + index &= 0x7; + uint* buffer = stackalloc uint[8]; + Store(buffer, value); + buffer[index] = data; + return LoadVector256(buffer); + } + } + + /// + /// __m256i _mm256_insert_epi64 (__m256i a, __int64 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, long data, byte index) + { + if (IntPtr.Size != 8) + { + throw new PlatformNotSupportedException(); + } + + unsafe + { + index &= 0x3; + long* buffer = stackalloc long[4]; + Store(buffer, value); + buffer[index] = data; + return LoadVector256(buffer); + } + } + + /// + /// __m256i _mm256_insert_epi64 (__m256i a, __int64 i, const int index) + /// HELPER + /// + public static Vector256 Insert(Vector256 value, ulong data, byte index) + { + if (IntPtr.Size != 8) + { + throw new PlatformNotSupportedException(); + } + + unsafe + { + index &= 0x3; + ulong* buffer = stackalloc ulong[4]; + Store(buffer, value); + buffer[index] = data; + return LoadVector256(buffer); + } + } + + /// + /// __m256 _mm256_insertf128_ps (__m256 a, __m128 b, int imm8) + /// VINSERTF128 ymm, ymm, xmm/m128, imm8 + /// __m256d _mm256_insertf128_pd (__m256d a, __m128d b, int imm8) + /// VINSERTF128 ymm, ymm, xmm/m128, imm8 + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, xmm/m128, imm8 + /// + public static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) where T : struct + { + return InsertVector128(value, data, index); + } + + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, sbyte* address, byte index) => InsertVector128(value, address, index); + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, byte* address, byte index) => InsertVector128(value, address, index); + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, short* address, byte index) => InsertVector128(value, address, index); + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, ushort* address, byte index) => InsertVector128(value, address, index); + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, int* address, byte index) => InsertVector128(value, address, index); + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, uint* address, byte index) => InsertVector128(value, address, index); + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, long* address, byte index) => InsertVector128(value, address, index); + /// + /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, ulong* address, byte index) => InsertVector128(value, address, index); + /// + /// __m256 _mm256_insertf128_ps (__m256 a, __m128 b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, float* address, byte index) => InsertVector128(value, address, index); + /// + /// __m256d _mm256_insertf128_pd (__m256d a, __m128d b, int imm8) + /// VINSERTF128 ymm, ymm, m128, imm8 + /// + public static unsafe Vector256 InsertVector128(Vector256 value, double* address, byte index) => InsertVector128(value, address, index); + + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(sbyte* address) => LoadVector256(address); + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(byte* address) => LoadVector256(address); + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(short* address) => LoadVector256(address); + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(ushort* address) => LoadVector256(address); + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(int* address) => LoadVector256(address); + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(uint* address) => LoadVector256(address); + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(long* address) => LoadVector256(address); + /// + /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) + /// VMOVDQU ymm, m256 + /// + public static unsafe Vector256 LoadVector256(ulong* address) => LoadVector256(address); + /// + /// __m256 _mm256_loadu_ps (float const * mem_addr) + /// VMOVUPS ymm, ymm/m256 + /// + public static unsafe Vector256 LoadVector256(float* address) => LoadVector256(address); + /// + /// __m256d _mm256_loadu_pd (double const * mem_addr) + /// VMOVUPD ymm, ymm/m256 + /// + public static unsafe Vector256 LoadVector256(double* address) => LoadVector256(address); + + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(sbyte* address) => LoadAlignedVector256(address); + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(byte* address) => LoadAlignedVector256(address); + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(short* address) => LoadAlignedVector256(address); + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(ushort* address) => LoadAlignedVector256(address); + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(int* address) => LoadAlignedVector256(address); + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(uint* address) => LoadAlignedVector256(address); + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(long* address) => LoadAlignedVector256(address); + /// + /// __m256i _mm256_load_si256 (__m256i const * mem_addr) + /// VMOVDQA ymm, m256 + /// + public static unsafe Vector256 LoadAlignedVector256(ulong* address) => LoadAlignedVector256(address); + /// + /// __m256 _mm256_load_ps (float const * mem_addr) + /// VMOVAPS ymm, ymm/m256 + /// + public static unsafe Vector256 LoadAlignedVector256(float* address) => LoadAlignedVector256(address); + /// + /// __m256d _mm256_load_pd (double const * mem_addr) + /// VMOVAPD ymm, ymm/m256 + /// + public static unsafe Vector256 LoadAlignedVector256(double* address) => LoadAlignedVector256(address); + + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(sbyte* address) => LoadDquVector256(address); + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(byte* address) => LoadDquVector256(address); + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(short* address) => LoadDquVector256(address); + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(ushort* address) => LoadDquVector256(address); + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(int* address) => LoadDquVector256(address); + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(uint* address) => LoadDquVector256(address); + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(long* address) => LoadDquVector256(address); + /// + /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) + /// VLDDQU ymm, m256 + /// + public static unsafe Vector256 LoadDquVector256(ulong* address) => LoadDquVector256(address); + + /// + /// __m128 _mm_maskload_ps (float const * mem_addr, __m128i mask) + /// VMASKMOVPS xmm, xmm, m128 + /// + public static unsafe Vector128 MaskLoad(float* address, Vector128 mask) => MaskLoad(address, mask); + /// + /// __m128d _mm_maskload_pd (double const * mem_addr, __m128i mask) + /// VMASKMOVPD xmm, xmm, m128 + /// + public static unsafe Vector128 MaskLoad(double* address, Vector128 mask) => MaskLoad(address, mask); + + /// + /// __m256 _mm256_maskload_ps (float const * mem_addr, __m256i mask) + /// VMASKMOVPS ymm, ymm, m256 + /// + public static unsafe Vector256 MaskLoad(float* address, Vector256 mask) => MaskLoad(address, mask); + /// + /// __m256d _mm256_maskload_pd (double const * mem_addr, __m256i mask) + /// VMASKMOVPD ymm, ymm, m256 + /// + public static unsafe Vector256 MaskLoad(double* address, Vector256 mask) => MaskLoad(address, mask); + + /// + /// void _mm_maskstore_ps (float * mem_addr, __m128i mask, __m128 a) + /// VMASKMOVPS m128, xmm, xmm + /// + public static unsafe void MaskStore(float* address, Vector128 mask, Vector128 source) => MaskStore(address, mask, source); + /// + /// void _mm_maskstore_pd (double * mem_addr, __m128i mask, __m128d a) + /// VMASKMOVPD m128, xmm, xmm + /// + public static unsafe void MaskStore(double* address, Vector128 mask, Vector128 source) => MaskStore(address, mask, source); + + /// + /// void _mm256_maskstore_ps (float * mem_addr, __m256i mask, __m256 a) + /// VMASKMOVPS m256, ymm, ymm + /// + public static unsafe void MaskStore(float* address, Vector256 mask, Vector256 source) => MaskStore(address, mask, source); + /// + /// void _mm256_maskstore_pd (double * mem_addr, __m256i mask, __m256d a) + /// VMASKMOVPD m256, ymm, ymm + /// + public static unsafe void MaskStore(double* address, Vector256 mask, Vector256 source) => MaskStore(address, mask, source); + + /// + /// __m256 _mm256_max_ps (__m256 a, __m256 b) + /// VMAXPS ymm, ymm, ymm/m256 + /// + public static Vector256 Max(Vector256 left, Vector256 right) => Max(left, right); + /// + /// __m256d _mm256_max_pd (__m256d a, __m256d b) + /// VMAXPD ymm, ymm, ymm/m256 + /// + public static Vector256 Max(Vector256 left, Vector256 right) => Max(left, right); + + /// + /// __m256 _mm256_min_ps (__m256 a, __m256 b) + /// VMINPS ymm, ymm, ymm/m256 + /// + public static Vector256 Min(Vector256 left, Vector256 right) => Min(left, right); + /// + /// __m256d _mm256_min_pd (__m256d a, __m256d b) + /// VMINPD ymm, ymm, ymm/m256 + /// + public static Vector256 Min(Vector256 left, Vector256 right) => Min(left, right); + + /// + /// int _mm256_movemask_ps (__m256 a) + /// VMOVMSKPS reg, ymm + /// + public static int MoveMask(Vector256 value) => MoveMask(value); + /// + /// int _mm256_movemask_pd (__m256d a) + /// VMOVMSKPD reg, ymm + /// + public static int MoveMask(Vector256 value) => MoveMask(value); + + /// + /// __m256 _mm256_mul_ps (__m256 a, __m256 b) + /// VMULPS ymm, ymm, ymm/m256 + /// + public static Vector256 Multiply(Vector256 left, Vector256 right) => Multiply(left, right); + /// + /// __m256d _mm256_mul_pd (__m256d a, __m256d b) + /// VMULPD ymm, ymm, ymm/m256 + /// + public static Vector256 Multiply(Vector256 left, Vector256 right) => Multiply(left, right); + + /// + /// __m256 _mm256_or_ps (__m256 a, __m256 b) + /// VORPS ymm, ymm, ymm/m256 + /// + public static Vector256 Or(Vector256 left, Vector256 right) => Or(left, right); + /// + /// __m256d _mm256_or_pd (__m256d a, __m256d b) + /// VORPD ymm, ymm, ymm/m256 + /// + public static Vector256 Or(Vector256 left, Vector256 right) => Or(left, right); + + /// + /// __m128 _mm_permute_ps (__m128 a, int imm8) + /// VPERMILPS xmm, xmm, imm8 + /// + public static Vector128 Permute(Vector128 value, byte control) => Permute(value, control); + /// + /// __m128d _mm_permute_pd (__m128d a, int imm8) + /// VPERMILPD xmm, xmm, imm8 + /// + public static Vector128 Permute(Vector128 value, byte control) => Permute(value, control); + + /// + /// __m256 _mm256_permute_ps (__m256 a, int imm8) + /// VPERMILPS ymm, ymm, imm8 + /// + public static Vector256 Permute(Vector256 value, byte control) => Permute(value, control); + /// + /// __m256d _mm256_permute_pd (__m256d a, int imm8) + /// VPERMILPD ymm, ymm, imm8 + /// + public static Vector256 Permute(Vector256 value, byte control) => Permute(value, control); + + /// + /// __m256 _mm256_permute2f128_ps (__m256 a, __m256 b, int imm8) + /// VPERM2F128 ymm, ymm, ymm/m256, imm8 + /// __m256d _mm256_permute2f128_pd (__m256d a, __m256d b, int imm8) + /// VPERM2F128 ymm, ymm, ymm/m256, imm8 + /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) + /// VPERM2F128 ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) where T : struct + { + return Permute2x128(left, right, control); + } + + /// + /// __m128 _mm_permutevar_ps (__m128 a, __m128i b) + /// VPERMILPS xmm, xmm, xmm/m128 + /// + public static Vector128 PermuteVar(Vector128 left, Vector128 control) => PermuteVar(left, control); + /// + /// __m128d _mm_permutevar_pd (__m128d a, __m128i b) + /// VPERMILPD xmm, xmm, xmm/m128 + /// + public static Vector128 PermuteVar(Vector128 left, Vector128 control) => PermuteVar(left, control); + /// + /// __m256 _mm256_permutevar_ps (__m256 a, __m256i b) + /// VPERMILPS ymm, ymm, ymm/m256 + /// + public static Vector256 PermuteVar(Vector256 left, Vector256 control) => PermuteVar(left, control); + /// + /// __m256d _mm256_permutevar_pd (__m256d a, __m256i b) + /// VPERMILPD ymm, ymm, ymm/m256 + /// + public static Vector256 PermuteVar(Vector256 left, Vector256 control) => PermuteVar(left, control); + + /// + /// __m256 _mm256_rcp_ps (__m256 a) + /// VRCPPS ymm, ymm/m256 + /// + public static Vector256 Reciprocal(Vector256 value) => Reciprocal(value); + + /// + /// __m256 _mm256_rsqrt_ps (__m256 a) + /// VRSQRTPS ymm, ymm/m256 + /// + public static Vector256 ReciprocalSqrt(Vector256 value) => ReciprocalSqrt(value); + + /// + /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) + /// VROUNDPS ymm, ymm/m256, imm8(8) + /// + public static Vector256 RoundToNearestInteger(Vector256 value) => RoundToNearestInteger(value); + /// + /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) + /// VROUNDPS ymm, ymm/m256, imm8(9) + /// + public static Vector256 RoundToNegativeInfinity(Vector256 value) => RoundToNegativeInfinity(value); + /// + /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) + /// VROUNDPS ymm, ymm/m256, imm8(10) + /// + public static Vector256 RoundToPositiveInfinity(Vector256 value) => RoundToPositiveInfinity(value); + /// + /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC) + /// VROUNDPS ymm, ymm/m256, imm8(11) + /// + public static Vector256 RoundToZero(Vector256 value) => RoundToZero(value); + /// + /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_CUR_DIRECTION) + /// VROUNDPS ymm, ymm/m256, imm8(4) + /// + public static Vector256 RoundCurrentDirection(Vector256 value) => RoundCurrentDirection(value); + + /// + /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) + /// VROUNDPD ymm, ymm/m256, imm8(8) + /// + public static Vector256 RoundToNearestInteger(Vector256 value) => RoundToNearestInteger(value); + /// + /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) + /// VROUNDPD ymm, ymm/m256, imm8(9) + /// + public static Vector256 RoundToNegativeInfinity(Vector256 value) => RoundToNegativeInfinity(value); + /// + /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) + /// VROUNDPD ymm, ymm/m256, imm8(10) + /// + public static Vector256 RoundToPositiveInfinity(Vector256 value) => RoundToPositiveInfinity(value); + /// + /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC) + /// VROUNDPD ymm, ymm/m256, imm8(11) + /// + public static Vector256 RoundToZero(Vector256 value) => RoundToZero(value); + /// + /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_CUR_DIRECTION) + /// VROUNDPD ymm, ymm/m256, imm8(4) + /// + public static Vector256 RoundCurrentDirection(Vector256 value) => RoundCurrentDirection(value); + + /// + /// __m256i _mm256_set_epi8 (char e31, char e30, char e29, char e28, char e27, char e26, char e25, char e24, char e23, char e22, char e21, char e20, char e19, char e18, char e17, char e16, char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) + /// HELPER + /// + public static Vector256 SetVector256(sbyte e31, sbyte e30, sbyte e29, sbyte e28, sbyte e27, sbyte e26, sbyte e25, sbyte e24, sbyte e23, sbyte e22, sbyte e21, sbyte e20, sbyte e19, sbyte e18, sbyte e17, sbyte e16, sbyte e15, sbyte e14, sbyte e13, sbyte e12, sbyte e11, sbyte e10, sbyte e9, sbyte e8, sbyte e7, sbyte e6, sbyte e5, sbyte e4, sbyte e3, sbyte e2, sbyte e1, sbyte e0) => SetVector256(e31, e30, e29, e28, e27, e26, e25, e24, e23, e22, e21, e20, e19, e18, e17, e16, e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0); + /// + /// __m256i _mm256_set_epi8 (char e31, char e30, char e29, char e28, char e27, char e26, char e25, char e24, char e23, char e22, char e21, char e20, char e19, char e18, char e17, char e16, char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) + /// HELPER + /// + public static Vector256 SetVector256(byte e31, byte e30, byte e29, byte e28, byte e27, byte e26, byte e25, byte e24, byte e23, byte e22, byte e21, byte e20, byte e19, byte e18, byte e17, byte e16, byte e15, byte e14, byte e13, byte e12, byte e11, byte e10, byte e9, byte e8, byte e7, byte e6, byte e5, byte e4, byte e3, byte e2, byte e1, byte e0) => SetVector256(e31, e30, e29, e28, e27, e26, e25, e24, e23, e22, e21, e20, e19, e18, e17, e16, e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0); + /// + /// __m256i _mm256_set_epi16 (short e15, short e14, short e13, short e12, short e11, short e10, short e9, short e8, short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) + /// HELPER + /// + public static Vector256 SetVector256(short e15, short e14, short e13, short e12, short e11, short e10, short e9, short e8, short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) => SetVector256(e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0); + /// + /// __m256i _mm256_set_epi16 (short e15, short e14, short e13, short e12, short e11, short e10, short e9, short e8, short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) + /// HELPER + /// + public static Vector256 SetVector256(ushort e15, ushort e14, ushort e13, ushort e12, ushort e11, ushort e10, ushort e9, ushort e8, ushort e7, ushort e6, ushort e5, ushort e4, ushort e3, ushort e2, ushort e1, ushort e0) => SetVector256(e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0); + /// + /// __m256i _mm256_set_epi32 (int e7, int e6, int e5, int e4, int e3, int e2, int e1, int e0) + /// HELPER + /// + public static Vector256 SetVector256(int e7, int e6, int e5, int e4, int e3, int e2, int e1, int e0) => SetVector256(e7, e6, e5, e4, e3, e2, e1, e0); + /// + /// __m256i _mm256_set_epi32 (int e7, int e6, int e5, int e4, int e3, int e2, int e1, int e0) + /// HELPER + /// + public static Vector256 SetVector256(uint e7, uint e6, uint e5, uint e4, uint e3, uint e2, uint e1, uint e0) => SetVector256(e7, e6, e5, e4, e3, e2, e1, e0); + /// + /// __m256i _mm256_set_epi64x (__int64 e3, __int64 e2, __int64 e1, __int64 e0) + /// HELPER + /// + public static Vector256 SetVector256(long e3, long e2, long e1, long e0) => SetVector256(e3, e2, e1, e0); + /// + /// __m256i _mm256_set_epi64x (__int64 e3, __int64 e2, __int64 e1, __int64 e0) + /// HELPER + /// + public static Vector256 SetVector256(ulong e3, ulong e2, ulong e1, ulong e0) => SetVector256(e3, e2, e1, e0); + /// + /// __m256 _mm256_set_ps (float e7, float e6, float e5, float e4, float e3, float e2, float e1, float e0) + /// HELPER + /// + public static Vector256 SetVector256(float e7, float e6, float e5, float e4, float e3, float e2, float e1, float e0) => SetVector256(e7, e6, e5, e4, e3, e2, e1, e0); + /// + /// __m256d _mm256_set_pd (double e3, double e2, double e1, double e0) + /// HELPER + /// + public static Vector256 SetVector256(double e3, double e2, double e1, double e0) => SetVector256(e3, e2, e1, e0); + + /// + /// __m256i _mm256_set1_epi8 (char a) + /// HELPER + /// __m256i _mm256_set1_epi16 (short a) + /// HELPER + /// __m256i _mm256_set1_epi32 (int a) + /// HELPER + /// __m256i _mm256_set1_epi64x (long long a) + /// HELPER + /// __m256 _mm256_set1_ps (float a) + /// HELPER + /// __m256d _mm256_set1_pd (double a) + /// HELPER + /// + public static Vector256 SetAllVector256(T value) where T : struct + { + return SetAllVector256(value); + } + + /// + /// __m256 _mm256_set_m128 (__m128 hi, __m128 lo) + /// HELPER + /// __m256d _mm256_set_m128d (__m128d hi, __m128d lo) + /// HELPER + /// __m256i _mm256_set_m128i (__m128i hi, __m128i lo) + /// HELPER + /// + public static Vector256 SetHighLow(Vector128 hi, Vector128 lo) where T : struct + { + return SetHighLow(hi, lo); + } + + /// + /// __m256i _mm256_setzero_si256 (void) + /// HELPER + /// __m256 _mm256_setzero_ps (void) + /// HELPER + /// __m256d _mm256_setzero_pd (void) + /// HELPER + /// + public static Vector256 SetZeroVector256() where T : struct + { + return SetZeroVector256(); + } + + /// + /// __m256 _mm256_shuffle_ps (__m256 a, __m256 b, const int imm8) + /// VSHUFPS ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 Shuffle(Vector256 value, Vector256 right, byte control) => Shuffle(value, right, control); + /// + /// __m256d _mm256_shuffle_pd (__m256d a, __m256d b, const int imm8) + /// VSHUFPD ymm, ymm, ymm/m256, imm8 + /// + public static Vector256 Shuffle(Vector256 value, Vector256 right, byte control) => Shuffle(value, right, control); + + /// + /// __m256 _mm256_sqrt_ps (__m256 a) + /// VSQRTPS ymm, ymm/m256 + /// + public static Vector256 Sqrt(Vector256 value) => Sqrt(value); + /// + /// __m256d _mm256_sqrt_pd (__m256d a) + /// VSQRTPD ymm, ymm/m256 + /// + public static Vector256 Sqrt(Vector256 value) => Sqrt(value); + + /// + /// __m256 _mm256_castpd_ps (__m256d a) + /// HELPER - No Codegen + /// __m256i _mm256_castpd_si256 (__m256d a) + /// HELPER - No Codegen + /// __m256d _mm256_castps_pd (__m256 a) + /// HELPER - No Codegen + /// __m256i _mm256_castps_si256 (__m256 a) + /// HELPER - No Codegen + /// __m256d _mm256_castsi256_pd (__m256i a) + /// HELPER - No Codegen + /// __m256 _mm256_castsi256_ps (__m256i a) + /// HELPER - No Codegen + /// + public static Vector256 StaticCast(Vector256 value) where T : struct where U : struct + { + return StaticCast(value); + } + + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(sbyte* address, Vector256 source) => StoreAligned(address, source); + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(byte* address, Vector256 source) => StoreAligned(address, source); + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(short* address, Vector256 source) => StoreAligned(address, source); + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(ushort* address, Vector256 source) => StoreAligned(address, source); + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(int* address, Vector256 source) => StoreAligned(address, source); + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(uint* address, Vector256 source) => StoreAligned(address, source); + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(long* address, Vector256 source) => StoreAligned(address, source); + /// + /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQA m256, ymm + /// + public static unsafe void StoreAligned(ulong* address, Vector256 source) => StoreAligned(address, source); + /// + /// void _mm256_store_ps (float * mem_addr, __m256 a) + /// VMOVAPS m256, ymm + /// + public static unsafe void StoreAligned(float* address, Vector256 source) => StoreAligned(address, source); + /// + /// void _mm256_store_pd (double * mem_addr, __m256d a) + /// VMOVAPD m256, ymm + /// + public static unsafe void StoreAligned(double* address, Vector256 source) => StoreAligned(address, source); + + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(sbyte* address, Vector256 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(byte* address, Vector256 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(short* address, Vector256 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(ushort* address, Vector256 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(int* address, Vector256 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(uint* address, Vector256 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(long* address, Vector256 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) + /// VMOVNTDQ m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(ulong* address, Vector256 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm256_stream_ps (float * mem_addr, __m256 a) + /// MOVNTPS m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(float* address, Vector256 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm256_stream_pd (double * mem_addr, __m256d a) + /// MOVNTPD m256, ymm + /// + public static unsafe void StoreAlignedNonTemporal(double* address, Vector256 source) => StoreAlignedNonTemporal(address, source); + + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(sbyte* address, Vector256 source) => Store(address, source); + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(byte* address, Vector256 source) => Store(address, source); + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(short* address, Vector256 source) => Store(address, source); + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(ushort* address, Vector256 source) => Store(address, source); + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(int* address, Vector256 source) => Store(address, source); + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(uint* address, Vector256 source) => Store(address, source); + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(long* address, Vector256 source) => Store(address, source); + /// + /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) + /// MOVDQU m256, ymm + /// + public static unsafe void Store(ulong* address, Vector256 source) => Store(address, source); + /// + /// void _mm256_storeu_ps (float * mem_addr, __m256 a) + /// MOVUPS m256, ymm + /// + public static unsafe void Store(float* address, Vector256 source) => Store(address, source); + /// + /// void _mm256_storeu_pd (double * mem_addr, __m256d a) + /// MOVUPD m256, ymm + /// + public static unsafe void Store(double* address, Vector256 source) => Store(address, source); + + /// + /// __m256 _mm256_sub_ps (__m256 a, __m256 b) + /// VSUBPS ymm, ymm, ymm/m256 + /// + public static Vector256 Subtract(Vector256 left, Vector256 right) => Subtract(left, right); + /// + /// __m256d _mm256_sub_pd (__m256d a, __m256d b) + /// VSUBPD ymm, ymm, ymm/m256 + /// + public static Vector256 Subtract(Vector256 left, Vector256 right) => Subtract(left, right); + + /// + /// int _mm_testc_ps (__m128 a, __m128 b) + /// VTESTPS xmm, xmm/m128 + /// + public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + /// + /// int _mm_testc_pd (__m128d a, __m128d b) + /// VTESTPD xmm, xmm/m128 + /// + public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + + /// + /// int _mm256_testc_si256 (__m256i a, __m256i b) + /// VPTEST ymm, ymm/m256 + /// int _mm256_testc_ps (__m256 a, __m256 b) + /// VTESTPS ymm, ymm/m256 + /// int _mm256_testc_pd (__m256d a, __m256d b) + /// VTESTPS ymm, ymm/m256 + /// + public static bool TestC(Vector256 left, Vector256 right) where T : struct + { + return TestC(left, right); + } + + /// + /// int _mm_testnzc_ps (__m128 a, __m128 b) + /// VTESTPS xmm, xmm/m128 + /// + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + /// + /// int _mm_testnzc_pd (__m128d a, __m128d b) + /// VTESTPD xmm, xmm/m128 + /// + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + + /// + /// int _mm256_testnzc_si256 (__m256i a, __m256i b) + /// VPTEST ymm, ymm/m256 + /// int _mm256_testnzc_ps (__m256 a, __m256 b) + /// VTESTPS ymm, ymm/m256 + /// int _mm256_testnzc_pd (__m256d a, __m256d b) + /// VTESTPD ymm, ymm/m256 + /// + public static bool TestNotZAndNotC(Vector256 left, Vector256 right) where T : struct + { + return TestNotZAndNotC(left, right); + } + + /// + /// int _mm_testz_ps (__m128 a, __m128 b) + /// VTESTPS xmm, xmm/m128 + /// + public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + /// + /// int _mm_testz_pd (__m128d a, __m128d b) + /// VTESTPD xmm, xmm/m128 + /// + public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + + /// + /// int _mm256_testz_si256 (__m256i a, __m256i b) + /// VPTEST ymm, ymm/m256 + /// int _mm256_testz_ps (__m256 a, __m256 b) + /// VTESTPS ymm, ymm/m256 + /// int _mm256_testz_pd (__m256d a, __m256d b) + /// VTESTPD ymm, ymm/m256 + /// + public static bool TestZ(Vector256 left, Vector256 right) where T : struct + { + return TestZ(left, right); + } + + /// + /// __m256 _mm256_unpackhi_ps (__m256 a, __m256 b) + /// VUNPCKHPS ymm, ymm, ymm/m256 + /// + public static Vector256 UnpackHigh(Vector256 left, Vector256 right) => UnpackHigh(left, right); + /// + /// __m256d _mm256_unpackhi_pd (__m256d a, __m256d b) + /// VUNPCKHPD ymm, ymm, ymm/m256 + /// + public static Vector256 UnpackHigh(Vector256 left, Vector256 right) => UnpackHigh(left, right); + + /// + /// __m256 _mm256_unpacklo_ps (__m256 a, __m256 b) + /// VUNPCKLPS ymm, ymm, ymm/m256 + /// + public static Vector256 UnpackLow(Vector256 left, Vector256 right) => UnpackLow(left, right); + /// + /// __m256d _mm256_unpacklo_pd (__m256d a, __m256d b) + /// VUNPCKLPD ymm, ymm, ymm/m256 + /// + public static Vector256 UnpackLow(Vector256 left, Vector256 right) => UnpackLow(left, right); + + /// + /// __m256 _mm256_xor_ps (__m256 a, __m256 b) + /// VXORPS ymm, ymm, ymm/m256 + /// + public static Vector256 Xor(Vector256 left, Vector256 right) => Xor(left, right); + /// + /// __m256d _mm256_xor_pd (__m256d a, __m256d b) + /// VXORPS ymm, ymm, ymm/m256 + /// + public static Vector256 Xor(Vector256 left, Vector256 right) => Xor(left, right); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx2.PlatformNotSupported.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx2.PlatformNotSupported.cs.REMOVED.git-id new file mode 100644 index 0000000000..ce3d700336 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx2.PlatformNotSupported.cs.REMOVED.git-id @@ -0,0 +1 @@ +79c30d37a285d65de0f0387fc9828c7904d33bf1 \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx2.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx2.cs.REMOVED.git-id new file mode 100644 index 0000000000..71c7e45e9d --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx2.cs.REMOVED.git-id @@ -0,0 +1 @@ +90c5b315b772150796a415c5561c9fd3274f36fe \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi1.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi1.PlatformNotSupported.cs new file mode 100644 index 0000000000..2b0b48fe78 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi1.PlatformNotSupported.cs @@ -0,0 +1,96 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel BMI1 hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Bmi1 + { + internal Bmi1() { } + + public static bool IsSupported { get { return false; } } + + /// + /// unsigned int _andn_u32 (unsigned int a, unsigned int b) + /// ANDN r32a, r32b, reg/m32 + /// + public static uint AndNot(uint left, uint right) { throw new PlatformNotSupportedException(); } + /// + /// unsigned __int64 _andn_u64 (unsigned __int64 a, unsigned __int64 b) + /// ANDN r64a, r64b, reg/m64 + /// + public static ulong AndNot(ulong left, ulong right) { throw new PlatformNotSupportedException(); } + + /// + /// unsigned int _bextr_u32 (unsigned int a, unsigned int start, unsigned int len) + /// BEXTR r32a, reg/m32, r32b + /// + public static uint BitFieldExtract(uint value, byte start, byte length) { throw new PlatformNotSupportedException(); } + /// + /// unsigned __int64 _bextr_u64 (unsigned __int64 a, unsigned int start, unsigned int len) + /// BEXTR r64a, reg/m64, r64b + /// + public static ulong BitFieldExtract(ulong value, byte start, byte length) { throw new PlatformNotSupportedException(); } + /// + /// unsigned int _bextr2_u32 (unsigned int a, unsigned int control) + /// BEXTR r32a, reg/m32, r32b + /// + public static uint BitFieldExtract(uint value, ushort control) { throw new PlatformNotSupportedException(); } + /// + /// unsigned __int64 _bextr2_u64 (unsigned __int64 a, unsigned __int64 control) + /// BEXTR r64a, reg/m64, r64b + /// + public static ulong BitFieldExtract(ulong value, ushort control) { throw new PlatformNotSupportedException(); } + + /// + /// unsigned int _blsi_u32 (unsigned int a) + /// BLSI reg, reg/m32 + /// + public static uint ExtractLowestSetBit(uint value) { throw new PlatformNotSupportedException(); } + /// + /// unsigned __int64 _blsi_u64 (unsigned __int64 a) + /// BLSI reg, reg/m64 + /// + public static ulong ExtractLowestSetBit(ulong value) { throw new PlatformNotSupportedException(); } + + /// + /// unsigned int _blsmsk_u32 (unsigned int a) + /// BLSMSK reg, reg/m32 + /// + public static uint GetMaskUpToLowestSetBit(uint value) { throw new PlatformNotSupportedException(); } + /// + /// unsigned __int64 _blsmsk_u64 (unsigned __int64 a) + /// BLSMSK reg, reg/m64 + /// + public static ulong GetMaskUpToLowestSetBit(ulong value) { throw new PlatformNotSupportedException(); } + + /// + /// unsigned int _blsr_u32 (unsigned int a) + /// BLSR reg, reg/m32 + /// + public static uint ResetLowestSetBit(uint value) { throw new PlatformNotSupportedException(); } + /// + /// unsigned __int64 _blsr_u64 (unsigned __int64 a) + /// BLSR reg, reg/m64 + /// + public static ulong ResetLowestSetBit(ulong value) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_tzcnt_32 (unsigned int a) + /// TZCNT reg, reg/m32 + /// + public static uint TrailingZeroCount(uint value) { throw new PlatformNotSupportedException(); } + /// + /// __int64 _mm_tzcnt_64 (unsigned __int64 a) + /// TZCNT reg, reg/m64 + /// + public static ulong TrailingZeroCount(ulong value) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi1.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi1.cs new file mode 100644 index 0000000000..f06f54d839 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi1.cs @@ -0,0 +1,96 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel BMI1 hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Bmi1 + { + internal Bmi1() { } + + public static bool IsSupported { get => IsSupported; } + + /// + /// unsigned int _andn_u32 (unsigned int a, unsigned int b) + /// ANDN r32a, r32b, reg/m32 + /// + public static uint AndNot(uint left, uint right) => AndNot(left, right); + /// + /// unsigned __int64 _andn_u64 (unsigned __int64 a, unsigned __int64 b) + /// ANDN r64a, r64b, reg/m64 + /// + public static ulong AndNot(ulong left, ulong right) => AndNot(left, right); + + /// + /// unsigned int _bextr_u32 (unsigned int a, unsigned int start, unsigned int len) + /// BEXTR r32a, reg/m32, r32b + /// + public static uint BitFieldExtract(uint value, byte start, byte length) => BitFieldExtract(value, start, length); + /// + /// unsigned __int64 _bextr_u64 (unsigned __int64 a, unsigned int start, unsigned int len) + /// BEXTR r64a, reg/m64, r64b + /// + public static ulong BitFieldExtract(ulong value, byte start, byte length) => BitFieldExtract(value, start, length); + /// + /// unsigned int _bextr2_u32 (unsigned int a, unsigned int control) + /// BEXTR r32a, reg/m32, r32b + /// + public static uint BitFieldExtract(uint value, ushort control) => BitFieldExtract(value, control); + /// + /// unsigned __int64 _bextr2_u64 (unsigned __int64 a, unsigned __int64 control) + /// BEXTR r64a, reg/m64, r64b + /// + public static ulong BitFieldExtract(ulong value, ushort control) => BitFieldExtract(value, control); + + /// + /// unsigned int _blsi_u32 (unsigned int a) + /// BLSI reg, reg/m32 + /// + public static uint ExtractLowestSetBit(uint value) => ExtractLowestSetBit(value); + /// + /// unsigned __int64 _blsi_u64 (unsigned __int64 a) + /// BLSI reg, reg/m64 + /// + public static ulong ExtractLowestSetBit(ulong value) => ExtractLowestSetBit(value); + + /// + /// unsigned int _blsmsk_u32 (unsigned int a) + /// BLSMSK reg, reg/m32 + /// + public static uint GetMaskUpToLowestSetBit(uint value) => GetMaskUpToLowestSetBit(value); + /// + /// unsigned __int64 _blsmsk_u64 (unsigned __int64 a) + /// BLSMSK reg, reg/m64 + /// + public static ulong GetMaskUpToLowestSetBit(ulong value) => GetMaskUpToLowestSetBit(value); + + /// + /// unsigned int _blsr_u32 (unsigned int a) + /// BLSR reg, reg/m32 + /// + public static uint ResetLowestSetBit(uint value) => ResetLowestSetBit(value); + /// + /// unsigned __int64 _blsr_u64 (unsigned __int64 a) + /// BLSR reg, reg/m64 + /// + public static ulong ResetLowestSetBit(ulong value) => ResetLowestSetBit(value); + + /// + /// int _mm_tzcnt_32 (unsigned int a) + /// TZCNT reg, reg/m32 + /// + public static uint TrailingZeroCount(uint value) => TrailingZeroCount(value); + /// + /// __int64 _mm_tzcnt_64 (unsigned __int64 a) + /// TZCNT reg, reg/m64 + /// + public static ulong TrailingZeroCount(ulong value) => TrailingZeroCount(value); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi2.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi2.PlatformNotSupported.cs new file mode 100644 index 0000000000..0789d6f3cd --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi2.PlatformNotSupported.cs @@ -0,0 +1,64 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel BMI2 hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Bmi2 + { + internal Bmi2() { } + + public static bool IsSupported { get { return false; } } + + /// + /// unsigned int _bzhi_u32 (unsigned int a, unsigned int index) + /// BZHI r32a, reg/m32, r32b + /// + public static uint ZeroHighBits(uint value, uint index) { throw new PlatformNotSupportedException(); } + /// + /// unsigned __int64 _bzhi_u64 (unsigned __int64 a, unsigned int index) + /// BZHI r64a, reg/m32, r64b + /// + public static ulong ZeroHighBits(ulong value, ulong index) { throw new PlatformNotSupportedException(); } + + /// + /// unsigned int _mulx_u32 (unsigned int a, unsigned int b, unsigned int* hi) + /// MULX r32a, r32b, reg/m32 + /// + public static unsafe uint MultiplyNoFlags(uint left, uint right, uint* high) { throw new PlatformNotSupportedException(); } + /// + /// unsigned __int64 _mulx_u64 (unsigned __int64 a, unsigned __int64 b, unsigned __int64* hi) + /// MULX r64a, r64b, reg/m64 + /// + public static unsafe ulong MultiplyNoFlags(ulong left, ulong right, ulong* high) { throw new PlatformNotSupportedException(); } + + /// + /// unsigned int _pdep_u32 (unsigned int a, unsigned int mask) + /// PDEP r32a, r32b, reg/m32 + /// + public static uint ParallelBitDeposit(uint value, uint mask) { throw new PlatformNotSupportedException(); } + /// + /// unsigned __int64 _pdep_u64 (unsigned __int64 a, unsigned __int64 mask) + /// PDEP r64a, r64b, reg/m64 + /// + public static ulong ParallelBitDeposit(ulong value, ulong mask) { throw new PlatformNotSupportedException(); } + + /// + /// unsigned int _pext_u32 (unsigned int a, unsigned int mask) + /// PEXT r32a, r32b, reg/m32 + /// + public static uint ParallelBitExtract(uint value, uint mask) { throw new PlatformNotSupportedException(); } + /// + /// unsigned __int64 _pext_u64 (unsigned __int64 a, unsigned __int64 mask) + /// PEXT r64a, r64b, reg/m64 + /// + public static ulong ParallelBitExtract(ulong value, ulong mask) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi2.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi2.cs new file mode 100644 index 0000000000..d8fb1521a2 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi2.cs @@ -0,0 +1,64 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel BMI2 hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Bmi2 + { + internal Bmi2() { } + + public static bool IsSupported { get => IsSupported; } + + /// + /// unsigned int _bzhi_u32 (unsigned int a, unsigned int index) + /// BZHI r32a, reg/m32, r32b + /// + public static uint ZeroHighBits(uint value, uint index) => ZeroHighBits(value, index); + /// + /// unsigned __int64 _bzhi_u64 (unsigned __int64 a, unsigned int index) + /// BZHI r64a, reg/m32, r64b + /// + public static ulong ZeroHighBits(ulong value, ulong index) => ZeroHighBits(value, index); + + /// + /// unsigned int _mulx_u32 (unsigned int a, unsigned int b, unsigned int* hi) + /// MULX r32a, r32b, reg/m32 + /// + public static unsafe uint MultiplyNoFlags(uint left, uint right, uint* high) => MultiplyNoFlags(left, right, high); + /// + /// unsigned __int64 _mulx_u64 (unsigned __int64 a, unsigned __int64 b, unsigned __int64* hi) + /// MULX r64a, r64b, reg/m64 + /// + public static unsafe ulong MultiplyNoFlags(ulong left, ulong right, ulong* high) => MultiplyNoFlags(left, right, high); + + /// + /// unsigned int _pdep_u32 (unsigned int a, unsigned int mask) + /// PDEP r32a, r32b, reg/m32 + /// + public static uint ParallelBitDeposit(uint value, uint mask) => ParallelBitDeposit(value, mask); + /// + /// unsigned __int64 _pdep_u64 (unsigned __int64 a, unsigned __int64 mask) + /// PDEP r64a, r64b, reg/m64 + /// + public static ulong ParallelBitDeposit(ulong value, ulong mask) => ParallelBitDeposit(value, mask); + + /// + /// unsigned int _pext_u32 (unsigned int a, unsigned int mask) + /// PEXT r32a, r32b, reg/m32 + /// + public static uint ParallelBitExtract(uint value, uint mask) => ParallelBitExtract(value, mask); + /// + /// unsigned __int64 _pext_u64 (unsigned __int64 a, unsigned __int64 mask) + /// PEXT r64a, r64b, reg/m64 + /// + public static ulong ParallelBitExtract(ulong value, ulong mask) => ParallelBitExtract(value, mask); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Enums.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Enums.cs new file mode 100644 index 0000000000..cf8cd43709 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Enums.cs @@ -0,0 +1,189 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Runtime.Intrinsics.X86 +{ + public enum FloatComparisonMode : byte + { + /// + /// _CMP_EQ_OQ + /// + EqualOrderedNonSignaling = 0, + + /// + /// _CMP_LT_OS + /// + LessThanOrderedSignaling = 1, + + /// + /// _CMP_LE_OS + /// + LessThanOrEqualOrderedSignaling = 2, + + /// + /// _CMP_UNORD_Q + /// + UnorderedNonSignaling = 3, + + /// + /// _CMP_NEQ_UQ + /// + NotEqualUnorderedNonSignaling = 4, + + /// + /// _CMP_NLT_US + /// + NotLessThanUnorderedSignaling = 5, + + /// + /// _CMP_NLE_US + /// + NotLessThanOrEqualUnorderedSignaling = 6, + + /// + /// _CMP_ORD_Q + /// + OrderedNonSignaling = 7, + + /// + /// _CMP_EQ_UQ + /// + EqualUnorderedNonSignaling = 8, + + /// + /// _CMP_NGE_US + /// + NotGreaterThanOrEqualUnorderedSignaling = 9, + + /// + /// _CMP_NGT_US + /// + NotGreaterThanUnorderedSignaling = 10, + + /// + /// _CMP_FALSE_OQ + /// + FalseOrderedNonSignaling = 11, + + /// + /// _CMP_NEQ_OQ + /// + NotEqualOrderedNonSignaling = 12, + + /// + /// _CMP_GE_OS + /// + GreaterThanOrEqualOrderedSignaling = 13, + + /// + /// _CMP_GT_OS + /// + GreaterThanOrderedSignaling = 14, + + /// + /// _CMP_TRUE_UQ + /// + TrueUnorderedNonSignaling = 15, + + /// + /// _CMP_EQ_OS + /// + EqualOrderedSignaling = 16, + + /// + /// _CMP_LT_OQ + /// + LessThanOrderedNonSignaling = 17, + + /// + /// _CMP_LE_OQ + /// + LessThanOrEqualOrderedNonSignaling = 18, + + /// + /// _CMP_UNORD_S + /// + UnorderedSignaling = 19, + + /// + /// _CMP_NEQ_US + /// + NotEqualUnorderedSignaling = 20, + + /// + /// _CMP_NLT_UQ + /// + NotLessThanUnorderedNonSignaling = 21, + + /// + /// _CMP_NLE_UQ + /// + NotLessThanOrEqualUnorderedNonSignaling = 22, + + /// + /// _CMP_ORD_S + /// + OrderedSignaling = 23, + + /// + /// _CMP_EQ_US + /// + EqualUnorderedSignaling = 24, + + /// + /// _CMP_NGE_UQ + /// + NotGreaterThanOrEqualUnorderedNonSignaling = 25, + + /// + /// _CMP_NGT_UQ + /// + NotGreaterThanUnorderedNonSignaling = 26, + + /// + /// _CMP_FALSE_OS + /// + FalseOrderedSignaling = 27, + + /// + /// _CMP_NEQ_OS + /// + NotEqualOrderedSignaling = 28, + + /// + /// _CMP_GE_OQ + /// + GreaterThanOrEqualOrderedNonSignaling = 29, + + /// + /// _CMP_GT_OQ + /// + GreaterThanOrderedNonSignaling = 30, + + /// + /// _CMP_TRUE_US + /// + TrueUnorderedSignaling = 31, + } + + public enum StringComparisonMode : byte { + EqualAny = 0x00, + Ranges = 0x04, + EqualEach = 0x08, + EqualOrdered = 0x0c, + NegativePolarity = 0x10, + MaskedNegativePolarity = 0x30, + LeastSignificant = 0x00, + MostSignificant = 0x40, + } + + + public enum ResultsFlag : byte { + CFlag = 0, + NotCFlagAndNotZFlag = 1, + OFlag = 2, + SFlag = 3, + ZFlag = 4, + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Fma.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Fma.PlatformNotSupported.cs new file mode 100644 index 0000000000..91becab4d5 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Fma.PlatformNotSupported.cs @@ -0,0 +1,190 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel FMA hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Fma : Avx + { + internal Fma() { } + + public new static bool IsSupported { get { return false; } } + + /// + /// __m128 _mm_fmadd_ps (__m128 a, __m128 b, __m128 c) + /// VFMADDPS xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplyAdd(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_fmadd_pd (__m128d a, __m128d b, __m128d c) + /// VFMADDPD xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplyAdd(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_fmadd_ps (__m256 a, __m256 b, __m256 c) + /// VFMADDPS ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplyAdd(Vector256 a, Vector256 b, Vector256 c) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_fmadd_pd (__m256d a, __m256d b, __m256d c) + /// VFMADDPS ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplyAdd(Vector256 a, Vector256 b, Vector256 c) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_fmadd_ss (__m128 a, __m128 b, __m128 c) + /// VFMADDSS xmm, xmm, xmm/m32 + /// + public static Vector128 MultiplyAddScalar(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_fmadd_sd (__m128d a, __m128d b, __m128d c) + /// VFMADDSS xmm, xmm, xmm/m64 + /// + public static Vector128 MultiplyAddScalar(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_fmaddsub_ps (__m128 a, __m128 b, __m128 c) + /// VFMADDSUBPS xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplyAddSubtract(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_fmaddsub_pd (__m128d a, __m128d b, __m128d c) + /// VFMADDSUBPD xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplyAddSubtract(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_fmaddsub_ps (__m256 a, __m256 b, __m256 c) + /// VFMADDSUBPS ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplyAddSubtract(Vector256 a, Vector256 b, Vector256 c) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_fmaddsub_pd (__m256d a, __m256d b, __m256d c) + /// VFMADDSUBPD ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplyAddSubtract(Vector256 a, Vector256 b, Vector256 c) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_fmsub_ps (__m128 a, __m128 b, __m128 c) + /// VFMSUBPS xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplySubtract(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_fmsub_pd (__m128d a, __m128d b, __m128d c) + /// VFMSUBPS xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplySubtract(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_fmsub_ps (__m256 a, __m256 b, __m256 c) + /// VFMSUBPS ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplySubtract(Vector256 a, Vector256 b, Vector256 c) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_fmsub_pd (__m256d a, __m256d b, __m256d c) + /// VFMSUBPD ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplySubtract(Vector256 a, Vector256 b, Vector256 c) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_fmsub_ss (__m128 a, __m128 b, __m128 c) + /// VFMSUBSS xmm, xmm, xmm/m32 + /// + public static Vector128 MultiplySubtractScalar(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_fmsub_sd (__m128d a, __m128d b, __m128d c) + /// VFMSUBSD xmm, xmm, xmm/m64 + /// + public static Vector128 MultiplySubtractScalar(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_fmsubadd_ps (__m128 a, __m128 b, __m128 c) + /// VFMSUBADDPS xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplySubtractAdd(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_fmsubadd_pd (__m128d a, __m128d b, __m128d c) + /// VFMSUBADDPD xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplySubtractAdd(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_fmsubadd_ps (__m256 a, __m256 b, __m256 c) + /// VFMSUBADDPS ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplySubtractAdd(Vector256 a, Vector256 b, Vector256 c) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_fmsubadd_pd (__m256d a, __m256d b, __m256d c) + /// VFMSUBADDPD ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplySubtractAdd(Vector256 a, Vector256 b, Vector256 c) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_fnmadd_ps (__m128 a, __m128 b, __m128 c) + /// VFNMADDPS xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplyAddNegated(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_fnmadd_pd (__m128d a, __m128d b, __m128d c) + /// VFNMADDPD xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplyAddNegated(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_fnmadd_ps (__m256 a, __m256 b, __m256 c) + /// VFNMADDPS ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplyAddNegated(Vector256 a, Vector256 b, Vector256 c) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_fnmadd_pd (__m256d a, __m256d b, __m256d c) + /// VFNMADDPD ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplyAddNegated(Vector256 a, Vector256 b, Vector256 c) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_fnmadd_ss (__m128 a, __m128 b, __m128 c) + /// VFNMADDSS xmm, xmm, xmm/m32 + /// + public static Vector128 MultiplyAddNegatedScalar(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_fnmadd_sd (__m128d a, __m128d b, __m128d c) + /// VFNMADDSD xmm, xmm, xmm/m64 + /// + public static Vector128 MultiplyAddNegatedScalar(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_fnmsub_ps (__m128 a, __m128 b, __m128 c) + /// VFNMSUBPS xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplySubtractNegated(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_fnmsub_pd (__m128d a, __m128d b, __m128d c) + /// VFNMSUBPD xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplySubtractNegated(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m256 _mm256_fnmsub_ps (__m256 a, __m256 b, __m256 c) + /// VFNMSUBPS ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplySubtractNegated(Vector256 a, Vector256 b, Vector256 c) { throw new PlatformNotSupportedException(); } + /// + /// __m256d _mm256_fnmsub_pd (__m256d a, __m256d b, __m256d c) + /// VFNMSUBPD ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplySubtractNegated(Vector256 a, Vector256 b, Vector256 c) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_fnmsub_ss (__m128 a, __m128 b, __m128 c) + /// VFNMSUBSS xmm, xmm, xmm/m32 + /// + public static Vector128 MultiplySubtractNegatedScalar(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_fnmsub_sd (__m128d a, __m128d b, __m128d c) + /// VFNMSUBSD xmm, xmm, xmm/m64 + /// + public static Vector128 MultiplySubtractNegatedScalar(Vector128 a, Vector128 b, Vector128 c) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Fma.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Fma.cs new file mode 100644 index 0000000000..88cb8d0cbe --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Fma.cs @@ -0,0 +1,190 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel FMA hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Fma : Avx + { + internal Fma() { } + + public new static bool IsSupported { get => IsSupported; } + + /// + /// __m128 _mm_fmadd_ps (__m128 a, __m128 b, __m128 c) + /// VFMADDPS xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplyAdd(Vector128 a, Vector128 b, Vector128 c) => MultiplyAdd(a, b, c); + /// + /// __m128d _mm_fmadd_pd (__m128d a, __m128d b, __m128d c) + /// VFMADDPD xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplyAdd(Vector128 a, Vector128 b, Vector128 c) => MultiplyAdd(a, b, c); + /// + /// __m256 _mm256_fmadd_ps (__m256 a, __m256 b, __m256 c) + /// VFMADDPS ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplyAdd(Vector256 a, Vector256 b, Vector256 c) => MultiplyAdd(a, b, c); + /// + /// __m256d _mm256_fmadd_pd (__m256d a, __m256d b, __m256d c) + /// VFMADDPS ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplyAdd(Vector256 a, Vector256 b, Vector256 c) => MultiplyAdd(a, b, c); + + /// + /// __m128 _mm_fmadd_ss (__m128 a, __m128 b, __m128 c) + /// VFMADDSS xmm, xmm, xmm/m32 + /// + public static Vector128 MultiplyAddScalar(Vector128 a, Vector128 b, Vector128 c) => MultiplyAddScalar(a, b, c); + /// + /// __m128d _mm_fmadd_sd (__m128d a, __m128d b, __m128d c) + /// VFMADDSS xmm, xmm, xmm/m64 + /// + public static Vector128 MultiplyAddScalar(Vector128 a, Vector128 b, Vector128 c) => MultiplyAddScalar(a, b, c); + + /// + /// __m128 _mm_fmaddsub_ps (__m128 a, __m128 b, __m128 c) + /// VFMADDSUBPS xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplyAddSubtract(Vector128 a, Vector128 b, Vector128 c) => MultiplyAddSubtract(a, b, c); + /// + /// __m128d _mm_fmaddsub_pd (__m128d a, __m128d b, __m128d c) + /// VFMADDSUBPD xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplyAddSubtract(Vector128 a, Vector128 b, Vector128 c) => MultiplyAddSubtract(a, b, c); + /// + /// __m256 _mm256_fmaddsub_ps (__m256 a, __m256 b, __m256 c) + /// VFMADDSUBPS ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplyAddSubtract(Vector256 a, Vector256 b, Vector256 c) => MultiplyAddSubtract(a, b, c); + /// + /// __m256d _mm256_fmaddsub_pd (__m256d a, __m256d b, __m256d c) + /// VFMADDSUBPD ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplyAddSubtract(Vector256 a, Vector256 b, Vector256 c) => MultiplyAddSubtract(a, b, c); + + /// + /// __m128 _mm_fmsub_ps (__m128 a, __m128 b, __m128 c) + /// VFMSUBPS xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplySubtract(Vector128 a, Vector128 b, Vector128 c) => MultiplySubtract(a, b, c); + /// + /// __m128d _mm_fmsub_pd (__m128d a, __m128d b, __m128d c) + /// VFMSUBPS xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplySubtract(Vector128 a, Vector128 b, Vector128 c) => MultiplySubtract(a, b, c); + /// + /// __m256 _mm256_fmsub_ps (__m256 a, __m256 b, __m256 c) + /// VFMSUBPS ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplySubtract(Vector256 a, Vector256 b, Vector256 c) => MultiplySubtract(a, b, c); + /// + /// __m256d _mm256_fmsub_pd (__m256d a, __m256d b, __m256d c) + /// VFMSUBPD ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplySubtract(Vector256 a, Vector256 b, Vector256 c) => MultiplySubtract(a, b, c); + + /// + /// __m128 _mm_fmsub_ss (__m128 a, __m128 b, __m128 c) + /// VFMSUBSS xmm, xmm, xmm/m32 + /// + public static Vector128 MultiplySubtractScalar(Vector128 a, Vector128 b, Vector128 c) => MultiplySubtractScalar(a, b, c); + /// + /// __m128d _mm_fmsub_sd (__m128d a, __m128d b, __m128d c) + /// VFMSUBSD xmm, xmm, xmm/m64 + /// + public static Vector128 MultiplySubtractScalar(Vector128 a, Vector128 b, Vector128 c) => MultiplySubtractScalar(a, b, c); + + /// + /// __m128 _mm_fmsubadd_ps (__m128 a, __m128 b, __m128 c) + /// VFMSUBADDPS xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplySubtractAdd(Vector128 a, Vector128 b, Vector128 c) => MultiplySubtractAdd(a, b, c); + /// + /// __m128d _mm_fmsubadd_pd (__m128d a, __m128d b, __m128d c) + /// VFMSUBADDPD xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplySubtractAdd(Vector128 a, Vector128 b, Vector128 c) => MultiplySubtractAdd(a, b, c); + /// + /// __m256 _mm256_fmsubadd_ps (__m256 a, __m256 b, __m256 c) + /// VFMSUBADDPS ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplySubtractAdd(Vector256 a, Vector256 b, Vector256 c) => MultiplySubtractAdd(a, b, c); + /// + /// __m256d _mm256_fmsubadd_pd (__m256d a, __m256d b, __m256d c) + /// VFMSUBADDPD ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplySubtractAdd(Vector256 a, Vector256 b, Vector256 c) => MultiplySubtractAdd(a, b, c); + + /// + /// __m128 _mm_fnmadd_ps (__m128 a, __m128 b, __m128 c) + /// VFNMADDPS xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplyAddNegated(Vector128 a, Vector128 b, Vector128 c) => MultiplyAddNegated(a, b, c); + /// + /// __m128d _mm_fnmadd_pd (__m128d a, __m128d b, __m128d c) + /// VFNMADDPD xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplyAddNegated(Vector128 a, Vector128 b, Vector128 c) => MultiplyAddNegated(a, b, c); + /// + /// __m256 _mm256_fnmadd_ps (__m256 a, __m256 b, __m256 c) + /// VFNMADDPS ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplyAddNegated(Vector256 a, Vector256 b, Vector256 c) => MultiplyAddNegated(a, b, c); + /// + /// __m256d _mm256_fnmadd_pd (__m256d a, __m256d b, __m256d c) + /// VFNMADDPD ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplyAddNegated(Vector256 a, Vector256 b, Vector256 c) => MultiplyAddNegated(a, b, c); + + /// + /// __m128 _mm_fnmadd_ss (__m128 a, __m128 b, __m128 c) + /// VFNMADDSS xmm, xmm, xmm/m32 + /// + public static Vector128 MultiplyAddNegatedScalar(Vector128 a, Vector128 b, Vector128 c) => MultiplyAddNegatedScalar(a, b, c); + /// + /// __m128d _mm_fnmadd_sd (__m128d a, __m128d b, __m128d c) + /// VFNMADDSD xmm, xmm, xmm/m64 + /// + public static Vector128 MultiplyAddNegatedScalar(Vector128 a, Vector128 b, Vector128 c) => MultiplyAddNegatedScalar(a, b, c); + + /// + /// __m128 _mm_fnmsub_ps (__m128 a, __m128 b, __m128 c) + /// VFNMSUBPS xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplySubtractNegated(Vector128 a, Vector128 b, Vector128 c) => MultiplySubtractNegated(a, b, c); + /// + /// __m128d _mm_fnmsub_pd (__m128d a, __m128d b, __m128d c) + /// VFNMSUBPD xmm, xmm, xmm/m128 + /// + public static Vector128 MultiplySubtractNegated(Vector128 a, Vector128 b, Vector128 c) => MultiplySubtractNegated(a, b, c); + /// + /// __m256 _mm256_fnmsub_ps (__m256 a, __m256 b, __m256 c) + /// VFNMSUBPS ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplySubtractNegated(Vector256 a, Vector256 b, Vector256 c) => MultiplySubtractNegated(a, b, c); + /// + /// __m256d _mm256_fnmsub_pd (__m256d a, __m256d b, __m256d c) + /// VFNMSUBPD ymm, ymm, ymm/m256 + /// + public static Vector256 MultiplySubtractNegated(Vector256 a, Vector256 b, Vector256 c) => MultiplySubtractNegated(a, b, c); + + /// + /// __m128 _mm_fnmsub_ss (__m128 a, __m128 b, __m128 c) + /// VFNMSUBSS xmm, xmm, xmm/m32 + /// + public static Vector128 MultiplySubtractNegatedScalar(Vector128 a, Vector128 b, Vector128 c) => MultiplySubtractNegatedScalar(a, b, c); + /// + /// __m128d _mm_fnmsub_sd (__m128d a, __m128d b, __m128d c) + /// VFNMSUBSD xmm, xmm, xmm/m64 + /// + public static Vector128 MultiplySubtractNegatedScalar(Vector128 a, Vector128 b, Vector128 c) => MultiplySubtractNegatedScalar(a, b, c); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Lzcnt.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Lzcnt.PlatformNotSupported.cs new file mode 100644 index 0000000000..4f92762168 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Lzcnt.PlatformNotSupported.cs @@ -0,0 +1,30 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel LZCNT hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Lzcnt + { + internal Lzcnt() { } + + public static bool IsSupported { get { return false; } } + + /// + /// unsigned int _lzcnt_u32 (unsigned int a) + /// LZCNT reg, reg/m32 + /// + public static uint LeadingZeroCount(uint value) { throw new PlatformNotSupportedException(); } + /// + /// unsigned __int64 _lzcnt_u64 (unsigned __int64 a) + /// LZCNT reg, reg/m64 + /// + public static ulong LeadingZeroCount(ulong value) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Lzcnt.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Lzcnt.cs new file mode 100644 index 0000000000..5e9594f7d6 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Lzcnt.cs @@ -0,0 +1,31 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel LZCNT hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Lzcnt + { + internal Lzcnt() { } + + public static bool IsSupported { get => IsSupported; } + + /// + /// unsigned int _lzcnt_u32 (unsigned int a) + /// LZCNT reg, reg/m32 + /// + public static uint LeadingZeroCount(uint value) => LeadingZeroCount(value); + /// + /// unsigned __int64 _lzcnt_u64 (unsigned __int64 a) + /// LZCNT reg, reg/m64 + /// + public static ulong LeadingZeroCount(ulong value) => LeadingZeroCount(value); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Pclmulqdq.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Pclmulqdq.PlatformNotSupported.cs new file mode 100644 index 0000000000..b79e50a2b7 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Pclmulqdq.PlatformNotSupported.cs @@ -0,0 +1,31 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel PCLMULQDQ hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Pclmulqdq : Sse2 + { + internal Pclmulqdq() { } + + public new static bool IsSupported { get { return false; } } + + /// + /// __m128i _mm_clmulepi64_si128 (__m128i a, __m128i b, const int imm8) + /// PCLMULQDQ xmm, xmm/m128, imm8 + /// + public static Vector128 CarrylessMultiply(Vector128 left, Vector128 right, byte control) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_clmulepi64_si128 (__m128i a, __m128i b, const int imm8) + /// PCLMULQDQ xmm, xmm/m128, imm8 + /// + public static Vector128 CarrylessMultiply(Vector128 left, Vector128 right, byte control) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Pclmulqdq.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Pclmulqdq.cs new file mode 100644 index 0000000000..c108e65f08 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Pclmulqdq.cs @@ -0,0 +1,31 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel PCLMULQDQ hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Pclmulqdq : Sse2 + { + internal Pclmulqdq() { } + + public new static bool IsSupported { get => IsSupported; } + + /// + /// __m128i _mm_clmulepi64_si128 (__m128i a, __m128i b, const int imm8) + /// PCLMULQDQ xmm, xmm/m128, imm8 + /// + public static Vector128 CarrylessMultiply(Vector128 left, Vector128 right, byte control) => CarrylessMultiply(left, right, control); + /// + /// __m128i _mm_clmulepi64_si128 (__m128i a, __m128i b, const int imm8) + /// PCLMULQDQ xmm, xmm/m128, imm8 + /// + public static Vector128 CarrylessMultiply(Vector128 left, Vector128 right, byte control) => CarrylessMultiply(left, right, control); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Popcnt.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Popcnt.PlatformNotSupported.cs new file mode 100644 index 0000000000..bf045bd1f7 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Popcnt.PlatformNotSupported.cs @@ -0,0 +1,30 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel POPCNT hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Popcnt : Sse42 + { + internal Popcnt() { } + + public new static bool IsSupported { get { return false; } } + + /// + /// int _mm_popcnt_u32 (unsigned int a) + /// POPCNT reg, reg/m32 + /// + public static uint PopCount(uint value) { throw new PlatformNotSupportedException(); } + /// + /// __int64 _mm_popcnt_u64 (unsigned __int64 a) + /// POPCNT reg64, reg/m64 + /// + public static ulong PopCount(ulong value) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Popcnt.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Popcnt.cs new file mode 100644 index 0000000000..ba73eb2340 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Popcnt.cs @@ -0,0 +1,31 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel POPCNT hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Popcnt : Sse42 + { + internal Popcnt() { } + + public new static bool IsSupported { get => IsSupported; } + + /// + /// int _mm_popcnt_u32 (unsigned int a) + /// POPCNT reg, reg/m32 + /// + public static uint PopCount(uint value) => PopCount(value); + /// + /// __int64 _mm_popcnt_u64 (unsigned __int64 a) + /// POPCNT reg, reg/m64 + /// + public static ulong PopCount(ulong value) => PopCount(value); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse.PlatformNotSupported.cs new file mode 100644 index 0000000000..77c63cee3f --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse.PlatformNotSupported.cs @@ -0,0 +1,606 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel SSE hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Sse + { + internal Sse() { } + + public static bool IsSupported { get { return false; } } + + /// + /// __m128 _mm_add_ps (__m128 a, __m128 b) + /// ADDPS xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_add_ss (__m128 a, __m128 b) + /// ADDSS xmm, xmm/m32 + /// + public static Vector128 AddScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_and_ps (__m128 a, __m128 b) + /// ANDPS xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_andnot_ps (__m128 a, __m128 b) + /// ANDNPS xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpeq_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(0) + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_comieq_ss (__m128 a, __m128 b) + /// COMISS xmm, xmm/m32 + /// + public static bool CompareEqualOrderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_ucomieq_ss (__m128 a, __m128 b) + /// UCOMISS xmm, xmm/m32 + /// + public static bool CompareEqualUnorderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpeq_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(0) + /// + public static Vector128 CompareEqualScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpgt_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(6) + /// + public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_comigt_ss (__m128 a, __m128 b) + /// COMISS xmm, xmm/m32 + /// + public static bool CompareGreaterThanOrderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_ucomigt_ss (__m128 a, __m128 b) + /// UCOMISS xmm, xmm/m32 + /// + public static bool CompareGreaterThanUnorderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpgt_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(6) + /// + public static Vector128 CompareGreaterThanScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpge_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(5) + /// + public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_comige_ss (__m128 a, __m128 b) + /// COMISS xmm, xmm/m32 + /// + public static bool CompareGreaterThanOrEqualOrderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_ucomige_ss (__m128 a, __m128 b) + /// UCOMISS xmm, xmm/m32 + /// + public static bool CompareGreaterThanOrEqualUnorderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpge_ss (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m32, imm8(5) + /// + public static Vector128 CompareGreaterThanOrEqualScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmplt_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(1) + /// + public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_comilt_ss (__m128 a, __m128 b) + /// COMISS xmm, xmm/m32 + /// + public static bool CompareLessThanOrderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_ucomilt_ss (__m128 a, __m128 b) + /// UCOMISS xmm, xmm/m32 + /// + public static bool CompareLessThanUnorderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmplt_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(1) + /// + public static Vector128 CompareLessThanScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmple_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(2) + /// + public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_comile_ss (__m128 a, __m128 b) + /// COMISS xmm, xmm/m32 + /// + public static bool CompareLessThanOrEqualOrderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_ucomile_ss (__m128 a, __m128 b) + /// UCOMISS xmm, xmm/m32 + /// + public static bool CompareLessThanOrEqualUnorderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmple_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(2) + /// + public static Vector128 CompareLessThanOrEqualScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpneq_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(4) + /// + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_comineq_ss (__m128 a, __m128 b) + /// COMISS xmm, xmm/m32 + /// + public static bool CompareNotEqualOrderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_ucomineq_ss (__m128 a, __m128 b) + /// UCOMISS xmm, xmm/m32 + /// + public static bool CompareNotEqualUnorderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpneq_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(4) + /// + public static Vector128 CompareNotEqualScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpngt_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(2) + /// + public static Vector128 CompareNotGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpngt_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(2) + /// + public static Vector128 CompareNotGreaterThanScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpnge_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(1) + /// + public static Vector128 CompareNotGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpnge_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(1) + /// + public static Vector128 CompareNotGreaterThanOrEqualScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpnlt_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(5) + /// + public static Vector128 CompareNotLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpnlt_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(5) + /// + public static Vector128 CompareNotLessThanScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpnle_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(6) + /// + public static Vector128 CompareNotLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpnle_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(6) + /// + public static Vector128 CompareNotLessThanOrEqualScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpord_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(7) + /// + public static Vector128 CompareOrdered(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpord_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(7) + /// + public static Vector128 CompareOrderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpunord_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(3) + /// + public static Vector128 CompareUnordered(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cmpunord_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(3) + /// + public static Vector128 CompareUnorderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cvtss_si32 (__m128 a) + /// CVTSS2SI r32, xmm/m32 + /// + public static int ConvertToInt32(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __int64 _mm_cvtss_si64 (__m128 a) + /// CVTSS2SI r64, xmm/m32 + /// + public static long ConvertToInt64(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// float _mm_cvtss_f32 (__m128 a) + /// HELPER: MOVSS + /// + public static float ConvertToSingle(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_cvtsi32_ss (__m128 a, int b) + /// CVTSI2SS xmm, reg/m32 + /// + public static Vector128 ConvertScalarToVector128Single(Vector128 upper, int value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_cvtsi64_ss (__m128 a, __int64 b) + /// CVTSI2SS xmm, reg/m64 + /// + public static Vector128 ConvertScalarToVector128Single(Vector128 upper, long value) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cvttss_si32 (__m128 a) + /// CVTTSS2SI r32, xmm/m32 + /// + public static int ConvertToInt32WithTruncation(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __int64 _mm_cvttss_si64 (__m128 a) + /// CVTTSS2SI r64, xmm/m32 + /// + public static long ConvertToInt64WithTruncation(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_div_ps (__m128 a, __m128 b) + /// DIVPS xmm, xmm/m128 + /// + public static Vector128 Divide(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_div_ss (__m128 a, __m128 b) + /// DIVSS xmm, xmm/m32 + /// + public static Vector128 DivideScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_loadu_ps (float const* mem_address) + /// MOVUPS xmm, m128 + /// + public static unsafe Vector128 LoadVector128(float* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_load_ss (float const* mem_address) + /// MOVSS xmm, m32 + /// + public static unsafe Vector128 LoadScalarVector128(float* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_load_ps (float const* mem_address) + /// MOVAPS xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(float* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_loadh_pi (__m128 a, __m64 const* mem_addr) + /// MOVHPS xmm, m64 + /// + public static unsafe Vector128 LoadHigh(Vector128 lower, float* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_loadl_pi (__m128 a, __m64 const* mem_addr) + /// MOVLPS xmm, m64 + /// + public static unsafe Vector128 LoadLow(Vector128 upper, float* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_max_ps (__m128 a, __m128 b) + /// MAXPS xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_max_ss (__m128 a, __m128 b) + /// MAXSS xmm, xmm/m32 + /// + public static Vector128 MaxScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_min_ps (__m128 a, __m128 b) + /// MINPS xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_min_ss (__m128 a, __m128 b) + /// MINSS xmm, xmm/m32 + /// + public static Vector128 MinScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_move_ss (__m128 a, __m128 b) + /// MOVSS xmm, xmm + /// + public static Vector128 MoveScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_movehl_ps (__m128 a, __m128 b) + /// MOVHLPS xmm, xmm + /// + public static Vector128 MoveHighToLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_movelh_ps (__m128 a, __m128 b) + /// MOVLHPS xmm, xmm + /// + public static Vector128 MoveLowToHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_movemask_ps (__m128 a) + /// MOVMSKPS reg, xmm + /// + public static int MoveMask(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_mul_ps (__m128 a, __m128 b) + /// MULPS xmm, xmm/m128 + /// + public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_mul_ss (__m128 a, __m128 b) + /// MULPS xmm, xmm/m32 + /// + public static Vector128 MultiplyScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_prefetch(char* p, int i) + /// PREFETCHT0 m8 + /// + public static unsafe void Prefetch0(void* address) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_prefetch(char* p, int i) + /// PREFETCHT1 m8 + /// + public static unsafe void Prefetch1(void* address) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_prefetch(char* p, int i) + /// PREFETCHT2 m8 + /// + public static unsafe void Prefetch2(void* address) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_prefetch(char* p, int i) + /// PREFETCHNTA m8 + /// + public static unsafe void PrefetchNonTemporal(void* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_or_ps (__m128 a, __m128 b) + /// ORPS xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_rcp_ps (__m128 a) + /// RCPPS xmm, xmm/m128 + /// + public static Vector128 Reciprocal(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_rcp_ss (__m128 a) + /// RCPSS xmm, xmm/m32 + /// + public static Vector128 ReciprocalScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_rcp_ss (__m128 a, __m128 b) + /// RCPSS xmm, xmm/m32 + /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. + /// + public static Vector128 ReciprocalScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_rsqrt_ps (__m128 a) + /// RSQRTPS xmm, xmm/m128 + /// + public static Vector128 ReciprocalSqrt(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_rsqrt_ss (__m128 a) + /// RSQRTSS xmm, xmm/m32 + /// + public static Vector128 ReciprocalSqrtScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_rsqrt_ss (__m128 a, __m128 b) + /// RSQRTSS xmm, xmm/m32 + /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. + /// + public static Vector128 ReciprocalSqrtScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_set_ps (float e3, float e2, float e1, float e0) + /// + public static Vector128 SetVector128(float e3, float e2, float e1, float e0) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_set_ss (float a) + /// HELPER + /// + public static Vector128 SetScalarVector128(float value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_set1_ps (float a) + /// HELPER + /// + public static Vector128 SetAllVector128(float value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_setzero_ps (void) + /// HELPER - XORPS + /// + public static Vector128 SetZeroVector128() { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_castpd_ps (__m128d a) + /// HELPER - No Codegen + /// __m128i _mm_castpd_si128 (__m128d a) + /// HELPER - No Codegen + /// __m128d _mm_castps_pd (__m128 a) + /// HELPER - No Codegen + /// __m128i _mm_castps_si128 (__m128 a) + /// HELPER - No Codegen + /// __m128d _mm_castsi128_pd (__m128i a) + /// HELPER - No Codegen + /// __m128 _mm_castsi128_ps (__m128i a) + /// HELPER - No Codegen + /// + public static Vector128 StaticCast(Vector128 value) where T : struct where U : struct { throw new PlatformNotSupportedException(); } + + + /// + /// __m128 _mm_shuffle_ps (__m128 a, __m128 b, unsigned int control) + /// SHUFPS xmm, xmm/m128, imm8 + /// + public static Vector128 Shuffle(Vector128 left, Vector128 right, byte control) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_sqrt_ps (__m128 a) + /// SQRTPS xmm, xmm/m128 + /// + public static Vector128 Sqrt(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_sqrt_ss (__m128 a) + /// SQRTSS xmm, xmm/m32 + /// + public static Vector128 SqrtScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_sqrt_ss (__m128 a, __m128 b) + /// SQRTSS xmm, xmm/m32 + /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. + /// + public static Vector128 SqrtScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_store_ps (float* mem_addr, __m128 a) + /// MOVAPS m128, xmm + /// + public static unsafe void StoreAligned(float* address, Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_stream_ps (float* mem_addr, __m128 a) + /// MOVNTPS m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(float* address, Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_storeu_ps (float* mem_addr, __m128 a) + /// MOVUPS m128, xmm + /// + public static unsafe void Store(float* address, Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_sfence(void) + /// SFENCE + /// + public static void StoreFence() { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_store_ss (float* mem_addr, __m128 a) + /// MOVSS m32, xmm + /// + public static unsafe void StoreScalar(float* address, Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_storeh_pi (__m64* mem_addr, __m128 a) + /// MOVHPS m64, xmm + /// + public static unsafe void StoreHigh(float* address, Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_storel_pi (__m64* mem_addr, __m128 a) + /// MOVLPS m64, xmm + /// + public static unsafe void StoreLow(float* address, Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_sub_ps (__m128d a, __m128d b) + /// SUBPS xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_sub_ss (__m128 a, __m128 b) + /// SUBSS xmm, xmm/m32 + /// + public static Vector128 SubtractScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_unpackhi_ps (__m128 a, __m128 b) + /// UNPCKHPS xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_unpacklo_ps (__m128 a, __m128 b) + /// UNPCKLPS xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_xor_ps (__m128 a, __m128 b) + /// XORPS xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse.cs new file mode 100644 index 0000000000..3b01aee70e --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse.cs @@ -0,0 +1,631 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel SSE hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Sse + { + internal Sse() { } + + public static bool IsSupported { get => IsSupported; } + + /// + /// __m128 _mm_add_ps (__m128 a, __m128 b) + /// ADDPS xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) => Add(left, right); + + /// + /// __m128 _mm_add_ss (__m128 a, __m128 b) + /// ADDSS xmm, xmm/m32 + /// + public static Vector128 AddScalar(Vector128 left, Vector128 right) => AddScalar(left, right); + + /// + /// __m128 _mm_and_ps (__m128 a, __m128 b) + /// ANDPS xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + + /// + /// __m128 _mm_andnot_ps (__m128 a, __m128 b) + /// ANDNPS xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) => AndNot(left, right); + + /// + /// __m128 _mm_cmpeq_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(0) + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + + /// + /// int _mm_comieq_ss (__m128 a, __m128 b) + /// COMISS xmm, xmm/m32 + /// + public static bool CompareEqualOrderedScalar(Vector128 left, Vector128 right) => CompareEqualOrderedScalar(left, right); + + /// + /// int _mm_ucomieq_ss (__m128 a, __m128 b) + /// UCOMISS xmm, xmm/m32 + /// + public static bool CompareEqualUnorderedScalar(Vector128 left, Vector128 right) => CompareEqualUnorderedScalar(left, right); + + /// + /// __m128 _mm_cmpeq_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(0) + /// + public static Vector128 CompareEqualScalar(Vector128 left, Vector128 right) => CompareEqualScalar(left, right); + + /// + /// __m128 _mm_cmpgt_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(6) + /// + public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) => CompareGreaterThan(left, right); + + /// + /// int _mm_comigt_ss (__m128 a, __m128 b) + /// COMISS xmm, xmm/m32 + /// + public static bool CompareGreaterThanOrderedScalar(Vector128 left, Vector128 right) => CompareGreaterThanOrderedScalar(left, right); + + /// + /// int _mm_ucomigt_ss (__m128 a, __m128 b) + /// UCOMISS xmm, xmm/m32 + /// + public static bool CompareGreaterThanUnorderedScalar(Vector128 left, Vector128 right) => CompareGreaterThanUnorderedScalar(left, right); + + /// + /// __m128 _mm_cmpgt_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(6) + /// + public static Vector128 CompareGreaterThanScalar(Vector128 left, Vector128 right) => CompareGreaterThanScalar(left, right); + + /// + /// __m128 _mm_cmpge_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(5) + /// + public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) => CompareGreaterThanOrEqual(left, right); + + /// + /// int _mm_comige_ss (__m128 a, __m128 b) + /// COMISS xmm, xmm/m32 + /// + public static bool CompareGreaterThanOrEqualOrderedScalar(Vector128 left, Vector128 right) => CompareGreaterThanOrEqualOrderedScalar(left, right); + + /// + /// int _mm_ucomige_ss (__m128 a, __m128 b) + /// UCOMISS xmm, xmm/m32 + /// + public static bool CompareGreaterThanOrEqualUnorderedScalar(Vector128 left, Vector128 right) => CompareGreaterThanOrEqualUnorderedScalar(left, right); + + /// + /// __m128 _mm_cmpge_ss (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m32, imm8(5) + /// + public static Vector128 CompareGreaterThanOrEqualScalar(Vector128 left, Vector128 right) => CompareGreaterThanOrEqualScalar(left, right); + + /// + /// __m128 _mm_cmplt_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(1) + /// + public static Vector128 CompareLessThan(Vector128 left, Vector128 right) => CompareLessThan(left, right); + + /// + /// int _mm_comilt_ss (__m128 a, __m128 b) + /// COMISS xmm, xmm/m32 + /// + public static bool CompareLessThanOrderedScalar(Vector128 left, Vector128 right) => CompareLessThanOrderedScalar(left, right); + + /// + /// int _mm_ucomilt_ss (__m128 a, __m128 b) + /// UCOMISS xmm, xmm/m32 + /// + public static bool CompareLessThanUnorderedScalar(Vector128 left, Vector128 right) => CompareLessThanUnorderedScalar(left, right); + + /// + /// __m128 _mm_cmplt_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(1) + /// + public static Vector128 CompareLessThanScalar(Vector128 left, Vector128 right) => CompareLessThanScalar(left, right); + + /// + /// __m128 _mm_cmple_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(2) + /// + public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) => CompareLessThanOrEqual(left, right); + + /// + /// int _mm_comile_ss (__m128 a, __m128 b) + /// COMISS xmm, xmm/m32 + /// + public static bool CompareLessThanOrEqualOrderedScalar(Vector128 left, Vector128 right) => CompareLessThanOrEqualOrderedScalar(left, right); + + /// + /// int _mm_ucomile_ss (__m128 a, __m128 b) + /// UCOMISS xmm, xmm/m32 + /// + public static bool CompareLessThanOrEqualUnorderedScalar(Vector128 left, Vector128 right) => CompareLessThanOrEqualUnorderedScalar(left, right); + + /// + /// __m128 _mm_cmple_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(2) + /// + public static Vector128 CompareLessThanOrEqualScalar(Vector128 left, Vector128 right) => CompareLessThanOrEqualScalar(left, right); + + /// + /// __m128 _mm_cmpneq_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(4) + /// + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) => CompareNotEqual(left, right); + + /// + /// int _mm_comineq_ss (__m128 a, __m128 b) + /// COMISS xmm, xmm/m32 + /// + public static bool CompareNotEqualOrderedScalar(Vector128 left, Vector128 right) => CompareNotEqualOrderedScalar(left, right); + + /// + /// int _mm_ucomineq_ss (__m128 a, __m128 b) + /// UCOMISS xmm, xmm/m32 + /// + public static bool CompareNotEqualUnorderedScalar(Vector128 left, Vector128 right) => CompareNotEqualUnorderedScalar(left, right); + + /// + /// __m128 _mm_cmpneq_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(4) + /// + public static Vector128 CompareNotEqualScalar(Vector128 left, Vector128 right) => CompareNotEqualScalar(left, right); + + /// + /// __m128 _mm_cmpngt_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(2) + /// + public static Vector128 CompareNotGreaterThan(Vector128 left, Vector128 right) => CompareNotGreaterThan(left, right); + + /// + /// __m128 _mm_cmpngt_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(2) + /// + public static Vector128 CompareNotGreaterThanScalar(Vector128 left, Vector128 right) => CompareNotGreaterThanScalar(left, right); + + /// + /// __m128 _mm_cmpnge_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(1) + /// + public static Vector128 CompareNotGreaterThanOrEqual(Vector128 left, Vector128 right) => CompareNotGreaterThanOrEqual(left, right); + + /// + /// __m128 _mm_cmpnge_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(1) + /// + public static Vector128 CompareNotGreaterThanOrEqualScalar(Vector128 left, Vector128 right) => CompareNotGreaterThanOrEqualScalar(left, right); + + /// + /// __m128 _mm_cmpnlt_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(5) + /// + public static Vector128 CompareNotLessThan(Vector128 left, Vector128 right) => CompareNotLessThan(left, right); + + /// + /// __m128 _mm_cmpnlt_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(5) + /// + public static Vector128 CompareNotLessThanScalar(Vector128 left, Vector128 right) => CompareNotLessThanScalar(left, right); + + /// + /// __m128 _mm_cmpnle_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(6) + /// + public static Vector128 CompareNotLessThanOrEqual(Vector128 left, Vector128 right) => CompareNotLessThanOrEqual(left, right); + + /// + /// __m128 _mm_cmpnle_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(6) + /// + public static Vector128 CompareNotLessThanOrEqualScalar(Vector128 left, Vector128 right) => CompareNotLessThanOrEqualScalar(left, right); + + /// + /// __m128 _mm_cmpord_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(7) + /// + public static Vector128 CompareOrdered(Vector128 left, Vector128 right) => CompareOrdered(left, right); + + /// + /// __m128 _mm_cmpord_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(7) + /// + public static Vector128 CompareOrderedScalar(Vector128 left, Vector128 right) => CompareOrderedScalar(left, right); + + /// + /// __m128 _mm_cmpunord_ps (__m128 a, __m128 b) + /// CMPPS xmm, xmm/m128, imm8(3) + /// + public static Vector128 CompareUnordered(Vector128 left, Vector128 right) => CompareUnordered(left, right); + + /// + /// __m128 _mm_cmpunord_ss (__m128 a, __m128 b) + /// CMPSS xmm, xmm/m32, imm8(3) + /// + public static Vector128 CompareUnorderedScalar(Vector128 left, Vector128 right) => CompareUnorderedScalar(left, right); + + /// + /// int _mm_cvtss_si32 (__m128 a) + /// CVTSS2SI r32, xmm/m32 + /// + public static int ConvertToInt32(Vector128 value) => ConvertToInt32(value); + /// + /// __int64 _mm_cvtss_si64 (__m128 a) + /// CVTSS2SI r64, xmm/m32 + /// + public static long ConvertToInt64(Vector128 value) => ConvertToInt64(value); + + /// + /// float _mm_cvtss_f32 (__m128 a) + /// HELPER: MOVSS + /// + public static float ConvertToSingle(Vector128 value) => ConvertToSingle(value); + + /// + /// __m128 _mm_cvtsi32_ss (__m128 a, int b) + /// CVTSI2SS xmm, reg/m32 + /// + public static Vector128 ConvertScalarToVector128Single(Vector128 upper, int value) => ConvertScalarToVector128Single(upper, value); + /// + /// __m128 _mm_cvtsi64_ss (__m128 a, __int64 b) + /// CVTSI2SS xmm, reg/m64 + /// + public static Vector128 ConvertScalarToVector128Single(Vector128 upper, long value) => ConvertScalarToVector128Single(upper, value); + + /// + /// int _mm_cvttss_si32 (__m128 a) + /// CVTTSS2SI r32, xmm/m32 + /// + public static int ConvertToInt32WithTruncation(Vector128 value) => ConvertToInt32WithTruncation(value); + /// + /// __int64 _mm_cvttss_si64 (__m128 a) + /// CVTTSS2SI r64, xmm/m32 + /// + public static long ConvertToInt64WithTruncation(Vector128 value) => ConvertToInt64WithTruncation(value); + + /// + /// __m128 _mm_div_ps (__m128 a, __m128 b) + /// DIVPS xmm, xmm/m128 + /// + public static Vector128 Divide(Vector128 left, Vector128 right) => Divide(left, right); + + /// + /// __m128 _mm_div_ss (__m128 a, __m128 b) + /// DIVSS xmm, xmm/m32 + /// + public static Vector128 DivideScalar(Vector128 left, Vector128 right) => DivideScalar(left, right); + + /// + /// __m128 _mm_loadu_ps (float const* mem_address) + /// MOVUPS xmm, m128 + /// + public static unsafe Vector128 LoadVector128(float* address) => LoadVector128(address); + + /// + /// __m128 _mm_load_ss (float const* mem_address) + /// MOVSS xmm, m32 + /// + public static unsafe Vector128 LoadScalarVector128(float* address) => LoadScalarVector128(address); + + /// + /// __m128 _mm_load_ps (float const* mem_address) + /// MOVAPS xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(float* address) => LoadAlignedVector128(address); + + /// + /// __m128 _mm_loadh_pi (__m128 a, __m64 const* mem_addr) + /// MOVHPS xmm, m64 + /// + public static unsafe Vector128 LoadHigh(Vector128 lower, float* address) => LoadHigh(lower, address); + + /// + /// __m128 _mm_loadl_pi (__m128 a, __m64 const* mem_addr) + /// MOVLPS xmm, m64 + /// + public static unsafe Vector128 LoadLow(Vector128 upper, float* address) => LoadLow(upper, address); + + /// + /// __m128 _mm_max_ps (__m128 a, __m128 b) + /// MAXPS xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + + /// + /// __m128 _mm_max_ss (__m128 a, __m128 b) + /// MAXSS xmm, xmm/m32 + /// + public static Vector128 MaxScalar(Vector128 left, Vector128 right) => MaxScalar(left, right); + + /// + /// __m128 _mm_min_ps (__m128 a, __m128 b) + /// MINPS xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + + /// + /// __m128 _mm_min_ss (__m128 a, __m128 b) + /// MINSS xmm, xmm/m32 + /// + public static Vector128 MinScalar(Vector128 left, Vector128 right) => MinScalar(left, right); + + /// + /// __m128 _mm_move_ss (__m128 a, __m128 b) + /// MOVSS xmm, xmm + /// + public static Vector128 MoveScalar(Vector128 upper, Vector128 value) => MoveScalar(upper, value); + + /// + /// __m128 _mm_movehl_ps (__m128 a, __m128 b) + /// MOVHLPS xmm, xmm + /// + public static Vector128 MoveHighToLow(Vector128 left, Vector128 right) => MoveHighToLow(left, right); + + /// + /// __m128 _mm_movelh_ps (__m128 a, __m128 b) + /// MOVLHPS xmm, xmm + /// + public static Vector128 MoveLowToHigh(Vector128 left, Vector128 right) => MoveLowToHigh(left, right); + + /// + /// int _mm_movemask_ps (__m128 a) + /// MOVMSKPS reg, xmm + /// + public static int MoveMask(Vector128 value) => MoveMask(value); + + /// + /// __m128 _mm_mul_ps (__m128 a, __m128 b) + /// MULPS xmm, xmm/m128 + /// + public static Vector128 Multiply(Vector128 left, Vector128 right) => Multiply(left, right); + + /// + /// __m128 _mm_mul_ss (__m128 a, __m128 b) + /// MULPS xmm, xmm/m32 + /// + public static Vector128 MultiplyScalar(Vector128 left, Vector128 right) => MultiplyScalar(left, right); + + /// + /// __m128 _mm_or_ps (__m128 a, __m128 b) + /// ORPS xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) => Or(left, right); + + /// + /// void _mm_prefetch(char* p, int i) + /// PREFETCHT0 m8 + /// + public static unsafe void Prefetch0(void* address) => Prefetch0(address); + + /// + /// void _mm_prefetch(char* p, int i) + /// PREFETCHT1 m8 + /// + public static unsafe void Prefetch1(void* address) => Prefetch1(address); + + /// + /// void _mm_prefetch(char* p, int i) + /// PREFETCHT2 m8 + /// + public static unsafe void Prefetch2(void* address) => Prefetch2(address); + + /// + /// void _mm_prefetch(char* p, int i) + /// PREFETCHNTA m8 + /// + public static unsafe void PrefetchNonTemporal(void* address) => PrefetchNonTemporal(address); + + /// + /// __m128 _mm_rcp_ps (__m128 a) + /// RCPPS xmm, xmm/m128 + /// + public static Vector128 Reciprocal(Vector128 value) => Reciprocal(value); + + /// + /// __m128 _mm_rcp_ss (__m128 a) + /// RCPSS xmm, xmm/m32 + /// + public static Vector128 ReciprocalScalar(Vector128 value) => ReciprocalScalar(value); + + /// + /// __m128 _mm_rcp_ss (__m128 a, __m128 b) + /// RCPSS xmm, xmm/m32 + /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. + /// + public static Vector128 ReciprocalScalar(Vector128 upper, Vector128 value) => ReciprocalScalar(upper, value); + + /// + /// __m128 _mm_rsqrt_ps (__m128 a) + /// RSQRTPS xmm, xmm/m128 + /// + public static Vector128 ReciprocalSqrt(Vector128 value) => ReciprocalSqrt(value); + + /// + /// __m128 _mm_rsqrt_ss (__m128 a) + /// RSQRTSS xmm, xmm/m32 + /// + public static Vector128 ReciprocalSqrtScalar(Vector128 value) => ReciprocalSqrtScalar(value); + + /// + /// __m128 _mm_rsqrt_ss (__m128 a, __m128 b) + /// RSQRTSS xmm, xmm/m32 + /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. + /// + public static Vector128 ReciprocalSqrtScalar(Vector128 upper, Vector128 value) => ReciprocalSqrtScalar(upper, value); + + /// + /// __m128 _mm_set1_ps (float a) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetAllVector128(float value) + { + // Zero vector and load value et index 0 + Vector128 vector = SetScalarVector128(value); + // Create { vl vl vl vl } and return result + return Shuffle(vector, vector, 0); + } + + /// + /// __m128 _mm_set_ss (float a) + /// HELPER + /// + public static Vector128 SetScalarVector128(float value) => SetScalarVector128(value); + + /// + /// __m128 _mm_set_ps (float e3, float e2, float e1, float e0) + /// + public static unsafe Vector128 SetVector128(float e3, float e2, float e1, float e0) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load e2 et index 0 + Vector128 e2Vector = SetScalarVector128(e2); + Vector128 e1Vector = SetScalarVector128(e1); + Vector128 e0Vector = SetScalarVector128(e0); + // Create { -- -- e2 e0 } + e0Vector = UnpackLow(e0Vector, e2Vector); + e2Vector = SetScalarVector128(e3); + // Create { -- -- e3 e1 } + e1Vector = UnpackLow(e1Vector, e2Vector); + // Create { e3 e2 e1 e0 } and return result + return UnpackLow(e0Vector, e1Vector); + } + + /// + /// __m128d _mm_setzero_ps (void) + /// HELPER - XORPS + /// + public static Vector128 SetZeroVector128() => SetZeroVector128(); + + /// + /// __m128 _mm_castpd_ps (__m128d a) + /// HELPER - No Codegen + /// __m128i _mm_castpd_si128 (__m128d a) + /// HELPER - No Codegen + /// __m128d _mm_castps_pd (__m128 a) + /// HELPER - No Codegen + /// __m128i _mm_castps_si128 (__m128 a) + /// HELPER - No Codegen + /// __m128d _mm_castsi128_pd (__m128i a) + /// HELPER - No Codegen + /// __m128 _mm_castsi128_ps (__m128i a) + /// HELPER - No Codegen + /// + public static Vector128 StaticCast(Vector128 value) where T : struct where U : struct + { + return StaticCast(value); + } + + /// + /// __m128 _mm_shuffle_ps (__m128 a, __m128 b, unsigned int control) + /// SHUFPS xmm, xmm/m128, imm8 + /// + public static Vector128 Shuffle(Vector128 left, Vector128 right, byte control) => Shuffle(left, right, control); + + /// + /// __m128 _mm_sqrt_ps (__m128 a) + /// SQRTPS xmm, xmm/m128 + /// + public static Vector128 Sqrt(Vector128 value) => Sqrt(value); + + /// + /// __m128 _mm_sqrt_ss (__m128 a) + /// SQRTSS xmm, xmm/m32 + /// + public static Vector128 SqrtScalar(Vector128 value) => SqrtScalar(value); + + /// + /// __m128 _mm_sqrt_ss (__m128 a, __m128 b) + /// SQRTSS xmm, xmm/m32 + /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. + /// + public static Vector128 SqrtScalar(Vector128 upper, Vector128 value) => SqrtScalar(upper, value); + + /// + /// void _mm_store_ps (float* mem_addr, __m128 a) + /// MOVAPS m128, xmm + /// + public static unsafe void StoreAligned(float* address, Vector128 source) => StoreAligned(address, source); + + /// + /// void _mm_stream_ps (float* mem_addr, __m128 a) + /// MOVNTPS m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(float* address, Vector128 source) => StoreAlignedNonTemporal(address, source); + + /// + /// void _mm_storeu_ps (float* mem_addr, __m128 a) + /// MOVUPS m128, xmm + /// + public static unsafe void Store(float* address, Vector128 source) => Store(address, source); + + /// + /// void _mm_sfence(void) + /// SFENCE + /// + public static void StoreFence() => StoreFence(); + + /// + /// void _mm_store_ss (float* mem_addr, __m128 a) + /// MOVSS m32, xmm + /// + public static unsafe void StoreScalar(float* address, Vector128 source) => StoreScalar(address, source); + + /// + /// void _mm_storeh_pi (__m64* mem_addr, __m128 a) + /// MOVHPS m64, xmm + /// + public static unsafe void StoreHigh(float* address, Vector128 source) => StoreHigh(address, source); + + /// + /// void _mm_storel_pi (__m64* mem_addr, __m128 a) + /// MOVLPS m64, xmm + /// + public static unsafe void StoreLow(float* address, Vector128 source) => StoreLow(address, source); + + /// + /// __m128d _mm_sub_ps (__m128d a, __m128d b) + /// SUBPS xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) => Subtract(left, right); + + /// + /// __m128 _mm_sub_ss (__m128 a, __m128 b) + /// SUBSS xmm, xmm/m32 + /// + public static Vector128 SubtractScalar(Vector128 left, Vector128 right) => SubtractScalar(left, right); + + /// + /// __m128 _mm_unpackhi_ps (__m128 a, __m128 b) + /// UNPCKHPS xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) => UnpackHigh(left, right); + + /// + /// __m128 _mm_unpacklo_ps (__m128 a, __m128 b) + /// UNPCKLPS xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) => UnpackLow(left, right); + + /// + /// __m128 _mm_xor_ps (__m128 a, __m128 b) + /// XORPS xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) => Xor(left, right); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse2.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse2.PlatformNotSupported.cs new file mode 100644 index 0000000000..0f9b1959b5 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse2.PlatformNotSupported.cs @@ -0,0 +1,1763 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel SSE2 hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Sse2 : Sse + { + internal Sse2() { } + + public new static bool IsSupported { get { return false; } } + + /// + /// __m128i _mm_add_epi8 (__m128i a, __m128i b) + /// PADDB xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_add_epi8 (__m128i a, __m128i b) + /// PADDB xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_add_epi16 (__m128i a, __m128i b) + /// PADDW xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_add_epi16 (__m128i a, __m128i b) + /// PADDW xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_add_epi32 (__m128i a, __m128i b) + /// PADDD xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_add_epi32 (__m128i a, __m128i b) + /// PADDD xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_add_epi64 (__m128i a, __m128i b) + /// PADDQ xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_add_epi64 (__m128i a, __m128i b) + /// PADDQ xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_add_pd (__m128d a, __m128d b) + /// ADDPD xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_add_sd (__m128d a, __m128d b) + /// ADDSD xmm, xmm/m64 + /// + public static Vector128 AddScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_adds_epi8 (__m128i a, __m128i b) + /// PADDSB xmm, xmm/m128 + /// + public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_adds_epu8 (__m128i a, __m128i b) + /// PADDUSB xmm, xmm/m128 + /// + public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_adds_epi16 (__m128i a, __m128i b) + /// PADDSW xmm, xmm/m128 + /// + public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_adds_epu16 (__m128i a, __m128i b) + /// PADDUSW xmm, xmm/m128 + /// + public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_and_pd (__m128d a, __m128d b) + /// ANDPD xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_andnot_pd (__m128d a, __m128d b) + /// ADDNPD xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_avg_epu8 (__m128i a, __m128i b) + /// PAVGB xmm, xmm/m128 + /// + public static Vector128 Average(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_avg_epu16 (__m128i a, __m128i b) + /// PAVGW xmm, xmm/m128 + /// + public static Vector128 Average(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpeq_epi8 (__m128i a, __m128i b) + /// PCMPEQB xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cmpeq_epi8 (__m128i a, __m128i b) + /// PCMPEQB xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cmpeq_epi16 (__m128i a, __m128i b) + /// PCMPEQW xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cmpeq_epi16 (__m128i a, __m128i b) + /// PCMPEQW xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cmpeq_epi32 (__m128i a, __m128i b) + /// PCMPEQD xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cmpeq_epi32 (__m128i a, __m128i b) + /// PCMPEQD xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_cmpeq_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(0) + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_comieq_sd (__m128d a, __m128d b) + /// COMISS xmm, xmm/m64 + /// + public static bool CompareEqualOrderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_ucomieq_sd (__m128d a, __m128d b) + /// UCOMISS xmm, xmm/m64 + /// + public static bool CompareEqualUnorderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpeq_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(0) + /// + public static Vector128 CompareEqualScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpgt_epi8 (__m128i a, __m128i b) + /// PCMPGTB xmm, xmm/m128 + /// + public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cmpgt_epi16 (__m128i a, __m128i b) + /// PCMPGTW xmm, xmm/m128 + /// + public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cmpgt_epi32 (__m128i a, __m128i b) + /// PCMPGTD xmm, xmm/m128 + /// + public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_cmpgt_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(6) + /// + public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_comigt_sd (__m128d a, __m128d b) + /// COMISS xmm, xmm/m64 + /// + public static bool CompareGreaterThanOrderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_ucomigt_sd (__m128d a, __m128d b) + /// UCOMISS xmm, xmm/m64 + /// + public static bool CompareGreaterThanUnorderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpgt_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(6) + /// + public static Vector128 CompareGreaterThanScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpge_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(5) + /// + public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_comige_sd (__m128d a, __m128d b) + /// COMISS xmm, xmm/m64 + /// + public static bool CompareGreaterThanOrEqualOrderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_ucomige_sd (__m128d a, __m128d b) + /// UCOMISS xmm, xmm/m64 + /// + public static bool CompareGreaterThanOrEqualUnorderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpge_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(5) + /// + public static Vector128 CompareGreaterThanOrEqualScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmplt_epi8 (__m128i a, __m128i b) + /// PCMPGTB xmm, xmm/m128 + /// + public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cmplt_epi16 (__m128i a, __m128i b) + /// PCMPGTW xmm, xmm/m128 + /// + public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cmplt_epi32 (__m128i a, __m128i b) + /// PCMPGTD xmm, xmm/m128 + /// + public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_cmplt_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(1) + /// + public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_comilt_sd (__m128d a, __m128d b) + /// COMISS xmm, xmm/m64 + /// + public static bool CompareLessThanOrderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_ucomilt_sd (__m128d a, __m128d b) + /// UCOMISS xmm, xmm/m64 + /// + public static bool CompareLessThanUnorderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmplt_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(1) + /// + public static Vector128 CompareLessThanScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmple_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(2) + /// + public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_comile_sd (__m128d a, __m128d b) + /// COMISS xmm, xmm/m64 + /// + public static bool CompareLessThanOrEqualOrderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_ucomile_sd (__m128d a, __m128d b) + /// UCOMISS xmm, xmm/m64 + /// + public static bool CompareLessThanOrEqualUnorderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmple_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(2) + /// + public static Vector128 CompareLessThanOrEqualScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpneq_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(4) + /// + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_comineq_sd (__m128d a, __m128d b) + /// COMISS xmm, xmm/m64 + /// + public static bool CompareNotEqualOrderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_ucomineq_sd (__m128d a, __m128d b) + /// UCOMISS xmm, xmm/m64 + /// + public static bool CompareNotEqualUnorderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpneq_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(4) + /// + public static Vector128 CompareNotEqualScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpngt_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(2) + /// + public static Vector128 CompareNotGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpngt_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(2) + /// + public static Vector128 CompareNotGreaterThanScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpnge_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(1) + /// + public static Vector128 CompareNotGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpnge_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(1) + /// + public static Vector128 CompareNotGreaterThanOrEqualScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpnlt_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(5) + /// + public static Vector128 CompareNotLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpnlt_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(5) + /// + public static Vector128 CompareNotLessThanScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpnle_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(6) + /// + public static Vector128 CompareNotLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpnle_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(6) + /// + public static Vector128 CompareNotLessThanOrEqualScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpord_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(7) + /// + public static Vector128 CompareOrdered(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpord_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(7) + /// + public static Vector128 CompareOrderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpunord_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(3) + /// + public static Vector128 CompareUnordered(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cmpunord_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(3) + /// + public static Vector128 CompareUnorderedScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cvtps_epi32 (__m128 a) + /// CVTPS2DQ xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Int32(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtpd_epi32 (__m128d a) + /// CVTPD2DQ xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Int32(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_cvtepi32_ps (__m128i a) + /// CVTDQ2PS xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Single(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_cvtpd_ps (__m128d a) + /// CVTPD2PS xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Single(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_cvtepi32_pd (__m128i a) + /// CVTDQ2PD xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Double(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_cvtps_pd (__m128 a) + /// CVTPS2PD xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Double(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// double _mm_cvtsd_f64(__m128d a) + /// HELPER: MOVSD + /// + public static double ConvertToDouble(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_cvtsd_si32 (__m128d a) + /// CVTSD2SI r32, xmm/m64 + /// + public static int ConvertToInt32(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_cvtsi128_si32 (__m128i a) + /// MOVD reg/m32, xmm + /// + public static int ConvertToInt32(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __int64 _mm_cvtsd_si64 (__m128d a) + /// CVTSD2SI r64, xmm/m64 + /// + public static long ConvertToInt64(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __int64 _mm_cvtsi128_si64 (__m128i a) + /// MOVQ reg/m64, xmm + /// + public static long ConvertToInt64(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_cvtsi128_si32 (__m128i a) + /// MOVD reg/m32, xmm + /// + public static uint ConvertToUInt32(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __int64 _mm_cvtsi128_si64 (__m128i a) + /// MOVQ reg/m64, xmm + /// + public static ulong ConvertToUInt64(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_cvtsi32_sd (__m128d a, int b) + /// CVTSI2SD xmm, reg/m64 + /// + public static Vector128 ConvertScalarToVector128Double(Vector128 upper, int value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_cvtsi64_sd (__m128d a, int b) + /// CVTSI2SD xmm, reg/m64 + /// + public static Vector128 ConvertScalarToVector128Double(Vector128 upper, long value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_cvtss_sd (__m128d a, __m128 b) + /// CVTSS2SD xmm, xmm/m32 + /// + public static Vector128 ConvertScalarToVector128Double(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtsi32_si128 (int a) + /// MOVD xmm, reg/m32 + /// + public static Vector128 ConvertScalarToVector128Int32(int value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtsi64_si128 (__int64 a) + /// MOVQ xmm, reg/m64 + /// + public static Vector128 ConvertScalarToVector128Int64(long value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_cvtsd_ss (__m128 a, __m128d b) + /// CVTSD2SS xmm, xmm/m64 + /// + public static Vector128 ConvertScalarToVector128Single(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtsi32_si128 (int a) + /// MOVD xmm, reg/m32 + /// + public static Vector128 ConvertScalarToVector128UInt32(uint value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtsi64_si128 (__int64 a) + /// MOVQ xmm, reg/m64 + /// + public static Vector128 ConvertScalarToVector128UInt64(ulong value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cvttps_epi32 (__m128 a) + /// CVTTPS2DQ xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Int32WithTruncation(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvttpd_epi32 (__m128d a) + /// CVTTPD2DQ xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Int32WithTruncation(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cvttsd_si32 (__m128d a) + /// CVTTSD2SI reg, xmm/m64 + /// + public static int ConvertToInt32WithTruncation(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __int64 _mm_cvttsd_si64 (__m128d a) + /// CVTTSD2SI reg, xmm/m64 + /// + public static long ConvertToInt64WithTruncation(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_div_pd (__m128d a, __m128d b) + /// DIVPD xmm, xmm/m128 + /// + public static Vector128 Divide(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_div_sd (__m128d a, __m128d b) + /// DIVSD xmm, xmm/m64 + /// + public static Vector128 DivideScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_extract_epi16 (__m128i a, int immediate) + /// PEXTRW reg, xmm, imm8 + /// + public static ushort Extract(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_insert_epi16 (__m128i a, int i, int immediate) + /// PINSRW xmm, reg/m16, imm8 + /// + public static Vector128 Insert(Vector128 value, short data, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_insert_epi16 (__m128i a, int i, int immediate) + /// PINSRW xmm, reg/m16, imm8 + /// + public static Vector128 Insert(Vector128 value, ushort data, byte index) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(sbyte* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(byte* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(short* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(ushort* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(int* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(uint* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(long* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(ulong* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_loadu_pd (double const* mem_address) + /// MOVUPD xmm, m128 + /// + public static unsafe Vector128 LoadVector128(double* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_load_sd (double const* mem_address) + /// MOVSD xmm, m64 + /// + public static unsafe Vector128 LoadScalarVector128(double* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(sbyte* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(byte* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(short* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(ushort* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(int* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(uint* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(long* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(ulong* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_load_pd (double const* mem_address) + /// MOVAPD xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(double* address) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_lfence(void) + /// LFENCE + /// + public static void LoadFence() { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_loadh_pd (__m128d a, double const* mem_addr) + /// MOVHPD xmm, m64 + /// + public static unsafe Vector128 LoadHigh(Vector128 lower, double* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_loadl_pd (__m128d a, double const* mem_addr) + /// MOVLPD xmm, m64 + /// + public static unsafe Vector128 LoadLow(Vector128 upper, double* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_loadl_epi32 (__m128i const* mem_addr) + /// MOVD xmm, reg/m64 + /// The above native signature does not exist. We provide this additional overload for completeness. + /// + public static unsafe Vector128 LoadScalarVector128(int* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_loadl_epi32 (__m128i const* mem_addr) + /// MOVD xmm, reg/m64 + /// The above native signature does not exist. We provide this additional overload for completeness. + /// + public static unsafe Vector128 LoadScalarVector128(uint* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_loadl_epi64 (__m128i const* mem_addr) + /// MOVQ xmm, reg/m64 + /// + public static unsafe Vector128 LoadScalarVector128(long* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_loadl_epi64 (__m128i const* mem_addr) + /// MOVQ xmm, reg/m64 + /// + public static unsafe Vector128 LoadScalarVector128(ulong* address) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_maskmoveu_si128 (__m128i a, __m128i mask, char* mem_address) + /// MASKMOVDQU xmm, xmm + /// + public static unsafe void MaskMove(Vector128 source, Vector128 mask, sbyte* address) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_maskmoveu_si128 (__m128i a, __m128i mask, char* mem_address) + /// MASKMOVDQU xmm, xmm + /// + public static unsafe void MaskMove(Vector128 source, Vector128 mask, byte* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_max_epu8 (__m128i a, __m128i b) + /// PMAXUB xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_max_epi16 (__m128i a, __m128i b) + /// PMAXSW xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_max_pd (__m128d a, __m128d b) + /// MAXPD xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_max_sd (__m128d a, __m128d b) + /// MAXSD xmm, xmm/m64 + /// + public static Vector128 MaxScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_mfence(void) + /// MFENCE + /// + public static void MemoryFence() { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_min_epu8 (__m128i a, __m128i b) + /// PMINUB xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_min_epi16 (__m128i a, __m128i b) + /// PMINSW xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_min_pd (__m128d a, __m128d b) + /// MINPD xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_min_sd (__m128d a, __m128d b) + /// MINSD xmm, xmm/m64 + /// + public static Vector128 MinScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_move_sd (__m128d a, __m128d b) + /// MOVSD xmm, xmm + /// + public static Vector128 MoveScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_movemask_epi8 (__m128i a) + /// PMOVMSKB reg, xmm + /// + public static int MoveMask(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_movemask_epi8 (__m128i a) + /// PMOVMSKB reg, xmm + /// + public static int MoveMask(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_movemask_pd (__m128d a) + /// MOVMSKPD reg, xmm + /// + public static int MoveMask(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_move_epi64 (__m128i a) + /// MOVQ xmm, xmm + /// + public static Vector128 MoveScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_move_epi64 (__m128i a) + /// MOVQ xmm, xmm + /// + public static Vector128 MoveScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_mul_epu32 (__m128i a, __m128i b) + /// PMULUDQ xmm, xmm/m128 + /// + public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_mul_pd (__m128d a, __m128d b) + /// MULPD xmm, xmm/m128 + /// + public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_mul_sd (__m128d a, __m128d b) + /// MULSD xmm, xmm/m64 + /// + public static Vector128 MultiplyScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_mulhi_epi16 (__m128i a, __m128i b) + /// PMULHW xmm, xmm/m128 + /// + public static Vector128 MultiplyHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_mulhi_epu16 (__m128i a, __m128i b) + /// PMULHUW xmm, xmm/m128 + /// + public static Vector128 MultiplyHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_madd_epi16 (__m128i a, __m128i b) + /// PMADDWD xmm, xmm/m128 + /// + public static Vector128 MultiplyAddAdjacent(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_mullo_epi16 (__m128i a, __m128i b) + /// PMULLW xmm, xmm/m128 + /// + public static Vector128 MultiplyLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_or_pd (__m128d a, __m128d b) + /// ORPD xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_packs_epi16 (__m128i a, __m128i b) + /// PACKSSWB xmm, xmm/m128 + /// + public static Vector128 PackSignedSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_packs_epi32 (__m128i a, __m128i b) + /// PACKSSDW xmm, xmm/m128 + /// + public static Vector128 PackSignedSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_packus_epi16 (__m128i a, __m128i b) + /// PACKUSWB xmm, xmm/m128 + /// + public static Vector128 PackUnsignedSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// ___m128i _mm_set_epi8 (char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) + /// HELPER + /// + public static Vector128 SetVector128(sbyte e15, sbyte e14, sbyte e13, sbyte e12, sbyte e11, sbyte e10, sbyte e9, sbyte e8, sbyte e7, sbyte e6, sbyte e5, sbyte e4, sbyte e3, sbyte e2, sbyte e1, sbyte e0) { throw new PlatformNotSupportedException(); } + /// + /// ___m128i _mm_set_epi8 (char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) + /// HELPER + /// + public static Vector128 SetVector128(byte e15, byte e14, byte e13, byte e12, byte e11, byte e10, byte e9, byte e8, byte e7, byte e6, byte e5, byte e4, byte e3, byte e2, byte e1, byte e0) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_set_epi16 (short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) + /// HELPER + /// + public static Vector128 SetVector128(short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_set_epi16 (short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) + /// HELPER + /// + public static Vector128 SetVector128(ushort e7, ushort e6, ushort e5, ushort e4, ushort e3, ushort e2, ushort e1, ushort e0) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_set_epi32 (int e3, int e2, int e1, int e0) + /// HELPER + /// + public static Vector128 SetVector128(int e3, int e2, int e1, int e0) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_set_epi32 (int e3, int e2, int e1, int e0) + /// HELPER + /// + public static Vector128 SetVector128(uint e3, uint e2, uint e1, uint e0) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_set_epi64x (__int64 e1, __int64 e0) + /// HELPER + /// + public static Vector128 SetVector128(long e1, long e0) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_set_epi64x (__int64 e1, __int64 e0) + /// HELPER + /// + public static Vector128 SetVector128(ulong e1, ulong e0) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_set_pd (double e1, double e0) + /// HELPER + /// + public static Vector128 SetVector128(double e1, double e0) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_set_sd (double a) + /// HELPER + /// + public static Vector128 SetScalarVector128(double value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_set1_epi8 (char a) + /// HELPER + /// + public static Vector128 SetAllVector128(byte value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_set1_epi8 (char a) + /// HELPER + /// + public static Vector128 SetAllVector128(sbyte value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_set1_epi16 (short a) + /// HELPER + /// + public static Vector128 SetAllVector128(short value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_set1_epi16 (short a) + /// HELPER + /// + public static Vector128 SetAllVector128(ushort value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_set1_epi32 (int a) + /// HELPER + /// + public static Vector128 SetAllVector128(int value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_set1_epi32 (int a) + /// HELPER + /// + public static Vector128 SetAllVector128(uint value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_set1_epi64x (long long a) + /// HELPER + /// + public static Vector128 SetAllVector128(long value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_set1_epi64x (long long a) + /// HELPER + /// + public static Vector128 SetAllVector128(ulong value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_set1_pd (double a) + /// HELPER + /// + public static Vector128 SetAllVector128(double value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_setzero_si128 () + /// HELPER: PXOR + /// __m128d _mm_setzero_pd (void) + /// HELPER: XORPD + /// + public static Vector128 SetZeroVector128() where T : struct { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_sad_epu8 (__m128i a, __m128i b) + /// PSADBW xmm, xmm/m128 + /// + public static Vector128 SumAbsoluteDifferences(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_shuffle_epi32 (__m128i a, int immediate) + /// PSHUFD xmm, xmm/m128, imm8 + /// + public static Vector128 Shuffle(Vector128 value, byte control) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_shuffle_epi32 (__m128i a, int immediate) + /// PSHUFD xmm, xmm/m128, imm8 + /// + public static Vector128 Shuffle(Vector128 value, byte control) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_shuffle_pd (__m128d a, __m128d b, int immediate) + /// SHUFPD xmm, xmm/m128, imm8 + /// + public static Vector128 Shuffle(Vector128 left, Vector128 right, byte control) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_shufflehi_epi16 (__m128i a, int immediate) + /// PSHUFHW xmm, xmm/m128, imm8 + /// + public static Vector128 ShuffleHigh(Vector128 value, byte control) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_shufflehi_epi16 (__m128i a, int control) + /// PSHUFHW xmm, xmm/m128, imm8 + /// + public static Vector128 ShuffleHigh(Vector128 value, byte control) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_shufflelo_epi16 (__m128i a, int control) + /// PSHUFLW xmm, xmm/m128, imm8 + /// + public static Vector128 ShuffleLow(Vector128 value, byte control) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_shufflelo_epi16 (__m128i a, int control) + /// PSHUFLW xmm, xmm/m128, imm8 + /// + public static Vector128 ShuffleLow(Vector128 value, byte control) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_sll_epi16 (__m128i a, __m128i count) + /// PSLLW xmm, xmm/m128 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sll_epi16 (__m128i a, __m128i count) + /// PSLLW xmm, xmm/m128 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sll_epi32 (__m128i a, __m128i count) + /// PSLLD xmm, xmm/m128 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sll_epi32 (__m128i a, __m128i count) + /// PSLLD xmm, xmm/m128 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sll_epi64 (__m128i a, __m128i count) + /// PSLLQ xmm, xmm/m128 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sll_epi64 (__m128i a, __m128i count) + /// PSLLQ xmm, xmm/m128 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_slli_epi16 (__m128i a, int immediate) + /// PSLLW xmm, imm8 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_slli_epi16 (__m128i a, int immediate) + /// PSLLW xmm, imm8 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_slli_epi32 (__m128i a, int immediate) + /// PSLLD xmm, imm8 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_slli_epi32 (__m128i a, int immediate) + /// PSLLD xmm, imm8 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_slli_epi64 (__m128i a, int immediate) + /// PSLLQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_slli_epi64 (__m128i a, int immediate) + /// PSLLQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_sra_epi16 (__m128i a, __m128i count) + /// PSRAW xmm, xmm/m128 + /// + public static Vector128 ShiftRightArithmetic(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sra_epi32 (__m128i a, __m128i count) + /// PSRAD xmm, xmm/m128 + /// + public static Vector128 ShiftRightArithmetic(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_srai_epi16 (__m128i a, int immediate) + /// PSRAW xmm, imm8 + /// + public static Vector128 ShiftRightArithmetic(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_srai_epi32 (__m128i a, int immediate) + /// PSRAD xmm, imm8 + /// + public static Vector128 ShiftRightArithmetic(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_srl_epi16 (__m128i a, __m128i count) + /// PSRLW xmm, xmm/m128 + /// + public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_srl_epi16 (__m128i a, __m128i count) + /// PSRLW xmm, xmm/m128 + /// + public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_srl_epi32 (__m128i a, __m128i count) + /// PSRLD xmm, xmm/m128 + /// + public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_srl_epi32 (__m128i a, __m128i count) + /// PSRLD xmm, xmm/m128 + /// + public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_srl_epi64 (__m128i a, __m128i count) + /// PSRLQ xmm, xmm/m128 + /// + public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_srl_epi64 (__m128i a, __m128i count) + /// PSRLQ xmm, xmm/m128 + /// + public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_srli_epi16 (__m128i a, int immediate) + /// PSRLW xmm, imm8 + /// + public static Vector128 ShiftRightLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_srli_epi16 (__m128i a, int immediate) + /// PSRLW xmm, imm8 + /// + public static Vector128 ShiftRightLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_srli_epi32 (__m128i a, int immediate) + /// PSRLD xmm, imm8 + /// + public static Vector128 ShiftRightLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_srli_epi32 (__m128i a, int immediate) + /// PSRLD xmm, imm8 + /// + public static Vector128 ShiftRightLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_srli_epi64 (__m128i a, int immediate) + /// PSRLQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_srli_epi64 (__m128i a, int immediate) + /// PSRLQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_sqrt_pd (__m128d a) + /// SQRTPD xmm, xmm/m128 + /// + public static Vector128 Sqrt(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_sqrt_sd (__m128d a) + /// SQRTSD xmm, xmm/64 + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 SqrtScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_sqrt_sd (__m128d a, __m128d b) + /// SQRTSD xmm, xmm/64 + /// + public static Vector128 SqrtScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_store_sd (double* mem_addr, __m128d a) + /// MOVSD m64, xmm + /// + public static unsafe void StoreScalar(double* address, Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(sbyte* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(byte* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(short* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(ushort* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(int* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(uint* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(long* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(ulong* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_store_pd (double* mem_addr, __m128d a) + /// MOVAPD m128, xmm + /// + public static unsafe void StoreAligned(double* address, Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(sbyte* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(byte* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(short* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(ushort* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(int* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(uint* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(long* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(ulong* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_stream_pd (double* mem_addr, __m128d a) + /// MOVNTPD m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(double* address, Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(sbyte* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(byte* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(short* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(ushort* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(int* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(uint* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(long* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(ulong* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_storeu_pd (double* mem_addr, __m128d a) + /// MOVUPD m128, xmm + /// + public static unsafe void Store(double* address, Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_storeh_pd (double* mem_addr, __m128d a) + /// MOVHPD m64, xmm + /// + public static unsafe void StoreHigh(double* address, Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_storel_epi64 (__m128i* mem_addr, __m128i a) + /// MOVQ m64, xmm + /// + public static unsafe void StoreLow(long* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_storel_epi64 (__m128i* mem_addr, __m128i a) + /// MOVQ m64, xmm + /// + public static unsafe void StoreLow(ulong* address, Vector128 source) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_storel_pd (double* mem_addr, __m128d a) + /// MOVLPD m64, xmm + /// + public static unsafe void StoreLow(double* address, Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_stream_si32(int *p, int a) + /// MOVNTI m32, r32 + /// + public static unsafe void StoreNonTemporal(int* address, int value) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_stream_si32(int *p, int a) + /// MOVNTI m32, r32 + /// + public static unsafe void StoreNonTemporal(uint* address, uint value) { throw new PlatformNotSupportedException(); } + + /// + /// void _mm_stream_si64(__int64 *p, __int64 a) + /// MOVNTI m64, r64 + /// + public static unsafe void StoreNonTemporal(long* address, long value) { throw new PlatformNotSupportedException(); } + /// + /// void _mm_stream_si64(__int64 *p, __int64 a) + /// MOVNTI m64, r64 + /// + public static unsafe void StoreNonTemporal(ulong* address, ulong value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_sub_epi8 (__m128i a, __m128i b) + /// PSUBB xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sub_epi8 (__m128i a, __m128i b) + /// PSUBB xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sub_epi16 (__m128i a, __m128i b) + /// PSUBW xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sub_epi16 (__m128i a, __m128i b) + /// PSUBW xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sub_epi32 (__m128i a, __m128i b) + /// PSUBD xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sub_epi32 (__m128i a, __m128i b) + /// PSUBD xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sub_epi64 (__m128i a, __m128i b) + /// PSUBQ xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sub_epi64 (__m128i a, __m128i b) + /// PSUBQ xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_sub_pd (__m128d a, __m128d b) + /// SUBPD xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_sub_sd (__m128d a, __m128d b) + /// SUBSD xmm, xmm/m64 + /// + public static Vector128 SubtractScalar(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_subs_epi8 (__m128i a, __m128i b) + /// PSUBSB xmm, xmm/m128 + /// + public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_subs_epi16 (__m128i a, __m128i b) + /// PSUBSW xmm, xmm/m128 + /// + public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_subs_epu8 (__m128i a, __m128i b) + /// PSUBUSB xmm, xmm/m128 + /// + public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_subs_epu16 (__m128i a, __m128i b) + /// PSUBUSW xmm, xmm/m128 + /// + public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_unpackhi_epi8 (__m128i a, __m128i b) + /// PUNPCKHBW xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_unpackhi_epi8 (__m128i a, __m128i b) + /// PUNPCKHBW xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_unpackhi_epi16 (__m128i a, __m128i b) + /// PUNPCKHWD xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_unpackhi_epi16 (__m128i a, __m128i b) + /// PUNPCKHWD xmm, xmm/m128 + /// UnpackHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_unpackhi_epi32 (__m128i a, __m128i b) + /// PUNPCKHDQ xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_unpackhi_epi32 (__m128i a, __m128i b) + /// PUNPCKHDQ xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_unpackhi_epi64 (__m128i a, __m128i b) + /// PUNPCKHQDQ xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_unpackhi_epi64 (__m128i a, __m128i b) + /// PUNPCKHQDQ xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_unpackhi_pd (__m128d a, __m128d b) + /// UNPCKHPD xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_unpacklo_epi8 (__m128i a, __m128i b) + /// PUNPCKLBW xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_unpacklo_epi8 (__m128i a, __m128i b) + /// PUNPCKLBW xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_unpacklo_epi16 (__m128i a, __m128i b) + /// PUNPCKLWD xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_unpacklo_epi16 (__m128i a, __m128i b) + /// PUNPCKLWD xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_unpacklo_epi32 (__m128i a, __m128i b) + /// PUNPCKLDQ xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_unpacklo_epi32 (__m128i a, __m128i b) + /// PUNPCKLDQ xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_unpacklo_epi64 (__m128i a, __m128i b) + /// PUNPCKLQDQ xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_unpacklo_epi64 (__m128i a, __m128i b) + /// PUNPCKLQDQ xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_unpacklo_pd (__m128d a, __m128d b) + /// UNPCKLPD xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_xor_pd (__m128d a, __m128d b) + /// XORPD xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse2.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse2.cs new file mode 100644 index 0000000000..0f8b9a8f5a --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse2.cs @@ -0,0 +1,2002 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel SSE2 hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Sse2 : Sse + { + internal Sse2() { } + + public new static bool IsSupported { get => IsSupported; } + + /// + /// __m128i _mm_add_epi8 (__m128i a, __m128i b) + /// PADDB xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) => Add(left, right); + /// + /// __m128i _mm_add_epi8 (__m128i a, __m128i b) + /// PADDB xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) => Add(left, right); + /// + /// __m128i _mm_add_epi16 (__m128i a, __m128i b) + /// PADDW xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) => Add(left, right); + /// + /// __m128i _mm_add_epi16 (__m128i a, __m128i b) + /// PADDW xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) => Add(left, right); + /// + /// __m128i _mm_add_epi32 (__m128i a, __m128i b) + /// PADDD xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) => Add(left, right); + /// + /// __m128i _mm_add_epi32 (__m128i a, __m128i b) + /// PADDD xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) => Add(left, right); + /// + /// __m128i _mm_add_epi64 (__m128i a, __m128i b) + /// PADDQ xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) => Add(left, right); + /// + /// __m128i _mm_add_epi64 (__m128i a, __m128i b) + /// PADDQ xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) => Add(left, right); + /// + /// __m128d _mm_add_pd (__m128d a, __m128d b) + /// ADDPD xmm, xmm/m128 + /// + public static Vector128 Add(Vector128 left, Vector128 right) => Add(left, right); + + /// + /// __m128d _mm_add_sd (__m128d a, __m128d b) + /// ADDSD xmm, xmm/m64 + /// + public static Vector128 AddScalar(Vector128 left, Vector128 right) => AddScalar(left, right); + + /// + /// __m128i _mm_adds_epi8 (__m128i a, __m128i b) + /// PADDSB xmm, xmm/m128 + /// + public static Vector128 AddSaturate(Vector128 left, Vector128 right) => AddSaturate(left, right); + /// + /// __m128i _mm_adds_epu8 (__m128i a, __m128i b) + /// PADDUSB xmm, xmm/m128 + /// + public static Vector128 AddSaturate(Vector128 left, Vector128 right) => AddSaturate(left, right); + /// + /// __m128i _mm_adds_epi16 (__m128i a, __m128i b) + /// PADDSW xmm, xmm/m128 + /// + public static Vector128 AddSaturate(Vector128 left, Vector128 right) => AddSaturate(left, right); + /// + /// __m128i _mm_adds_epu16 (__m128i a, __m128i b) + /// PADDUSW xmm, xmm/m128 + /// + public static Vector128 AddSaturate(Vector128 left, Vector128 right) => AddSaturate(left, right); + + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + /// + /// __m128i _mm_and_si128 (__m128i a, __m128i b) + /// PAND xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + /// + /// __m128d _mm_and_pd (__m128d a, __m128d b) + /// ANDPD xmm, xmm/m128 + /// + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) => AndNot(left, right); + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) => AndNot(left, right); + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) => AndNot(left, right); + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) => AndNot(left, right); + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) => AndNot(left, right); + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) => AndNot(left, right); + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) => AndNot(left, right); + /// + /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) + /// PANDN xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) => AndNot(left, right); + /// + /// __m128d _mm_andnot_pd (__m128d a, __m128d b) + /// ADDNPD xmm, xmm/m128 + /// + public static Vector128 AndNot(Vector128 left, Vector128 right) => AndNot(left, right); + + /// + /// __m128i _mm_avg_epu8 (__m128i a, __m128i b) + /// PAVGB xmm, xmm/m128 + /// + public static Vector128 Average(Vector128 left, Vector128 right) => Average(left, right); + /// + /// __m128i _mm_avg_epu16 (__m128i a, __m128i b) + /// PAVGW xmm, xmm/m128 + /// + public static Vector128 Average(Vector128 left, Vector128 right) => Average(left, right); + + /// + /// __m128i _mm_cmpeq_epi8 (__m128i a, __m128i b) + /// PCMPEQB xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + /// + /// __m128i _mm_cmpeq_epi8 (__m128i a, __m128i b) + /// PCMPEQB xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + /// + /// __m128i _mm_cmpeq_epi16 (__m128i a, __m128i b) + /// PCMPEQW xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + /// + /// __m128i _mm_cmpeq_epi16 (__m128i a, __m128i b) + /// PCMPEQW xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + /// + /// __m128i _mm_cmpeq_epi32 (__m128i a, __m128i b) + /// PCMPEQD xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + /// + /// __m128i _mm_cmpeq_epi32 (__m128i a, __m128i b) + /// PCMPEQD xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + /// + /// __m128d _mm_cmpeq_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(0) + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + + /// + /// int _mm_comieq_sd (__m128d a, __m128d b) + /// COMISS xmm, xmm/m64 + /// + public static bool CompareEqualOrderedScalar(Vector128 left, Vector128 right) => CompareEqualOrderedScalar(left, right); + + /// + /// int _mm_ucomieq_sd (__m128d a, __m128d b) + /// UCOMISS xmm, xmm/m64 + /// + public static bool CompareEqualUnorderedScalar(Vector128 left, Vector128 right) => CompareEqualUnorderedScalar(left, right); + + /// + /// __m128d _mm_cmpeq_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(0) + /// + public static Vector128 CompareEqualScalar(Vector128 left, Vector128 right) => CompareEqualScalar(left, right); + + /// + /// __m128i _mm_cmpgt_epi8 (__m128i a, __m128i b) + /// PCMPGTB xmm, xmm/m128 + /// + public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) => CompareGreaterThan(left, right); + /// + /// __m128i _mm_cmpgt_epi16 (__m128i a, __m128i b) + /// PCMPGTW xmm, xmm/m128 + /// + public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) => CompareGreaterThan(left, right); + /// + /// __m128i _mm_cmpgt_epi32 (__m128i a, __m128i b) + /// PCMPGTD xmm, xmm/m128 + /// + public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) => CompareGreaterThan(left, right); + /// + /// __m128d _mm_cmpgt_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(6) + /// + public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) => CompareGreaterThan(left, right); + + /// + /// int _mm_comigt_sd (__m128d a, __m128d b) + /// COMISS xmm, xmm/m64 + /// + public static bool CompareGreaterThanOrderedScalar(Vector128 left, Vector128 right) => CompareGreaterThanOrderedScalar(left, right); + + /// + /// int _mm_ucomigt_sd (__m128d a, __m128d b) + /// UCOMISS xmm, xmm/m64 + /// + public static bool CompareGreaterThanUnorderedScalar(Vector128 left, Vector128 right) => CompareGreaterThanUnorderedScalar(left, right); + + /// + /// __m128d _mm_cmpgt_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(6) + /// + public static Vector128 CompareGreaterThanScalar(Vector128 left, Vector128 right) => CompareGreaterThanScalar(left, right); + + /// + /// __m128d _mm_cmpge_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(5) + /// + public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) => CompareGreaterThanOrEqual(left, right); + + /// + /// int _mm_comige_sd (__m128d a, __m128d b) + /// COMISS xmm, xmm/m64 + /// + public static bool CompareGreaterThanOrEqualOrderedScalar(Vector128 left, Vector128 right) => CompareGreaterThanOrEqualOrderedScalar(left, right); + + /// + /// int _mm_ucomige_sd (__m128d a, __m128d b) + /// UCOMISS xmm, xmm/m64 + /// + public static bool CompareGreaterThanOrEqualUnorderedScalar(Vector128 left, Vector128 right) => CompareGreaterThanOrEqualUnorderedScalar(left, right); + + /// + /// __m128d _mm_cmpge_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(5) + /// + public static Vector128 CompareGreaterThanOrEqualScalar(Vector128 left, Vector128 right) => CompareGreaterThanOrEqualScalar(left, right); + + /// + /// __m128i _mm_cmplt_epi8 (__m128i a, __m128i b) + /// PCMPGTB xmm, xmm/m128 + /// + public static Vector128 CompareLessThan(Vector128 left, Vector128 right) => CompareLessThan(left, right); + /// + /// __m128i _mm_cmplt_epi16 (__m128i a, __m128i b) + /// PCMPGTW xmm, xmm/m128 + /// + public static Vector128 CompareLessThan(Vector128 left, Vector128 right) => CompareLessThan(left, right); + /// + /// __m128i _mm_cmplt_epi32 (__m128i a, __m128i b) + /// PCMPGTD xmm, xmm/m128 + /// + public static Vector128 CompareLessThan(Vector128 left, Vector128 right) => CompareLessThan(left, right); + /// + /// __m128d _mm_cmplt_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(1) + /// + public static Vector128 CompareLessThan(Vector128 left, Vector128 right) => CompareLessThan(left, right); + + /// + /// int _mm_comilt_sd (__m128d a, __m128d b) + /// COMISS xmm, xmm/m64 + /// + public static bool CompareLessThanOrderedScalar(Vector128 left, Vector128 right) => CompareLessThanOrderedScalar(left, right); + + /// + /// int _mm_ucomilt_sd (__m128d a, __m128d b) + /// UCOMISS xmm, xmm/m64 + /// + public static bool CompareLessThanUnorderedScalar(Vector128 left, Vector128 right) => CompareLessThanUnorderedScalar(left, right); + + /// + /// __m128d _mm_cmplt_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(1) + /// + public static Vector128 CompareLessThanScalar(Vector128 left, Vector128 right) => CompareLessThanScalar(left, right); + + /// + /// __m128d _mm_cmple_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(2) + /// + public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) => CompareLessThanOrEqual(left, right); + + /// + /// int _mm_comile_sd (__m128d a, __m128d b) + /// COMISS xmm, xmm/m64 + /// + public static bool CompareLessThanOrEqualOrderedScalar(Vector128 left, Vector128 right) => CompareLessThanOrEqualOrderedScalar(left, right); + + /// + /// int _mm_ucomile_sd (__m128d a, __m128d b) + /// UCOMISS xmm, xmm/m64 + /// + public static bool CompareLessThanOrEqualUnorderedScalar(Vector128 left, Vector128 right) => CompareLessThanOrEqualUnorderedScalar(left, right); + + /// + /// __m128d _mm_cmple_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(2) + /// + public static Vector128 CompareLessThanOrEqualScalar(Vector128 left, Vector128 right) => CompareLessThanOrEqualScalar(left, right); + + /// + /// __m128d _mm_cmpneq_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(4) + /// + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) => CompareNotEqual(left, right); + + /// + /// int _mm_comineq_sd (__m128d a, __m128d b) + /// COMISS xmm, xmm/m64 + /// + public static bool CompareNotEqualOrderedScalar(Vector128 left, Vector128 right) => CompareNotEqualOrderedScalar(left, right); + + /// + /// int _mm_ucomineq_sd (__m128d a, __m128d b) + /// UCOMISS xmm, xmm/m64 + /// + public static bool CompareNotEqualUnorderedScalar(Vector128 left, Vector128 right) => CompareNotEqualUnorderedScalar(left, right); + + /// + /// __m128d _mm_cmpneq_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(4) + /// + public static Vector128 CompareNotEqualScalar(Vector128 left, Vector128 right) => CompareNotEqualScalar(left, right); + + /// + /// __m128d _mm_cmpngt_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(2) + /// + public static Vector128 CompareNotGreaterThan(Vector128 left, Vector128 right) => CompareNotGreaterThan(left, right); + + /// + /// __m128d _mm_cmpngt_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(2) + /// + public static Vector128 CompareNotGreaterThanScalar(Vector128 left, Vector128 right) => CompareNotGreaterThanScalar(left, right); + + /// + /// __m128d _mm_cmpnge_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(1) + /// + public static Vector128 CompareNotGreaterThanOrEqual(Vector128 left, Vector128 right) => CompareNotGreaterThanOrEqual(left, right); + + /// + /// __m128d _mm_cmpnge_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(1) + /// + public static Vector128 CompareNotGreaterThanOrEqualScalar(Vector128 left, Vector128 right) => CompareNotGreaterThanOrEqualScalar(left, right); + + /// + /// __m128d _mm_cmpnlt_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(5) + /// + public static Vector128 CompareNotLessThan(Vector128 left, Vector128 right) => CompareNotLessThan(left, right); + + /// + /// __m128d _mm_cmpnlt_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(5) + /// + public static Vector128 CompareNotLessThanScalar(Vector128 left, Vector128 right) => CompareNotLessThanScalar(left, right); + + /// + /// __m128d _mm_cmpnle_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(6) + /// + public static Vector128 CompareNotLessThanOrEqual(Vector128 left, Vector128 right) => CompareNotLessThanOrEqual(left, right); + + /// + /// __m128d _mm_cmpnle_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(6) + /// + public static Vector128 CompareNotLessThanOrEqualScalar(Vector128 left, Vector128 right) => CompareNotLessThanOrEqualScalar(left, right); + + /// + /// __m128d _mm_cmpord_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(7) + /// + public static Vector128 CompareOrdered(Vector128 left, Vector128 right) => CompareOrdered(left, right); + + /// + /// __m128d _mm_cmpord_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(7) + /// + public static Vector128 CompareOrderedScalar(Vector128 left, Vector128 right) => CompareOrderedScalar(left, right); + + /// + /// __m128d _mm_cmpunord_pd (__m128d a, __m128d b) + /// CMPPD xmm, xmm/m128, imm8(3) + /// + public static Vector128 CompareUnordered(Vector128 left, Vector128 right) => CompareUnordered(left, right); + + /// + /// __m128d _mm_cmpunord_sd (__m128d a, __m128d b) + /// CMPSD xmm, xmm/m64, imm8(3) + /// + public static Vector128 CompareUnorderedScalar(Vector128 left, Vector128 right) => CompareUnorderedScalar(left, right); + + /// + /// __m128i _mm_cvtps_epi32 (__m128 a) + /// CVTPS2DQ xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Int32(Vector128 value) => ConvertToVector128Int32(value); + /// + /// __m128i _mm_cvtpd_epi32 (__m128d a) + /// CVTPD2DQ xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Int32(Vector128 value) => ConvertToVector128Int32(value); + /// + /// __m128 _mm_cvtepi32_ps (__m128i a) + /// CVTDQ2PS xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Single(Vector128 value) => ConvertToVector128Single(value); + /// + /// __m128 _mm_cvtpd_ps (__m128d a) + /// CVTPD2PS xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Single(Vector128 value) => ConvertToVector128Single(value); + /// + /// __m128d _mm_cvtepi32_pd (__m128i a) + /// CVTDQ2PD xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Double(Vector128 value) => ConvertToVector128Double(value); + /// + /// __m128d _mm_cvtps_pd (__m128 a) + /// CVTPS2PD xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Double(Vector128 value) => ConvertToVector128Double(value); + + /// + /// double _mm_cvtsd_f64(__m128d a) + /// HELPER: MOVSD + /// + public static double ConvertToDouble(Vector128 value) => ConvertToDouble(value); + /// + /// int _mm_cvtsd_si32 (__m128d a) + /// CVTSD2SI r32, xmm/m64 + /// + public static int ConvertToInt32(Vector128 value) => ConvertToInt32(value); + /// + /// int _mm_cvtsi128_si32 (__m128i a) + /// MOVD reg/m32, xmm + /// + public static int ConvertToInt32(Vector128 value) => ConvertToInt32(value); + /// + /// __int64 _mm_cvtsd_si64 (__m128d a) + /// CVTSD2SI r64, xmm/m64 + /// + public static long ConvertToInt64(Vector128 value) => ConvertToInt64(value); + /// + /// __int64 _mm_cvtsi128_si64 (__m128i a) + /// MOVQ reg/m64, xmm + /// + public static long ConvertToInt64(Vector128 value) => ConvertToInt64(value); + /// + /// int _mm_cvtsi128_si32 (__m128i a) + /// MOVD reg/m32, xmm + /// + public static uint ConvertToUInt32(Vector128 value) => ConvertToUInt32(value); + /// + /// __int64 _mm_cvtsi128_si64 (__m128i a) + /// MOVQ reg/m64, xmm + /// + public static ulong ConvertToUInt64(Vector128 value) => ConvertToUInt64(value); + + /// + /// __m128d _mm_cvtsi32_sd (__m128d a, int b) + /// CVTSI2SD xmm, reg/m64 + /// + public static Vector128 ConvertScalarToVector128Double(Vector128 upper, int value) => ConvertScalarToVector128Double(upper, value); + /// + /// __m128d _mm_cvtsi64_sd (__m128d a, int b) + /// CVTSI2SD xmm, reg/m64 + /// + public static Vector128 ConvertScalarToVector128Double(Vector128 upper, long value) => ConvertScalarToVector128Double(upper, value); + /// + /// __m128d _mm_cvtss_sd (__m128d a, __m128 b) + /// CVTSS2SD xmm, xmm/m32 + /// + public static Vector128 ConvertScalarToVector128Double(Vector128 upper, Vector128 value) => ConvertScalarToVector128Double(upper, value); + /// + /// __m128i _mm_cvtsi32_si128 (int a) + /// MOVD xmm, reg/m32 + /// + public static Vector128 ConvertScalarToVector128Int32(int value) => ConvertScalarToVector128Int32(value); + /// + /// __m128i _mm_cvtsi64_si128 (__int64 a) + /// MOVQ xmm, reg/m64 + /// + public static Vector128 ConvertScalarToVector128Int64(long value) => ConvertScalarToVector128Int64(value); + /// + /// __m128 _mm_cvtsd_ss (__m128 a, __m128d b) + /// CVTSD2SS xmm, xmm/m64 + /// + public static Vector128 ConvertScalarToVector128Single(Vector128 upper, Vector128 value) => ConvertScalarToVector128Single(upper, value); + /// + /// __m128i _mm_cvtsi32_si128 (int a) + /// MOVD xmm, reg/m32 + /// + public static Vector128 ConvertScalarToVector128UInt32(uint value) => ConvertScalarToVector128UInt32(value); + /// + /// __m128i _mm_cvtsi64_si128 (__int64 a) + /// MOVQ xmm, reg/m64 + /// + public static Vector128 ConvertScalarToVector128UInt64(ulong value) => ConvertScalarToVector128UInt64(value); + + /// + /// __m128i _mm_cvttps_epi32 (__m128 a) + /// CVTTPS2DQ xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Int32WithTruncation(Vector128 value) => ConvertToVector128Int32WithTruncation(value); + /// + /// __m128i _mm_cvttpd_epi32 (__m128d a) + /// CVTTPD2DQ xmm, xmm/m128 + /// + public static Vector128 ConvertToVector128Int32WithTruncation(Vector128 value) => ConvertToVector128Int32WithTruncation(value); + + /// + /// int _mm_cvttsd_si32 (__m128d a) + /// CVTTSD2SI reg, xmm/m64 + /// + public static int ConvertToInt32WithTruncation(Vector128 value) => ConvertToInt32WithTruncation(value); + /// + /// __int64 _mm_cvttsd_si64 (__m128d a) + /// CVTTSD2SI reg, xmm/m64 + /// + public static long ConvertToInt64WithTruncation(Vector128 value) => ConvertToInt64WithTruncation(value); + + /// + /// __m128d _mm_div_pd (__m128d a, __m128d b) + /// DIVPD xmm, xmm/m128 + /// + public static Vector128 Divide(Vector128 left, Vector128 right) => Divide(left, right); + + /// + /// __m128d _mm_div_sd (__m128d a, __m128d b) + /// DIVSD xmm, xmm/m64 + /// + public static Vector128 DivideScalar(Vector128 left, Vector128 right) => DivideScalar(left, right); + + /// + /// int _mm_extract_epi16 (__m128i a, int immediate) + /// PEXTRW reg, xmm, imm8 + /// + public static ushort Extract(Vector128 value, byte index) => Extract(value, index); + + /// + /// __m128i _mm_insert_epi16 (__m128i a, int i, int immediate) + /// PINSRW xmm, reg/m16, imm8 + /// + public static Vector128 Insert(Vector128 value, short data, byte index) => Insert(value, data, index); + /// + /// __m128i _mm_insert_epi16 (__m128i a, int i, int immediate) + /// PINSRW xmm, reg/m16, imm8 + /// + public static Vector128 Insert(Vector128 value, ushort data, byte index) => Insert(value, data, index); + + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(sbyte* address) => LoadVector128(address); + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(byte* address) => LoadVector128(address); + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(short* address) => LoadVector128(address); + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(ushort* address) => LoadVector128(address); + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(int* address) => LoadVector128(address); + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(uint* address) => LoadVector128(address); + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(long* address) => LoadVector128(address); + /// + /// __m128i _mm_loadu_si128 (__m128i const* mem_address) + /// MOVDQU xmm, m128 + /// + public static unsafe Vector128 LoadVector128(ulong* address) => LoadVector128(address); + /// + /// __m128d _mm_loadu_pd (double const* mem_address) + /// MOVUPD xmm, m128 + /// + public static unsafe Vector128 LoadVector128(double* address) => LoadVector128(address); + + /// + /// __m128d _mm_load_sd (double const* mem_address) + /// MOVSD xmm, m64 + /// + public static unsafe Vector128 LoadScalarVector128(double* address) => LoadScalarVector128(address); + + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(sbyte* address) => LoadAlignedVector128(address); + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(byte* address) => LoadAlignedVector128(address); + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(short* address) => LoadAlignedVector128(address); + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(ushort* address) => LoadAlignedVector128(address); + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(int* address) => LoadAlignedVector128(address); + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(uint* address) => LoadAlignedVector128(address); + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(long* address) => LoadAlignedVector128(address); + /// + /// __m128i _mm_load_si128 (__m128i const* mem_address) + /// MOVDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(ulong* address) => LoadAlignedVector128(address); + /// + /// __m128d _mm_load_pd (double const* mem_address) + /// MOVAPD xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128(double* address) => LoadAlignedVector128(address); + + /// + /// void _mm_lfence(void) + /// LFENCE + /// + public static void LoadFence() => LoadFence(); + + /// + /// __m128d _mm_loadh_pd (__m128d a, double const* mem_addr) + /// MOVHPD xmm, m64 + /// + public static unsafe Vector128 LoadHigh(Vector128 lower, double* address) => LoadHigh(lower, address); + + /// + /// __m128d _mm_loadl_pd (__m128d a, double const* mem_addr) + /// MOVLPD xmm, m64 + /// + public static unsafe Vector128 LoadLow(Vector128 upper, double* address) => LoadLow(upper, address); + + /// + /// __m128i _mm_loadl_epi32 (__m128i const* mem_addr) + /// MOVD xmm, reg/m32 + /// The above native signature does not exist. We provide this additional overload for completeness. + /// + public static unsafe Vector128 LoadScalarVector128(int* address) => LoadScalarVector128(address); + /// + /// __m128i _mm_loadl_epi32 (__m128i const* mem_addr) + /// MOVD xmm, reg/m32 + /// The above native signature does not exist. We provide this additional overload for completeness. + /// + public static unsafe Vector128 LoadScalarVector128(uint* address) => LoadScalarVector128(address); + /// + /// __m128i _mm_loadl_epi64 (__m128i const* mem_addr) + /// MOVQ xmm, reg/m64 + /// + public static unsafe Vector128 LoadScalarVector128(long* address) => LoadScalarVector128(address); + /// + /// __m128i _mm_loadl_epi64 (__m128i const* mem_addr) + /// MOVQ xmm, reg/m64 + /// + public static unsafe Vector128 LoadScalarVector128(ulong* address) => LoadScalarVector128(address); + + /// + /// void _mm_maskmoveu_si128 (__m128i a, __m128i mask, char* mem_address) + /// MASKMOVDQU xmm, xmm + /// + public static unsafe void MaskMove(Vector128 source, Vector128 mask, sbyte* address) => MaskMove(source, mask, address); + /// + /// void _mm_maskmoveu_si128 (__m128i a, __m128i mask, char* mem_address) + /// MASKMOVDQU xmm, xmm + /// + public static unsafe void MaskMove(Vector128 source, Vector128 mask, byte* address) => MaskMove(source, mask, address); + + /// + /// __m128i _mm_max_epu8 (__m128i a, __m128i b) + /// PMAXUB xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + /// + /// __m128i _mm_max_epi16 (__m128i a, __m128i b) + /// PMAXSW xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + /// + /// __m128d _mm_max_pd (__m128d a, __m128d b) + /// MAXPD xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + + /// + /// __m128d _mm_max_sd (__m128d a, __m128d b) + /// MAXSD xmm, xmm/m64 + /// + public static Vector128 MaxScalar(Vector128 left, Vector128 right) => MaxScalar(left, right); + + /// + /// void _mm_mfence(void) + /// MFENCE + /// + public static void MemoryFence() => MemoryFence(); + + /// + /// __m128i _mm_min_epu8 (__m128i a, __m128i b) + /// PMINUB xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + /// + /// __m128i _mm_min_epi16 (__m128i a, __m128i b) + /// PMINSW xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + /// + /// __m128d _mm_min_pd (__m128d a, __m128d b) + /// MINPD xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + + /// + /// __m128d _mm_min_sd (__m128d a, __m128d b) + /// MINSD xmm, xmm/m64 + /// + public static Vector128 MinScalar(Vector128 left, Vector128 right) => MinScalar(left, right); + + /// + /// __m128d _mm_move_sd (__m128d a, __m128d b) + /// MOVSD xmm, xmm + /// + public static Vector128 MoveScalar(Vector128 upper, Vector128 value) => MoveScalar(upper, value); + + /// + /// int _mm_movemask_epi8 (__m128i a) + /// PMOVMSKB reg, xmm + /// + public static int MoveMask(Vector128 value) => MoveMask(value); + /// + /// int _mm_movemask_epi8 (__m128i a) + /// PMOVMSKB reg, xmm + /// + public static int MoveMask(Vector128 value) => MoveMask(value); + /// + /// int _mm_movemask_pd (__m128d a) + /// MOVMSKPD reg, xmm + /// + public static int MoveMask(Vector128 value) => MoveMask(value); + + /// + /// __m128i _mm_move_epi64 (__m128i a) + /// MOVQ xmm, xmm + /// + public static Vector128 MoveScalar(Vector128 value) => MoveScalar(value); + /// + /// __m128i _mm_move_epi64 (__m128i a) + /// MOVQ xmm, xmm + /// + public static Vector128 MoveScalar(Vector128 value) => MoveScalar(value); + + /// + /// __m128i _mm_mul_epu32 (__m128i a, __m128i b) + /// PMULUDQ xmm, xmm/m128 + /// + public static Vector128 Multiply(Vector128 left, Vector128 right) => Multiply(left, right); + /// + /// __m128d _mm_mul_pd (__m128d a, __m128d b) + /// MULPD xmm, xmm/m128 + /// + public static Vector128 Multiply(Vector128 left, Vector128 right) => Multiply(left, right); + + /// + /// __m128d _mm_mul_sd (__m128d a, __m128d b) + /// MULSD xmm, xmm/m64 + /// + public static Vector128 MultiplyScalar(Vector128 left, Vector128 right) => MultiplyScalar(left, right); + + /// + /// __m128i _mm_mulhi_epi16 (__m128i a, __m128i b) + /// PMULHW xmm, xmm/m128 + /// + public static Vector128 MultiplyHigh(Vector128 left, Vector128 right) => MultiplyHigh(left, right); + /// + /// __m128i _mm_mulhi_epu16 (__m128i a, __m128i b) + /// PMULHUW xmm, xmm/m128 + /// + public static Vector128 MultiplyHigh(Vector128 left, Vector128 right) => MultiplyHigh(left, right); + + /// + /// __m128i _mm_madd_epi16 (__m128i a, __m128i b) + /// PMADDWD xmm, xmm/m128 + /// + public static Vector128 MultiplyAddAdjacent(Vector128 left, Vector128 right) => MultiplyAddAdjacent(left, right); + + /// + /// __m128i _mm_mullo_epi16 (__m128i a, __m128i b) + /// PMULLW xmm, xmm/m128 + /// + public static Vector128 MultiplyLow(Vector128 left, Vector128 right) => MultiplyLow(left, right); + + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) => Or(left, right); + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) => Or(left, right); + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) => Or(left, right); + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) => Or(left, right); + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) => Or(left, right); + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) => Or(left, right); + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) => Or(left, right); + /// + /// __m128i _mm_or_si128 (__m128i a, __m128i b) + /// POR xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) => Or(left, right); + /// + /// __m128d _mm_or_pd (__m128d a, __m128d b) + /// ORPD xmm, xmm/m128 + /// + public static Vector128 Or(Vector128 left, Vector128 right) => Or(left, right); + + /// + /// __m128i _mm_packs_epi16 (__m128i a, __m128i b) + /// PACKSSWB xmm, xmm/m128 + /// + public static Vector128 PackSignedSaturate(Vector128 left, Vector128 right) => PackSignedSaturate(left, right); + /// + /// __m128i _mm_packs_epi32 (__m128i a, __m128i b) + /// PACKSSDW xmm, xmm/m128 + /// + public static Vector128 PackSignedSaturate(Vector128 left, Vector128 right) => PackSignedSaturate(left, right); + + /// + /// __m128i _mm_packus_epi16 (__m128i a, __m128i b) + /// PACKUSWB xmm, xmm/m128 + /// + public static Vector128 PackUnsignedSaturate(Vector128 left, Vector128 right) => PackUnsignedSaturate(left, right); + + /// + /// __m128i _mm_set1_epi8 (char a) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetAllVector128(byte value) + { + // Zero vector and load value et index 0 + Vector128 vector1 = Sse.StaticCast(ConvertScalarToVector128UInt32(value)); + // Create { -- -- -- -- -- -- -- -- -- -- -- -- -- -- vl vl } + Vector128 tmpVector1 = Sse.StaticCast(UnpackLow(vector1, vector1)); + // Create { -- -- -- -- -- -- -- -- -- -- -- -- vl vl vl vl } + Vector128 tmpVector2 = Sse.StaticCast(UnpackLow(tmpVector1, tmpVector1)); + // Create { vl vl vl vl vl vl vl vl vl vl vl vl vl vl vl vl } and return result + return Sse.StaticCast(Shuffle(tmpVector2, 0)); + } + /// + /// __m128i _mm_set1_epi8 (char a) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetAllVector128(sbyte value) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load value et index 0 + Vector128 vector = Sse.StaticCast(ConvertScalarToVector128Int32(value)); + // Create { -- -- -- -- -- -- -- -- -- -- -- -- -- -- vl vl } + Vector128 tmpVector1 = Sse.StaticCast(UnpackLow(vector, vector)); + // Create { -- -- -- -- -- -- -- -- -- -- -- -- vl vl vl vl } + Vector128 tmpVector2 = Sse.StaticCast(UnpackLow(tmpVector1, tmpVector1)); + // Create { vl vl vl vl vl vl vl vl vl vl vl vl vl vl vl vl } and return result + return Sse.StaticCast(Shuffle(tmpVector2, 0)); + } + /// + /// __m128i _mm_set1_epi16 (short a) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetAllVector128(short value) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load value et index 0 + Vector128 vector = Sse.StaticCast(ConvertScalarToVector128Int32(value)); + // Create { -- -- -- -- -- -- vl vl } + Vector128 tmpVector = Sse.StaticCast(UnpackLow(vector, vector)); + // Create { vl vl vl vl vl vl vl vl } and return result + return Sse.StaticCast(Shuffle(tmpVector, (byte)0)); + } + /// + /// __m128i _mm_set1_epi16 (short a) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetAllVector128(ushort value) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load value et index 0 + Vector128 vector = Sse.StaticCast(ConvertScalarToVector128UInt32(value)); + // Create { -- -- -- -- -- -- vl vl } + Vector128 tmpVector = Sse.StaticCast(UnpackLow(vector, vector)); + // Create { vl vl vl vl vl vl vl vl } and return result + return Sse.StaticCast(Shuffle(tmpVector, (byte)0)); + } + /// + /// __m128i _mm_set1_epi32 (int a) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetAllVector128(int value) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load value et index 0 + Vector128 vector = ConvertScalarToVector128Int32(value); + // Create { vl vl vl vl } and return result + return Shuffle(vector, 0); + } + /// + /// __m128i _mm_set1_epi32 (int a) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetAllVector128(uint value) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load value et index 0 + Vector128 vector = ConvertScalarToVector128UInt32(value); + // Create { vl vl vl vl } and return result + return Shuffle(vector, 0); + } + /// + /// __m128i _mm_set1_epi64x (long long a) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetAllVector128(long value) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load value et index 0 + Vector128 vector = ConvertScalarToVector128Int64(value); + // Create { vl vl } and return result + return UnpackLow(vector, vector); + } + /// + /// __m128i _mm_set1_epi64x (long long a) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetAllVector128(ulong value) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load value et index 0 + Vector128 vector = ConvertScalarToVector128UInt64(value); + // Create { vl vl } and return result + return UnpackLow(vector, vector); + } + /// + /// __m128d _mm_set1_pd (double a) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetAllVector128(double value) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load value et index 0 + Vector128 vector = SetScalarVector128(value); + // Create { vl vl } and return result + return UnpackLow(vector, vector); + } + + /// + /// __m128d _mm_set_sd (double a) + /// HELPER + /// + public static Vector128 SetScalarVector128(double value) => SetScalarVector128(value); + + /// + /// ___m128i _mm_set_epi8 (char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector128 SetVector128(sbyte e15, sbyte e14, sbyte e13, sbyte e12, sbyte e11, sbyte e10, sbyte e9, sbyte e8, sbyte e7, sbyte e6, sbyte e5, sbyte e4, sbyte e3, sbyte e2, sbyte e1, sbyte e0) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + sbyte* buffer = stackalloc sbyte[16]; + buffer[0] = e0; + buffer[1] = e1; + buffer[2] = e2; + buffer[3] = e3; + buffer[4] = e4; + buffer[5] = e5; + buffer[6] = e6; + buffer[7] = e7; + buffer[8] = e8; + buffer[9] = e9; + buffer[10] = e10; + buffer[11] = e11; + buffer[12] = e12; + buffer[13] = e13; + buffer[14] = e14; + buffer[15] = e15; + + // Load 16-byte buffer into Vector + return LoadVector128(buffer); + } + /// + /// ___m128i _mm_set_epi8 (char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector128 SetVector128(byte e15, byte e14, byte e13, byte e12, byte e11, byte e10, byte e9, byte e8, byte e7, byte e6, byte e5, byte e4, byte e3, byte e2, byte e1, byte e0) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + byte* buffer = stackalloc byte[16]; + buffer[0] = e0; + buffer[1] = e1; + buffer[2] = e2; + buffer[3] = e3; + buffer[4] = e4; + buffer[5] = e5; + buffer[6] = e6; + buffer[7] = e7; + buffer[8] = e8; + buffer[9] = e9; + buffer[10] = e10; + buffer[11] = e11; + buffer[12] = e12; + buffer[13] = e13; + buffer[14] = e14; + buffer[15] = e15; + + // Load 16-byte buffer into Vector + return LoadVector128(buffer); + } + /// + /// __m128i _mm_set_epi16 (short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetVector128(short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load e0 et index 0 + Vector128 e0Vector = ConvertScalarToVector128Int32(e0); + Vector128 vector = Sse.StaticCast(e0Vector); + // Insert e1 ... e7 at corresponding index + vector = Insert(vector, e1, (byte)1); + vector = Insert(vector, e2, (byte)2); + vector = Insert(vector, e3, (byte)3); + vector = Insert(vector, e4, (byte)4); + vector = Insert(vector, e5, (byte)5); + vector = Insert(vector, e6, (byte)6); + return Insert(vector, e7, (byte)7); + } + /// + /// __m128i _mm_set_epi16 (short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetVector128(ushort e7, ushort e6, ushort e5, ushort e4, ushort e3, ushort e2, ushort e1, ushort e0) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load e0 et index 0 + Vector128 e0vector = ConvertScalarToVector128UInt32(e0); + Vector128 vector = Sse.StaticCast(e0vector); + // Insert e1 ... e7 at corresponding index + vector = Insert(vector, e1, (byte)1); + vector = Insert(vector, e2, (byte)2); + vector = Insert(vector, e3, (byte)3); + vector = Insert(vector, e4, (byte)4); + vector = Insert(vector, e5, (byte)5); + vector = Insert(vector, e6, (byte)6); + return Insert(vector, e7, (byte)7); + } + /// + /// __m128i _mm_set_epi32 (int e3, int e2, int e1, int e0) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetVector128(int e3, int e2, int e1, int e0) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load e2 et index 0 + Vector128 e2Vector = ConvertScalarToVector128Int32(e2); + Vector128 e1Vector = ConvertScalarToVector128Int32(e1); + Vector128 e0Vector = ConvertScalarToVector128Int32(e0); + // Create { -- -- e2 e0 } + e0Vector = UnpackLow(e0Vector, e2Vector); + e2Vector = ConvertScalarToVector128Int32(e3); + // Create { -- -- e3 e1 } + e1Vector = UnpackLow(e1Vector, e2Vector); + // Create { e3 e2 e1 e0 } and return result + return UnpackLow(e0Vector, e1Vector); + } + /// + /// __m128i _mm_set_epi32 (int e3, int e2, int e1, int e0) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetVector128(uint e3, uint e2, uint e1, uint e0) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load e2 et index 0 + Vector128 e2Vector = ConvertScalarToVector128UInt32(e2); + Vector128 e1Vector = ConvertScalarToVector128UInt32(e1); + Vector128 e0Vector = ConvertScalarToVector128UInt32(e0); + // Create { -- -- e2 e0 } + e0Vector = UnpackLow(e0Vector, e2Vector); + e2Vector = ConvertScalarToVector128UInt32(e3); + // Create { -- -- e3 e1 } + e1Vector = UnpackLow(e1Vector, e2Vector); + // Create { e3 e2 e1 e0 } and return result + return UnpackLow(e0Vector, e1Vector); + } + /// + /// __m128i _mm_set_epi64x (__int64 e1, __int64 e0) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetVector128(long e1, long e0) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load e1 et index 0 + Vector128 e1Vector = ConvertScalarToVector128Int64(e1); + Vector128 e0vector = ConvertScalarToVector128Int64(e0); + // Create { e1 e0 } and return result + return UnpackLow(e0vector, e1Vector); + } + /// + /// __m128i _mm_set_epi64x (__int64 e1, __int64 e0) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 SetVector128(ulong e1, ulong e0) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load e1 et index 0 + Vector128 e1vector = ConvertScalarToVector128UInt64(e1); + Vector128 e0Vector = ConvertScalarToVector128UInt64(e0); + // Create { e1 e0 } and return result + return UnpackLow(e0Vector, e1vector); + } + /// + /// __m128d _mm_set_pd (double e1, double e0) + /// HELPER + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector128 SetVector128(double e1, double e0) + { + // TODO-CQ Optimize algorithm choice based on benchmarks + + // Zero vector and load e1 et index 0 + Vector128 e1Vector = SetScalarVector128(e1); + Vector128 e0Vector = SetScalarVector128(e0); + // Create { e1 e0 } and return result + return UnpackLow(e0Vector, e1Vector); + } + + /// + /// __m128i _mm_setzero_si128 () + /// HELPER: PXOR + /// __m128d _mm_setzero_pd (void) + /// HELPER: XORPD + /// + public static Vector128 SetZeroVector128() where T : struct + { + return SetZeroVector128(); + } + + /// + /// __m128i _mm_sad_epu8 (__m128i a, __m128i b) + /// PSADBW xmm, xmm/m128 + /// + public static Vector128 SumAbsoluteDifferences(Vector128 left, Vector128 right) => SumAbsoluteDifferences(left, right); + + /// + /// __m128i _mm_shuffle_epi32 (__m128i a, int immediate) + /// PSHUFD xmm, xmm/m128, imm8 + /// + public static Vector128 Shuffle(Vector128 value, byte control) => Shuffle(value, control); + /// + /// __m128i _mm_shuffle_epi32 (__m128i a, int immediate) + /// PSHUFD xmm, xmm/m128, imm8 + /// + public static Vector128 Shuffle(Vector128 value, byte control) => Shuffle(value, control); + /// + /// __m128d _mm_shuffle_pd (__m128d a, __m128d b, int immediate) + /// SHUFPD xmm, xmm/m128, imm8 + /// + public static Vector128 Shuffle(Vector128 left, Vector128 right, byte control) => Shuffle(left, right, control); + + /// + /// __m128i _mm_shufflehi_epi16 (__m128i a, int immediate) + /// PSHUFHW xmm, xmm/m128, imm8 + /// + public static Vector128 ShuffleHigh(Vector128 value, byte control) => ShuffleHigh(value, control); + /// + /// __m128i _mm_shufflehi_epi16 (__m128i a, int control) + /// PSHUFHW xmm, xmm/m128, imm8 + /// + public static Vector128 ShuffleHigh(Vector128 value, byte control) => ShuffleHigh(value, control); + + /// + /// __m128i _mm_shufflelo_epi16 (__m128i a, int control) + /// PSHUFLW xmm, xmm/m128, imm8 + /// + public static Vector128 ShuffleLow(Vector128 value, byte control) => ShuffleLow(value, control); + /// + /// __m128i _mm_shufflelo_epi16 (__m128i a, int control) + /// PSHUFLW xmm, xmm/m128, imm8 + /// + public static Vector128 ShuffleLow(Vector128 value, byte control) => ShuffleLow(value, control); + + /// + /// __m128i _mm_sll_epi16 (__m128i a, __m128i count) + /// PSLLW xmm, xmm/m128 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) => ShiftLeftLogical(value, count); + /// + /// __m128i _mm_sll_epi16 (__m128i a, __m128i count) + /// PSLLW xmm, xmm/m128 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) => ShiftLeftLogical(value, count); + /// + /// __m128i _mm_sll_epi32 (__m128i a, __m128i count) + /// PSLLD xmm, xmm/m128 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) => ShiftLeftLogical(value, count); + /// + /// __m128i _mm_sll_epi32 (__m128i a, __m128i count) + /// PSLLD xmm, xmm/m128 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) => ShiftLeftLogical(value, count); + /// + /// __m128i _mm_sll_epi64 (__m128i a, __m128i count) + /// PSLLQ xmm, xmm/m128 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) => ShiftLeftLogical(value, count); + /// + /// __m128i _mm_sll_epi64 (__m128i a, __m128i count) + /// PSLLQ xmm, xmm/m128 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) => ShiftLeftLogical(value, count); + + /// + /// __m128i _mm_slli_epi16 (__m128i a, int immediate) + /// PSLLW xmm, imm8 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, byte count) => ShiftLeftLogical(value, count); + /// + /// __m128i _mm_slli_epi16 (__m128i a, int immediate) + /// PSLLW xmm, imm8 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, byte count) => ShiftLeftLogical(value, count); + /// + /// __m128i _mm_slli_epi32 (__m128i a, int immediate) + /// PSLLD xmm, imm8 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, byte count) => ShiftLeftLogical(value, count); + /// + /// __m128i _mm_slli_epi32 (__m128i a, int immediate) + /// PSLLD xmm, imm8 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, byte count) => ShiftLeftLogical(value, count); + /// + /// __m128i _mm_slli_epi64 (__m128i a, int immediate) + /// PSLLQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, byte count) => ShiftLeftLogical(value, count); + /// + /// __m128i _mm_slli_epi64 (__m128i a, int immediate) + /// PSLLQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical(Vector128 value, byte count) => ShiftLeftLogical(value, count); + + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); + /// + /// __m128i _mm_bslli_si128 (__m128i a, int imm8) + /// PSLLDQ xmm, imm8 + /// + public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); + + /// + /// __m128i _mm_sra_epi16 (__m128i a, __m128i count) + /// PSRAW xmm, xmm/m128 + /// + public static Vector128 ShiftRightArithmetic(Vector128 value, Vector128 count) => ShiftRightArithmetic(value, count); + /// + /// __m128i _mm_sra_epi32 (__m128i a, __m128i count) + /// PSRAD xmm, xmm/m128 + /// + public static Vector128 ShiftRightArithmetic(Vector128 value, Vector128 count) => ShiftRightArithmetic(value, count); + + /// + /// __m128i _mm_srai_epi16 (__m128i a, int immediate) + /// PSRAW xmm, imm8 + /// + public static Vector128 ShiftRightArithmetic(Vector128 value, byte count) => ShiftRightArithmetic(value, count); + /// + /// __m128i _mm_srai_epi32 (__m128i a, int immediate) + /// PSRAD xmm, imm8 + /// + public static Vector128 ShiftRightArithmetic(Vector128 value, byte count) => ShiftRightArithmetic(value, count); + + /// + /// __m128i _mm_srl_epi16 (__m128i a, __m128i count) + /// PSRLW xmm, xmm/m128 + /// + public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) => ShiftRightLogical(value, count); + /// + /// __m128i _mm_srl_epi16 (__m128i a, __m128i count) + /// PSRLW xmm, xmm/m128 + /// + public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) => ShiftRightLogical(value, count); + /// + /// __m128i _mm_srl_epi32 (__m128i a, __m128i count) + /// PSRLD xmm, xmm/m128 + /// + public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) => ShiftRightLogical(value, count); + /// + /// __m128i _mm_srl_epi32 (__m128i a, __m128i count) + /// PSRLD xmm, xmm/m128 + /// + public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) => ShiftRightLogical(value, count); + /// + /// __m128i _mm_srl_epi64 (__m128i a, __m128i count) + /// PSRLQ xmm, xmm/m128 + /// + public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) => ShiftRightLogical(value, count); + /// + /// __m128i _mm_srl_epi64 (__m128i a, __m128i count) + /// PSRLQ xmm, xmm/m128 + /// + public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) => ShiftRightLogical(value, count); + + /// + /// __m128i _mm_srli_epi16 (__m128i a, int immediate) + /// PSRLW xmm, imm8 + /// + public static Vector128 ShiftRightLogical(Vector128 value, byte count) => ShiftRightLogical(value, count); + /// + /// __m128i _mm_srli_epi16 (__m128i a, int immediate) + /// PSRLW xmm, imm8 + /// + public static Vector128 ShiftRightLogical(Vector128 value, byte count) => ShiftRightLogical(value, count); + /// + /// __m128i _mm_srli_epi32 (__m128i a, int immediate) + /// PSRLD xmm, imm8 + /// + public static Vector128 ShiftRightLogical(Vector128 value, byte count) => ShiftRightLogical(value, count); + /// + /// __m128i _mm_srli_epi32 (__m128i a, int immediate) + /// PSRLD xmm, imm8 + /// + public static Vector128 ShiftRightLogical(Vector128 value, byte count) => ShiftRightLogical(value, count); + /// + /// __m128i _mm_srli_epi64 (__m128i a, int immediate) + /// PSRLQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical(Vector128 value, byte count) => ShiftRightLogical(value, count); + /// + /// __m128i _mm_srli_epi64 (__m128i a, int immediate) + /// PSRLQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical(Vector128 value, byte count) => ShiftRightLogical(value, count); + + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); + /// + /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) + /// PSRLDQ xmm, imm8 + /// + public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); + + /// + /// __m128d _mm_sqrt_pd (__m128d a) + /// SQRTPD xmm, xmm/m128 + /// + public static Vector128 Sqrt(Vector128 value) => Sqrt(value); + + /// + /// __m128d _mm_sqrt_sd (__m128d a) + /// SQRTSD xmm, xmm/64 + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 SqrtScalar(Vector128 value) => SqrtScalar(value); + + /// + /// __m128d _mm_sqrt_sd (__m128d a, __m128d b) + /// SQRTSD xmm, xmm/64 + /// + public static Vector128 SqrtScalar(Vector128 upper, Vector128 value) => SqrtScalar(upper, value); + + /// + /// void _mm_store_sd (double* mem_addr, __m128d a) + /// MOVSD m64, xmm + /// + public static unsafe void StoreScalar(double* address, Vector128 source) => StoreScalar(address, source); + + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(sbyte* address, Vector128 source) => StoreAligned(address, source); + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(byte* address, Vector128 source) => StoreAligned(address, source); + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(short* address, Vector128 source) => StoreAligned(address, source); + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(ushort* address, Vector128 source) => StoreAligned(address, source); + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(int* address, Vector128 source) => StoreAligned(address, source); + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(uint* address, Vector128 source) => StoreAligned(address, source); + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(long* address, Vector128 source) => StoreAligned(address, source); + /// + /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQA m128, xmm + /// + public static unsafe void StoreAligned(ulong* address, Vector128 source) => StoreAligned(address, source); + /// + /// void _mm_store_pd (double* mem_addr, __m128d a) + /// MOVAPD m128, xmm + /// + public static unsafe void StoreAligned(double* address, Vector128 source) => StoreAligned(address, source); + + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(sbyte* address, Vector128 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(byte* address, Vector128 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(short* address, Vector128 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(ushort* address, Vector128 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(int* address, Vector128 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(uint* address, Vector128 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(long* address, Vector128 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) + /// MOVNTDQ m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(ulong* address, Vector128 source) => StoreAlignedNonTemporal(address, source); + /// + /// void _mm_stream_pd (double* mem_addr, __m128d a) + /// MOVNTPD m128, xmm + /// + public static unsafe void StoreAlignedNonTemporal(double* address, Vector128 source) => StoreAlignedNonTemporal(address, source); + + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(sbyte* address, Vector128 source) => Store(address, source); + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(byte* address, Vector128 source) => Store(address, source); + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(short* address, Vector128 source) => Store(address, source); + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(ushort* address, Vector128 source) => Store(address, source); + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(int* address, Vector128 source) => Store(address, source); + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(uint* address, Vector128 source) => Store(address, source); + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(long* address, Vector128 source) => Store(address, source); + /// + /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) + /// MOVDQU m128, xmm + /// + public static unsafe void Store(ulong* address, Vector128 source) => Store(address, source); + /// + /// void _mm_storeu_pd (double* mem_addr, __m128d a) + /// MOVUPD m128, xmm + /// + public static unsafe void Store(double* address, Vector128 source) => Store(address, source); + + /// + /// void _mm_storeh_pd (double* mem_addr, __m128d a) + /// MOVHPD m64, xmm + /// + public static unsafe void StoreHigh(double* address, Vector128 source) => StoreHigh(address, source); + + /// + /// void _mm_storel_epi64 (__m128i* mem_addr, __m128i a) + /// MOVQ m64, xmm + /// + public static unsafe void StoreLow(long* address, Vector128 source) => StoreLow(address, source); + /// + /// void _mm_storel_epi64 (__m128i* mem_addr, __m128i a) + /// MOVQ m64, xmm + /// + public static unsafe void StoreLow(ulong* address, Vector128 source) => StoreLow(address, source); + /// + /// void _mm_storel_pd (double* mem_addr, __m128d a) + /// MOVLPD m64, xmm + /// + public static unsafe void StoreLow(double* address, Vector128 source) => StoreLow(address, source); + + /// + /// void _mm_stream_si32(int *p, int a) + /// MOVNTI m32, r32 + /// + public static unsafe void StoreNonTemporal(int* address, int value) => StoreNonTemporal(address, value); + /// + /// void _mm_stream_si32(int *p, int a) + /// MOVNTI m32, r32 + /// + public static unsafe void StoreNonTemporal(uint* address, uint value) => StoreNonTemporal(address, value); + + /// + /// void _mm_stream_si64(__int64 *p, __int64 a) + /// MOVNTI m64, r64 + /// + public static unsafe void StoreNonTemporal(long* address, long value) => StoreNonTemporal(address, value); + /// + /// void _mm_stream_si64(__int64 *p, __int64 a) + /// MOVNTI m64, r64 + /// + public static unsafe void StoreNonTemporal(ulong* address, ulong value) => StoreNonTemporal(address, value); + + /// + /// __m128i _mm_sub_epi8 (__m128i a, __m128i b) + /// PSUBB xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) => Subtract(left, right); + /// + /// __m128i _mm_sub_epi8 (__m128i a, __m128i b) + /// PSUBB xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) => Subtract(left, right); + /// + /// __m128i _mm_sub_epi16 (__m128i a, __m128i b) + /// PSUBW xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) => Subtract(left, right); + /// + /// __m128i _mm_sub_epi16 (__m128i a, __m128i b) + /// PSUBW xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) => Subtract(left, right); + /// + /// __m128i _mm_sub_epi32 (__m128i a, __m128i b) + /// PSUBD xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) => Subtract(left, right); + /// + /// __m128i _mm_sub_epi32 (__m128i a, __m128i b) + /// PSUBD xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) => Subtract(left, right); + /// + /// __m128i _mm_sub_epi64 (__m128i a, __m128i b) + /// PSUBQ xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) => Subtract(left, right); + /// + /// __m128i _mm_sub_epi64 (__m128i a, __m128i b) + /// PSUBQ xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) => Subtract(left, right); + /// + /// __m128d _mm_sub_pd (__m128d a, __m128d b) + /// SUBPD xmm, xmm/m128 + /// + public static Vector128 Subtract(Vector128 left, Vector128 right) => Subtract(left, right); + + /// + /// __m128d _mm_sub_sd (__m128d a, __m128d b) + /// SUBSD xmm, xmm/m64 + /// + public static Vector128 SubtractScalar(Vector128 left, Vector128 right) => SubtractScalar(left, right); + + /// + /// __m128i _mm_subs_epi8 (__m128i a, __m128i b) + /// PSUBSB xmm, xmm/m128 + /// + public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) => SubtractSaturate(left, right); + /// + /// __m128i _mm_subs_epi16 (__m128i a, __m128i b) + /// PSUBSW xmm, xmm/m128 + /// + public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) => SubtractSaturate(left, right); + /// + /// __m128i _mm_subs_epu8 (__m128i a, __m128i b) + /// PSUBUSB xmm, xmm/m128 + /// + public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) => SubtractSaturate(left, right); + /// + /// __m128i _mm_subs_epu16 (__m128i a, __m128i b) + /// PSUBUSW xmm, xmm/m128 + /// + public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) => SubtractSaturate(left, right); + + /// + /// __m128i _mm_unpackhi_epi8 (__m128i a, __m128i b) + /// PUNPCKHBW xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) => UnpackHigh(left, right); + /// + /// __m128i _mm_unpackhi_epi8 (__m128i a, __m128i b) + /// PUNPCKHBW xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) => UnpackHigh(left, right); + /// + /// __m128i _mm_unpackhi_epi16 (__m128i a, __m128i b) + /// PUNPCKHWD xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) => UnpackHigh(left, right); + /// + /// __m128i _mm_unpackhi_epi16 (__m128i a, __m128i b) + /// PUNPCKHWD xmm, xmm/m128 + /// UnpackHigh(Vector128 left, Vector128 right) => UnpackHigh(left, right); + /// + /// __m128i _mm_unpackhi_epi32 (__m128i a, __m128i b) + /// PUNPCKHDQ xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) => UnpackHigh(left, right); + /// + /// __m128i _mm_unpackhi_epi32 (__m128i a, __m128i b) + /// PUNPCKHDQ xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) => UnpackHigh(left, right); + /// + /// __m128i _mm_unpackhi_epi64 (__m128i a, __m128i b) + /// PUNPCKHQDQ xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) => UnpackHigh(left, right); + /// + /// __m128i _mm_unpackhi_epi64 (__m128i a, __m128i b) + /// PUNPCKHQDQ xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) => UnpackHigh(left, right); + /// + /// __m128d _mm_unpackhi_pd (__m128d a, __m128d b) + /// UNPCKHPD xmm, xmm/m128 + /// + public static Vector128 UnpackHigh(Vector128 left, Vector128 right) => UnpackHigh(left, right); + + /// + /// __m128i _mm_unpacklo_epi8 (__m128i a, __m128i b) + /// PUNPCKLBW xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) => UnpackLow(left, right); + /// + /// __m128i _mm_unpacklo_epi8 (__m128i a, __m128i b) + /// PUNPCKLBW xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) => UnpackLow(left, right); + /// + /// __m128i _mm_unpacklo_epi16 (__m128i a, __m128i b) + /// PUNPCKLWD xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) => UnpackLow(left, right); + /// + /// __m128i _mm_unpacklo_epi16 (__m128i a, __m128i b) + /// PUNPCKLWD xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) => UnpackLow(left, right); + /// + /// __m128i _mm_unpacklo_epi32 (__m128i a, __m128i b) + /// PUNPCKLDQ xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) => UnpackLow(left, right); + /// + /// __m128i _mm_unpacklo_epi32 (__m128i a, __m128i b) + /// PUNPCKLDQ xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) => UnpackLow(left, right); + /// + /// __m128i _mm_unpacklo_epi64 (__m128i a, __m128i b) + /// PUNPCKLQDQ xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) => UnpackLow(left, right); + /// + /// __m128i _mm_unpacklo_epi64 (__m128i a, __m128i b) + /// PUNPCKLQDQ xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) => UnpackLow(left, right); + /// + /// __m128d _mm_unpacklo_pd (__m128d a, __m128d b) + /// UNPCKLPD xmm, xmm/m128 + /// + public static Vector128 UnpackLow(Vector128 left, Vector128 right) => UnpackLow(left, right); + + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) => Xor(left, right); + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) => Xor(left, right); + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) => Xor(left, right); + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) => Xor(left, right); + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) => Xor(left, right); + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) => Xor(left, right); + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) => Xor(left, right); + /// + /// __m128i _mm_xor_si128 (__m128i a, __m128i b) + /// PXOR xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) => Xor(left, right); + /// + /// __m128d _mm_xor_pd (__m128d a, __m128d b) + /// XORPD xmm, xmm/m128 + /// + public static Vector128 Xor(Vector128 left, Vector128 right) => Xor(left, right); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse3.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse3.PlatformNotSupported.cs new file mode 100644 index 0000000000..f004266443 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse3.PlatformNotSupported.cs @@ -0,0 +1,91 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel SSE3 hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Sse3 : Sse2 + { + internal Sse3() { } + + public new static bool IsSupported { get { return false; } } + + /// + /// __m128 _mm_addsub_ps (__m128 a, __m128 b) + /// ADDSUBPS xmm, xmm/m128 + /// + public static Vector128 AddSubtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_addsub_pd (__m128d a, __m128d b) + /// ADDSUBPD xmm, xmm/m128 + /// + public static Vector128 AddSubtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_hadd_ps (__m128 a, __m128 b) + /// HADDPS xmm, xmm/m128 + /// + public static Vector128 HorizontalAdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_hadd_pd (__m128d a, __m128d b) + /// HADDPD xmm, xmm/m128 + /// + public static Vector128 HorizontalAdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_hsub_ps (__m128 a, __m128 b) + /// HSUBPS xmm, xmm/m128 + /// + public static Vector128 HorizontalSubtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_hsub_pd (__m128d a, __m128d b) + /// HSUBPD xmm, xmm/m128 + /// + public static Vector128 HorizontalSubtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_loaddup_pd (double const* mem_addr) + /// MOVDDUP xmm, m64 + /// + public static unsafe Vector128 LoadAndDuplicateToVector128(double* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_lddqu_si128 (__m128i const* mem_addr) + /// LDDQU xmm, m128 + /// + public static unsafe Vector128 LoadDquVector128(sbyte* address) { throw new PlatformNotSupportedException(); } + public static unsafe Vector128 LoadDquVector128(byte* address) { throw new PlatformNotSupportedException(); } + public static unsafe Vector128 LoadDquVector128(short* address) { throw new PlatformNotSupportedException(); } + public static unsafe Vector128 LoadDquVector128(ushort* address) { throw new PlatformNotSupportedException(); } + public static unsafe Vector128 LoadDquVector128(int* address) { throw new PlatformNotSupportedException(); } + public static unsafe Vector128 LoadDquVector128(uint* address) { throw new PlatformNotSupportedException(); } + public static unsafe Vector128 LoadDquVector128(long* address) { throw new PlatformNotSupportedException(); } + public static unsafe Vector128 LoadDquVector128(ulong* address) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_movedup_pd (__m128d a) + /// MOVDDUP xmm, xmm/m64 + /// + public static Vector128 MoveAndDuplicate(Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_movehdup_ps (__m128 a) + /// MOVSHDUP xmm, xmm/m128 + /// + public static Vector128 MoveHighAndDuplicate(Vector128 source) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_moveldup_ps (__m128 a) + /// MOVSLDUP xmm, xmm/m128 + /// + public static Vector128 MoveLowAndDuplicate(Vector128 source) { throw new PlatformNotSupportedException(); } + + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse3.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse3.cs new file mode 100644 index 0000000000..7c0eaad051 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse3.cs @@ -0,0 +1,90 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel SSE3 hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Sse3 : Sse2 + { + internal Sse3() { } + + public new static bool IsSupported { get => IsSupported; } + + /// + /// __m128 _mm_addsub_ps (__m128 a, __m128 b) + /// ADDSUBPS xmm, xmm/m128 + /// + public static Vector128 AddSubtract(Vector128 left, Vector128 right) => AddSubtract(left, right); + /// + /// __m128d _mm_addsub_pd (__m128d a, __m128d b) + /// ADDSUBPD xmm, xmm/m128 + /// + public static Vector128 AddSubtract(Vector128 left, Vector128 right) => AddSubtract(left, right); + + /// + /// __m128 _mm_hadd_ps (__m128 a, __m128 b) + /// HADDPS xmm, xmm/m128 + /// + public static Vector128 HorizontalAdd(Vector128 left, Vector128 right) => HorizontalAdd(left, right); + /// + /// __m128d _mm_hadd_pd (__m128d a, __m128d b) + /// HADDPD xmm, xmm/m128 + /// + public static Vector128 HorizontalAdd(Vector128 left, Vector128 right) => HorizontalAdd(left, right); + + /// + /// __m128 _mm_hsub_ps (__m128 a, __m128 b) + /// HSUBPS xmm, xmm/m128 + /// + public static Vector128 HorizontalSubtract(Vector128 left, Vector128 right) => HorizontalSubtract(left, right); + /// + /// __m128d _mm_hsub_pd (__m128d a, __m128d b) + /// HSUBPD xmm, xmm/m128 + /// + public static Vector128 HorizontalSubtract(Vector128 left, Vector128 right) => HorizontalSubtract(left, right); + + /// + /// __m128d _mm_loaddup_pd (double const* mem_addr) + /// MOVDDUP xmm, m64 + /// + public static unsafe Vector128 LoadAndDuplicateToVector128(double* address) => LoadAndDuplicateToVector128(address); + + /// + /// __m128i _mm_lddqu_si128 (__m128i const* mem_addr) + /// LDDQU xmm, m128 + /// + public static unsafe Vector128 LoadDquVector128(sbyte* address) => LoadDquVector128(address); + public static unsafe Vector128 LoadDquVector128(byte* address) => LoadDquVector128(address); + public static unsafe Vector128 LoadDquVector128(short* address) => LoadDquVector128(address); + public static unsafe Vector128 LoadDquVector128(ushort* address) => LoadDquVector128(address); + public static unsafe Vector128 LoadDquVector128(int* address) => LoadDquVector128(address); + public static unsafe Vector128 LoadDquVector128(uint* address) => LoadDquVector128(address); + public static unsafe Vector128 LoadDquVector128(long* address) => LoadDquVector128(address); + public static unsafe Vector128 LoadDquVector128(ulong* address) => LoadDquVector128(address); + + /// + /// __m128d _mm_movedup_pd (__m128d a) + /// MOVDDUP xmm, xmm/m64 + /// + public static Vector128 MoveAndDuplicate(Vector128 source) => MoveAndDuplicate(source); + + /// + /// __m128 _mm_movehdup_ps (__m128 a) + /// MOVSHDUP xmm, xmm/m128 + /// + public static Vector128 MoveHighAndDuplicate(Vector128 source) => MoveHighAndDuplicate(source); + + /// + /// __m128 _mm_moveldup_ps (__m128 a) + /// MOVSLDUP xmm, xmm/m128 + /// + public static Vector128 MoveLowAndDuplicate(Vector128 source) => MoveLowAndDuplicate(source); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse41.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse41.PlatformNotSupported.cs new file mode 100644 index 0000000000..58d06fa14a --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse41.PlatformNotSupported.cs @@ -0,0 +1,636 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel SSE4.1 hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Sse41 : Ssse3 + { + internal Sse41() { } + + public new static bool IsSupported { get { return false; } } + + /// + /// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8) + /// PBLENDW xmm, xmm/m128 imm8 + /// + public static Vector128 Blend(Vector128 left, Vector128 right, byte control) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8) + /// PBLENDW xmm, xmm/m128 imm8 + /// + public static Vector128 Blend(Vector128 left, Vector128 right, byte control) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_blend_ps (__m128 a, __m128 b, const int imm8) + /// BLENDPS xmm, xmm/m128, imm8 + /// + public static Vector128 Blend(Vector128 left, Vector128 right, byte control) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_blend_pd (__m128d a, __m128d b, const int imm8) + /// BLENDPD xmm, xmm/m128, imm8 + /// + public static Vector128 Blend(Vector128 left, Vector128 right, byte control) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask) + /// PBLENDVB xmm, xmm/m128, xmm + /// + public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask) + /// PBLENDVB xmm, xmm/m128, xmm + /// + public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_blendv_ps (__m128 a, __m128 b, __m128 mask) + /// BLENDVPS xmm, xmm/m128, xmm0 + /// + public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_blendv_pd (__m128d a, __m128d b, __m128d mask) + /// BLENDVPD xmm, xmm/m128, xmm0 + /// + public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_ceil_ps (__m128 a) + /// ROUNDPS xmm, xmm/m128, imm8(10) + /// + public static Vector128 Ceiling(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_ceil_pd (__m128d a) + /// ROUNDPD xmm, xmm/m128, imm8(10) + /// + public static Vector128 Ceiling(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_ceil_sd (__m128d a) + /// ROUNDSD xmm, xmm/m128, imm8(10) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 CeilingScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_ceil_ss (__m128 a) + /// ROUNDSD xmm, xmm/m128, imm8(10) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 CeilingScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_ceil_sd (__m128d a, __m128d b) + /// ROUNDSD xmm, xmm/m128, imm8(10) + /// + public static Vector128 CeilingScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_ceil_ss (__m128 a, __m128 b) + /// ROUNDSS xmm, xmm/m128, imm8(10) + /// + public static Vector128 CeilingScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b) + /// PCMPEQQ xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b) + /// PCMPEQQ xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cvtepi8_epi16 (__m128i a) + /// PMOVSXBW xmm, xmm/m64 + /// + public static Vector128 ConvertToVector128Int16(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtepu8_epi16 (__m128i a) + /// PMOVZXBW xmm, xmm/m64 + /// + public static Vector128 ConvertToVector128Int16(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtepi8_epi32 (__m128i a) + /// PMOVSXBD xmm, xmm/m32 + /// + public static Vector128 ConvertToVector128Int32(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtepu8_epi32 (__m128i a) + /// PMOVZXBD xmm, xmm/m32 + /// + public static Vector128 ConvertToVector128Int32(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtepi16_epi32 (__m128i a) + /// PMOVSXWD xmm, xmm/m64 + /// + public static Vector128 ConvertToVector128Int32(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtepu16_epi32 (__m128i a) + /// PMOVZXWD xmm, xmm/m64 + /// + public static Vector128 ConvertToVector128Int32(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtepi8_epi64 (__m128i a) + /// PMOVSXBQ xmm, xmm/m16 + /// + public static Vector128 ConvertToVector128Int64(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtepu8_epi64 (__m128i a) + /// PMOVZXBQ xmm, xmm/m16 + /// + public static Vector128 ConvertToVector128Int64(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtepi16_epi64 (__m128i a) + /// PMOVSXWQ xmm, xmm/m32 + /// + public static Vector128 ConvertToVector128Int64(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtepu16_epi64 (__m128i a) + /// PMOVZXWQ xmm, xmm/m32 + /// + public static Vector128 ConvertToVector128Int64(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtepi32_epi64 (__m128i a) + /// PMOVSXDQ xmm, xmm/m64 + /// + public static Vector128 ConvertToVector128Int64(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_cvtepu32_epi64 (__m128i a) + /// PMOVZXDQ xmm, xmm/m64 + /// + public static Vector128 ConvertToVector128Int64(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_dp_ps (__m128 a, __m128 b, const int imm8) + /// DPPS xmm, xmm/m128, imm8 + /// + public static Vector128 DotProduct(Vector128 left, Vector128 right, byte control) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_dp_pd (__m128d a, __m128d b, const int imm8) + /// DPPD xmm, xmm/m128, imm8 + /// + public static Vector128 DotProduct(Vector128 left, Vector128 right, byte control) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_extract_epi8 (__m128i a, const int imm8) + /// PEXTRB reg/m8, xmm, imm8 + /// + public static byte Extract(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_extract_epi32 (__m128i a, const int imm8) + /// PEXTRD reg/m32, xmm, imm8 + /// + public static int Extract(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_extract_epi32 (__m128i a, const int imm8) + /// PEXTRD reg/m32, xmm, imm8 + /// + public static uint Extract(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __int64 _mm_extract_epi64 (__m128i a, const int imm8) + /// PEXTRQ reg/m64, xmm, imm8 + /// + public static long Extract(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __int64 _mm_extract_epi64 (__m128i a, const int imm8) + /// PEXTRQ reg/m64, xmm, imm8 + /// + public static ulong Extract(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_extract_ps (__m128 a, const int imm8) + /// EXTRACTPS xmm, xmm/m32, imm8 + /// + public static float Extract(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_floor_ps (__m128 a) + /// ROUNDPS xmm, xmm/m128, imm8(9) + /// + public static Vector128 Floor(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_floor_pd (__m128d a) + /// ROUNDPD xmm, xmm/m128, imm8(9) + /// + public static Vector128 Floor(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_floor_sd (__m128d a) + /// ROUNDSD xmm, xmm/m128, imm8(9) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 FloorScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_floor_ss (__m128 a) + /// ROUNDSS xmm, xmm/m128, imm8(9) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 FloorScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_floor_sd (__m128d a, __m128d b) + /// ROUNDSD xmm, xmm/m128, imm8(9) + /// + public static Vector128 FloorScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_floor_ss (__m128 a, __m128 b) + /// ROUNDSS xmm, xmm/m128, imm8(9) + /// + public static Vector128 FloorScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8) + /// PINSRB xmm, reg/m8, imm8 + /// + public static Vector128 Insert(Vector128 value, sbyte data, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8) + /// PINSRB xmm, reg/m8, imm8 + /// + public static Vector128 Insert(Vector128 value, byte data, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8) + /// PINSRD xmm, reg/m32, imm8 + /// + public static Vector128 Insert(Vector128 value, int data, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8) + /// PINSRD xmm, reg/m32, imm8 + /// + public static Vector128 Insert(Vector128 value, uint data, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8) + /// PINSRQ xmm, reg/m64, imm8 + /// + public static Vector128 Insert(Vector128 value, long data, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8) + /// PINSRQ xmm, reg/m64, imm8 + /// + public static Vector128 Insert(Vector128 value, ulong data, byte index) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_insert_ps (__m128 a, __m128 b, const int imm8) + /// INSERTPS xmm, xmm/m32, imm8 + /// + public static Vector128 Insert(Vector128 value, Vector128 data, byte index) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_max_epi8 (__m128i a, __m128i b) + /// PMAXSB xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_max_epu16 (__m128i a, __m128i b) + /// PMAXUW xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_max_epi32 (__m128i a, __m128i b) + /// PMAXSD xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_max_epu32 (__m128i a, __m128i b) + /// PMAXUD xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_min_epi8 (__m128i a, __m128i b) + /// PMINSB xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_min_epu16 (__m128i a, __m128i b) + /// PMINUW xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_min_epi32 (__m128i a, __m128i b) + /// PMINSD xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_min_epu32 (__m128i a, __m128i b) + /// PMINUD xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_minpos_epu16 (__m128i a) + /// PHMINPOSUW xmm, xmm/m128 + /// + public static Vector128 MinHorizontal(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_mpsadbw_epu8 (__m128i a, __m128i b, const int imm8) + /// MPSADBW xmm, xmm/m128, imm8 + /// + public static Vector128 MultipleSumAbsoluteDifferences(Vector128 left, Vector128 right, byte mask) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_mul_epi32 (__m128i a, __m128i b) + /// PMULDQ xmm, xmm/m128 + /// + public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_mullo_epi32 (__m128i a, __m128i b) + /// PMULLD xmm, xmm/m128 + /// + public static Vector128 MultiplyLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_packus_epi32 (__m128i a, __m128i b) + /// PACKUSDW xmm, xmm/m128 + /// + public static Vector128 PackUnsignedSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_round_ps (__m128 a, int rounding) + /// ROUNDPS xmm, xmm/m128, imm8(8) + /// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC + /// + public static Vector128 RoundToNearestInteger(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(9) + /// + public static Vector128 RoundToNegativeInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(10) + /// + public static Vector128 RoundToPositiveInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(11) + /// + public static Vector128 RoundToZero(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// _MM_FROUND_CUR_DIRECTION; ROUNDPS xmm, xmm/m128, imm8(4) + /// + public static Vector128 RoundCurrentDirection(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_round_pd (__m128d a, int rounding) + /// ROUNDPD xmm, xmm/m128, imm8(8) + /// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC + /// + public static Vector128 RoundToNearestInteger(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(9) + /// + public static Vector128 RoundToNegativeInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(10) + /// + public static Vector128 RoundToPositiveInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(11) + /// + public static Vector128 RoundToZero(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// _MM_FROUND_CUR_DIRECTION; ROUNDPD xmm, xmm/m128, imm8(4) + /// + public static Vector128 RoundCurrentDirection(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_CUR_DIRECTION) + /// ROUNDSD xmm, xmm/m128, imm8(4) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundCurrentDirectionScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(8) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToNearestIntegerScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(9) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToNegativeInfinityScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(10) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToPositiveInfinityScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(11) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToZeroScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_CUR_DIRECTION) + /// ROUNDSD xmm, xmm/m128, imm8(4) + /// + public static Vector128 RoundCurrentDirectionScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(8) + /// + public static Vector128 RoundToNearestIntegerScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(9) + /// + public static Vector128 RoundToNegativeInfinityScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(10) + /// + public static Vector128 RoundToPositiveInfinityScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(11) + /// + public static Vector128 RoundToZeroScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_CUR_DIRECTION) + /// ROUNDSS xmm, xmm/m128, imm8(4) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundCurrentDirectionScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(8) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToNearestIntegerScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(9) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToNegativeInfinityScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(10) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToPositiveInfinityScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(11) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToZeroScalar(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_CUR_DIRECTION) + /// ROUNDSS xmm, xmm/m128, imm8(4) + /// + public static Vector128 RoundCurrentDirectionScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(8) + /// + public static Vector128 RoundToNearestIntegerScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(9) + /// + public static Vector128 RoundToNegativeInfinityScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(10) + /// + public static Vector128 RoundToPositiveInfinityScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(11) + /// + public static Vector128 RoundToZeroScalar(Vector128 upper, Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(sbyte* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(byte* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(short* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(ushort* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(int* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(uint* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(long* address) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(ulong* address) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_test_all_ones (__m128i a) + /// HELPER + /// + public static bool TestAllOnes(Vector128 value) { throw new PlatformNotSupportedException(); } + public static bool TestAllOnes(Vector128 value) { throw new PlatformNotSupportedException(); } + public static bool TestAllOnes(Vector128 value) { throw new PlatformNotSupportedException(); } + public static bool TestAllOnes(Vector128 value) { throw new PlatformNotSupportedException(); } + public static bool TestAllOnes(Vector128 value) { throw new PlatformNotSupportedException(); } + public static bool TestAllOnes(Vector128 value) { throw new PlatformNotSupportedException(); } + public static bool TestAllOnes(Vector128 value) { throw new PlatformNotSupportedException(); } + public static bool TestAllOnes(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_test_all_zeros (__m128i a, __m128i mask) + /// PTEST xmm, xmm/m128 + /// + public static bool TestAllZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestAllZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestAllZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestAllZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestAllZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestAllZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestAllZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestAllZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// + public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_test_mix_ones_zeros (__m128i a, __m128i mask) + /// PTEST xmm, xmm/m128 + /// + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// + public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse41.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse41.cs new file mode 100644 index 0000000000..2547e41db5 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse41.cs @@ -0,0 +1,636 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel SSE4.1 hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Sse41 : Ssse3 + { + internal Sse41() { } + + public new static bool IsSupported { get => IsSupported; } + + /// + /// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8) + /// PBLENDW xmm, xmm/m128 imm8 + /// + public static Vector128 Blend(Vector128 left, Vector128 right, byte control) => Blend(left, right, control); + + /// + /// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8) + /// PBLENDW xmm, xmm/m128 imm8 + /// + public static Vector128 Blend(Vector128 left, Vector128 right, byte control) => Blend(left, right, control); + + /// + /// __m128 _mm_blend_ps (__m128 a, __m128 b, const int imm8) + /// BLENDPS xmm, xmm/m128, imm8 + /// + public static Vector128 Blend(Vector128 left, Vector128 right, byte control) => Blend(left, right, control); + + /// + /// __m128d _mm_blend_pd (__m128d a, __m128d b, const int imm8) + /// BLENDPD xmm, xmm/m128, imm8 + /// + public static Vector128 Blend(Vector128 left, Vector128 right, byte control) => Blend(left, right, control); + + /// + /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask) + /// PBLENDVB xmm, xmm/m128, xmm + /// + public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) => BlendVariable(left, right, mask); + /// + /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask) + /// PBLENDVB xmm, xmm/m128, xmm + /// + public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) => BlendVariable(left, right, mask); + /// + /// __m128 _mm_blendv_ps (__m128 a, __m128 b, __m128 mask) + /// BLENDVPS xmm, xmm/m128, xmm0 + /// + public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) => BlendVariable(left, right, mask); + /// + /// __m128d _mm_blendv_pd (__m128d a, __m128d b, __m128d mask) + /// BLENDVPD xmm, xmm/m128, xmm0 + /// + public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) => BlendVariable(left, right, mask); + + /// + /// __m128 _mm_ceil_ps (__m128 a) + /// ROUNDPS xmm, xmm/m128, imm8(10) + /// + public static Vector128 Ceiling(Vector128 value) => Ceiling(value); + /// + /// __m128d _mm_ceil_pd (__m128d a) + /// ROUNDPD xmm, xmm/m128, imm8(10) + /// + public static Vector128 Ceiling(Vector128 value) => Ceiling(value); + + /// + /// __m128d _mm_ceil_sd (__m128d a) + /// ROUNDSD xmm, xmm/m128, imm8(10) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 CeilingScalar(Vector128 value) => CeilingScalar(value); + /// + /// __m128 _mm_ceil_ss (__m128 a) + /// ROUNDSD xmm, xmm/m128, imm8(10) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 CeilingScalar(Vector128 value) => CeilingScalar(value); + + /// + /// __m128d _mm_ceil_sd (__m128d a, __m128d b) + /// ROUNDSD xmm, xmm/m128, imm8(10) + /// + public static Vector128 CeilingScalar(Vector128 upper, Vector128 value) => CeilingScalar(upper, value); + /// + /// __m128 _mm_ceil_ss (__m128 a, __m128 b) + /// ROUNDSS xmm, xmm/m128, imm8(10) + /// + public static Vector128 CeilingScalar(Vector128 upper, Vector128 value) => CeilingScalar(upper, value); + + /// + /// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b) + /// PCMPEQQ xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + /// + /// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b) + /// PCMPEQQ xmm, xmm/m128 + /// + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + + /// + /// __m128i _mm_cvtepi8_epi16 (__m128i a) + /// PMOVSXBW xmm, xmm/m64 + /// + public static Vector128 ConvertToVector128Int16(Vector128 value) => ConvertToVector128Int16(value); + /// + /// __m128i _mm_cvtepu8_epi16 (__m128i a) + /// PMOVZXBW xmm, xmm/m64 + /// + public static Vector128 ConvertToVector128Int16(Vector128 value) => ConvertToVector128Int16(value); + /// + /// __m128i _mm_cvtepi8_epi32 (__m128i a) + /// PMOVSXBD xmm, xmm/m32 + /// + public static Vector128 ConvertToVector128Int32(Vector128 value) => ConvertToVector128Int32(value); + /// + /// __m128i _mm_cvtepu8_epi32 (__m128i a) + /// PMOVZXBD xmm, xmm/m32 + /// + public static Vector128 ConvertToVector128Int32(Vector128 value) => ConvertToVector128Int32(value); + /// + /// __m128i _mm_cvtepi16_epi32 (__m128i a) + /// PMOVSXWD xmm, xmm/m64 + /// + public static Vector128 ConvertToVector128Int32(Vector128 value) => ConvertToVector128Int32(value); + /// + /// __m128i _mm_cvtepu16_epi32 (__m128i a) + /// PMOVZXWD xmm, xmm/m64 + /// + public static Vector128 ConvertToVector128Int32(Vector128 value) => ConvertToVector128Int32(value); + /// + /// __m128i _mm_cvtepi8_epi64 (__m128i a) + /// PMOVSXBQ xmm, xmm/m16 + /// + public static Vector128 ConvertToVector128Int64(Vector128 value) => ConvertToVector128Int64(value); + /// + /// __m128i _mm_cvtepu8_epi64 (__m128i a) + /// PMOVZXBQ xmm, xmm/m16 + /// + public static Vector128 ConvertToVector128Int64(Vector128 value) => ConvertToVector128Int64(value); + /// + /// __m128i _mm_cvtepi16_epi64 (__m128i a) + /// PMOVSXWQ xmm, xmm/m32 + /// + public static Vector128 ConvertToVector128Int64(Vector128 value) => ConvertToVector128Int64(value); + /// + /// __m128i _mm_cvtepu16_epi64 (__m128i a) + /// PMOVZXWQ xmm, xmm/m32 + /// + public static Vector128 ConvertToVector128Int64(Vector128 value) => ConvertToVector128Int64(value); + /// + /// __m128i _mm_cvtepi32_epi64 (__m128i a) + /// PMOVSXDQ xmm, xmm/m64 + /// + public static Vector128 ConvertToVector128Int64(Vector128 value) => ConvertToVector128Int64(value); + /// + /// __m128i _mm_cvtepu32_epi64 (__m128i a) + /// PMOVZXDQ xmm, xmm/m64 + /// + public static Vector128 ConvertToVector128Int64(Vector128 value) => ConvertToVector128Int64(value); + + /// + /// __m128 _mm_dp_ps (__m128 a, __m128 b, const int imm8) + /// DPPS xmm, xmm/m128, imm8 + /// + public static Vector128 DotProduct(Vector128 left, Vector128 right, byte control) => DotProduct(left, right, control); + /// + /// __m128d _mm_dp_pd (__m128d a, __m128d b, const int imm8) + /// DPPD xmm, xmm/m128, imm8 + /// + public static Vector128 DotProduct(Vector128 left, Vector128 right, byte control) => DotProduct(left, right, control); + + /// + /// int _mm_extract_epi8 (__m128i a, const int imm8) + /// PEXTRB reg/m8, xmm, imm8 + /// + public static byte Extract(Vector128 value, byte index) => Extract(value, index); + /// + /// int _mm_extract_epi32 (__m128i a, const int imm8) + /// PEXTRD reg/m32, xmm, imm8 + /// + public static int Extract(Vector128 value, byte index) => Extract(value, index); + /// + /// int _mm_extract_epi32 (__m128i a, const int imm8) + /// PEXTRD reg/m32, xmm, imm8 + /// + public static uint Extract(Vector128 value, byte index) => Extract(value, index); + /// + /// __int64 _mm_extract_epi64 (__m128i a, const int imm8) + /// PEXTRQ reg/m64, xmm, imm8 + /// + public static long Extract(Vector128 value, byte index) => Extract(value, index); + /// + /// __int64 _mm_extract_epi64 (__m128i a, const int imm8) + /// PEXTRQ reg/m64, xmm, imm8 + /// + public static ulong Extract(Vector128 value, byte index) => Extract(value, index); + /// + /// int _mm_extract_ps (__m128 a, const int imm8) + /// EXTRACTPS xmm, xmm/m32, imm8 + /// + public static float Extract(Vector128 value, byte index) => Extract(value, index); + + /// + /// __m128 _mm_floor_ps (__m128 a) + /// ROUNDPS xmm, xmm/m128, imm8(9) + /// + public static Vector128 Floor(Vector128 value) => Floor(value); + /// + /// __m128d _mm_floor_pd (__m128d a) + /// ROUNDPD xmm, xmm/m128, imm8(9) + /// + public static Vector128 Floor(Vector128 value) => Floor(value); + + /// + /// __m128d _mm_floor_sd (__m128d a) + /// ROUNDSD xmm, xmm/m128, imm8(9) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 FloorScalar(Vector128 value) => FloorScalar(value); + /// + /// __m128 _mm_floor_ss (__m128 a) + /// ROUNDSS xmm, xmm/m128, imm8(9) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 FloorScalar(Vector128 value) => FloorScalar(value); + + /// + /// __m128d _mm_floor_sd (__m128d a, __m128d b) + /// ROUNDSD xmm, xmm/m128, imm8(9) + /// + public static Vector128 FloorScalar(Vector128 upper, Vector128 value) => FloorScalar(upper, value); + /// + /// __m128 _mm_floor_ss (__m128 a, __m128 b) + /// ROUNDSS xmm, xmm/m128, imm8(9) + /// + public static Vector128 FloorScalar(Vector128 upper, Vector128 value) => FloorScalar(upper, value); + + /// + /// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8) + /// PINSRB xmm, reg/m8, imm8 + /// + public static Vector128 Insert(Vector128 value, sbyte data, byte index) => Insert(value, data, index); + /// + /// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8) + /// PINSRB xmm, reg/m8, imm8 + /// + public static Vector128 Insert(Vector128 value, byte data, byte index) => Insert(value, data, index); + /// + /// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8) + /// PINSRD xmm, reg/m32, imm8 + /// + public static Vector128 Insert(Vector128 value, int data, byte index) => Insert(value, data, index); + /// + /// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8) + /// PINSRD xmm, reg/m32, imm8 + /// + public static Vector128 Insert(Vector128 value, uint data, byte index) => Insert(value, data, index); + /// + /// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8) + /// PINSRQ xmm, reg/m64, imm8 + /// + public static Vector128 Insert(Vector128 value, long data, byte index) => Insert(value, data, index); + /// + /// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8) + /// PINSRQ xmm, reg/m64, imm8 + /// + public static Vector128 Insert(Vector128 value, ulong data, byte index) => Insert(value, data, index); + /// + /// __m128 _mm_insert_ps (__m128 a, __m128 b, const int imm8) + /// INSERTPS xmm, xmm/m32, imm8 + /// + public static Vector128 Insert(Vector128 value, Vector128 data, byte index) => Insert(value, data, index); + + /// + /// __m128i _mm_max_epi8 (__m128i a, __m128i b) + /// PMAXSB xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + /// + /// __m128i _mm_max_epu16 (__m128i a, __m128i b) + /// PMAXUW xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + /// + /// __m128i _mm_max_epi32 (__m128i a, __m128i b) + /// PMAXSD xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + /// + /// __m128i _mm_max_epu32 (__m128i a, __m128i b) + /// PMAXUD xmm, xmm/m128 + /// + public static Vector128 Max(Vector128 left, Vector128 right) => Max(left, right); + + /// + /// __m128i _mm_min_epi8 (__m128i a, __m128i b) + /// PMINSB xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + /// + /// __m128i _mm_min_epu16 (__m128i a, __m128i b) + /// PMINUW xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + /// + /// __m128i _mm_min_epi32 (__m128i a, __m128i b) + /// PMINSD xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + /// + /// __m128i _mm_min_epu32 (__m128i a, __m128i b) + /// PMINUD xmm, xmm/m128 + /// + public static Vector128 Min(Vector128 left, Vector128 right) => Min(left, right); + + /// + /// __m128i _mm_minpos_epu16 (__m128i a) + /// PHMINPOSUW xmm, xmm/m128 + /// + public static Vector128 MinHorizontal(Vector128 value) => MinHorizontal(value); + + /// + /// __m128i _mm_mpsadbw_epu8 (__m128i a, __m128i b, const int imm8) + /// MPSADBW xmm, xmm/m128, imm8 + /// + public static Vector128 MultipleSumAbsoluteDifferences(Vector128 left, Vector128 right, byte mask) => MultipleSumAbsoluteDifferences(left, right, mask); + + /// + /// __m128i _mm_mul_epi32 (__m128i a, __m128i b) + /// PMULDQ xmm, xmm/m128 + /// + public static Vector128 Multiply(Vector128 left, Vector128 right) => Multiply(left, right); + + /// + /// __m128i _mm_mullo_epi32 (__m128i a, __m128i b) + /// PMULLD xmm, xmm/m128 + /// + public static Vector128 MultiplyLow(Vector128 left, Vector128 right) => MultiplyLow(left, right); + + /// + /// __m128i _mm_packus_epi32 (__m128i a, __m128i b) + /// PACKUSDW xmm, xmm/m128 + /// + public static Vector128 PackUnsignedSaturate(Vector128 left, Vector128 right) => PackUnsignedSaturate(left, right); + + /// + /// __m128 _mm_round_ps (__m128 a, int rounding) + /// ROUNDPS xmm, xmm/m128, imm8(8) + /// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC + /// + public static Vector128 RoundToNearestInteger(Vector128 value) => RoundToNearestInteger(value); + /// + /// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(9) + /// + public static Vector128 RoundToNegativeInfinity(Vector128 value) => RoundToNegativeInfinity(value); + /// + /// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(10) + /// + public static Vector128 RoundToPositiveInfinity(Vector128 value) => RoundToPositiveInfinity(value); + /// + /// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(11) + /// + public static Vector128 RoundToZero(Vector128 value) => RoundToZero(value); + /// + /// _MM_FROUND_CUR_DIRECTION; ROUNDPS xmm, xmm/m128, imm8(4) + /// + public static Vector128 RoundCurrentDirection(Vector128 value) => RoundCurrentDirection(value); + + /// + /// __m128d _mm_round_pd (__m128d a, int rounding) + /// ROUNDPD xmm, xmm/m128, imm8(8) + /// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC + /// + public static Vector128 RoundToNearestInteger(Vector128 value) => RoundToNearestInteger(value); + /// + /// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(9) + /// + public static Vector128 RoundToNegativeInfinity(Vector128 value) => RoundToNegativeInfinity(value); + /// + /// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(10) + /// + public static Vector128 RoundToPositiveInfinity(Vector128 value) => RoundToPositiveInfinity(value); + /// + /// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(11) + /// + public static Vector128 RoundToZero(Vector128 value) => RoundToZero(value); + /// + /// _MM_FROUND_CUR_DIRECTION; ROUNDPD xmm, xmm/m128, imm8(4) + /// + public static Vector128 RoundCurrentDirection(Vector128 value) => RoundCurrentDirection(value); + + /// + /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_CUR_DIRECTION) + /// ROUNDSD xmm, xmm/m128, imm8(4) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundCurrentDirectionScalar(Vector128 value) => RoundCurrentDirectionScalar(value); + /// + /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(8) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToNearestIntegerScalar(Vector128 value) => RoundToNearestIntegerScalar(value); + /// + /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(9) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToNegativeInfinityScalar(Vector128 value) => RoundToNegativeInfinityScalar(value); + /// + /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(10) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToPositiveInfinityScalar(Vector128 value) => RoundToPositiveInfinityScalar(value); + /// + /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(11) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToZeroScalar(Vector128 value) => RoundToZeroScalar(value); + + /// + /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_CUR_DIRECTION) + /// ROUNDSD xmm, xmm/m128, imm8(4) + /// + public static Vector128 RoundCurrentDirectionScalar(Vector128 upper, Vector128 value) => RoundCurrentDirectionScalar(upper, value); + /// + /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(8) + /// + public static Vector128 RoundToNearestIntegerScalar(Vector128 upper, Vector128 value) => RoundToNearestIntegerScalar(upper, value); + /// + /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(9) + /// + public static Vector128 RoundToNegativeInfinityScalar(Vector128 upper, Vector128 value) => RoundToNegativeInfinityScalar(upper, value); + /// + /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(10) + /// + public static Vector128 RoundToPositiveInfinityScalar(Vector128 upper, Vector128 value) => RoundToPositiveInfinityScalar(upper, value); + /// + /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC) + /// ROUNDSD xmm, xmm/m128, imm8(11) + /// + public static Vector128 RoundToZeroScalar(Vector128 upper, Vector128 value) => RoundToZeroScalar(upper, value); + + /// + /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_CUR_DIRECTION) + /// ROUNDSS xmm, xmm/m128, imm8(4) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundCurrentDirectionScalar(Vector128 value) => RoundCurrentDirectionScalar(value); + /// + /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(8) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToNearestIntegerScalar(Vector128 value) => RoundToNearestIntegerScalar(value); + /// + /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(9) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToNegativeInfinityScalar(Vector128 value) => RoundToNegativeInfinityScalar(value); + /// + /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(10) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToPositiveInfinityScalar(Vector128 value) => RoundToPositiveInfinityScalar(value); + /// + /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(11) + /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. + /// + public static Vector128 RoundToZeroScalar(Vector128 value) => RoundToZeroScalar(value); + + /// + /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_CUR_DIRECTION) + /// ROUNDSS xmm, xmm/m128, imm8(4) + /// + public static Vector128 RoundCurrentDirectionScalar(Vector128 upper, Vector128 value) => RoundCurrentDirectionScalar(upper, value); + /// + /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(8) + /// + public static Vector128 RoundToNearestIntegerScalar(Vector128 upper, Vector128 value) => RoundToNearestIntegerScalar(upper, value); + /// + /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(9) + /// + public static Vector128 RoundToNegativeInfinityScalar(Vector128 upper, Vector128 value) => RoundToNegativeInfinityScalar(upper, value); + /// + /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(10) + /// + public static Vector128 RoundToPositiveInfinityScalar(Vector128 upper, Vector128 value) => RoundToPositiveInfinityScalar(upper, value); + /// + /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC) + /// ROUNDSS xmm, xmm/m128, imm8(11) + /// + public static Vector128 RoundToZeroScalar(Vector128 upper, Vector128 value) => RoundToZeroScalar(upper, value); + + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(sbyte* address) => LoadAlignedVector128NonTemporal(address); + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(byte* address) => LoadAlignedVector128NonTemporal(address); + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(short* address) => LoadAlignedVector128NonTemporal(address); + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(ushort* address) => LoadAlignedVector128NonTemporal(address); + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(int* address) => LoadAlignedVector128NonTemporal(address); + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(uint* address) => LoadAlignedVector128NonTemporal(address); + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(long* address) => LoadAlignedVector128NonTemporal(address); + /// + /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) + /// MOVNTDQA xmm, m128 + /// + public static unsafe Vector128 LoadAlignedVector128NonTemporal(ulong* address) => LoadAlignedVector128NonTemporal(address); + + /// + /// int _mm_test_all_ones (__m128i a) + /// HELPER + /// + public static bool TestAllOnes(Vector128 value) => TestAllOnes(value); + public static bool TestAllOnes(Vector128 value) => TestAllOnes(value); + public static bool TestAllOnes(Vector128 value) => TestAllOnes(value); + public static bool TestAllOnes(Vector128 value) => TestAllOnes(value); + public static bool TestAllOnes(Vector128 value) => TestAllOnes(value); + public static bool TestAllOnes(Vector128 value) => TestAllOnes(value); + public static bool TestAllOnes(Vector128 value) => TestAllOnes(value); + public static bool TestAllOnes(Vector128 value) => TestAllOnes(value); + + /// + /// int _mm_test_all_zeros (__m128i a, __m128i mask) + /// PTEST xmm, xmm/m128 + /// + public static bool TestAllZeros(Vector128 left, Vector128 right) => TestAllZeros(left, right); + public static bool TestAllZeros(Vector128 left, Vector128 right) => TestAllZeros(left, right); + public static bool TestAllZeros(Vector128 left, Vector128 right) => TestAllZeros(left, right); + public static bool TestAllZeros(Vector128 left, Vector128 right) => TestAllZeros(left, right); + public static bool TestAllZeros(Vector128 left, Vector128 right) => TestAllZeros(left, right); + public static bool TestAllZeros(Vector128 left, Vector128 right) => TestAllZeros(left, right); + public static bool TestAllZeros(Vector128 left, Vector128 right) => TestAllZeros(left, right); + public static bool TestAllZeros(Vector128 left, Vector128 right) => TestAllZeros(left, right); + + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// + public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + + /// + /// int _mm_test_mix_ones_zeros (__m128i a, __m128i mask) + /// PTEST xmm, xmm/m128 + /// + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) => TestMixOnesZeros(left, right); + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) => TestMixOnesZeros(left, right); + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) => TestMixOnesZeros(left, right); + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) => TestMixOnesZeros(left, right); + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) => TestMixOnesZeros(left, right); + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) => TestMixOnesZeros(left, right); + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) => TestMixOnesZeros(left, right); + public static bool TestMixOnesZeros(Vector128 left, Vector128 right) => TestMixOnesZeros(left, right); + + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// + public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse42.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse42.PlatformNotSupported.cs new file mode 100644 index 0000000000..8ea2d6f075 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse42.PlatformNotSupported.cs @@ -0,0 +1,304 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel SSE4.2 hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Sse42 : Sse41 + { + internal Sse42() { } + + public new static bool IsSupported { get { return false; } } + + /// + /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static bool CompareImplicitLength(Vector128 left, Vector128 right, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static bool CompareImplicitLength(Vector128 left, Vector128 right, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static bool CompareImplicitLength(Vector128 left, Vector128 right, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + + /// + /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static bool CompareImplicitLength(Vector128 left, Vector128 right, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static bool CompareExplicitLength(Vector128 left, byte leftLength, Vector128 right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static bool CompareExplicitLength(Vector128 left, byte leftLength, Vector128 right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static bool CompareExplicitLength(Vector128 left, byte leftLength, Vector128 right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static bool CompareExplicitLength(Vector128 left, byte leftLength, Vector128 right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static int CompareImplicitLengthIndex(Vector128 left, Vector128 right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static int CompareImplicitLengthIndex(Vector128 left, Vector128 right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static int CompareImplicitLengthIndex(Vector128 left, Vector128 right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static int CompareImplicitLengthIndex(Vector128 left, Vector128 right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static int CompareExplicitLengthIndex(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static int CompareExplicitLengthIndex(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static int CompareExplicitLengthIndex(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static int CompareExplicitLengthIndex(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthBitMask(Vector128 left, Vector128 right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthBitMask(Vector128 left, Vector128 right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthBitMask(Vector128 left, Vector128 right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthBitMask(Vector128 left, Vector128 right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthUnitMask(Vector128 left, Vector128 right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthUnitMask(Vector128 left, Vector128 right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthUnitMask(Vector128 left, Vector128 right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthUnitMask(Vector128 left, Vector128 right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthBitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthBitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthBitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthBitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthUnitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthUnitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthUnitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthUnitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_cmpgt_epi64 (__m128i a, __m128i b) + /// PCMPGTQ xmm, xmm/m128 + /// + public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// unsigned int _mm_crc32_u8 (unsigned int crc, unsigned char v) + /// CRC32 reg, reg/m8 + /// + public static uint Crc32(uint crc, byte data) { throw new PlatformNotSupportedException(); } + /// + /// unsigned int _mm_crc32_u16 (unsigned int crc, unsigned short v) + /// CRC32 reg, reg/m16 + /// + public static uint Crc32(uint crc, ushort data) { throw new PlatformNotSupportedException(); } + /// + /// unsigned int _mm_crc32_u32 (unsigned int crc, unsigned int v) + /// CRC32 reg, reg/m32 + /// + public static uint Crc32(uint crc, uint data) { throw new PlatformNotSupportedException(); } + /// + /// unsigned __int64 _mm_crc32_u64 (unsigned __int64 crc, unsigned __int64 v) + /// CRC32 reg, reg/m64 + /// + public static ulong Crc32(ulong crc, ulong data) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse42.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse42.cs new file mode 100644 index 0000000000..a7353382bb --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Sse42.cs @@ -0,0 +1,304 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel SSE4.2 hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Sse42 : Sse41 + { + internal Sse42() { } + + public new static bool IsSupported { get => IsSupported; } + + /// + /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static bool CompareImplicitLength(Vector128 left, Vector128 right, ResultsFlag flag, StringComparisonMode mode) => CompareImplicitLength(left, right, flag, mode); + + /// + /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static bool CompareImplicitLength(Vector128 left, Vector128 right, ResultsFlag flag, StringComparisonMode mode) => CompareImplicitLength(left, right, flag, mode); + + /// + /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static bool CompareImplicitLength(Vector128 left, Vector128 right, ResultsFlag flag, StringComparisonMode mode) => CompareImplicitLength(left, right, flag, mode); + + + /// + /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static bool CompareImplicitLength(Vector128 left, Vector128 right, ResultsFlag flag, StringComparisonMode mode) => CompareImplicitLength(left, right, flag, mode); + + /// + /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static bool CompareExplicitLength(Vector128 left, byte leftLength, Vector128 right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) => CompareExplicitLength(left, leftLength, right, rightLength, flag, mode); + + /// + /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static bool CompareExplicitLength(Vector128 left, byte leftLength, Vector128 right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) => CompareExplicitLength(left, leftLength, right, rightLength, flag, mode); + + /// + /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static bool CompareExplicitLength(Vector128 left, byte leftLength, Vector128 right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) => CompareExplicitLength(left, leftLength, right, rightLength, flag, mode); + + /// + /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static bool CompareExplicitLength(Vector128 left, byte leftLength, Vector128 right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) => CompareExplicitLength(left, leftLength, right, rightLength, flag, mode); + + /// + /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static int CompareImplicitLengthIndex(Vector128 left, Vector128 right, StringComparisonMode mode) => CompareImplicitLengthIndex(left, right, mode); + + /// + /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static int CompareImplicitLengthIndex(Vector128 left, Vector128 right, StringComparisonMode mode) => CompareImplicitLengthIndex(left, right, mode); + + /// + /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static int CompareImplicitLengthIndex(Vector128 left, Vector128 right, StringComparisonMode mode) => CompareImplicitLengthIndex(left, right, mode); + + /// + /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8) + /// PCMPISTRI xmm, xmm/m128, imm8 + /// + public static int CompareImplicitLengthIndex(Vector128 left, Vector128 right, StringComparisonMode mode) => CompareImplicitLengthIndex(left, right, mode); + + /// + /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static int CompareExplicitLengthIndex(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthIndex(left, leftLength, right, rightLength, mode); + + /// + /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static int CompareExplicitLengthIndex(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthIndex(left, leftLength, right, rightLength, mode); + + /// + /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static int CompareExplicitLengthIndex(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthIndex(left, leftLength, right, rightLength, mode); + + /// + /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRI xmm, xmm/m128, imm8 + /// + public static int CompareExplicitLengthIndex(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthIndex(left, leftLength, right, rightLength, mode); + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthBitMask(Vector128 left, Vector128 right, StringComparisonMode mode) => CompareImplicitLengthBitMask(left, right, mode); + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthBitMask(Vector128 left, Vector128 right, StringComparisonMode mode) => CompareImplicitLengthBitMask(left, right, mode); + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthBitMask(Vector128 left, Vector128 right, StringComparisonMode mode) => CompareImplicitLengthBitMask(left, right, mode); + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthBitMask(Vector128 left, Vector128 right, StringComparisonMode mode) => CompareImplicitLengthBitMask(left, right, mode); + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthUnitMask(Vector128 left, Vector128 right, StringComparisonMode mode) => CompareImplicitLengthUnitMask(left, right, mode); + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthUnitMask(Vector128 left, Vector128 right, StringComparisonMode mode) => CompareImplicitLengthUnitMask(left, right, mode); + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthUnitMask(Vector128 left, Vector128 right, StringComparisonMode mode) => CompareImplicitLengthUnitMask(left, right, mode); + + /// + /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) + /// PCMPISTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareImplicitLengthUnitMask(Vector128 left, Vector128 right, StringComparisonMode mode) => CompareImplicitLengthUnitMask(left, right, mode); + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthBitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthBitMask(left, leftLength, right, rightLength, mode); + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthBitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthBitMask(left, leftLength, right, rightLength, mode); + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthBitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthBitMask(left, leftLength, right, rightLength, mode); + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthBitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthBitMask(left, leftLength, right, rightLength, mode); + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthUnitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthUnitMask(left, leftLength, right, rightLength, mode); + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthUnitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthUnitMask(left, leftLength, right, rightLength, mode); + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthUnitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthUnitMask(left, leftLength, right, rightLength, mode); + + /// + /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) + /// PCMPESTRM xmm, xmm/m128, imm8 + /// + public static Vector128 CompareExplicitLengthUnitMask(Vector128 left, byte leftLength, Vector128 right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthUnitMask(left, leftLength, right, rightLength, mode); + + /// + /// __m128i _mm_cmpgt_epi64 (__m128i a, __m128i b) + /// PCMPGTQ xmm, xmm/m128 + /// + public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) => CompareGreaterThan(left, right); + + /// + /// unsigned int _mm_crc32_u8 (unsigned int crc, unsigned char v) + /// CRC32 reg, reg/m8 + /// + public static uint Crc32(uint crc, byte data) => Crc32(crc, data); + /// + /// unsigned int _mm_crc32_u16 (unsigned int crc, unsigned short v) + /// CRC32 reg, reg/m16 + /// + public static uint Crc32(uint crc, ushort data) => Crc32(crc, data); + /// + /// unsigned int _mm_crc32_u32 (unsigned int crc, unsigned int v) + /// CRC32 reg, reg/m32 + /// + public static uint Crc32(uint crc, uint data) => Crc32(crc, data); + /// + /// unsigned __int64 _mm_crc32_u64 (unsigned __int64 crc, unsigned __int64 v) + /// CRC32 reg, reg/m64 + /// + public static ulong Crc32(ulong crc, ulong data) => Crc32(crc, data); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Ssse3.PlatformNotSupported.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Ssse3.PlatformNotSupported.cs new file mode 100644 index 0000000000..a99f7f6a67 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Ssse3.PlatformNotSupported.cs @@ -0,0 +1,116 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel SSSE3 hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Ssse3 : Sse3 + { + internal Ssse3() { } + + public new static bool IsSupported { get { return false; } } + + /// + /// __m128i _mm_abs_epi8 (__m128i a) + /// PABSB xmm, xmm/m128 + /// + public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_abs_epi16 (__m128i a) + /// PABSW xmm, xmm/m128 + /// + public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_abs_epi32 (__m128i a) + /// PABSD xmm, xmm/m128 + /// + public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_alignr_epi8 (__m128i a, __m128i b, int count) + /// PALIGNR xmm, xmm/m128, imm8 + /// + public static Vector128 AlignRight(Vector128 left, Vector128 right, byte mask) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_hadd_epi16 (__m128i a, __m128i b) + /// PHADDW xmm, xmm/m128 + /// + public static Vector128 HorizontalAdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_hadd_epi32 (__m128i a, __m128i b) + /// PHADDD xmm, xmm/m128 + /// + public static Vector128 HorizontalAdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_hadds_epi16 (__m128i a, __m128i b) + /// PHADDSW xmm, xmm/m128 + /// + public static Vector128 HorizontalAddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_hsub_epi16 (__m128i a, __m128i b) + /// PHSUBW xmm, xmm/m128 + /// + public static Vector128 HorizontalSubtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_hsub_epi32 (__m128i a, __m128i b) + /// PHSUBD xmm, xmm/m128 + /// + public static Vector128 HorizontalSubtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_hsubs_epi16 (__m128i a, __m128i b) + /// PHSUBSW xmm, xmm/m128 + /// + public static Vector128 HorizontalSubtractSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_maddubs_epi16 (__m128i a, __m128i b) + /// PMADDUBSW xmm, xmm/m128 + /// + public static Vector128 MultiplyAddAdjacent(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_mulhrs_epi16 (__m128i a, __m128i b) + /// PMULHRSW xmm, xmm/m128 + /// + public static Vector128 MultiplyHighRoundScale(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_shuffle_epi8 (__m128i a, __m128i b) + /// PSHUFB xmm, xmm/m128 + /// + public static Vector128 Shuffle(Vector128 value, Vector128 mask) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_shuffle_epi8 (__m128i a, __m128i b) + /// PSHUFB xmm, xmm/m128 + /// + public static Vector128 Shuffle(Vector128 value, Vector128 mask) { throw new PlatformNotSupportedException(); } + + /// + /// __m128i _mm_sign_epi8 (__m128i a, __m128i b) + /// PSIGNB xmm, xmm/m128 + /// + public static Vector128 Sign(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sign_epi16 (__m128i a, __m128i b) + /// PSIGNW xmm, xmm/m128 + /// + public static Vector128 Sign(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_sign_epi32 (__m128i a, __m128i b) + /// PSIGND xmm, xmm/m128 + /// + public static Vector128 Sign(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Ssse3.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Ssse3.cs new file mode 100644 index 0000000000..6fd7778877 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Ssse3.cs @@ -0,0 +1,116 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.X86 +{ + /// + /// This class provides access to Intel SSSE3 hardware instructions via intrinsics + /// + [CLSCompliant(false)] + public abstract class Ssse3 : Sse3 + { + internal Ssse3() { } + + public new static bool IsSupported { get => IsSupported; } + + /// + /// __m128i _mm_abs_epi8 (__m128i a) + /// PABSB xmm, xmm/m128 + /// + public static Vector128 Abs(Vector128 value) => Abs(value); + /// + /// __m128i _mm_abs_epi16 (__m128i a) + /// PABSW xmm, xmm/m128 + /// + public static Vector128 Abs(Vector128 value) => Abs(value); + /// + /// __m128i _mm_abs_epi32 (__m128i a) + /// PABSD xmm, xmm/m128 + /// + public static Vector128 Abs(Vector128 value) => Abs(value); + + /// + /// __m128i _mm_alignr_epi8 (__m128i a, __m128i b, int count) + /// PALIGNR xmm, xmm/m128, imm8 + /// + public static Vector128 AlignRight(Vector128 left, Vector128 right, byte mask) => AlignRight(left, right, mask); + + /// + /// __m128i _mm_hadd_epi16 (__m128i a, __m128i b) + /// PHADDW xmm, xmm/m128 + /// + public static Vector128 HorizontalAdd(Vector128 left, Vector128 right) => HorizontalAdd(left, right); + /// + /// __m128i _mm_hadd_epi32 (__m128i a, __m128i b) + /// PHADDD xmm, xmm/m128 + /// + public static Vector128 HorizontalAdd(Vector128 left, Vector128 right) => HorizontalAdd(left, right); + + /// + /// __m128i _mm_hadds_epi16 (__m128i a, __m128i b) + /// PHADDSW xmm, xmm/m128 + /// + public static Vector128 HorizontalAddSaturate(Vector128 left, Vector128 right) => HorizontalAddSaturate(left, right); + + /// + /// __m128i _mm_hsub_epi16 (__m128i a, __m128i b) + /// PHSUBW xmm, xmm/m128 + /// + public static Vector128 HorizontalSubtract(Vector128 left, Vector128 right) => HorizontalSubtract(left, right); + /// + /// __m128i _mm_hsub_epi32 (__m128i a, __m128i b) + /// PHSUBD xmm, xmm/m128 + /// + public static Vector128 HorizontalSubtract(Vector128 left, Vector128 right) => HorizontalSubtract(left, right); + + /// + /// __m128i _mm_hsubs_epi16 (__m128i a, __m128i b) + /// PHSUBSW xmm, xmm/m128 + /// + public static Vector128 HorizontalSubtractSaturate(Vector128 left, Vector128 right) => HorizontalSubtractSaturate(left, right); + + /// + /// __m128i _mm_maddubs_epi16 (__m128i a, __m128i b) + /// PMADDUBSW xmm, xmm/m128 + /// + public static Vector128 MultiplyAddAdjacent(Vector128 left, Vector128 right) => MultiplyAddAdjacent(left, right); + + /// + /// __m128i _mm_mulhrs_epi16 (__m128i a, __m128i b) + /// PMULHRSW xmm, xmm/m128 + /// + public static Vector128 MultiplyHighRoundScale(Vector128 left, Vector128 right) => MultiplyHighRoundScale(left, right); + + /// + /// __m128i _mm_shuffle_epi8 (__m128i a, __m128i b) + /// PSHUFB xmm, xmm/m128 + /// + public static Vector128 Shuffle(Vector128 value, Vector128 mask) => Shuffle(value, mask); + + /// + /// __m128i _mm_shuffle_epi8 (__m128i a, __m128i b) + /// PSHUFB xmm, xmm/m128 + /// + public static Vector128 Shuffle(Vector128 value, Vector128 mask) => Shuffle(value, mask); + + /// + /// __m128i _mm_sign_epi8 (__m128i a, __m128i b) + /// PSIGNB xmm, xmm/m128 + /// + public static Vector128 Sign(Vector128 left, Vector128 right) => Sign(left, right); + /// + /// __m128i _mm_sign_epi16 (__m128i a, __m128i b) + /// PSIGNW xmm, xmm/m128 + /// + public static Vector128 Sign(Vector128 left, Vector128 right) => Sign(left, right); + /// + /// __m128i _mm_sign_epi32 (__m128i a, __m128i b) + /// PSIGND xmm, xmm/m128 + /// + public static Vector128 Sign(Vector128 left, Vector128 right) => Sign(left, right); + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs new file mode 100644 index 0000000000..a47aaf9ca1 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs @@ -0,0 +1,25 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Runtime.Remoting +{ + public class ObjectHandle : MarshalByRefObject + { + private object _wrappedObject; + + private ObjectHandle() + { + } + + public ObjectHandle(object o) + { + _wrappedObject = o; + } + + public object Unwrap() + { + return _wrappedObject; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationException.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationException.cs index 1c9c21eabb..92c01ee30f 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationException.cs @@ -10,7 +10,7 @@ namespace System.Runtime.Serialization [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SerializationException : SystemException { - private static String s_nullMessage = SR.SerializationException; + private static string s_nullMessage = SR.SerializationException; // Creates a new SerializationException with its message // string set to a default message. @@ -20,13 +20,13 @@ namespace System.Runtime.Serialization HResult = HResults.COR_E_SERIALIZATION; } - public SerializationException(String message) + public SerializationException(string message) : base(message) { HResult = HResults.COR_E_SERIALIZATION; } - public SerializationException(String message, Exception innerException) + public SerializationException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_SERIALIZATION; diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs similarity index 76% rename from external/corert/src/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs index 7bb19995ba..a97418963d 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs @@ -1,13 +1,13 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; -using System.Reflection; namespace System.Runtime.Serialization { + /// The structure for holding all of the data needed for object serialization and deserialization. public sealed class SerializationInfo { private const int DefaultSize = 4; @@ -19,19 +19,19 @@ namespace System.Runtime.Serialization private Type[] _types; private int _count; private Dictionary _nameToIndex; - private IFormatterConverter _converter; private string _rootTypeName; private string _rootTypeAssemblyName; private Type _rootType; [CLSCompliant(false)] - public SerializationInfo(Type type, IFormatterConverter converter) + public SerializationInfo(Type type, IFormatterConverter converter) { - if (type == null) + if ((object)type == null) { throw new ArgumentNullException(nameof(type)); } + if (converter == null) { throw new ArgumentNullException(nameof(converter)); @@ -44,7 +44,9 @@ namespace System.Runtime.Serialization _names = new string[DefaultSize]; _values = new object[DefaultSize]; _types = new Type[DefaultSize]; + _nameToIndex = new Dictionary(); + _converter = converter; } @@ -79,7 +81,6 @@ namespace System.Runtime.Serialization { throw new ArgumentNullException(nameof(value)); } - _rootTypeAssemblyName = value; IsAssemblyNameSetExplicit = true; } @@ -91,7 +92,7 @@ namespace System.Runtime.Serialization public void SetType(Type type) { - if (type == null) + if ((object)type == null) { throw new ArgumentNullException(nameof(type)); } @@ -115,7 +116,7 @@ namespace System.Runtime.Serialization private void ExpandArrays() { int newSize; - Debug.Assert(_names.Length == _count); + Debug.Assert(_names.Length == _count, "[SerializationInfo.ExpandArrays]_names.Length == _count"); newSize = (_count * 2); @@ -129,40 +130,20 @@ namespace System.Runtime.Serialization } // Allocate more space and copy the data - string[] newMembers = new string[newSize]; - Array.Copy(_names, 0, newMembers, 0, _count); - _names = newMembers; - object[] newData = new object[newSize]; - Array.Copy(_values, 0, newData, 0, _count); - _values = newData; - Type[] newTypes = new Type[newSize]; - Array.Copy(_types, 0, newTypes, 0, _count); + + Array.Copy(_names, newMembers, _count); + Array.Copy(_values, newData, _count); + Array.Copy(_types, newTypes, _count); + + // Assign the new arrays back to the member vars. + _names = newMembers; + _values = newData; _types = newTypes; } - // This isn't a public API, but it gets invoked dynamically by - // BinaryFormatter - public void UpdateValue(string name, object value, Type type) - { - Debug.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null"); - Debug.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null"); - Debug.Assert(null != type, "[SerializationInfo.UpdateValue]type!=null"); - - int index = FindElement(name); - if (index < 0) - { - AddValueInternal(name, value, type); - } - else - { - _values[index] = value; - _types[index] = type; - } - } - public void AddValue(string name, object value, Type type) { if (null == name) @@ -170,7 +151,7 @@ namespace System.Runtime.Serialization throw new ArgumentNullException(nameof(name)); } - if (type == null) + if ((object)type == null) { throw new ArgumentNullException(nameof(type)); } @@ -192,76 +173,76 @@ namespace System.Runtime.Serialization public void AddValue(string name, bool value) { - AddValue(name, value, typeof(bool)); + AddValue(name, (object)value, typeof(bool)); } public void AddValue(string name, char value) { - AddValue(name, value, typeof(char)); + AddValue(name, (object)value, typeof(char)); } [CLSCompliant(false)] public void AddValue(string name, sbyte value) { - AddValue(name, value, typeof(sbyte)); + AddValue(name, (object)value, typeof(sbyte)); } public void AddValue(string name, byte value) { - AddValue(name, value, typeof(byte)); + AddValue(name, (object)value, typeof(byte)); } public void AddValue(string name, short value) { - AddValue(name, value, typeof(short)); + AddValue(name, (object)value, typeof(short)); } [CLSCompliant(false)] public void AddValue(string name, ushort value) { - AddValue(name, value, typeof(ushort)); + AddValue(name, (object)value, typeof(ushort)); } public void AddValue(string name, int value) { - AddValue(name, value, typeof(int)); + AddValue(name, (object)value, typeof(int)); } [CLSCompliant(false)] public void AddValue(string name, uint value) { - AddValue(name, value, typeof(uint)); + AddValue(name, (object)value, typeof(uint)); } public void AddValue(string name, long value) { - AddValue(name, value, typeof(long)); + AddValue(name, (object)value, typeof(long)); } [CLSCompliant(false)] public void AddValue(string name, ulong value) { - AddValue(name, value, typeof(ulong)); + AddValue(name, (object)value, typeof(ulong)); } public void AddValue(string name, float value) { - AddValue(name, value, typeof(float)); + AddValue(name, (object)value, typeof(float)); } public void AddValue(string name, double value) { - AddValue(name, value, typeof(double)); + AddValue(name, (object)value, typeof(double)); } public void AddValue(string name, decimal value) { - AddValue(name, value, typeof(decimal)); + AddValue(name, (object)value, typeof(decimal)); } public void AddValue(string name, DateTime value) { - AddValue(name, value, typeof(DateTime)); + AddValue(name, (object)value, typeof(DateTime)); } internal void AddValueInternal(string name, object value, Type type) @@ -285,13 +266,48 @@ namespace System.Runtime.Serialization _count++; } + /// + /// Finds the value if it exists in the current data. If it does, we replace + /// the values, if not, we append it to the end. This is useful to the + /// ObjectManager when it's performing fixups. + /// + /// All error checking is done with asserts. Although public in coreclr, + /// it's not exposed in a contract and is only meant to be used by corefx. + /// + /// This isn't a public API, but it gets invoked dynamically by + /// BinaryFormatter + /// + /// This should not be used by clients: exposing out this functionality would allow children + /// to overwrite their parent's values. It is public in order to give corefx access to it for + /// its ObjectManager implementation, but it should not be exposed out of a contract. + /// + /// The name of the data to be updated. + /// The new value. + /// The type of the data being added. + public void UpdateValue(string name, object value, Type type) + { + Debug.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null"); + Debug.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null"); + Debug.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null"); + + int index = FindElement(name); + if (index < 0) + { + AddValueInternal(name, value, type); + } + else + { + _values[index] = value; + _types[index] = type; + } + } + private int FindElement(string name) { if (null == name) { throw new ArgumentNullException(nameof(name)); } - int index; if (_nameToIndex.TryGetValue(name, out index)) { @@ -300,6 +316,14 @@ namespace System.Runtime.Serialization return -1; } + /// + /// Gets the location of a particular member and then returns + /// the value of the element at that location. The type of the member is + /// returned in the foundType field. + /// + /// The name of the element to find. + /// The type of the element associated with the given name. + /// The value of the element at the position associated with name. private object GetElement(string name, out Type foundType) { int index = FindElement(name); @@ -308,11 +332,11 @@ namespace System.Runtime.Serialization throw new SerializationException(SR.Format(SR.Serialization_NotFound, name)); } - Debug.Assert(index < _values.Length); - Debug.Assert(index < _types.Length); + Debug.Assert(index < _values.Length, "[SerializationInfo.GetElement]index<_values.Length"); + Debug.Assert(index < _types.Length, "[SerializationInfo.GetElement]index<_types.Length"); foundType = _types[index]; - Debug.Assert(foundType != null); + Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null"); return _values[index]; } @@ -325,40 +349,46 @@ namespace System.Runtime.Serialization return null; } - Debug.Assert(index < _values.Length, "[SerializationInfo.GetElement]index, IEquatable, ISpanFormattable + public readonly struct SByte : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private sbyte m_value; // Do not rename (binary serialization) + private readonly sbyte m_value; // Do not rename (binary serialization) // The maximum value that a Byte may represent: 127. public const sbyte MaxValue = (sbyte)0x7F; @@ -29,36 +29,36 @@ namespace System // null is considered to be less than any instance. // If object is not of type SByte, this method throws an ArgumentException. // - public int CompareTo(Object obj) + public int CompareTo(object obj) { if (obj == null) { return 1; } - if (!(obj is SByte)) + if (!(obj is sbyte)) { throw new ArgumentException(SR.Arg_MustBeSByte); } - return m_value - ((SByte)obj).m_value; + return m_value - ((sbyte)obj).m_value; } - public int CompareTo(SByte value) + public int CompareTo(sbyte value) { return m_value - value; } // Determines whether two Byte objects are equal. - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is SByte)) + if (!(obj is sbyte)) { return false; } - return m_value == ((SByte)obj).m_value; + return m_value == ((sbyte)obj).m_value; } [NonVersionable] - public bool Equals(SByte obj) + public bool Equals(sbyte obj) { return m_value == obj; } @@ -71,22 +71,22 @@ namespace System // Provides a string representation of a byte. - public override String ToString() + public override string ToString() { return Number.FormatInt32(m_value, null, null); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatInt32(m_value, null, provider); } - public String ToString(String format) + public string ToString(string format) { return ToString(format, null); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { @@ -107,14 +107,14 @@ namespace System } [CLSCompliant(false)] - public static sbyte Parse(String s) + public static sbyte Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] - public static sbyte Parse(String s, NumberStyles style) + public static sbyte Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -122,7 +122,7 @@ namespace System } [CLSCompliant(false)] - public static sbyte Parse(String s, IFormatProvider provider) + public static sbyte Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); @@ -133,7 +133,7 @@ namespace System // NumberFormatInfo is assumed. // [CLSCompliant(false)] - public static sbyte Parse(String s, NumberStyles style, IFormatProvider provider) + public static sbyte Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -147,7 +147,7 @@ namespace System return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } - private static sbyte Parse(String s, NumberStyles style, NumberFormatInfo info) + private static sbyte Parse(string s, NumberStyles style, NumberFormatInfo info) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, style, info); @@ -167,7 +167,7 @@ namespace System if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number - if ((i < 0) || i > Byte.MaxValue) + if ((i < 0) || i > byte.MaxValue) { throw new OverflowException(SR.Overflow_SByte); } @@ -179,7 +179,7 @@ namespace System } [CLSCompliant(false)] - public static bool TryParse(String s, out SByte result) + public static bool TryParse(string s, out sbyte result) { if (s == null) { @@ -197,7 +197,7 @@ namespace System } [CLSCompliant(false)] - public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out SByte result) + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out sbyte result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -217,7 +217,7 @@ namespace System return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } - private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out SByte result) + private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out sbyte result) { result = 0; int i; @@ -228,7 +228,7 @@ namespace System if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number - if ((i < 0) || i > Byte.MaxValue) + if ((i < 0) || i > byte.MaxValue) { return false; } @@ -314,7 +314,7 @@ namespace System return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -324,7 +324,7 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "SByte", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Security/AccessControl/RegistryRights.cs b/external/corert/src/System.Private.CoreLib/shared/System/Security/AccessControl/RegistryRights.cs new file mode 100644 index 0000000000..729e2f6b58 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Security/AccessControl/RegistryRights.cs @@ -0,0 +1,42 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.Win32; + +namespace System.Security.AccessControl +{ + // We derived this enum from the definitions of KEY_READ and such from + // winnt.h and from MSDN, plus some experimental validation with regedit. + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/registry_key_security_and_access_rights.asp + [Flags] +#if REGISTRY_ASSEMBLY + public +#else + internal +#endif + enum RegistryRights + { + // No None field - An ACE with the value 0 cannot grant nor deny. + QueryValues = Interop.Advapi32.RegistryOperations.KEY_QUERY_VALUE, // 0x0001 query the values of a registry key + SetValue = Interop.Advapi32.RegistryOperations.KEY_SET_VALUE, // 0x0002 create, delete, or set a registry value + CreateSubKey = Interop.Advapi32.RegistryOperations.KEY_CREATE_SUB_KEY, // 0x0004 required to create a subkey of a specific key + EnumerateSubKeys = Interop.Advapi32.RegistryOperations.KEY_ENUMERATE_SUB_KEYS, // 0x0008 required to enumerate sub keys of a key + Notify = Interop.Advapi32.RegistryOperations.KEY_NOTIFY, // 0x0010 needed to request change notifications + CreateLink = Interop.Advapi32.RegistryOperations.KEY_CREATE_LINK, // 0x0020 reserved for system use + /// + /// The Windows Kernel team agrees that it was a bad design to expose the WOW64_n options as permissions. + /// in the .NET Framework these options are exposed via the RegistryView enum + /// + /// Reg64 = Interop.Advapi32.RegistryOptions.KEY_WOW64_64KEY, // 0x0100 operate on the 64-bit registry view + /// Reg32 = Interop.Advapi32.RegistryOptions.KEY_WOW64_32KEY, // 0x0200 operate on the 32-bit registry view + ExecuteKey = ReadKey, + ReadKey = Interop.Advapi32.RegistryOperations.STANDARD_RIGHTS_READ | QueryValues | EnumerateSubKeys | Notify, + WriteKey = Interop.Advapi32.RegistryOperations.STANDARD_RIGHTS_WRITE | SetValue | CreateSubKey, + Delete = 0x10000, + ReadPermissions = 0x20000, + ChangePermissions = 0x40000, + TakeOwnership = 0x80000, + FullControl = 0xF003F | Interop.Advapi32.RegistryOperations.STANDARD_RIGHTS_READ | Interop.Advapi32.RegistryOperations.STANDARD_RIGHTS_WRITE + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Security/SafeBSTRHandle.cs b/external/corert/src/System.Private.CoreLib/shared/System/Security/SafeBSTRHandle.cs index 227fed3fc3..bc93fecef1 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Security/SafeBSTRHandle.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Security/SafeBSTRHandle.cs @@ -50,7 +50,7 @@ namespace System.Security internal unsafe uint Length => Interop.OleAut32.SysStringLen(this); - internal unsafe static void Copy(SafeBSTRHandle source, SafeBSTRHandle target, uint bytesToCopy) + internal static unsafe void Copy(SafeBSTRHandle source, SafeBSTRHandle target, uint bytesToCopy) { if (bytesToCopy == 0) { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Security/SecureString.Unix.cs b/external/corert/src/System.Private.CoreLib/shared/System/Security/SecureString.Unix.cs index cfeebc1daf..ad14bcd296 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Security/SecureString.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Security/SecureString.Unix.cs @@ -70,14 +70,6 @@ namespace System.Security } } - private void EnsureNotDisposed() - { - if (_buffer == null) - { - throw new ObjectDisposedException(GetType().Name); - } - } - private void ClearCore() { _decryptedLength = 0; @@ -143,7 +135,7 @@ namespace System.Security _buffer.Write((ulong)(index * sizeof(char)), c); } - internal unsafe IntPtr MarshalToBSTR() + internal unsafe IntPtr MarshalToBSTRCore() { int length = _decryptedLength; IntPtr ptr = IntPtr.Zero; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Security/SecureString.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/System/Security/SecureString.Windows.cs index 2a80081912..a78fbc222c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Security/SecureString.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Security/SecureString.Windows.cs @@ -6,7 +6,6 @@ using System.Diagnostics; using System.Runtime; using System.Runtime.InteropServices; using System.Security.Cryptography; -using Microsoft.Win32; namespace System.Security { @@ -145,7 +144,7 @@ namespace System.Security } } - internal unsafe IntPtr MarshalToBSTR() + internal unsafe IntPtr MarshalToBSTRCore() { int length = _decryptedLength; IntPtr ptr = IntPtr.Zero; @@ -232,14 +231,6 @@ namespace System.Security return result; } - private void EnsureNotDisposed() - { - if (_buffer == null) - { - throw new ObjectDisposedException(GetType().Name); - } - } - // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Security/SecureString.cs b/external/corert/src/System.Private.CoreLib/shared/System/Security/SecureString.cs index 22f15accaa..cdee9c9076 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Security/SecureString.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Security/SecureString.cs @@ -139,7 +139,7 @@ namespace System.Security { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexString); } - Debug.Assert(index <= Int32.MaxValue / sizeof(char)); + Debug.Assert(index <= int.MaxValue / sizeof(char)); EnsureNotDisposed(); EnsureNotReadOnly(); @@ -156,6 +156,23 @@ namespace System.Security } } + private void EnsureNotDisposed() + { + if (_buffer == null) + { + throw new ObjectDisposedException(GetType().Name); + } + } + + internal IntPtr MarshalToBSTR() + { + lock (_methodLock) + { + EnsureNotDisposed(); + return MarshalToBSTRCore(); + } + } + internal unsafe IntPtr MarshalToString(bool globalAlloc, bool unicode) { lock (_methodLock) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Single.cs b/external/corert/src/System.Private.CoreLib/shared/System/Single.cs index 7bffa1ac77..8d1788f731 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Single.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Single.cs @@ -23,9 +23,9 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Single : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct Single : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private float m_value; // Do not rename (binary serialization) + private readonly float m_value; // Do not rename (binary serialization) // // Public constants @@ -52,7 +52,7 @@ namespace System /// Determines whether the specified value is infinite. [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static bool IsInfinity(float f) + public static unsafe bool IsInfinity(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) == 0x7F800000; @@ -61,7 +61,7 @@ namespace System /// Determines whether the specified value is NaN. [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static bool IsNaN(float f) + public static unsafe bool IsNaN(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) > 0x7F800000; @@ -70,16 +70,15 @@ namespace System /// Determines whether the specified value is negative. [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static bool IsNegative(float f) + public static unsafe bool IsNegative(float f) { - var bits = unchecked((uint)BitConverter.SingleToInt32Bits(f)); - return (bits & 0x80000000) == 0x80000000; + return BitConverter.SingleToInt32Bits(f) < 0; } /// Determines whether the specified value is negative infinity. [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static bool IsNegativeInfinity(float f) + public static unsafe bool IsNegativeInfinity(float f) { return (f == float.NegativeInfinity); } @@ -87,7 +86,7 @@ namespace System /// Determines whether the specified value is normal. [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called - public unsafe static bool IsNormal(float f) + public static unsafe bool IsNormal(float f) { var bits = BitConverter.SingleToInt32Bits(f); bits &= 0x7FFFFFFF; @@ -97,7 +96,7 @@ namespace System /// Determines whether the specified value is positive infinity. [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe static bool IsPositiveInfinity(float f) + public static unsafe bool IsPositiveInfinity(float f) { return (f == float.PositiveInfinity); } @@ -105,7 +104,7 @@ namespace System /// Determines whether the specified value is subnormal. [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called - public unsafe static bool IsSubnormal(float f) + public static unsafe bool IsSubnormal(float f) { var bits = BitConverter.SingleToInt32Bits(f); bits &= 0x7FFFFFFF; @@ -118,13 +117,13 @@ namespace System // null is considered to be less than any instance. // If object is not of type Single, this method throws an ArgumentException. // - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) { return 1; } - if (value is Single) + if (value is float) { float f = (float)value; if (m_value < f) return -1; @@ -141,7 +140,7 @@ namespace System } - public int CompareTo(Single value) + public int CompareTo(float value) { if (m_value < value) return -1; if (m_value > value) return 1; @@ -155,48 +154,48 @@ namespace System } [NonVersionable] - public static bool operator ==(Single left, Single right) + public static bool operator ==(float left, float right) { return left == right; } [NonVersionable] - public static bool operator !=(Single left, Single right) + public static bool operator !=(float left, float right) { return left != right; } [NonVersionable] - public static bool operator <(Single left, Single right) + public static bool operator <(float left, float right) { return left < right; } [NonVersionable] - public static bool operator >(Single left, Single right) + public static bool operator >(float left, float right) { return left > right; } [NonVersionable] - public static bool operator <=(Single left, Single right) + public static bool operator <=(float left, float right) { return left <= right; } [NonVersionable] - public static bool operator >=(Single left, Single right) + public static bool operator >=(float left, float right) { return left >= right; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is Single)) + if (!(obj is float)) { return false; } - float temp = ((Single)obj).m_value; + float temp = ((float)obj).m_value; if (temp == m_value) { return true; @@ -205,7 +204,7 @@ namespace System return IsNaN(temp) && IsNaN(m_value); } - public bool Equals(Single obj) + public bool Equals(float obj) { if (obj == m_value) { @@ -217,7 +216,7 @@ namespace System public override int GetHashCode() { - var bits = Unsafe.As(ref m_value); + var bits = Unsafe.As(ref Unsafe.AsRef(in m_value)); // Optimized check for IsNan() || IsZero() if (((bits - 1) & 0x7FFFFFFF) >= 0x7F800000) @@ -229,22 +228,22 @@ namespace System return bits; } - public override String ToString() + public override string ToString() { return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider)); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider)); } @@ -262,39 +261,39 @@ namespace System // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. // - public static float Parse(String s) + public static float Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } - public static float Parse(String s, NumberStyles style) + public static float Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, style, NumberFormatInfo.CurrentInfo); } - public static float Parse(String s, IFormatProvider provider) + public static float Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } - public static float Parse(String s, NumberStyles style, IFormatProvider provider) + public static float Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider)); } - public static float Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) + public static float Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Float | NumberStyles.AllowThousands, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider)); } - public static Boolean TryParse(String s, out Single result) + public static bool TryParse(string s, out float result) { if (s == null) { @@ -310,7 +309,7 @@ namespace System return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } - public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Single result) + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out float result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); @@ -329,21 +328,21 @@ namespace System return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } - private static Boolean TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out Single result) + private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out float result) { bool success = Number.TryParseSingle(s, style, info, out result); if (!success) { ReadOnlySpan sTrim = s.Trim(); - if (StringSpanHelpers.Equals(sTrim, info.PositiveInfinitySymbol)) + if (sTrim.EqualsOrdinal(info.PositiveInfinitySymbol)) { result = PositiveInfinity; } - else if (StringSpanHelpers.Equals(sTrim, info.NegativeInfinitySymbol)) + else if (sTrim.EqualsOrdinal(info.NegativeInfinitySymbol)) { result = NegativeInfinity; } - else if (StringSpanHelpers.Equals(sTrim, info.NaNSymbol)) + else if (sTrim.EqualsOrdinal(info.NaNSymbol)) { result = NaN; } @@ -425,7 +424,7 @@ namespace System return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -435,7 +434,7 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Span.Fast.cs b/external/corert/src/System.Private.CoreLib/shared/System/Span.Fast.cs index 0ae1922fd4..b3cfc8daff 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Span.Fast.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Span.Fast.cs @@ -2,10 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Versioning; +using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; +using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using Internal.Runtime.CompilerServices; #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span.Equals(object)' overrides non-obsolete member 'object.Equals(object)' @@ -22,8 +23,6 @@ namespace System /// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed /// or native memory, or to memory allocated on the stack. It is type- and memory-safe. /// - [DebuggerTypeProxy(typeof(SpanDebugView<>))] - [DebuggerDisplay("{ToString(),raw}")] [NonVersionable] public readonly ref partial struct Span { @@ -154,6 +153,13 @@ namespace System #endif } + /// + /// Returns a reference to the 0th element of the Span. If the Span is empty, returns null reference. + /// It can be used for pinning and is required to support the use of span within a fixed statement. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe ref T GetPinnableReference() => ref (_length != 0) ? ref _pointer.Value : ref Unsafe.AsRef(null); + /// /// Clears the contents of this span. /// @@ -232,6 +238,7 @@ namespace System /// /// Thrown when the destination Span is shorter than the source Span. /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(Span destination) { // Using "if (!TryCopyTo(...))" results in two branches: one for the length @@ -283,7 +290,7 @@ namespace System /// /// For , returns a new instance of string that represents the characters pointed to by the span. - /// Otherwise, returns a with the name of the type and the number of elements. + /// Otherwise, returns a with the name of the type and the number of elements. /// public override string ToString() { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Span.cs b/external/corert/src/System.Private.CoreLib/shared/System/Span.cs index 78733515cd..185042fb55 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Span.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Span.cs @@ -5,9 +5,8 @@ using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; -#if !FEATURE_PORTABLE_SPAN + using System.Runtime.Versioning; -#endif // !FEATURE_PORTABLE_SPAN #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span.Equals(object)' overrides non-obsolete member 'object.Equals(object)' @@ -26,9 +25,7 @@ namespace System /// public int Length { -#if !FEATURE_PORTABLE_SPAN [NonVersionable] -#endif // !FEATURE_PORTABLE_SPAN get { return _length; @@ -40,12 +37,11 @@ namespace System /// public bool IsEmpty { -#if !FEATURE_PORTABLE_SPAN [NonVersionable] -#endif // !FEATURE_PORTABLE_SPAN get { - return _length == 0; + // Workaround for https://github.com/dotnet/coreclr/issues/19620 + return 0 >= (uint)_length; } } @@ -89,13 +85,13 @@ namespace System /// /// Defines an implicit conversion of a to a /// - public static implicit operator Span(ArraySegment arraySegment) - => new Span(arraySegment.Array, arraySegment.Offset, arraySegment.Count); + public static implicit operator Span(ArraySegment segment) + => new Span(segment.Array, segment.Offset, segment.Count); /// /// Returns an empty /// - public static Span Empty => default(Span); + public static Span Empty => default; /// Gets an enumerator for this span. public Enumerator GetEnumerator() => new Enumerator(this); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/SpanDebugView.cs b/external/corert/src/System.Private.CoreLib/shared/System/SpanDebugView.cs index caa12ef9ed..f79c67306c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/SpanDebugView.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/SpanDebugView.cs @@ -3,8 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Reflection; -using System.Runtime.CompilerServices; namespace System { @@ -14,7 +12,7 @@ namespace System public SpanDebugView(Span span) { - _array = span.ToArray(); + _array = span.ToArray(); } public SpanDebugView(ReadOnlySpan span) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.BinarySearch.cs b/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.BinarySearch.cs index 656b864e22..2aec704096 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.BinarySearch.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.BinarySearch.cs @@ -6,9 +6,7 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -#if !netstandard using Internal.Runtime.CompilerServices; -#endif namespace System { @@ -26,7 +24,7 @@ namespace System } public static int BinarySearch( - ref T spanStart, int length, TComparable comparable) + ref T spanStart, int length, TComparable comparable) where TComparable : IComparable { int lo = 0; @@ -64,11 +62,11 @@ namespace System } // Helper to allow sharing all code via IComparable inlineable - internal struct ComparerComparable : IComparable + internal readonly struct ComparerComparable : IComparable where TComparer : IComparer { - readonly T _value; - readonly TComparer _comparer; + private readonly T _value; + private readonly TComparer _comparer; public ComparerComparable(T value, TComparer comparer) { diff --git a/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.Byte.cs b/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.Byte.cs index 860b2efa0b..373065363b 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.Byte.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.Byte.cs @@ -4,18 +4,19 @@ using System.Diagnostics; using System.Runtime.CompilerServices; - -#if !netstandard -using Internal.Runtime.CompilerServices; -#endif - -#if !netstandard11 using System.Numerics; -#endif + +using Internal.Runtime.CompilerServices; + +#if BIT64 +using nuint = System.UInt64; +#else +using nuint = System.UInt32; +#endif // BIT64 namespace System { - internal static partial class SpanHelpers + internal static partial class SpanHelpers // .Byte { public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { @@ -70,7 +71,8 @@ namespace System // Reduce space for search, cause we don't care if we find the search value after the index of a previously found value searchSpaceLength = tempIndex; - if (index == 0) break; + if (index == 0) + break; } } return index; @@ -88,48 +90,137 @@ namespace System for (int i = 0; i < valueLength; i++) { var tempIndex = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); - if (tempIndex > index) index = tempIndex; + if (tempIndex > index) + index = tempIndex; } return index; } + // Adapted from IndexOf(...) + public static unsafe bool Contains(ref byte searchSpace, byte value, int length) + { + Debug.Assert(length >= 0); + + uint uValue = value; // Use uint for comparisons to avoid unnecessary 8->32 extensions + IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations + IntPtr nLength = (IntPtr)length; + + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) + { + int unaligned = (int)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); + nLength = (IntPtr)((Vector.Count - unaligned) & (Vector.Count - 1)); + } + + SequentialScan: + while ((byte*)nLength >= (byte*)8) + { + nLength -= 8; + + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 0) || + uValue == Unsafe.AddByteOffset(ref searchSpace, index + 1) || + uValue == Unsafe.AddByteOffset(ref searchSpace, index + 2) || + uValue == Unsafe.AddByteOffset(ref searchSpace, index + 3) || + uValue == Unsafe.AddByteOffset(ref searchSpace, index + 4) || + uValue == Unsafe.AddByteOffset(ref searchSpace, index + 5) || + uValue == Unsafe.AddByteOffset(ref searchSpace, index + 6) || + uValue == Unsafe.AddByteOffset(ref searchSpace, index + 7)) + { + goto Found; + } + + index += 8; + } + + if ((byte*)nLength >= (byte*)4) + { + nLength -= 4; + + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 0) || + uValue == Unsafe.AddByteOffset(ref searchSpace, index + 1) || + uValue == Unsafe.AddByteOffset(ref searchSpace, index + 2) || + uValue == Unsafe.AddByteOffset(ref searchSpace, index + 3)) + { + goto Found; + } + + index += 4; + } + + while ((byte*)nLength > (byte*)0) + { + nLength -= 1; + + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index)) + goto Found; + + index += 1; + } + + if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length)) + { + nLength = (IntPtr)((length - (int)(byte*)index) & ~(Vector.Count - 1)); + + // Get comparison Vector + Vector vComparison = new Vector(value); + + while ((byte*)nLength > (byte*)index) + { + var vMatches = Vector.Equals(vComparison, Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref searchSpace, index))); + if (Vector.Zero.Equals(vMatches)) + { + index += Vector.Count; + continue; + } + + goto Found; + } + + if ((int)(byte*)index < length) + { + nLength = (IntPtr)(length - (int)(byte*)index); + goto SequentialScan; + } + } + + return false; + + Found: + return true; + } + public static unsafe int IndexOf(ref byte searchSpace, byte value, int length) { Debug.Assert(length >= 0); uint uValue = value; // Use uint for comparisons to avoid unnecessary 8->32 extensions - IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations - IntPtr nLength = (IntPtr)(uint)length; -#if !netstandard11 + IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations + IntPtr nLength = (IntPtr)length; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { - unchecked - { - int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); - nLength = (IntPtr)(uint)((Vector.Count - unaligned) & (Vector.Count - 1)); - } + int unaligned = (int)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); + nLength = (IntPtr)((Vector.Count - unaligned) & (Vector.Count - 1)); } SequentialScan: -#endif while ((byte*)nLength >= (byte*)8) { nLength -= 8; - if (uValue == Unsafe.Add(ref searchSpace, index)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index)) goto Found; - if (uValue == Unsafe.Add(ref searchSpace, index + 1)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 1)) goto Found1; - if (uValue == Unsafe.Add(ref searchSpace, index + 2)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 2)) goto Found2; - if (uValue == Unsafe.Add(ref searchSpace, index + 3)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 3)) goto Found3; - if (uValue == Unsafe.Add(ref searchSpace, index + 4)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 4)) goto Found4; - if (uValue == Unsafe.Add(ref searchSpace, index + 5)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 5)) goto Found5; - if (uValue == Unsafe.Add(ref searchSpace, index + 6)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 6)) goto Found6; - if (uValue == Unsafe.Add(ref searchSpace, index + 7)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 7)) goto Found7; index += 8; @@ -139,13 +230,13 @@ namespace System { nLength -= 4; - if (uValue == Unsafe.Add(ref searchSpace, index)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index)) goto Found; - if (uValue == Unsafe.Add(ref searchSpace, index + 1)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 1)) goto Found1; - if (uValue == Unsafe.Add(ref searchSpace, index + 2)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 2)) goto Found2; - if (uValue == Unsafe.Add(ref searchSpace, index + 3)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 3)) goto Found3; index += 4; @@ -155,17 +246,19 @@ namespace System { nLength -= 1; - if (uValue == Unsafe.Add(ref searchSpace, index)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index)) goto Found; index += 1; } -#if !netstandard11 + if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length)) { - nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector.Count - 1)); + nLength = (IntPtr)((length - (int)(byte*)index) & ~(Vector.Count - 1)); + // Get comparison Vector - Vector vComparison = GetVector(value); + Vector vComparison = new Vector(value); + while ((byte*)nLength > (byte*)index) { var vMatches = Vector.Equals(vComparison, Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref searchSpace, index))); @@ -180,14 +273,10 @@ namespace System if ((int)(byte*)index < length) { - unchecked - { - nLength = (IntPtr)(length - (int)(byte*)index); - } + nLength = (IntPtr)(length - (int)(byte*)index); goto SequentialScan; } } -#endif return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return (int)(byte*)index; @@ -246,39 +335,35 @@ namespace System Debug.Assert(length >= 0); uint uValue = value; // Use uint for comparisons to avoid unnecessary 8->32 extensions - IntPtr index = (IntPtr)(uint)length; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations - IntPtr nLength = (IntPtr)(uint)length; -#if !netstandard11 + IntPtr index = (IntPtr)length; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations + IntPtr nLength = (IntPtr)length; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { - unchecked - { - int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); - nLength = (IntPtr)(((length & (Vector.Count - 1)) + unaligned) & (Vector.Count - 1)); - } + int unaligned = (int)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); + nLength = (IntPtr)(((length & (Vector.Count - 1)) + unaligned) & (Vector.Count - 1)); } SequentialScan: -#endif while ((byte*)nLength >= (byte*)8) { nLength -= 8; index -= 8; - if (uValue == Unsafe.Add(ref searchSpace, index + 7)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 7)) goto Found7; - if (uValue == Unsafe.Add(ref searchSpace, index + 6)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 6)) goto Found6; - if (uValue == Unsafe.Add(ref searchSpace, index + 5)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 5)) goto Found5; - if (uValue == Unsafe.Add(ref searchSpace, index + 4)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 4)) goto Found4; - if (uValue == Unsafe.Add(ref searchSpace, index + 3)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 3)) goto Found3; - if (uValue == Unsafe.Add(ref searchSpace, index + 2)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 2)) goto Found2; - if (uValue == Unsafe.Add(ref searchSpace, index + 1)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 1)) goto Found1; - if (uValue == Unsafe.Add(ref searchSpace, index)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index)) goto Found; } @@ -287,13 +372,13 @@ namespace System nLength -= 4; index -= 4; - if (uValue == Unsafe.Add(ref searchSpace, index + 3)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 3)) goto Found3; - if (uValue == Unsafe.Add(ref searchSpace, index + 2)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 2)) goto Found2; - if (uValue == Unsafe.Add(ref searchSpace, index + 1)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 1)) goto Found1; - if (uValue == Unsafe.Add(ref searchSpace, index)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index)) goto Found; } @@ -302,16 +387,17 @@ namespace System nLength -= 1; index -= 1; - if (uValue == Unsafe.Add(ref searchSpace, index)) + if (uValue == Unsafe.AddByteOffset(ref searchSpace, index)) goto Found; } -#if !netstandard11 - if (Vector.IsHardwareAccelerated && ((int)(byte*)index > 0)) + + if (Vector.IsHardwareAccelerated && ((byte*)index > (byte*)0)) { - nLength = (IntPtr)(uint)((uint)index & ~(Vector.Count - 1)); + nLength = (IntPtr)((int)(byte*)index & ~(Vector.Count - 1)); // Get comparison Vector - Vector vComparison = GetVector(value); + Vector vComparison = new Vector(value); + while ((byte*)nLength > (byte*)(Vector.Count - 1)) { var vMatches = Vector.Equals(vComparison, Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref searchSpace, index - Vector.Count))); @@ -322,15 +408,14 @@ namespace System continue; } // Find offset of first match - return (int)(byte*)(index) - Vector.Count + LocateLastFoundByte(vMatches); + return (int)(index) - Vector.Count + LocateLastFoundByte(vMatches); } - if ((int)(byte*)index > 0) + if ((byte*)index > (byte*)0) { nLength = index; goto SequentialScan; } } -#endif return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return (int)(byte*)index; @@ -356,46 +441,42 @@ namespace System uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions - IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations - IntPtr nLength = (IntPtr)(uint)length; -#if !netstandard11 + IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations + IntPtr nLength = (IntPtr)length; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { - unchecked - { - int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); - nLength = (IntPtr)(uint)((Vector.Count - unaligned) & (Vector.Count - 1)); - } + int unaligned = (int)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); + nLength = (IntPtr)((Vector.Count - unaligned) & (Vector.Count - 1)); } SequentialScan: -#endif uint lookUp; while ((byte*)nLength >= (byte*)8) { nLength -= 8; - lookUp = Unsafe.Add(ref searchSpace, index); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index); if (uValue0 == lookUp || uValue1 == lookUp) goto Found; - lookUp = Unsafe.Add(ref searchSpace, index + 1); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1); if (uValue0 == lookUp || uValue1 == lookUp) goto Found1; - lookUp = Unsafe.Add(ref searchSpace, index + 2); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2); if (uValue0 == lookUp || uValue1 == lookUp) goto Found2; - lookUp = Unsafe.Add(ref searchSpace, index + 3); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3); if (uValue0 == lookUp || uValue1 == lookUp) goto Found3; - lookUp = Unsafe.Add(ref searchSpace, index + 4); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 4); if (uValue0 == lookUp || uValue1 == lookUp) goto Found4; - lookUp = Unsafe.Add(ref searchSpace, index + 5); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 5); if (uValue0 == lookUp || uValue1 == lookUp) goto Found5; - lookUp = Unsafe.Add(ref searchSpace, index + 6); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 6); if (uValue0 == lookUp || uValue1 == lookUp) goto Found6; - lookUp = Unsafe.Add(ref searchSpace, index + 7); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 7); if (uValue0 == lookUp || uValue1 == lookUp) goto Found7; @@ -406,16 +487,16 @@ namespace System { nLength -= 4; - lookUp = Unsafe.Add(ref searchSpace, index); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index); if (uValue0 == lookUp || uValue1 == lookUp) goto Found; - lookUp = Unsafe.Add(ref searchSpace, index + 1); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1); if (uValue0 == lookUp || uValue1 == lookUp) goto Found1; - lookUp = Unsafe.Add(ref searchSpace, index + 2); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2); if (uValue0 == lookUp || uValue1 == lookUp) goto Found2; - lookUp = Unsafe.Add(ref searchSpace, index + 3); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3); if (uValue0 == lookUp || uValue1 == lookUp) goto Found3; @@ -426,19 +507,20 @@ namespace System { nLength -= 1; - lookUp = Unsafe.Add(ref searchSpace, index); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index); if (uValue0 == lookUp || uValue1 == lookUp) goto Found; index += 1; } -#if !netstandard11 + if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length)) { - nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector.Count - 1)); + nLength = (IntPtr)((length - (int)(byte*)index) & ~(Vector.Count - 1)); + // Get comparison Vector - Vector values0 = GetVector(value0); - Vector values1 = GetVector(value1); + Vector values0 = new Vector(value0); + Vector values1 = new Vector(value1); while ((byte*)nLength > (byte*)index) { @@ -457,14 +539,10 @@ namespace System if ((int)(byte*)index < length) { - unchecked - { - nLength = (IntPtr)(length - (int)(byte*)index); - } + nLength = (IntPtr)(length - (int)(byte*)index); goto SequentialScan; } } -#endif return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return (int)(byte*)index; @@ -491,46 +569,42 @@ namespace System uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions uint uValue2 = value2; // Use uint for comparisons to avoid unnecessary 8->32 extensions - IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations - IntPtr nLength = (IntPtr)(uint)length; -#if !netstandard11 + IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations + IntPtr nLength = (IntPtr)length; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { - unchecked - { - int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); - nLength = (IntPtr)(uint)((Vector.Count - unaligned) & (Vector.Count - 1)); - } + int unaligned = (int)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); + nLength = (IntPtr)((Vector.Count - unaligned) & (Vector.Count - 1)); } SequentialScan: -#endif uint lookUp; while ((byte*)nLength >= (byte*)8) { nLength -= 8; - lookUp = Unsafe.Add(ref searchSpace, index); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found; - lookUp = Unsafe.Add(ref searchSpace, index + 1); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found1; - lookUp = Unsafe.Add(ref searchSpace, index + 2); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found2; - lookUp = Unsafe.Add(ref searchSpace, index + 3); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found3; - lookUp = Unsafe.Add(ref searchSpace, index + 4); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 4); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found4; - lookUp = Unsafe.Add(ref searchSpace, index + 5); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 5); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found5; - lookUp = Unsafe.Add(ref searchSpace, index + 6); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 6); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found6; - lookUp = Unsafe.Add(ref searchSpace, index + 7); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 7); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found7; @@ -541,16 +615,16 @@ namespace System { nLength -= 4; - lookUp = Unsafe.Add(ref searchSpace, index); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found; - lookUp = Unsafe.Add(ref searchSpace, index + 1); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found1; - lookUp = Unsafe.Add(ref searchSpace, index + 2); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found2; - lookUp = Unsafe.Add(ref searchSpace, index + 3); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found3; @@ -561,20 +635,22 @@ namespace System { nLength -= 1; - lookUp = Unsafe.Add(ref searchSpace, index); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found; index += 1; } -#if !netstandard11 + if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length)) { - nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector.Count - 1)); + nLength = (IntPtr)((length - (int)(byte*)index) & ~(Vector.Count - 1)); + // Get comparison Vector - Vector values0 = GetVector(value0); - Vector values1 = GetVector(value1); - Vector values2 = GetVector(value2); + Vector values0 = new Vector(value0); + Vector values1 = new Vector(value1); + Vector values2 = new Vector(value2); + while ((byte*)nLength > (byte*)index) { Vector vData = Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref searchSpace, index)); @@ -596,14 +672,10 @@ namespace System if ((int)(byte*)index < length) { - unchecked - { - nLength = (IntPtr)(length - (int)(byte*)index); - } + nLength = (IntPtr)(length - (int)(byte*)index); goto SequentialScan; } } -#endif return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return (int)(byte*)index; @@ -629,47 +701,43 @@ namespace System uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions - IntPtr index = (IntPtr)(uint)length; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations - IntPtr nLength = (IntPtr)(uint)length; -#if !netstandard11 + IntPtr index = (IntPtr)length; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations + IntPtr nLength = (IntPtr)length; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { - unchecked - { - int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); - nLength = (IntPtr)(((length & (Vector.Count - 1)) + unaligned) & (Vector.Count - 1)); - } + int unaligned = (int)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); + nLength = (IntPtr)(((length & (Vector.Count - 1)) + unaligned) & (Vector.Count - 1)); } SequentialScan: -#endif uint lookUp; while ((byte*)nLength >= (byte*)8) { nLength -= 8; index -= 8; - lookUp = Unsafe.Add(ref searchSpace, index + 7); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 7); if (uValue0 == lookUp || uValue1 == lookUp) goto Found7; - lookUp = Unsafe.Add(ref searchSpace, index + 6); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 6); if (uValue0 == lookUp || uValue1 == lookUp) goto Found6; - lookUp = Unsafe.Add(ref searchSpace, index + 5); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 5); if (uValue0 == lookUp || uValue1 == lookUp) goto Found5; - lookUp = Unsafe.Add(ref searchSpace, index + 4); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 4); if (uValue0 == lookUp || uValue1 == lookUp) goto Found4; - lookUp = Unsafe.Add(ref searchSpace, index + 3); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3); if (uValue0 == lookUp || uValue1 == lookUp) goto Found3; - lookUp = Unsafe.Add(ref searchSpace, index + 2); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2); if (uValue0 == lookUp || uValue1 == lookUp) goto Found2; - lookUp = Unsafe.Add(ref searchSpace, index + 1); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1); if (uValue0 == lookUp || uValue1 == lookUp) goto Found1; - lookUp = Unsafe.Add(ref searchSpace, index); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index); if (uValue0 == lookUp || uValue1 == lookUp) goto Found; } @@ -679,16 +747,16 @@ namespace System nLength -= 4; index -= 4; - lookUp = Unsafe.Add(ref searchSpace, index + 3); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3); if (uValue0 == lookUp || uValue1 == lookUp) goto Found3; - lookUp = Unsafe.Add(ref searchSpace, index + 2); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2); if (uValue0 == lookUp || uValue1 == lookUp) goto Found2; - lookUp = Unsafe.Add(ref searchSpace, index + 1); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1); if (uValue0 == lookUp || uValue1 == lookUp) goto Found1; - lookUp = Unsafe.Add(ref searchSpace, index); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index); if (uValue0 == lookUp || uValue1 == lookUp) goto Found; } @@ -698,17 +766,18 @@ namespace System nLength -= 1; index -= 1; - lookUp = Unsafe.Add(ref searchSpace, index); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index); if (uValue0 == lookUp || uValue1 == lookUp) goto Found; } -#if !netstandard11 - if (Vector.IsHardwareAccelerated && ((int)(byte*)index > 0)) + + if (Vector.IsHardwareAccelerated && ((byte*)index > (byte*)0)) { - nLength = (IntPtr)(uint)((uint)index & ~(Vector.Count - 1)); + nLength = (IntPtr)((int)(byte*)index & ~(Vector.Count - 1)); + // Get comparison Vector - Vector values0 = GetVector(value0); - Vector values1 = GetVector(value1); + Vector values0 = new Vector(value0); + Vector values1 = new Vector(value1); while ((byte*)nLength > (byte*)(Vector.Count - 1)) { @@ -723,16 +792,15 @@ namespace System continue; } // Find offset of first match - return (int)(byte*)(index) - Vector.Count + LocateLastFoundByte(vMatches); + return (int)(index) - Vector.Count + LocateLastFoundByte(vMatches); } - if ((int)(byte*)index > 0) + if ((byte*)index > (byte*)0) { nLength = index; goto SequentialScan; } } -#endif return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return (int)(byte*)index; @@ -759,47 +827,43 @@ namespace System uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions uint uValue2 = value2; // Use uint for comparisons to avoid unnecessary 8->32 extensions - IntPtr index = (IntPtr)(uint)length; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations - IntPtr nLength = (IntPtr)(uint)length; -#if !netstandard11 + IntPtr index = (IntPtr)length; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations + IntPtr nLength = (IntPtr)length; + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { - unchecked - { - int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); - nLength = (IntPtr)(((length & (Vector.Count - 1)) + unaligned) & (Vector.Count - 1)); - } + int unaligned = (int)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); + nLength = (IntPtr)(((length & (Vector.Count - 1)) + unaligned) & (Vector.Count - 1)); } SequentialScan: -#endif uint lookUp; while ((byte*)nLength >= (byte*)8) { nLength -= 8; index -= 8; - lookUp = Unsafe.Add(ref searchSpace, index + 7); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 7); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found7; - lookUp = Unsafe.Add(ref searchSpace, index + 6); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 6); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found6; - lookUp = Unsafe.Add(ref searchSpace, index + 5); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 5); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found5; - lookUp = Unsafe.Add(ref searchSpace, index + 4); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 4); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found4; - lookUp = Unsafe.Add(ref searchSpace, index + 3); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found3; - lookUp = Unsafe.Add(ref searchSpace, index + 2); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found2; - lookUp = Unsafe.Add(ref searchSpace, index + 1); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found1; - lookUp = Unsafe.Add(ref searchSpace, index); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found; } @@ -809,16 +873,16 @@ namespace System nLength -= 4; index -= 4; - lookUp = Unsafe.Add(ref searchSpace, index + 3); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found3; - lookUp = Unsafe.Add(ref searchSpace, index + 2); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found2; - lookUp = Unsafe.Add(ref searchSpace, index + 1); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found1; - lookUp = Unsafe.Add(ref searchSpace, index); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found; } @@ -828,18 +892,20 @@ namespace System nLength -= 1; index -= 1; - lookUp = Unsafe.Add(ref searchSpace, index); + lookUp = Unsafe.AddByteOffset(ref searchSpace, index); if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp) goto Found; } -#if !netstandard11 - if (Vector.IsHardwareAccelerated && ((int)(byte*)index > 0)) + + if (Vector.IsHardwareAccelerated && ((byte*)index > (byte*)0)) { - nLength = (IntPtr)(uint)((uint)index & ~(Vector.Count - 1)); + nLength = (IntPtr)((int)(byte*)index & ~(Vector.Count - 1)); + // Get comparison Vector - Vector values0 = GetVector(value0); - Vector values1 = GetVector(value1); - Vector values2 = GetVector(value2); + Vector values0 = new Vector(value0); + Vector values1 = new Vector(value1); + Vector values2 = new Vector(value2); + while ((byte*)nLength > (byte*)(Vector.Count - 1)) { Vector vData = Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref searchSpace, index - Vector.Count)); @@ -857,16 +923,15 @@ namespace System continue; } // Find offset of first match - return (int)(byte*)(index) - Vector.Count + LocateLastFoundByte(vMatches); + return (int)(index) - Vector.Count + LocateLastFoundByte(vMatches); } - if ((int)(byte*)index > 0) + if ((byte*)index > (byte*)0) { nLength = index; goto SequentialScan; } } -#endif return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return (int)(byte*)index; @@ -886,17 +951,16 @@ namespace System return (int)(byte*)(index + 7); } - public static unsafe bool SequenceEqual(ref byte first, ref byte second, int length) + // Optimized byte-based SequenceEquals. The "length" parameter for this one is declared a nuint rather than int as we also use it for types other than byte + // where the length can exceed 2Gb once scaled by sizeof(T). + public static unsafe bool SequenceEqual(ref byte first, ref byte second, nuint length) { - Debug.Assert(length >= 0); - if (Unsafe.AreSame(ref first, ref second)) goto Equal; - IntPtr i = (IntPtr)0; // Use IntPtr and byte* for arithmetic to avoid unnecessary 64->32->64 truncations - IntPtr n = (IntPtr)length; + IntPtr i = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations + IntPtr n = (IntPtr)(void*)length; -#if !netstandard11 if (Vector.IsHardwareAccelerated && (byte*)n >= (byte*)Vector.Count) { n -= Vector.Count; @@ -912,7 +976,6 @@ namespace System return Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref first, n)) == Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref second, n)); } -#endif if ((byte*)n >= (byte*)sizeof(UIntPtr)) { @@ -944,7 +1007,6 @@ namespace System return false; } -#if !netstandard11 // Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138 [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateFirstFoundByte(Vector match) @@ -965,7 +1027,6 @@ namespace System // Single LEA instruction with jitted const (using function result) return i * 8 + LocateFirstFoundByte(candidate); } -#endif public static unsafe int SequenceCompareTo(ref byte first, int firstLength, ref byte second, int secondLength) { @@ -975,13 +1036,11 @@ namespace System if (Unsafe.AreSame(ref first, ref second)) goto Equal; - var minLength = firstLength; - if (minLength > secondLength) minLength = secondLength; + IntPtr minLength = (IntPtr)((firstLength < secondLength) ? firstLength : secondLength); - IntPtr i = (IntPtr)0; // Use IntPtr and byte* for arithmetic to avoid unnecessary 64->32->64 truncations - IntPtr n = (IntPtr)minLength; + IntPtr i = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations + IntPtr n = (IntPtr)(void*)minLength; -#if !netstandard11 if (Vector.IsHardwareAccelerated && (byte*)n > (byte*)Vector.Count) { n -= Vector.Count; @@ -996,7 +1055,6 @@ namespace System } goto NotEqual; } -#endif if ((byte*)n > (byte*)sizeof(UIntPtr)) { @@ -1013,10 +1071,11 @@ namespace System } NotEqual: // Workaround for https://github.com/dotnet/coreclr/issues/13549 - while((byte*)minLength > (byte*)i) + while ((byte*)minLength > (byte*)i) { int result = Unsafe.AddByteOffset(ref first, i).CompareTo(Unsafe.AddByteOffset(ref second, i)); - if (result != 0) return result; + if (result != 0) + return result; i += 1; } @@ -1024,7 +1083,6 @@ namespace System return firstLength - secondLength; } -#if !netstandard11 // Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138 [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateLastFoundByte(Vector match) @@ -1045,23 +1103,16 @@ namespace System // Single LEA instruction with jitted const (using function result) return i * 8 + LocateLastFoundByte(candidate); } -#endif -#if !netstandard11 [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateFirstFoundByte(ulong match) { - unchecked - { - // Flag least significant power of two bit - var powerOfTwoFlag = match ^ (match - 1); - // Shift all powers of two into the high byte and extract - return (int)((powerOfTwoFlag * XorPowerOfTwoToHighByte) >> 57); - } + // Flag least significant power of two bit + var powerOfTwoFlag = match ^ (match - 1); + // Shift all powers of two into the high byte and extract + return (int)((powerOfTwoFlag * XorPowerOfTwoToHighByte) >> 57); } -#endif -#if !netstandard11 [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateLastFoundByte(ulong match) { @@ -1074,24 +1125,7 @@ namespace System } return index; } -#endif -#if !netstandard11 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static Vector GetVector(byte vectorByte) - { -#if !netcoreapp - // Vector .ctor doesn't become an intrinsic due to detection issue - // However this does cause it to become an intrinsic (with additional multiply and reg->reg copy) - // https://github.com/dotnet/coreclr/issues/7459#issuecomment-253965670 - return Vector.AsVectorByte(new Vector(vectorByte * 0x01010101u)); -#else - return new Vector(vectorByte); -#endif - } -#endif - -#if !netstandard11 private const ulong XorPowerOfTwoToHighByte = (0x07ul | 0x06ul << 8 | 0x05ul << 16 | @@ -1099,6 +1133,5 @@ namespace System 0x03ul << 32 | 0x02ul << 40 | 0x01ul << 48) + 1; -#endif } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.Char.cs b/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.Char.cs new file mode 100644 index 0000000000..02df69feb5 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.Char.cs @@ -0,0 +1,420 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Numerics; + +#if !netstandard +using Internal.Runtime.CompilerServices; +#endif + +namespace System +{ + internal static partial class SpanHelpers // .Char + { + public static unsafe int SequenceCompareTo(ref char first, int firstLength, ref char second, int secondLength) + { + Debug.Assert(firstLength >= 0); + Debug.Assert(secondLength >= 0); + + int lengthDelta = firstLength - secondLength; + + if (Unsafe.AreSame(ref first, ref second)) + goto Equal; + + IntPtr minLength = (IntPtr)((firstLength < secondLength) ? firstLength : secondLength); + IntPtr i = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations + + if ((byte*)minLength >= (byte*)(sizeof(UIntPtr) / sizeof(char))) + { + if (Vector.IsHardwareAccelerated && (byte*)minLength >= (byte*)Vector.Count) + { + IntPtr nLength = minLength - Vector.Count; + do + { + if (Unsafe.ReadUnaligned>(ref Unsafe.As(ref Unsafe.Add(ref first, i))) != + Unsafe.ReadUnaligned>(ref Unsafe.As(ref Unsafe.Add(ref second, i)))) + { + break; + } + i += Vector.Count; + } + while ((byte*)nLength >= (byte*)i); + } + + while ((byte*)minLength >= (byte*)(i + sizeof(UIntPtr) / sizeof(char))) + { + if (Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.Add(ref first, i))) != + Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.Add(ref second, i)))) + { + break; + } + i += sizeof(UIntPtr) / sizeof(char); + } + } + + if (sizeof(UIntPtr) > sizeof(int) && (byte*)minLength >= (byte*)(i + sizeof(int) / sizeof(char))) + { + if (Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.Add(ref first, i))) == + Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.Add(ref second, i)))) + { + i += sizeof(int) / sizeof(char); + } + } + + while ((byte*)i < (byte*)minLength) + { + int result = Unsafe.Add(ref first, i).CompareTo(Unsafe.Add(ref second, i)); + if (result != 0) + return result; + i += 1; + } + + Equal: + return lengthDelta; + } + + // Adapted from IndexOf(...) + public static unsafe bool Contains(ref char searchSpace, char value, int length) + { + Debug.Assert(length >= 0); + + fixed (char* pChars = &searchSpace) + { + char* pCh = pChars; + char* pEndCh = pCh + length; + + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) + { + // Figure out how many characters to read sequentially until we are vector aligned + // This is equivalent to: + // unaligned = ((int)pCh % Unsafe.SizeOf>()) / elementsPerByte + // length = (Vector.Count - unaligned) % Vector.Count + const int elementsPerByte = sizeof(ushort) / sizeof(byte); + int unaligned = ((int)pCh & (Unsafe.SizeOf>() - 1)) / elementsPerByte; + length = (Vector.Count - unaligned) & (Vector.Count - 1); + } + + SequentialScan: + while (length >= 4) + { + length -= 4; + + if (value == *pCh || + value == *(pCh + 1) || + value == *(pCh + 2) || + value == *(pCh + 3)) + { + goto Found; + } + + pCh += 4; + } + + while (length > 0) + { + length -= 1; + + if (value == *pCh) + goto Found; + + pCh += 1; + } + + // We get past SequentialScan only if IsHardwareAccelerated is true. However, we still have the redundant check to allow + // the JIT to see that the code is unreachable and eliminate it when the platform does not have hardware accelerated. + if (Vector.IsHardwareAccelerated && pCh < pEndCh) + { + // Get the highest multiple of Vector.Count that is within the search space. + // That will be how many times we iterate in the loop below. + // This is equivalent to: length = Vector.Count * ((int)(pEndCh - pCh) / Vector.Count) + length = (int)((pEndCh - pCh) & ~(Vector.Count - 1)); + + // Get comparison Vector + Vector vComparison = new Vector(value); + + while (length > 0) + { + // Using Unsafe.Read instead of ReadUnaligned since the search space is pinned and pCh is always vector aligned + Debug.Assert(((int)pCh & (Unsafe.SizeOf>() - 1)) == 0); + Vector vMatches = Vector.Equals(vComparison, Unsafe.Read>(pCh)); + if (Vector.Zero.Equals(vMatches)) + { + pCh += Vector.Count; + length -= Vector.Count; + continue; + } + + goto Found; + } + + if (pCh < pEndCh) + { + length = (int)(pEndCh - pCh); + goto SequentialScan; + } + } + + return false; + + Found: + return true; + } + } + + public static unsafe int IndexOf(ref char searchSpace, char value, int length) + { + Debug.Assert(length >= 0); + + fixed (char* pChars = &searchSpace) + { + char* pCh = pChars; + char* pEndCh = pCh + length; + + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) + { + // Figure out how many characters to read sequentially until we are vector aligned + // This is equivalent to: + // unaligned = ((int)pCh % Unsafe.SizeOf>()) / elementsPerByte + // length = (Vector.Count - unaligned) % Vector.Count + const int elementsPerByte = sizeof(ushort) / sizeof(byte); + int unaligned = ((int)pCh & (Unsafe.SizeOf>() - 1)) / elementsPerByte; + length = (Vector.Count - unaligned) & (Vector.Count - 1); + } + + SequentialScan: + while (length >= 4) + { + length -= 4; + + if (*pCh == value) + goto Found; + if (*(pCh + 1) == value) + goto Found1; + if (*(pCh + 2) == value) + goto Found2; + if (*(pCh + 3) == value) + goto Found3; + + pCh += 4; + } + + while (length > 0) + { + length -= 1; + + if (*pCh == value) + goto Found; + + pCh += 1; + } + + // We get past SequentialScan only if IsHardwareAccelerated is true. However, we still have the redundant check to allow + // the JIT to see that the code is unreachable and eliminate it when the platform does not have hardware accelerated. + if (Vector.IsHardwareAccelerated && pCh < pEndCh) + { + // Get the highest multiple of Vector.Count that is within the search space. + // That will be how many times we iterate in the loop below. + // This is equivalent to: length = Vector.Count * ((int)(pEndCh - pCh) / Vector.Count) + length = (int)((pEndCh - pCh) & ~(Vector.Count - 1)); + + // Get comparison Vector + Vector vComparison = new Vector(value); + + while (length > 0) + { + // Using Unsafe.Read instead of ReadUnaligned since the search space is pinned and pCh is always vector aligned + Debug.Assert(((int)pCh & (Unsafe.SizeOf>() - 1)) == 0); + Vector vMatches = Vector.Equals(vComparison, Unsafe.Read>(pCh)); + if (Vector.Zero.Equals(vMatches)) + { + pCh += Vector.Count; + length -= Vector.Count; + continue; + } + // Find offset of first match + return (int)(pCh - pChars) + LocateFirstFoundChar(vMatches); + } + + if (pCh < pEndCh) + { + length = (int)(pEndCh - pCh); + goto SequentialScan; + } + } + + return -1; + Found3: + pCh++; + Found2: + pCh++; + Found1: + pCh++; + Found: + return (int)(pCh - pChars); + } + } + + public static unsafe int LastIndexOf(ref char searchSpace, char value, int length) + { + Debug.Assert(length >= 0); + + fixed (char* pChars = &searchSpace) + { + char* pCh = pChars + length; + char* pEndCh = pChars; + + if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) + { + // Figure out how many characters to read sequentially from the end until we are vector aligned + // This is equivalent to: length = ((int)pCh % Unsafe.SizeOf>()) / elementsPerByte + const int elementsPerByte = sizeof(ushort) / sizeof(byte); + length = ((int)pCh & (Unsafe.SizeOf>() - 1)) / elementsPerByte; + } + + SequentialScan: + while (length >= 4) + { + length -= 4; + pCh -= 4; + + if (*(pCh + 3) == value) + goto Found3; + if (*(pCh + 2) == value) + goto Found2; + if (*(pCh + 1) == value) + goto Found1; + if (*pCh == value) + goto Found; + } + + while (length > 0) + { + length -= 1; + pCh -= 1; + + if (*pCh == value) + goto Found; + } + + // We get past SequentialScan only if IsHardwareAccelerated is true. However, we still have the redundant check to allow + // the JIT to see that the code is unreachable and eliminate it when the platform does not have hardware accelerated. + if (Vector.IsHardwareAccelerated && pCh > pEndCh) + { + // Get the highest multiple of Vector.Count that is within the search space. + // That will be how many times we iterate in the loop below. + // This is equivalent to: length = Vector.Count * ((int)(pCh - pEndCh) / Vector.Count) + length = (int)((pCh - pEndCh) & ~(Vector.Count - 1)); + + // Get comparison Vector + Vector vComparison = new Vector(value); + + while (length > 0) + { + char* pStart = pCh - Vector.Count; + // Using Unsafe.Read instead of ReadUnaligned since the search space is pinned and pCh (and hence pSart) is always vector aligned + Debug.Assert(((int)pStart & (Unsafe.SizeOf>() - 1)) == 0); + Vector vMatches = Vector.Equals(vComparison, Unsafe.Read>(pStart)); + if (Vector.Zero.Equals(vMatches)) + { + pCh -= Vector.Count; + length -= Vector.Count; + continue; + } + // Find offset of last match + return (int)(pStart - pEndCh) + LocateLastFoundChar(vMatches); + } + + if (pCh > pEndCh) + { + length = (int)(pCh - pEndCh); + goto SequentialScan; + } + } + + return -1; + Found: + return (int)(pCh - pEndCh); + Found1: + return (int)(pCh - pEndCh) + 1; + Found2: + return (int)(pCh - pEndCh) + 2; + Found3: + return (int)(pCh - pEndCh) + 3; + } + } + + // Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int LocateFirstFoundChar(Vector match) + { + var vector64 = Vector.AsVectorUInt64(match); + ulong candidate = 0; + int i = 0; + // Pattern unrolled by jit https://github.com/dotnet/coreclr/pull/8001 + for (; i < Vector.Count; i++) + { + candidate = vector64[i]; + if (candidate != 0) + { + break; + } + } + + // Single LEA instruction with jitted const (using function result) + return i * 4 + LocateFirstFoundChar(candidate); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int LocateFirstFoundChar(ulong match) + { + unchecked + { + // Flag least significant power of two bit + var powerOfTwoFlag = match ^ (match - 1); + // Shift all powers of two into the high byte and extract + return (int)((powerOfTwoFlag * XorPowerOfTwoToHighChar) >> 49); + } + } + + private const ulong XorPowerOfTwoToHighChar = (0x03ul | + 0x02ul << 16 | + 0x01ul << 32) + 1; + + // Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int LocateLastFoundChar(Vector match) + { + var vector64 = Vector.AsVectorUInt64(match); + ulong candidate = 0; + int i = Vector.Count - 1; + // Pattern unrolled by jit https://github.com/dotnet/coreclr/pull/8001 + for (; i >= 0; i--) + { + candidate = vector64[i]; + if (candidate != 0) + { + break; + } + } + + // Single LEA instruction with jitted const (using function result) + return i * 4 + LocateLastFoundChar(candidate); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int LocateLastFoundChar(ulong match) + { + // Find the most significant char that has its highest bit set + int index = 3; + while ((long)match > 0) + { + match = match << 16; + index--; + } + return index; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.T.cs b/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.T.cs index d1c62c8d51..d6f45d2260 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.T.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.T.cs @@ -3,16 +3,16 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; +using System.Runtime.CompilerServices; // Do not remove. This is necessary for netstandard, since this file is mirrored into corefx +using System.Numerics; #if !netstandard using Internal.Runtime.CompilerServices; -#else -using System.Runtime.CompilerServices; #endif namespace System { - internal static partial class SpanHelpers + internal static partial class SpanHelpers // .T { public static int IndexOf(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) where T : IEquatable @@ -49,7 +49,64 @@ namespace System } return -1; } - + + // Adapted from IndexOf(...) + public static bool Contains(ref T searchSpace, T value, int length) + where T : IEquatable + { + Debug.Assert(length >= 0); + + IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations + while (length >= 8) + { + length -= 8; + + if (value.Equals(Unsafe.Add(ref searchSpace, index + 0)) || + value.Equals(Unsafe.Add(ref searchSpace, index + 1)) || + value.Equals(Unsafe.Add(ref searchSpace, index + 2)) || + value.Equals(Unsafe.Add(ref searchSpace, index + 3)) || + value.Equals(Unsafe.Add(ref searchSpace, index + 4)) || + value.Equals(Unsafe.Add(ref searchSpace, index + 5)) || + value.Equals(Unsafe.Add(ref searchSpace, index + 6)) || + value.Equals(Unsafe.Add(ref searchSpace, index + 7))) + { + goto Found; + } + + index += 8; + } + + if (length >= 4) + { + length -= 4; + + if (value.Equals(Unsafe.Add(ref searchSpace, index + 0)) || + value.Equals(Unsafe.Add(ref searchSpace, index + 1)) || + value.Equals(Unsafe.Add(ref searchSpace, index + 2)) || + value.Equals(Unsafe.Add(ref searchSpace, index + 3))) + { + goto Found; + } + + index += 4; + } + + while (length > 0) + { + length -= 1; + + if (value.Equals(Unsafe.Add(ref searchSpace, index))) + goto Found; + + index += 1; + } + + return false; + + Found: + return true; + } + public static unsafe int IndexOf(ref T searchSpace, T value, int length) where T : IEquatable { @@ -189,21 +246,21 @@ namespace System } return -1; - Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 + Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return index; - Found1: + Found1: return index + 1; - Found2: + Found2: return index + 2; - Found3: + Found3: return index + 3; - Found4: + Found4: return index + 4; - Found5: + Found5: return index + 5; - Found6: + Found6: return index + 6; - Found7: + Found7: return index + 7; } @@ -272,21 +329,21 @@ namespace System } return -1; - Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 + Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return index; - Found1: + Found1: return index + 1; - Found2: + Found2: return index + 2; - Found3: + Found3: return index + 3; - Found4: + Found4: return index + 4; - Found5: + Found5: return index + 5; - Found6: + Found6: return index + 6; - Found7: + Found7: return index + 7; } @@ -309,7 +366,8 @@ namespace System // Reduce space for search, cause we don't care if we find the search value after the index of a previously found value searchSpaceLength = tempIndex; - if (index == 0) break; + if (index == 0) + break; } } return index; @@ -595,7 +653,8 @@ namespace System for (int i = 0; i < valueLength; i++) { var tempIndex = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); - if (tempIndex > index) index = tempIndex; + if (tempIndex > index) + index = tempIndex; } return index; } @@ -671,11 +730,13 @@ namespace System Debug.Assert(secondLength >= 0); var minLength = firstLength; - if (minLength > secondLength) minLength = secondLength; + if (minLength > secondLength) + minLength = secondLength; for (int i = 0; i < minLength; i++) { int result = Unsafe.Add(ref first, i).CompareTo(Unsafe.Add(ref second, i)); - if (result != 0) return result; + if (result != 0) + return result; } return firstLength.CompareTo(secondLength); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.cs b/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.cs index dad0f6294c..0d5c57c5db 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/SpanHelpers.cs @@ -5,7 +5,6 @@ using System.Diagnostics; using System.Globalization; using System.Runtime; -using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; @@ -19,127 +18,6 @@ namespace System { internal static partial class SpanHelpers { - public static int IndexOfCultureHelper(ReadOnlySpan span, ReadOnlySpan value, CompareInfo compareInfo) - { - Debug.Assert(span.Length != 0); - Debug.Assert(value.Length != 0); - - if (GlobalizationMode.Invariant) - { - return CompareInfo.InvariantIndexOf(span, value, ignoreCase: false); - } - - return compareInfo.IndexOf(span, value, CompareOptions.None); - } - - public static int IndexOfCultureIgnoreCaseHelper(ReadOnlySpan span, ReadOnlySpan value, CompareInfo compareInfo) - { - Debug.Assert(span.Length != 0); - Debug.Assert(value.Length != 0); - - if (GlobalizationMode.Invariant) - { - return CompareInfo.InvariantIndexOf(span, value, ignoreCase: true); - } - - return compareInfo.IndexOf(span, value, CompareOptions.IgnoreCase); - } - - public static int IndexOfOrdinalHelper(ReadOnlySpan span, ReadOnlySpan value, bool ignoreCase) - { - Debug.Assert(span.Length != 0); - Debug.Assert(value.Length != 0); - - if (GlobalizationMode.Invariant) - { - return CompareInfo.InvariantIndexOf(span, value, ignoreCase); - } - - return CompareInfo.Invariant.IndexOfOrdinal(span, value, ignoreCase); - } - - public static bool StartsWithCultureHelper(ReadOnlySpan span, ReadOnlySpan value, CompareInfo compareInfo) - { - Debug.Assert(value.Length != 0); - - if (GlobalizationMode.Invariant) - { - return span.StartsWith(value); - } - if (span.Length == 0) - { - return false; - } - return compareInfo.IsPrefix(span, value, CompareOptions.None); - } - - public static bool StartsWithCultureIgnoreCaseHelper(ReadOnlySpan span, ReadOnlySpan value, CompareInfo compareInfo) - { - Debug.Assert(value.Length != 0); - - if (GlobalizationMode.Invariant) - { - return StartsWithOrdinalIgnoreCaseHelper(span, value); - } - if (span.Length == 0) - { - return false; - } - return compareInfo.IsPrefix(span, value, CompareOptions.IgnoreCase); - } - - public static bool StartsWithOrdinalIgnoreCaseHelper(ReadOnlySpan span, ReadOnlySpan value) - { - Debug.Assert(value.Length != 0); - - if (span.Length < value.Length) - { - return false; - } - return CompareInfo.CompareOrdinalIgnoreCase(span.Slice(0, value.Length), value) == 0; - } - - public static bool EndsWithCultureHelper(ReadOnlySpan span, ReadOnlySpan value, CompareInfo compareInfo) - { - Debug.Assert(value.Length != 0); - - if (GlobalizationMode.Invariant) - { - return span.EndsWith(value); - } - if (span.Length == 0) - { - return false; - } - return compareInfo.IsSuffix(span, value, CompareOptions.None); - } - - public static bool EndsWithCultureIgnoreCaseHelper(ReadOnlySpan span, ReadOnlySpan value, CompareInfo compareInfo) - { - Debug.Assert(value.Length != 0); - - if (GlobalizationMode.Invariant) - { - return EndsWithOrdinalIgnoreCaseHelper(span, value); - } - if (span.Length == 0) - { - return false; - } - return compareInfo.IsSuffix(span, value, CompareOptions.IgnoreCase); - } - - public static bool EndsWithOrdinalIgnoreCaseHelper(ReadOnlySpan span, ReadOnlySpan value) - { - Debug.Assert(value.Length != 0); - - if (span.Length < value.Length) - { - return false; - } - return (CompareInfo.CompareOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value) == 0); - } - public static unsafe void ClearWithoutReferences(ref byte b, nuint byteLength) { if (byteLength == 0) @@ -355,13 +233,13 @@ namespace System nuint i = 0; // byte offset at which we're copying - if ((Unsafe.As(ref b) & 3) != 0) + if (((nuint)Unsafe.AsPointer(ref b) & 3) != 0) { - if ((Unsafe.As(ref b) & 1) != 0) + if (((nuint)Unsafe.AsPointer(ref b) & 1) != 0) { - Unsafe.AddByteOffset(ref b, i) = 0; + b = 0; i += 1; - if ((Unsafe.As(ref b) & 2) != 0) + if (((nuint)Unsafe.AsPointer(ref b) & 2) != 0) goto IntAligned; } Unsafe.As(ref Unsafe.AddByteOffset(ref b, i)) = 0; @@ -378,7 +256,7 @@ namespace System // The thing 1, 2, 3, and 4 have in common that the others don't is that if you // subtract one from them, their 3rd lsb will not be set. Hence, the below check. - if (((Unsafe.As(ref b) - 1) & 4) == 0) + if ((((nuint)Unsafe.AsPointer(ref b) - 1) & 4) == 0) { Unsafe.As(ref Unsafe.AddByteOffset(ref b, i)) = 0; i += 4; @@ -461,43 +339,77 @@ namespace System public static unsafe void ClearWithReferences(ref IntPtr ip, nuint pointerSizeLength) { - if (pointerSizeLength == 0) - return; + Debug.Assert((int)Unsafe.AsPointer(ref ip) % sizeof(IntPtr) == 0, "Should've been aligned on natural word boundary."); - // TODO: Perhaps do switch casing to improve small size perf + // First write backward 8 natural words at a time. + // Writing backward allows us to get away with only simple modifications to the + // mov instruction's base and index registers between loop iterations. - nuint i = 0; - nuint n = 0; - while ((n = i + 8) <= (pointerSizeLength)) + for (; pointerSizeLength >= 8; pointerSizeLength -= 8) { - Unsafe.AddByteOffset(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); - Unsafe.AddByteOffset(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr); - Unsafe.AddByteOffset(ref ip, (i + 2) * (nuint)sizeof(IntPtr)) = default(IntPtr); - Unsafe.AddByteOffset(ref ip, (i + 3) * (nuint)sizeof(IntPtr)) = default(IntPtr); - Unsafe.AddByteOffset(ref ip, (i + 4) * (nuint)sizeof(IntPtr)) = default(IntPtr); - Unsafe.AddByteOffset(ref ip, (i + 5) * (nuint)sizeof(IntPtr)) = default(IntPtr); - Unsafe.AddByteOffset(ref ip, (i + 6) * (nuint)sizeof(IntPtr)) = default(IntPtr); - Unsafe.AddByteOffset(ref ip, (i + 7) * (nuint)sizeof(IntPtr)) = default(IntPtr); - i = n; + Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -1) = default; + Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -2) = default; + Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -3) = default; + Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -4) = default; + Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -5) = default; + Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -6) = default; + Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -7) = default; + Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -8) = default; } - if ((n = i + 4) <= (pointerSizeLength)) + + Debug.Assert(pointerSizeLength <= 7); + + // The logic below works by trying to minimize the number of branches taken for any + // given range of lengths. For example, the lengths [ 4 .. 7 ] are handled by a single + // branch, [ 2 .. 3 ] are handled by a single branch, and [ 1 ] is handled by a single + // branch. + // + // We can write both forward and backward as a perf improvement. For example, + // the lengths [ 4 .. 7 ] can be handled by zeroing out the first four natural + // words and the last 3 natural words. In the best case (length = 7), there are + // no overlapping writes. In the worst case (length = 4), there are three + // overlapping writes near the middle of the buffer. In perf testing, the + // penalty for performing duplicate writes is less expensive than the penalty + // for complex branching. + + if (pointerSizeLength >= 4) { - Unsafe.AddByteOffset(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); - Unsafe.AddByteOffset(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr); - Unsafe.AddByteOffset(ref ip, (i + 2) * (nuint)sizeof(IntPtr)) = default(IntPtr); - Unsafe.AddByteOffset(ref ip, (i + 3) * (nuint)sizeof(IntPtr)) = default(IntPtr); - i = n; + goto Write4To7; } - if ((n = i + 2) <= (pointerSizeLength)) + else if (pointerSizeLength >= 2) { - Unsafe.AddByteOffset(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); - Unsafe.AddByteOffset(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr); - i = n; + goto Write2To3; } - if ((i + 1) <= (pointerSizeLength)) + else if (pointerSizeLength > 0) { - Unsafe.AddByteOffset(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); + goto Write1; } + else + { + return; // nothing to write + } + + Write4To7: + Debug.Assert(pointerSizeLength >= 4); + + // Write first four and last three. + Unsafe.Add(ref ip, 2) = default; + Unsafe.Add(ref ip, 3) = default; + Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -3) = default; + Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -2) = default; + + Write2To3: + Debug.Assert(pointerSizeLength >= 2); + + // Write first two and last one. + Unsafe.Add(ref ip, 1) = default; + Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -1) = default; + + Write1: + Debug.Assert(pointerSizeLength >= 1); + + // Write only element. + ip = default; } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/StackOverflowException.cs b/external/corert/src/System.Private.CoreLib/shared/System/StackOverflowException.cs index 6f954cc75a..a603ea88b2 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/StackOverflowException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/StackOverflowException.cs @@ -25,13 +25,13 @@ namespace System HResult = HResults.COR_E_STACKOVERFLOW; } - public StackOverflowException(String message) + public StackOverflowException(string message) : base(message) { HResult = HResults.COR_E_STACKOVERFLOW; } - public StackOverflowException(String message, Exception innerException) + public StackOverflowException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_STACKOVERFLOW; diff --git a/external/corert/src/System.Private.CoreLib/src/System/String.Comparison.cs b/external/corert/src/System.Private.CoreLib/shared/System/String.Comparison.cs similarity index 53% rename from external/corert/src/System.Private.CoreLib/src/System/String.Comparison.cs rename to external/corert/src/System.Private.CoreLib/shared/System/String.Comparison.cs index 5086ea0ae1..267bfe1fd4 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/String.Comparison.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/String.Comparison.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics.Private; +using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -19,270 +19,42 @@ namespace System { public partial class String { - // - //Native Static Methods - // -#if !MONO - private static unsafe int FastCompareStringHelper(uint* strAChars, int countA, uint* strBChars, int countB) - { - int count = (countA < countB) ? countA : countB; - -#if BIT64 - long diff = (long)((byte*)strAChars - (byte*)strBChars); -#else - int diff = (int)((byte*)strAChars - (byte*)strBChars); -#endif - -#if BIT64 - int alignmentA = (int)((long)strAChars) & (sizeof(IntPtr) - 1); - int alignmentB = (int)((long)strBChars) & (sizeof(IntPtr) - 1); - - if (alignmentA == alignmentB) - { - if ((alignmentA == 2 || alignmentA == 6) && (count >= 1)) - { - char* ptr2 = (char*)strBChars; - - if ((*((char*)((byte*)ptr2 + diff)) - *ptr2) != 0) - return ((int)*((char*)((byte*)ptr2 + diff)) - (int)*ptr2); - - strBChars = (uint*)(++ptr2); - count -= 1; - alignmentA = (alignmentA == 2 ? 4 : 0); - } - - if ((alignmentA == 4) && (count >= 2)) - { - uint* ptr2 = (uint*)strBChars; - - if ((*((uint*)((byte*)ptr2 + diff)) - *ptr2) != 0) - { - char* chkptr1 = (char*)((byte*)strBChars + diff); - char* chkptr2 = (char*)strBChars; - - if (*chkptr1 != *chkptr2) - return ((int)*chkptr1 - (int)*chkptr2); - return ((int)*(chkptr1 + 1) - (int)*(chkptr2 + 1)); - } - strBChars = ++ptr2; - count -= 2; - alignmentA = 0; - } - - if ((alignmentA == 0)) - { - while (count >= 4) - { - long* ptr2 = (long*)strBChars; - - if ((*((long*)((byte*)ptr2 + diff)) - *ptr2) != 0) - { - if ((*((uint*)((byte*)ptr2 + diff)) - *(uint*)ptr2) != 0) - { - char* chkptr1 = (char*)((byte*)strBChars + diff); - char* chkptr2 = (char*)strBChars; - - if (*chkptr1 != *chkptr2) - return ((int)*chkptr1 - (int)*chkptr2); - return ((int)*(chkptr1 + 1) - (int)*(chkptr2 + 1)); - } - else - { - char* chkptr1 = (char*)((uint*)((byte*)strBChars + diff) + 1); - char* chkptr2 = (char*)((uint*)strBChars + 1); - - if (*chkptr1 != *chkptr2) - return ((int)*chkptr1 - (int)*chkptr2); - return ((int)*(chkptr1 + 1) - (int)*(chkptr2 + 1)); - } - } - strBChars = (uint*)(++ptr2); - count -= 4; - } - } - - { - char* ptr2 = (char*)strBChars; - while ((count -= 1) >= 0) - { - if ((*((char*)((byte*)ptr2 + diff)) - *ptr2) != 0) - return ((int)*((char*)((byte*)ptr2 + diff)) - (int)*ptr2); - ++ptr2; - } - } - } - else -#endif // BIT64 - { -#if BIT64 - if (Math.Abs(alignmentA - alignmentB) == 4) - { - if ((alignmentA == 2) || (alignmentB == 2)) - { - char* ptr2 = (char*)strBChars; - - if ((*((char*)((byte*)ptr2 + diff)) - *ptr2) != 0) - return ((int)*((char*)((byte*)ptr2 + diff)) - (int)*ptr2); - strBChars = (uint*)(++ptr2); - count -= 1; - } - } -#endif // BIT64 - - // Loop comparing a DWORD at a time. - // Reads are potentially unaligned - while ((count -= 2) >= 0) - { - if ((*((uint*)((byte*)strBChars + diff)) - *strBChars) != 0) - { - char* ptr1 = (char*)((byte*)strBChars + diff); - char* ptr2 = (char*)strBChars; - if (*ptr1 != *ptr2) - return ((int)*ptr1 - (int)*ptr2); - return ((int)*(ptr1 + 1) - (int)*(ptr2 + 1)); - } - ++strBChars; - } - - int c; - if (count == -1) - if ((c = *((char*)((byte*)strBChars + diff)) - *((char*)strBChars)) != 0) - return c; - } - - return countA - countB; - } -#endif - // - // - // NATIVE INSTANCE METHODS - // - // - // // Search/Query methods // - // - // Common worker for the various Equality methods. The caller must have already ensured that - // both strings are non-null and that their lengths are equal. Ther caller should also have - // done the Object.ReferenceEquals() fastpath check as we won't repeat it here. - // - private static unsafe bool EqualsHelper(String strA, String strB) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool EqualsHelper(string strA, string strB) { Debug.Assert(strA != null); Debug.Assert(strB != null); Debug.Assert(strA.Length == strB.Length); - int length = strA.Length; - fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar) - { - char* a = ap; - char* b = bp; - -#if BIT64 - // Single int read aligns pointers for the following long reads - // PERF: No length check needed as there is always an int32 worth of string allocated - // This read can also include the null terminator which both strings will have - if (*(int*)a != *(int*)b) return false; - length -= 2; a += 2; b += 2; - - // for 64-bit platforms we unroll by 12 and - // check 3 qword at a time. This is less code - // than the 32 bit case and is a shorter path length - - while (length >= 12) - { - if (*(long*)a != *(long*)b) goto ReturnFalse; - if (*(long*)(a + 4) != *(long*)(b + 4)) goto ReturnFalse; - if (*(long*)(a + 8) != *(long*)(b + 8)) goto ReturnFalse; - length -= 12; a += 12; b += 12; - } -#else - while (length >= 10) - { - if (*(int*)a != *(int*)b) goto ReturnFalse; - if (*(int*)(a + 2) != *(int*)(b + 2)) goto ReturnFalse; - if (*(int*)(a + 4) != *(int*)(b + 4)) goto ReturnFalse; - if (*(int*)(a + 6) != *(int*)(b + 6)) goto ReturnFalse; - if (*(int*)(a + 8) != *(int*)(b + 8)) goto ReturnFalse; - length -= 10; a += 10; b += 10; - } -#endif - - // This depends on the fact that the String objects are - // always zero terminated and that the terminating zero is not included - // in the length. For odd string sizes, the last compare will include - // the zero terminator. - while (length > 0) - { - if (*(int*)a != *(int*)b) goto ReturnFalse; - length -= 2; a += 2; b += 2; - } - - return true; - - ReturnFalse: - return false; - } + return SpanHelpers.SequenceEqual( + ref Unsafe.As(ref strA.GetRawStringData()), + ref Unsafe.As(ref strB.GetRawStringData()), + ((nuint)strA.Length) * 2); } - private static unsafe bool StartsWithOrdinalHelper(String str, String startsWith) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int CompareOrdinalHelper(string strA, int indexA, int countA, string strB, int indexB, int countB) { - Debug.Assert(str != null); - Debug.Assert(startsWith != null); - Debug.Assert(str.Length >= startsWith.Length); + Debug.Assert(strA != null); + Debug.Assert(strB != null); + Debug.Assert(indexA >= 0 && indexB >= 0); + Debug.Assert(countA >= 0 && countB >= 0); + Debug.Assert(indexA + countA <= strA.Length && indexB + countB <= strB.Length); - int length = startsWith.Length; - - fixed (char* ap = &str._firstChar) fixed (char* bp = &startsWith._firstChar) - { - char* a = ap; - char* b = bp; - -#if BIT64 - // Single int read aligns pointers for the following long reads - // No length check needed as this method is called when length >= 2 - Debug.Assert(length >= 2); - if (*(int*)a != *(int*)b) goto ReturnFalse; - length -= 2; a += 2; b += 2; - - while (length >= 12) - { - if (*(long*)a != *(long*)b) goto ReturnFalse; - if (*(long*)(a + 4) != *(long*)(b + 4)) goto ReturnFalse; - if (*(long*)(a + 8) != *(long*)(b + 8)) goto ReturnFalse; - length -= 12; a += 12; b += 12; - } -#else - while (length >= 10) - { - if (*(int*)a != *(int*)b) goto ReturnFalse; - if (*(int*)(a + 2) != *(int*)(b + 2)) goto ReturnFalse; - if (*(int*)(a + 4) != *(int*)(b + 4)) goto ReturnFalse; - if (*(int*)(a + 6) != *(int*)(b + 6)) goto ReturnFalse; - if (*(int*)(a + 8) != *(int*)(b + 8)) goto ReturnFalse; - length -= 10; a += 10; b += 10; - } -#endif - - while (length >= 2) - { - if (*(int*)a != *(int*)b) goto ReturnFalse; - length -= 2; a += 2; b += 2; - } - - // PERF: This depends on the fact that the String objects are always zero terminated - // and that the terminating zero is not included in the length. For even string sizes - // this compare can include the zero terminator. Bitwise OR avoids a branch. - return length == 0 | *a == *b; - - ReturnFalse: - return false; - } + return SpanHelpers.SequenceCompareTo(ref Unsafe.Add(ref strA.GetRawStringData(), indexA), countA, ref Unsafe.Add(ref strB.GetRawStringData(), indexB), countB); } - private static unsafe int CompareOrdinalHelper(String strA, String strB) + private static bool EqualsOrdinalIgnoreCase(string strA, string strB) + { + Debug.Assert(strA.Length == strB.Length); + + return CompareInfo.EqualsOrdinalIgnoreCase(ref strA.GetRawStringData(), ref strB.GetRawStringData(), strB.Length); + } + private static unsafe int CompareOrdinalHelper(string strA, string strB) { Debug.Assert(strA != null); Debug.Assert(strB != null); @@ -310,9 +82,9 @@ namespace System // and 64-bit (16 bytes) platforms. // For empty strings, the second char will be null due to padding. - // The start of the string is the EE type pointer + string length, - // which takes up 8 bytes on 32-bit, 12 on x64. For empty strings, - // the null terminator immediately follows, leaving us with an object + // The start of the string is the type pointer + string length, which + // takes up 8 bytes on 32-bit, 12 on x64. For empty strings the null + // terminator immediately follows, leaving us with an object // 10/14 bytes in size. Since everything needs to be a multiple // of 4/8, this will get padded and zeroed out. @@ -348,7 +120,7 @@ namespace System if (*(int*)(a + 4) != *(int*)(b + 4)) goto DiffOffset4; if (*(int*)(a + 6) != *(int*)(b + 6)) goto DiffOffset6; if (*(int*)(a + 8) != *(int*)(b + 8)) goto DiffOffset8; - length -= 10; a += 10; b += 10; + length -= 10; a += 10; b += 10; } #endif // BIT64 @@ -371,20 +143,20 @@ namespace System return strA.Length - strB.Length; #if BIT64 - DiffOffset8: a += 4; b += 4; - DiffOffset4: a += 4; b += 4; + DiffOffset8: a += 4; b += 4; + DiffOffset4: a += 4; b += 4; #else // BIT64 - // Use jumps instead of falling through, since - // otherwise going to DiffOffset8 will involve - // 8 add instructions before getting to DiffNextInt - DiffOffset8: a += 8; b += 8; goto DiffOffset0; - DiffOffset6: a += 6; b += 6; goto DiffOffset0; - DiffOffset4: a += 2; b += 2; - DiffOffset2: a += 2; b += 2; + // Use jumps instead of falling through, since + // otherwise going to DiffOffset8 will involve + // 8 add instructions before getting to DiffNextInt + DiffOffset8: a += 8; b += 8; goto DiffOffset0; + DiffOffset6: a += 6; b += 6; goto DiffOffset0; + DiffOffset4: a += 2; b += 2; + DiffOffset2: a += 2; b += 2; #endif // BIT64 DiffOffset0: - // If we reached here, we already see a difference in the unrolled loop above + // If we reached here, we already see a difference in the unrolled loop above #if BIT64 if (*(int*)a == *(int*)b) { @@ -401,65 +173,59 @@ namespace System } } - internal static unsafe int CompareOrdinalHelper(string strA, int indexA, int countA, string strB, int indexB, int countB) - { - // Argument validation should be handled by callers. - Debug.Assert(strA != null && strB != null); - Debug.Assert(indexA >= 0 && indexB >= 0); - Debug.Assert(countA >= 0 && countB >= 0); - Debug.Assert(countA <= strA.Length - indexA); - Debug.Assert(countB <= strB.Length - indexB); - - // Set up the loop variables. - fixed (char* pStrA = &strA._firstChar, pStrB = &strB._firstChar) - { - char* strAChars = pStrA + indexA; - char* strBChars = pStrB + indexB; - return FastCompareStringHelper((uint*)strAChars, countA, (uint*)strBChars, countB); - } - } - - public static int Compare(String strA, String strB) + // Provides a culture-correct string comparison. StrA is compared to StrB + // to determine whether it is lexicographically less, equal, or greater, and then returns + // either a negative integer, 0, or a positive integer; respectively. + // + public static int Compare(string strA, string strB) { return Compare(strA, strB, StringComparison.CurrentCulture); } - public static int Compare(String strA, String strB, bool ignoreCase) + + // Provides a culture-correct string comparison. strA is compared to strB + // to determine whether it is lexicographically less, equal, or greater, and then a + // negative integer, 0, or a positive integer is returned; respectively. + // The case-sensitive option is set by ignoreCase + // + public static int Compare(string strA, string strB, bool ignoreCase) { var comparisonType = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture; return Compare(strA, strB, comparisonType); } - // Provides a more flexible function for string comparision. See StringComparison + + // Provides a more flexible function for string comparison. See StringComparison // for meaning of different comparisonType. - public static int Compare(String strA, String strB, StringComparison comparisonType) + public static int Compare(string strA, string strB, StringComparison comparisonType) { if (object.ReferenceEquals(strA, strB)) { - StringSpanHelpers.CheckStringComparison(comparisonType); + CheckStringComparison(comparisonType); return 0; } // They can't both be null at this point. if (strA == null) { - StringSpanHelpers.CheckStringComparison(comparisonType); + CheckStringComparison(comparisonType); return -1; } if (strB == null) { - StringSpanHelpers.CheckStringComparison(comparisonType); + CheckStringComparison(comparisonType); return 1; } - switch (comparisonType) { case StringComparison.CurrentCulture: - return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, 0, strA.Length, strB, 0, strB.Length, CompareOptions.None); - case StringComparison.CurrentCultureIgnoreCase: - return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, 0, strA.Length, strB, 0, strB.Length, CompareOptions.IgnoreCase); + return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, GetCaseCompareOfComparisonCulture(comparisonType)); + + case StringComparison.InvariantCulture: + case StringComparison.InvariantCultureIgnoreCase: + return CompareInfo.Invariant.Compare(strA, strB, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: // Most common case: first character is different. @@ -472,24 +238,19 @@ namespace System return CompareOrdinalHelper(strA, strB); case StringComparison.OrdinalIgnoreCase: - return CompareInfo.CompareOrdinalIgnoreCase(strA, 0, strA.Length, strB, 0, strB.Length); - - case StringComparison.InvariantCulture: - return CompareInfo.Invariant.Compare(strA, strB, CompareOptions.None); - - case StringComparison.InvariantCultureIgnoreCase: - return CompareInfo.Invariant.Compare(strA, strB, CompareOptions.IgnoreCase); + return CompareInfo.CompareOrdinalIgnoreCase(strA, strB); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } + // Provides a culture-correct string comparison. strA is compared to strB // to determine whether it is lexicographically less, equal, or greater, and then a // negative integer, 0, or a positive integer is returned; respectively. // - public static int Compare(String strA, String strB, CultureInfo culture, CompareOptions options) + public static int Compare(string strA, string strB, CultureInfo culture, CompareOptions options) { if (culture == null) { @@ -499,24 +260,25 @@ namespace System return culture.CompareInfo.Compare(strA, strB, options); } + + // Provides a culture-correct string comparison. strA is compared to strB // to determine whether it is lexicographically less, equal, or greater, and then a // negative integer, 0, or a positive integer is returned; respectively. // The case-sensitive option is set by ignoreCase, and the culture is set // by culture // - public static int Compare(String strA, String strB, bool ignoreCase, CultureInfo culture) + public static int Compare(string strA, string strB, bool ignoreCase, CultureInfo culture) { - CompareOptions options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; + var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; return Compare(strA, strB, culture, options); } // Determines whether two string regions match. The substring of strA beginning - // at indexA of length length is compared with the substring of strB + // at indexA of given length is compared with the substring of strB // beginning at indexB of the same length. // - - public static int Compare(String strA, int indexA, String strB, int indexB, int length) + public static int Compare(string strA, int indexA, string strB, int indexB, int length) { // NOTE: It's important we call the boolean overload, and not the StringComparison // one. The two have some subtly different behavior (see notes in the former). @@ -524,11 +286,10 @@ namespace System } // Determines whether two string regions match. The substring of strA beginning - // at indexA of length count is compared with the substring of strB + // at indexA of given length is compared with the substring of strB // beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean. // - - public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase) + public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase) { // Ideally we would just forward to the string.Compare overload that takes // a StringComparison parameter, and just pass in CurrentCulture/CurrentCultureIgnoreCase. @@ -539,7 +300,7 @@ namespace System // - string.Compare(null, -1, null, -1, -1, StringComparison.CurrentCulture) works // since that method also returns early for nulls before validation. It shouldn't // for this overload. - // - Since we originally forwarded to FormatProvider for all of the argument + // - Since we originally forwarded to CompareInfo.Compare for all of the argument // validation logic, the ArgumentOutOfRangeExceptions thrown will contain different // parameter names. // Therefore, we have to duplicate some of the logic here. @@ -557,7 +318,7 @@ namespace System lengthB = Math.Min(lengthB, strB.Length - indexB); } - CompareOptions options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; + var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options); } @@ -566,17 +327,18 @@ namespace System // beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean, // and the culture is set by culture. // - public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase, CultureInfo culture) + public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, CultureInfo culture) { - CompareOptions options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; + var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; return Compare(strA, indexA, strB, indexB, length, culture, options); } + // Determines whether two string regions match. The substring of strA beginning // at indexA of length length is compared with the substring of strB // beginning at indexB of the same length. // - public static int Compare(String strA, int indexA, String strB, int indexB, int length, CultureInfo culture, CompareOptions options) + public static int Compare(string strA, int indexA, string strB, int indexB, int length, CultureInfo culture, CompareOptions options) { if (culture == null) { @@ -599,12 +361,13 @@ namespace System return culture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options); } - public static int Compare(String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType) + public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType) { - StringSpanHelpers.CheckStringComparison(comparisonType); + CheckStringComparison(comparisonType); if (strA == null || strB == null) { + if (object.ReferenceEquals(strA, strB)) { // They're both null @@ -614,7 +377,6 @@ namespace System return strA == null ? -1 : 1; } - // @TODO: Spec#: Figure out what to do here with the return statement above. if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); @@ -643,32 +405,25 @@ namespace System switch (comparisonType) { case StringComparison.CurrentCulture: - return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None); - case StringComparison.CurrentCultureIgnoreCase: - return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase); + return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, GetCaseCompareOfComparisonCulture(comparisonType)); + + case StringComparison.InvariantCulture: + case StringComparison.InvariantCultureIgnoreCase: + return CompareInfo.Invariant.Compare(strA, indexA, lengthA, strB, indexB, lengthB, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB); - case StringComparison.OrdinalIgnoreCase: - return CompareInfo.CompareOrdinalIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB); - - case StringComparison.InvariantCulture: - return CompareInfo.Invariant.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None); - - case StringComparison.InvariantCultureIgnoreCase: - return CompareInfo.Invariant.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase); - default: - throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); + Debug.Assert(comparisonType == StringComparison.OrdinalIgnoreCase); // CheckStringComparison validated these earlier + return CompareInfo.CompareOrdinalIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB); } } // Compares strA and strB using an ordinal (code-point) comparison. // - - public static int CompareOrdinal(String strA, String strB) + public static int CompareOrdinal(string strA, string strB) { if (object.ReferenceEquals(strA, strB)) { @@ -695,43 +450,13 @@ namespace System return CompareOrdinalHelper(strA, strB); } - // TODO https://github.com/dotnet/corefx/issues/21395: Expose this publicly? + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int CompareOrdinal(ReadOnlySpan strA, ReadOnlySpan strB) - { - // TODO: Add a vectorized code path, similar to SequenceEqual - // https://github.com/dotnet/corefx/blob/master/src/System.Memory/src/System/SpanHelpers.byte.cs#L900 + => SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(strA), strA.Length, ref MemoryMarshal.GetReference(strB), strB.Length); - int minLength = Math.Min(strA.Length, strB.Length); - ref char first = ref MemoryMarshal.GetReference(strA); - ref char second = ref MemoryMarshal.GetReference(strB); - - int i = 0; - if (minLength >= sizeof(nuint) / sizeof(char)) - { - while (i < minLength - sizeof(nuint) / sizeof(char)) - { - if (Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.Add(ref first, i))) != - Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.Add(ref second, i)))) - { - break; - } - i += sizeof(nuint) / sizeof(char); - } - } - while (i < minLength) - { - char a = Unsafe.Add(ref first, i); - char b = Unsafe.Add(ref second, i); - if (a != b) - { - return a - b; - } - i++; - } - return strA.Length - strB.Length; - } - - public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length) + // Compares strA and strB using an ordinal (code-point) comparison. + // + public static int CompareOrdinal(string strA, int indexA, string strB, int indexB, int length) { if (strA == null || strB == null) { @@ -779,8 +504,7 @@ namespace System // indicates the relationship. This method returns a value less than 0 if this is less than value, 0 // if this is equal to value, or a value greater than 0 if this is greater than value. // - - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) { @@ -799,49 +523,49 @@ namespace System // Determines the sorting relation of StrB to the current instance. // - - public int CompareTo(String strB) + public int CompareTo(string strB) { return string.Compare(this, strB, StringComparison.CurrentCulture); } - // Determines whether a specified string is a suffix of the the current instance. + // Determines whether a specified string is a suffix of the current instance. // // The case-sensitive and culture-sensitive option is set by options, // and the default culture is used. // - - public Boolean EndsWith(String value) + public bool EndsWith(string value) { return EndsWith(value, StringComparison.CurrentCulture); } - public Boolean EndsWith(String value, StringComparison comparisonType) + public bool EndsWith(string value, StringComparison comparisonType) { - if ((Object)value == null) + if ((object)value == null) { throw new ArgumentNullException(nameof(value)); } - - if ((Object)this == (Object)value) + + if ((object)this == (object)value) { - StringSpanHelpers.CheckStringComparison(comparisonType); + CheckStringComparison(comparisonType); return true; } if (value.Length == 0) { - StringSpanHelpers.CheckStringComparison(comparisonType); + CheckStringComparison(comparisonType); return true; } switch (comparisonType) { case StringComparison.CurrentCulture: - return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, CompareOptions.None); - case StringComparison.CurrentCultureIgnoreCase: - return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, CompareOptions.IgnoreCase); + return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); + + case StringComparison.InvariantCulture: + case StringComparison.InvariantCultureIgnoreCase: + return CompareInfo.Invariant.IsSuffix(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: return this.Length < value.Length ? false : (CompareOrdinalHelper(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0); @@ -849,18 +573,12 @@ namespace System case StringComparison.OrdinalIgnoreCase: return this.Length < value.Length ? false : (CompareInfo.CompareOrdinalIgnoreCase(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0); - case StringComparison.InvariantCulture: - return CompareInfo.Invariant.IsSuffix(this, value, CompareOptions.None); - - case StringComparison.InvariantCultureIgnoreCase: - return CompareInfo.Invariant.IsSuffix(this, value, CompareOptions.IgnoreCase); - default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } - public Boolean EndsWith(String value, Boolean ignoreCase, CultureInfo culture) + public bool EndsWith(string value, bool ignoreCase, CultureInfo culture) { if (null == value) { @@ -872,12 +590,7 @@ namespace System return true; } - CultureInfo referenceCulture; - if (culture == null) - referenceCulture = CultureInfo.CurrentCulture; - else - referenceCulture = culture; - + CultureInfo referenceCulture = culture ?? CultureInfo.CurrentCulture; return referenceCulture.CompareInfo.IsSuffix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } @@ -888,13 +601,12 @@ namespace System } // Determines whether two strings match. - - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (Object.ReferenceEquals(this, obj)) + if (object.ReferenceEquals(this, obj)) return true; - String str = obj as String; + string str = obj as string; if (str == null) return false; @@ -905,11 +617,9 @@ namespace System } // Determines whether two strings match. - - - public bool Equals(String value) + public bool Equals(string value) { - if (Object.ReferenceEquals(this, value)) + if (object.ReferenceEquals(this, value)) return true; // NOTE: No need to worry about casting to object here. @@ -925,28 +635,29 @@ namespace System return EqualsHelper(this, value); } - - public bool Equals(String value, StringComparison comparisonType) + public bool Equals(string value, StringComparison comparisonType) { - if ((Object)this == (Object)value) + if ((object)this == (object)value) { - StringSpanHelpers.CheckStringComparison(comparisonType); + CheckStringComparison(comparisonType); return true; } - if ((Object)value == null) + if ((object)value == null) { - StringSpanHelpers.CheckStringComparison(comparisonType); + CheckStringComparison(comparisonType); return false; } switch (comparisonType) { case StringComparison.CurrentCulture: - return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, 0, this.Length, value, 0, value.Length, CompareOptions.None) == 0); - case StringComparison.CurrentCultureIgnoreCase: - return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, 0, this.Length, value, 0, value.Length, CompareOptions.IgnoreCase) == 0); + return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, GetCaseCompareOfComparisonCulture(comparisonType)) == 0); + + case StringComparison.InvariantCulture: + case StringComparison.InvariantCultureIgnoreCase: + return (CompareInfo.Invariant.Compare(this, value, GetCaseCompareOfComparisonCulture(comparisonType)) == 0); case StringComparison.Ordinal: if (this.Length != value.Length) @@ -956,32 +667,24 @@ namespace System case StringComparison.OrdinalIgnoreCase: if (this.Length != value.Length) return false; - else - { - return CompareInfo.CompareOrdinalIgnoreCase(this, 0, this.Length, value, 0, value.Length) == 0; - } - case StringComparison.InvariantCulture: - return (CompareInfo.Invariant.Compare(this, value, CompareOptions.None) == 0); - - case StringComparison.InvariantCultureIgnoreCase: - return (CompareInfo.Invariant.Compare(this, value, CompareOptions.IgnoreCase) == 0); + return EqualsOrdinalIgnoreCase(this, value); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } - // Determines whether two Strings match. - public static bool Equals(String a, String b) + // Determines whether two Strings match. + public static bool Equals(string a, string b) { - if ((Object)a == (Object)b) + if ((object)a == (object)b) { return true; } - if ((Object)a == null || (Object)b == null || a.Length != b.Length) + if ((object)a == null || (object)b == null || a.Length != b.Length) { return false; } @@ -989,27 +692,29 @@ namespace System return EqualsHelper(a, b); } - public static bool Equals(String a, String b, StringComparison comparisonType) + public static bool Equals(string a, string b, StringComparison comparisonType) { - if ((Object)a == (Object)b) + if ((object)a == (object)b) { - StringSpanHelpers.CheckStringComparison(comparisonType); + CheckStringComparison(comparisonType); return true; } - if ((Object)a == null || (Object)b == null) + if ((object)a == null || (object)b == null) { - StringSpanHelpers.CheckStringComparison(comparisonType); + CheckStringComparison(comparisonType); return false; } switch (comparisonType) { case StringComparison.CurrentCulture: - return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, 0, a.Length, b, 0, b.Length, CompareOptions.None) == 0); - case StringComparison.CurrentCultureIgnoreCase: - return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, 0, a.Length, b, 0, b.Length, CompareOptions.IgnoreCase) == 0); + return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, GetCaseCompareOfComparisonCulture(comparisonType)) == 0); + + case StringComparison.InvariantCulture: + case StringComparison.InvariantCultureIgnoreCase: + return (CompareInfo.Invariant.Compare(a, b, GetCaseCompareOfComparisonCulture(comparisonType)) == 0); case StringComparison.Ordinal: if (a.Length != b.Length) @@ -1019,38 +724,22 @@ namespace System case StringComparison.OrdinalIgnoreCase: if (a.Length != b.Length) return false; - else - { - return CompareInfo.CompareOrdinalIgnoreCase(a, 0, a.Length, b, 0, b.Length) == 0; - } - case StringComparison.InvariantCulture: - return (CompareInfo.Invariant.Compare(a, b, CompareOptions.None) == 0); - - case StringComparison.InvariantCultureIgnoreCase: - return (CompareInfo.Invariant.Compare(a, b, CompareOptions.IgnoreCase) == 0); + return EqualsOrdinalIgnoreCase(a, b); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } - public static bool operator ==(String a, String b) + public static bool operator ==(string a, string b) { - if (Object.ReferenceEquals(a, b)) - return true; - if (a == null || b == null || a.Length != b.Length) - return false; - return EqualsHelper(a, b); + return string.Equals(a, b); } - public static bool operator !=(String a, String b) + public static bool operator !=(string a, string b) { - if (Object.ReferenceEquals(a, b)) - return false; - if (a == null || b == null || a.Length != b.Length) - return true; - return !EqualsHelper(a, b); + return !string.Equals(a, b); } // Gets a hash code for this string. If strings A and B are such that A.Equals(B), then @@ -1065,97 +754,82 @@ namespace System } // Gets a hash code for this string and this comparison. If strings A and B and comparison C are such - // that String.Equals(A, B, C), then they will return the same hash code with this comparison C. + // that string.Equals(A, B, C), then they will return the same hash code with this comparison C. public int GetHashCode(StringComparison comparisonType) => StringComparer.FromComparison(comparisonType).GetHashCode(this); - // Use this if and only if you need the hashcode to not change across app domains (e.g. you have an app domain agile - // hash table). - internal int GetLegacyNonRandomizedHashCode() + // Use this if and only if 'Denial of Service' attacks are not a concern (i.e. never used for free-form user input), + // or are otherwise mitigated + internal unsafe int GetNonRandomizedHashCode() { - unsafe + fixed (char* src = &_firstChar) { - fixed (char* src = &_firstChar) + Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'"); + Debug.Assert(((int)src) % 4 == 0, "Managed string should start at 4 bytes boundary"); + + uint hash1 = (5381 << 16) + 5381; + uint hash2 = hash1; + + uint* ptr = (uint*)src; + int length = this.Length; + + while (length > 2) { - Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'"); - Debug.Assert(((int)src) % 4 == 0, "Managed string should start at 4 bytes boundary"); -#if BIT64 - int hash1 = 5381; -#else // !BIT64 (32) - int hash1 = (5381<<16) + 5381; -#endif - int hash2 = hash1; - -#if BIT64 - int c; - char* s = src; - while ((c = s[0]) != 0) - { - hash1 = ((hash1 << 5) + hash1) ^ c; - c = s[1]; - if (c == 0) - break; - hash2 = ((hash2 << 5) + hash2) ^ c; - s += 2; - } -#else // !BIT64 (32) - // 32 bit machines. - int* pint = (int *)src; - int len = this.Length; - while (len > 2) - { - hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0]; - hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ pint[1]; - pint += 2; - len -= 4; - } - - if (len > 0) - { - hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0]; - } -#endif - return hash1 + (hash2 * 1566083941); + length -= 4; + // Where length is 4n-1 (e.g. 3,7,11,15,19) this additionally consumes the null terminator + hash1 = (((hash1 << 5) | (hash1 >> 27)) + hash1) ^ ptr[0]; + hash2 = (((hash2 << 5) | (hash2 >> 27)) + hash2) ^ ptr[1]; + ptr += 2; } + + if (length > 0) + { + // Where length is 4n-3 (e.g. 1,5,9,13,17) this additionally consumes the null terminator + hash2 = (((hash2 << 5) | (hash2 >> 27)) + hash2) ^ ptr[0]; + } + + return (int)(hash1 + (hash2 * 1566083941)); } } // Determines whether a specified string is a prefix of the current instance // - public Boolean StartsWith(String value) + public bool StartsWith(string value) { - if ((Object)value == null) + if ((object)value == null) { throw new ArgumentNullException(nameof(value)); } return StartsWith(value, StringComparison.CurrentCulture); } - public Boolean StartsWith(String value, StringComparison comparisonType) + public bool StartsWith(string value, StringComparison comparisonType) { - if ((Object)value == null) + if ((object)value == null) { throw new ArgumentNullException(nameof(value)); } - if ((Object)this == (Object)value) + if ((object)this == (object)value) { - StringSpanHelpers.CheckStringComparison(comparisonType); + CheckStringComparison(comparisonType); return true; } if (value.Length == 0) { - StringSpanHelpers.CheckStringComparison(comparisonType); + CheckStringComparison(comparisonType); return true; } switch (comparisonType) { case StringComparison.CurrentCulture: - return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.None); - case StringComparison.CurrentCultureIgnoreCase: - return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.IgnoreCase); + return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); + + case StringComparison.InvariantCulture: + case StringComparison.InvariantCultureIgnoreCase: + return CompareInfo.Invariant.IsPrefix(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: if (this.Length < value.Length || _firstChar != value._firstChar) @@ -1163,28 +837,25 @@ namespace System return false; } return (value.Length == 1) ? - true : // First char is the same and thats all there is to compare - StartsWithOrdinalHelper(this, value); + true : // First char is the same and thats all there is to compare + SpanHelpers.SequenceEqual( + ref Unsafe.As(ref this.GetRawStringData()), + ref Unsafe.As(ref value.GetRawStringData()), + ((nuint)value.Length) * 2); case StringComparison.OrdinalIgnoreCase: if (this.Length < value.Length) { return false; } - return CompareInfo.CompareOrdinalIgnoreCase(this, 0, value.Length, value, 0, value.Length) == 0; - - case StringComparison.InvariantCulture: - return CompareInfo.Invariant.IsPrefix(this, value, CompareOptions.None); - - case StringComparison.InvariantCultureIgnoreCase: - return CompareInfo.Invariant.IsPrefix(this, value, CompareOptions.IgnoreCase); + return CompareInfo.EqualsOrdinalIgnoreCase(ref this.GetRawStringData(), ref value.GetRawStringData(), value.Length); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } - public Boolean StartsWith(String value, Boolean ignoreCase, CultureInfo culture) + public bool StartsWith(string value, bool ignoreCase, CultureInfo culture) { if (null == value) { @@ -1196,15 +867,39 @@ namespace System return true; } - CultureInfo referenceCulture; - if (culture == null) - referenceCulture = CultureInfo.CurrentCulture; - else - referenceCulture = culture; - + CultureInfo referenceCulture = culture ?? CultureInfo.CurrentCulture; return referenceCulture.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } public bool StartsWith(char value) => Length != 0 && _firstChar == value; + + internal static void CheckStringComparison(StringComparison comparisonType) + { + // Single comparison to check if comparisonType is within [CurrentCulture .. OrdinalIgnoreCase] + if ((uint)comparisonType > (uint)StringComparison.OrdinalIgnoreCase) + { + ThrowHelper.ThrowArgumentException(ExceptionResource.NotSupported_StringComparison, ExceptionArgument.comparisonType); + } + } + + internal static CompareOptions GetCaseCompareOfComparisonCulture(StringComparison comparisonType) + { + Debug.Assert((uint)comparisonType <= (uint)StringComparison.OrdinalIgnoreCase); + + // Culture enums can be & with CompareOptions.IgnoreCase 0x01 to extract if IgnoreCase or CompareOptions.None 0x00 + // + // CompareOptions.None 0x00 + // CompareOptions.IgnoreCase 0x01 + // + // StringComparison.CurrentCulture: 0x00 + // StringComparison.InvariantCulture: 0x02 + // StringComparison.Ordinal 0x04 + // + // StringComparison.CurrentCultureIgnoreCase: 0x01 + // StringComparison.InvariantCultureIgnoreCase: 0x03 + // StringComparison.OrdinalIgnoreCase 0x05 + + return (CompareOptions)((int)comparisonType & (int)CompareOptions.IgnoreCase); + } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/String.Manipulation.cs b/external/corert/src/System.Private.CoreLib/shared/System/String.Manipulation.cs index 94f34b5829..3da96bb3ba 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/String.Manipulation.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/String.Manipulation.cs @@ -4,7 +4,7 @@ using System.Buffers; using System.Collections.Generic; -using System.Diagnostics.Private; +using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -897,7 +897,7 @@ namespace System return result; } - // a remove that just takes a startindex. + // a remove that just takes a startindex. public string Remove(int startIndex) { if (startIndex < 0) @@ -919,16 +919,12 @@ namespace System switch (comparisonType) { case StringComparison.CurrentCulture: - return ReplaceCore(oldValue, newValue, CultureInfo.CurrentCulture, CompareOptions.None); - case StringComparison.CurrentCultureIgnoreCase: - return ReplaceCore(oldValue, newValue, CultureInfo.CurrentCulture, CompareOptions.IgnoreCase); + return ReplaceCore(oldValue, newValue, CultureInfo.CurrentCulture, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: - return ReplaceCore(oldValue, newValue, CultureInfo.InvariantCulture, CompareOptions.None); - case StringComparison.InvariantCultureIgnoreCase: - return ReplaceCore(oldValue, newValue, CultureInfo.InvariantCulture, CompareOptions.IgnoreCase); + return ReplaceCore(oldValue, newValue, CultureInfo.InvariantCulture, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: return Replace(oldValue, newValue); @@ -1140,7 +1136,7 @@ namespace System int count = replacementIdx - thisIdx; if (count != 0) { - this.AsSpan().Slice(thisIdx, count).CopyTo(dstSpan.Slice(dstIdx)); + this.AsSpan(thisIdx, count).CopyTo(dstSpan.Slice(dstIdx)); dstIdx += count; } thisIdx = replacementIdx + oldValueLength; @@ -1152,7 +1148,7 @@ namespace System // Copy over the final non-matching portion at the end of the string. Debug.Assert(this.Length - thisIdx == dstSpan.Length - dstIdx); - this.AsSpan().Slice(thisIdx).CopyTo(dstSpan.Slice(dstIdx)); + this.AsSpan(thisIdx).CopyTo(dstSpan.Slice(dstIdx)); return dst; } @@ -1252,7 +1248,7 @@ namespace System return new string[] { this }; } - string[] result = omitEmptyEntries + string[] result = omitEmptyEntries ? SplitOmitEmptyEntries(sepList, default, 1, count) : SplitKeepEmptyEntries(sepList, default, 1, count); @@ -1266,7 +1262,7 @@ namespace System return SplitInternal(separator ?? string.Empty, null, int.MaxValue, options); } - public string[] Split(string separator, Int32 count, StringSplitOptions options = StringSplitOptions.None) + public string[] Split(string separator, int count, StringSplitOptions options = StringSplitOptions.None) { return SplitInternal(separator ?? string.Empty, null, count, options); } @@ -1276,7 +1272,7 @@ namespace System return SplitInternal(null, separator, int.MaxValue, options); } - public string[] Split(string[] separator, Int32 count, StringSplitOptions options) + public string[] Split(string[] separator, int count, StringSplitOptions options) { return SplitInternal(null, separator, count, options); } @@ -1317,7 +1313,7 @@ namespace System { return SplitInternal(separator, count, options); } - + Span sepListInitialSpan = stackalloc int[StackallocIntBufferSizeLimit]; var sepListBuilder = new ValueListBuilder(sepListInitialSpan); @@ -1327,14 +1323,14 @@ namespace System MakeSeparatorList(separators, ref sepListBuilder, ref lengthListBuilder); ReadOnlySpan sepList = sepListBuilder.AsSpan(); ReadOnlySpan lengthList = lengthListBuilder.AsSpan(); - + // Handle the special case of no replaces. if (sepList.Length == 0) { return new string[] { this }; } - string[] result = omitEmptyEntries + string[] result = omitEmptyEntries ? SplitOmitEmptyEntries(sepList, lengthList, 0, count) : SplitKeepEmptyEntries(sepList, lengthList, 0, count); @@ -1357,7 +1353,7 @@ namespace System return new string[] { this }; } - string[] result = options == StringSplitOptions.RemoveEmptyEntries + string[] result = options == StringSplitOptions.RemoveEmptyEntries ? SplitOmitEmptyEntries(sepList, default, separator.Length, count) : SplitKeepEmptyEntries(sepList, default, separator.Length, count); @@ -1402,15 +1398,15 @@ namespace System } - // This function will not keep the Empty string + // This function will not keep the Empty string private string[] SplitOmitEmptyEntries(ReadOnlySpan sepList, ReadOnlySpan lengthList, int defaultLength, int count) { Debug.Assert(count >= 2); int numReplaces = sepList.Length; - // Allocate array to hold items. This array may not be - // filled completely in this function, we will create a + // Allocate array to hold items. This array may not be + // filled completely in this function, we will create a // new array and copy string references to that new array. int maxItems = (numReplaces < count) ? (numReplaces + 1) : count; string[] splitStrings = new string[maxItems]; @@ -1557,7 +1553,7 @@ namespace System if (this[i] == separator[0] && currentSepLength <= Length - i) { if (currentSepLength == 1 - || CompareOrdinal(this, i, separator, 0, currentSepLength) == 0) + || this.AsSpan(i, currentSepLength).SequenceEqual(separator)) { sepListBuilder.Append(i); i += currentSepLength - 1; @@ -1571,7 +1567,7 @@ namespace System /// /// separator strngs /// for separator indexes - /// for separator length values + /// for separator length values private void MakeSeparatorList(string[] separators, ref ValueListBuilder sepListBuilder, ref ValueListBuilder lengthListBuilder) { Debug.Assert(separators != null && separators.Length > 0, "separators != null && separators.Length > 0"); @@ -1591,7 +1587,7 @@ namespace System if (this[i] == separator[0] && currentSepLength <= Length - i) { if (currentSepLength == 1 - || CompareOrdinal(this, i, separator, 0, currentSepLength) == 0) + || this.AsSpan(i, currentSepLength).SequenceEqual(separator)) { sepListBuilder.Append(i); lengthListBuilder.Append(currentSepLength); @@ -1702,7 +1698,7 @@ namespace System } // Trims the whitespace from both ends of the string. Whitespace is defined by - // Char.IsWhiteSpace. + // char.IsWhiteSpace. // public string Trim() => TrimWhiteSpaceHelper(TrimType.Both); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/String.Searching.cs b/external/corert/src/System.Private.CoreLib/shared/System/String.Searching.cs index c86d135246..7660c5225f 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/String.Searching.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/String.Searching.cs @@ -22,10 +22,7 @@ namespace System return (IndexOf(value, comparisonType) >= 0); } - public bool Contains(char value) - { - return IndexOf(value) != -1; - } + public bool Contains(char value) => SpanHelpers.Contains(ref _firstChar, value, Length); public bool Contains(char value, StringComparison comparisonType) { @@ -35,10 +32,7 @@ namespace System // Returns the index of the first occurrence of a specified character in the current instance. // The search starts at startIndex and runs thorough the next count characters. // - public int IndexOf(char value) - { - return IndexOf(value, 0, this.Length); - } + public int IndexOf(char value) => SpanHelpers.IndexOf(ref _firstChar, value, Length); public int IndexOf(char value, int startIndex) { @@ -50,19 +44,15 @@ namespace System switch (comparisonType) { case StringComparison.CurrentCulture: - return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, CompareOptions.None); - case StringComparison.CurrentCultureIgnoreCase: - return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, CompareOptions.IgnoreCase); + return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: - return CompareInfo.Invariant.IndexOf(this, value, CompareOptions.None); - case StringComparison.InvariantCultureIgnoreCase: - return CompareInfo.Invariant.IndexOf(this, value, CompareOptions.IgnoreCase); + return CompareInfo.Invariant.IndexOf(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: - return CompareInfo.Invariant.IndexOf(this, value, CompareOptions.Ordinal); + return IndexOf(value); case StringComparison.OrdinalIgnoreCase: return CompareInfo.Invariant.IndexOf(this, value, CompareOptions.OrdinalIgnoreCase); @@ -80,116 +70,11 @@ namespace System if ((uint)count > (uint)(Length - startIndex)) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); - fixed (char* pChars = &_firstChar) - { - char* pCh = pChars + startIndex; - char* pEndCh = pCh + count; + int result = SpanHelpers.IndexOf(ref Unsafe.Add(ref _firstChar, startIndex), value, count); - if (Vector.IsHardwareAccelerated && count >= Vector.Count * 2) - { - unchecked - { - const int elementsPerByte = sizeof(ushort) / sizeof(byte); - int unaligned = ((int)pCh & (Vector.Count - 1)) / elementsPerByte; - count = ((Vector.Count - unaligned) & (Vector.Count - 1)); - } - } - SequentialScan: - while (count >= 4) - { - if (*pCh == value) goto ReturnIndex; - if (*(pCh + 1) == value) goto ReturnIndex1; - if (*(pCh + 2) == value) goto ReturnIndex2; - if (*(pCh + 3) == value) goto ReturnIndex3; - - count -= 4; - pCh += 4; - } - - while (count > 0) - { - if (*pCh == value) - goto ReturnIndex; - - count--; - pCh++; - } - - if (pCh < pEndCh) - { - count = (int)((pEndCh - pCh) & ~(Vector.Count - 1)); - // Get comparison Vector - Vector vComparison = new Vector(value); - while (count > 0) - { - var vMatches = Vector.Equals(vComparison, Unsafe.ReadUnaligned>(pCh)); - if (Vector.Zero.Equals(vMatches)) - { - pCh += Vector.Count; - count -= Vector.Count; - continue; - } - // Find offset of first match - return (int)(pCh - pChars) + LocateFirstFoundChar(vMatches); - } - - if (pCh < pEndCh) - { - unchecked - { - count = (int)(pEndCh - pCh); - } - goto SequentialScan; - } - } - - return -1; - - ReturnIndex3: pCh++; - ReturnIndex2: pCh++; - ReturnIndex1: pCh++; - ReturnIndex: - return (int)(pCh - pChars); - } + return result == -1 ? result : result + startIndex; } - // Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static int LocateFirstFoundChar(Vector match) - { - var vector64 = Vector.AsVectorUInt64(match); - ulong candidate = 0; - int i = 0; - // Pattern unrolled by jit https://github.com/dotnet/coreclr/pull/8001 - for (; i < Vector.Count; i++) - { - candidate = vector64[i]; - if (candidate != 0) - { - break; - } - } - - // Single LEA instruction with jitted const (using function result) - return i * 4 + LocateFirstFoundChar(candidate); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static int LocateFirstFoundChar(ulong match) - { - unchecked - { - // Flag least significant power of two bit - var powerOfTwoFlag = match ^ (match - 1); - // Shift all powers of two into the high byte and extract - return (int)((powerOfTwoFlag * XorPowerOfTwoToHighChar) >> 49); - } - } - - private const ulong XorPowerOfTwoToHighChar = (0x03ul | - 0x02ul << 16 | - 0x01ul << 32) + 1; - // Returns the index of the first occurrence of any specified character in the current instance. // The search starts at startIndex and runs to startIndex + count - 1. // @@ -289,7 +174,7 @@ namespace System private unsafe int IndexOfCharArray(char[] anyOf, int startIndex, int count) { // use probabilistic map, see InitializeProbabilisticMap - ProbabilisticMap map = default(ProbabilisticMap); + ProbabilisticMap map = default; uint* charMap = (uint*)↦ InitializeProbabilisticMap(charMap, anyOf); @@ -374,12 +259,12 @@ namespace System return false; } - private unsafe static bool IsCharBitSet(uint* charMap, byte value) + private static unsafe bool IsCharBitSet(uint* charMap, byte value) { return (charMap[value & PROBABILISTICMAP_BLOCK_INDEX_MASK] & (1u << (value >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT))) != 0; } - private unsafe static void SetCharBit(uint* charMap, byte value) + private static unsafe void SetCharBit(uint* charMap, byte value) { charMap[value & PROBABILISTICMAP_BLOCK_INDEX_MASK] |= 1u << (value >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT); } @@ -434,22 +319,16 @@ namespace System switch (comparisonType) { case StringComparison.CurrentCulture: - return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None); - case StringComparison.CurrentCultureIgnoreCase: - return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); + return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: - return CompareInfo.Invariant.IndexOf(this, value, startIndex, count, CompareOptions.None); - case StringComparison.InvariantCultureIgnoreCase: - return CompareInfo.Invariant.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); + return CompareInfo.Invariant.IndexOf(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: - return CompareInfo.Invariant.IndexOfOrdinal(this, value, startIndex, count, ignoreCase: false); - case StringComparison.OrdinalIgnoreCase: - return CompareInfo.Invariant.IndexOfOrdinal(this, value, startIndex, count, ignoreCase: true); + return CompareInfo.Invariant.IndexOfOrdinal(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); @@ -461,10 +340,7 @@ namespace System // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // - public int LastIndexOf(char value) - { - return LastIndexOf(value, this.Length - 1, this.Length); - } + public int LastIndexOf(char value) => SpanHelpers.LastIndexOf(ref _firstChar, value, Length); public int LastIndexOf(char value, int startIndex) { @@ -482,112 +358,10 @@ namespace System if ((uint)count > (uint)startIndex + 1) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); - fixed (char* pChars = &_firstChar) - { - char* pCh = pChars + startIndex; - char* pEndCh = pCh - count; + int startSearchAt = startIndex + 1 - count; + int result = SpanHelpers.LastIndexOf(ref Unsafe.Add(ref _firstChar, startSearchAt), value, count); - //We search [startIndex..EndIndex] - if (Vector.IsHardwareAccelerated && count >= Vector.Count * 2) - { - unchecked - { - const int elementsPerByte = sizeof(ushort) / sizeof(byte); - count = (((int)pCh & (Vector.Count - 1)) / elementsPerByte) + 1; - } - } - SequentialScan: - while (count >= 4) - { - if (*pCh == value) goto ReturnIndex; - if (*(pCh - 1) == value) goto ReturnIndex1; - if (*(pCh - 2) == value) goto ReturnIndex2; - if (*(pCh - 3) == value) goto ReturnIndex3; - - count -= 4; - pCh -= 4; - } - - while (count > 0) - { - if (*pCh == value) - goto ReturnIndex; - - count--; - pCh--; - } - - if (pCh > pEndCh) - { - count = (int)((pCh - pEndCh) & ~(Vector.Count - 1)); - - // Get comparison Vector - Vector vComparison = new Vector(value); - while (count > 0) - { - char* pStart = pCh - Vector.Count + 1; - var vMatches = Vector.Equals(vComparison, Unsafe.ReadUnaligned>(pStart)); - if (Vector.Zero.Equals(vMatches)) - { - pCh -= Vector.Count; - count -= Vector.Count; - continue; - } - // Find offset of last match - return (int)(pStart - pChars) + LocateLastFoundChar(vMatches); - } - - if (pCh > pEndCh) - { - unchecked - { - count = (int)(pCh - pEndCh); - } - goto SequentialScan; - } - } - return -1; - - ReturnIndex3: pCh--; - ReturnIndex2: pCh--; - ReturnIndex1: pCh--; - ReturnIndex: - return (int)(pCh - pChars); - } - } - - // Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static int LocateLastFoundChar(Vector match) - { - var vector64 = Vector.AsVectorUInt64(match); - ulong candidate = 0; - int i = Vector.Count - 1; - // Pattern unrolled by jit https://github.com/dotnet/coreclr/pull/8001 - for (; i >= 0; i--) - { - candidate = vector64[i]; - if (candidate != 0) - { - break; - } - } - - // Single LEA instruction with jitted const (using function result) - return i * 4 + LocateLastFoundChar(candidate); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static int LocateLastFoundChar(ulong match) - { - // Find the most significant char that has its highest bit set - int index = 3; - while ((long)match > 0) - { - match = match << 16; - index--; - } - return index; + return result == -1 ? result : result + startSearchAt; } // Returns the index of the last occurrence of any specified character in the current instance. @@ -640,7 +414,7 @@ namespace System private unsafe int LastIndexOfCharArray(char[] anyOf, int startIndex, int count) { // use probabilistic map, see InitializeProbabilisticMap - ProbabilisticMap map = default(ProbabilisticMap); + ProbabilisticMap map = default; uint* charMap = (uint*)↦ InitializeProbabilisticMap(charMap, anyOf); @@ -735,22 +509,16 @@ namespace System switch (comparisonType) { case StringComparison.CurrentCulture: - return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.None); - case StringComparison.CurrentCultureIgnoreCase: - return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); + return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: - return CompareInfo.Invariant.LastIndexOf(this, value, startIndex, count, CompareOptions.None); - case StringComparison.InvariantCultureIgnoreCase: - return CompareInfo.Invariant.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); + return CompareInfo.Invariant.LastIndexOf(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: - return CompareInfo.Invariant.LastIndexOfOrdinal(this, value, startIndex, count, ignoreCase: false); - case StringComparison.OrdinalIgnoreCase: - return CompareInfo.Invariant.LastIndexOfOrdinal(this, value, startIndex, count, ignoreCase: true); + return CompareInfo.Invariant.LastIndexOfOrdinal(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); diff --git a/external/corert/src/System.Private.CoreLib/src/System/String.cs b/external/corert/src/System.Private.CoreLib/shared/System/String.cs similarity index 61% rename from external/corert/src/System.Private.CoreLib/src/System/String.cs rename to external/corert/src/System.Private.CoreLib/shared/System/String.cs index 4e43f26c33..c573072eb9 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/String.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/String.cs @@ -2,115 +2,66 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================ -** -** Purpose: Your favorite String class. Native methods -** are implemented in StringNative.cpp -** -===========================================================*/ - using System.Buffers; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; -using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; -using Internal.Runtime.CompilerServices; - namespace System { // The String class represents a static string of characters. Many of - // the String methods perform some type of transformation on the current - // instance and return the result as a new String. All comparison methods are - // implemented as a part of String. As with arrays, character positions - // (indices) are zero-based. + // the string methods perform some type of transformation on the current + // instance and return the result as a new string. As with arrays, character + // positions (indices) are zero-based. - // STRING LAYOUT - // ------------- - // Strings are null-terminated for easy interop with native, but the value returned by String.Length - // does NOT include this null character in its count. As a result, there's some trickiness here in the - // layout and allocation of strings that needs explanation... - // - // String is allocated like any other array, using the RhNewArray API. It is essentially a very special - // char[] object. In order to be an array, the String EEType must have an 'array element size' of 2, - // which is setup by a special case in the binder. Strings must also have a typical array instance - // layout, which means that the first field after the m_pEEType field is the 'number of array elements' - // field. However, here, it is called _stringLength because it contains the number of characters in the - // string (NOT including the terminating null element) and, thus, directly represents both the array - // length and String.Length. - // - // As with all arrays, the GC calculates the size of an object using the following formula: - // - // obj_size = align(base_size + (num_elements * element_size), sizeof(void*)) - // - // The values 'base_size' and 'element_size' are both stored in the EEType for String and 'num_elements' - // is _stringLength. - // - // Our base_size is the size of the fixed portion of the string defined below. It, therefore, contains - // the size of the _firstChar field in it. This means that, since our string data actually starts - // inside the fixed 'base_size' area, and our num_elements is equal to String.Length, we end up with one - // extra character at the end. This is how we get our extra null terminator which allows us to pass a - // pinned string out to native code as a null-terminated string. This is also why we don't increment the - // requested string length by one before passing it to RhNewArray. There is no need to allocate an extra - // array element, it is already allocated here in the fixed layout of the String. - // - // Typically, the base_size of an array type is aligned up to the nearest pointer size multiple (so that - // array elements start out aligned in case they need alignment themselves), but we don't want to do that - // with String because we are allocating String.Length components with RhNewArray and the overall object - // size will then need another alignment, resulting in wasted space. So the binder specially shrinks the - // base_size of String, leaving it unaligned in order to allow the use of that otherwise wasted space. - // - // One more note on base_size -- on 64-bit, the base_size ends up being 22 bytes, which is less than the - // min_obj_size of (3 * sizeof(void*)). This is OK because our array allocator will still align up the - // overall object size, so a 0-length string will end up with an object size of 24 bytes, which meets the - // min_obj_size requirement. - // - // NOTE: This class is marked EagerStaticClassConstruction because McgCurrentModule class being eagerly - // constructed itself depends on this class also being eagerly constructed. Plus, it's nice to have this - // eagerly constructed to avoid the cost of defered ctors. I can't imagine any app that doesn't use string - // [Serializable] - public sealed partial class String : IComparable, IEnumerable, IEnumerable, IComparable, IEquatable, IConvertible, ICloneable + [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] + public sealed partial class String : IComparable, IEnumerable, IConvertible, IEnumerable, IComparable, IEquatable, ICloneable { // String constructors - // These are special. the implementation methods for these have a different signature from the + // These are special. The implementation methods for these have a different signature from the // declared constructors. [MethodImplAttribute(MethodImplOptions.InternalCall)] [PreserveDependency("System.String.CreateString(System.Char[])")] public extern String(char[] value); - [System.Runtime.CompilerServices.DependencyReductionRoot] - private static String Ctor(char[] value) +#if PROJECTN + [DependencyReductionRoot] +#endif +#if !CORECLR + static +#endif + private string Ctor(char[] value) { - if (value != null && value.Length != 0) - { - String result = FastAllocateString(value.Length); + if (value == null || value.Length == 0) + return Empty; - unsafe - { - fixed (char* dest = &result._firstChar, source = value) - { - wstrcpy(dest, source, value.Length); - } - } - return result; + string result = FastAllocateString(value.Length); + unsafe + { + fixed (char* dest = &result._firstChar, source = value) + wstrcpy(dest, source, value.Length); } - else - return String.Empty; + return result; } [MethodImplAttribute(MethodImplOptions.InternalCall)] [PreserveDependency("System.String.CreateString(System.Char[], System.Int32, System.Int32)")] public extern String(char[] value, int startIndex, int length); - [System.Runtime.CompilerServices.DependencyReductionRoot] - private static String Ctor(char[] value, int startIndex, int length) +#if PROJECTN + [DependencyReductionRoot] +#endif +#if !CORECLR + static +#endif + private string Ctor(char[] value, int startIndex, int length) { if (value == null) throw new ArgumentNullException(nameof(value)); @@ -124,96 +75,79 @@ namespace System if (startIndex > value.Length - length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); - if (length > 0) - { - String result = FastAllocateString(length); + if (length == 0) + return Empty; - unsafe - { - fixed (char* dest = &result._firstChar, source = value) - { - wstrcpy(dest, source + startIndex, length); - } - } - return result; + string result = FastAllocateString(length); + unsafe + { + fixed (char* dest = &result._firstChar, source = value) + wstrcpy(dest, source + startIndex, length); } - else - return String.Empty; + return result; } [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [PreserveDependency("System.String.CreateString(System.Char*)")] - unsafe public extern String(char* value); + public extern unsafe String(char* value); - [System.Runtime.CompilerServices.DependencyReductionRoot] - private static unsafe String Ctor(char* ptr) +#if PROJECTN + [DependencyReductionRoot] +#endif +#if !CORECLR + static +#endif + private unsafe string Ctor(char* ptr) { if (ptr == null) - return String.Empty; + return Empty; -#if !PLATFORM_UNIX - if (ptr < (char*)64000) - throw new ArgumentException(SR.Arg_MustBeStringPtrNotAtom); -#endif // PLATFORM_UNIX + int count = wcslen(ptr); + if (count == 0) + return Empty; - try - { - int count = wcslen(ptr); - if (count == 0) - return String.Empty; - - String result = FastAllocateString(count); - fixed (char* dest = &result._firstChar) - wstrcpy(dest, ptr, count); - return result; - } - catch (NullReferenceException) - { - throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR); - } + string result = FastAllocateString(count); + fixed (char* dest = &result._firstChar) + wstrcpy(dest, ptr, count); + return result; } [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [PreserveDependency("System.String.CreateString(System.Char*, System.Int32, System.Int32)")] - unsafe public extern String(char* value, int startIndex, int length); + public extern unsafe String(char* value, int startIndex, int length); - [System.Runtime.CompilerServices.DependencyReductionRoot] - private static unsafe String Ctor(char* ptr, int startIndex, int length) +#if PROJECTN + [DependencyReductionRoot] +#endif +#if !CORECLR + static +#endif + private unsafe string Ctor(char* ptr, int startIndex, int length) { if (length < 0) - { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); - } if (startIndex < 0) - { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); - } - char* pFrom = ptr + startIndex; - if (pFrom < ptr) - { - // This means that the pointer operation has had an overflow + char* pStart = ptr + startIndex; + + // overflow check + if (pStart < ptr) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR); - } if (length == 0) - return String.Empty; + return Empty; - String result = FastAllocateString(length); - - try - { - fixed (char* dest = &result._firstChar) - wstrcpy(dest, pFrom, length); - return result; - } - catch (NullReferenceException) - { + if (ptr == null) throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR); - } + + string result = FastAllocateString(length); + fixed (char* dest = &result._firstChar) + wstrcpy(dest, pStart, length); + return result; } [CLSCompliant(false)] @@ -221,16 +155,23 @@ namespace System [PreserveDependency("System.String.CreateString(System.SByte*)")] public extern unsafe String(sbyte* value); +#if PROJECTN [DependencyReductionRoot] - private static unsafe string Ctor(sbyte* value) +#endif +#if !CORECLR + static +#endif + private unsafe string Ctor(sbyte* value) { byte* pb = (byte*)value; if (pb == null) - return string.Empty; // Compatibility + return Empty; - int numBytes = Buffer.IndexOfByte(pb, 0, 0, int.MaxValue); - if (numBytes < 0) // This check covers the "-1 = not-found" case and "negative length" case (downstream code assumes length is non-negative). - throw new ArgumentException(SR.Arg_ExpectedNulTermination); // We'll likely have AV'd before we get to this point, but just in case... + int numBytes = new ReadOnlySpan((byte*)value, int.MaxValue).IndexOf(0); + + // Check for overflow + if (numBytes < 0) + throw new ArgumentException(SR.Arg_MustBeNullTerminatedString); return CreateStringForSByteConstructor(pb, numBytes); } @@ -240,39 +181,47 @@ namespace System [PreserveDependency("System.String.CreateString(System.SByte*, System.Int32, System.Int32)")] public extern unsafe String(sbyte* value, int startIndex, int length); +#if PROJECTN [DependencyReductionRoot] - private static unsafe string Ctor(sbyte* value, int startIndex, int length) +#endif +#if !CORECLR + static +#endif + private unsafe string Ctor(sbyte* value, int startIndex, int length) { - byte* pb = (byte*)value; - if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); - if (pb == null) - throw new ArgumentNullException(nameof(value)); + if (value == null) + { + if (length == 0) + return Empty; - byte* pStart = pb + startIndex; - if (pStart < pb) + throw new ArgumentNullException(nameof(value)); + } + + byte* pStart = (byte*)(value + startIndex); + + // overflow check + if (pStart < value) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_PartialWCHAR); return CreateStringForSByteConstructor(pStart, length); } - // Encoder for String..ctor(sbyte*) and String..ctor(sbyte*, int, int). One of the last bastions of ANSI in the framework... + // Encoder for String..ctor(sbyte*) and String..ctor(sbyte*, int, int) private static unsafe string CreateStringForSByteConstructor(byte *pb, int numBytes) { Debug.Assert(numBytes >= 0); Debug.Assert(pb <= (pb + numBytes)); if (numBytes == 0) - return string.Empty; + return Empty; -#if PLATFORM_UNIX || MONO - return Encoding.UTF8.GetString(pb, numBytes); -#else +#if PLATFORM_WINDOWS int numCharsRequired = Interop.Kernel32.MultiByteToWideChar(Interop.Kernel32.CP_ACP, Interop.Kernel32.MB_PRECOMPOSED, pb, numBytes, (char*)null, 0); if (numCharsRequired == 0) throw new ArgumentException(SR.Arg_InvalidANSIString); @@ -285,6 +234,8 @@ namespace System if (numCharsRequired == 0) throw new ArgumentException(SR.Arg_InvalidANSIString); return newString; +#else + return Encoding.UTF8.GetString(pb, numBytes); #endif } @@ -293,14 +244,20 @@ namespace System [PreserveDependency("System.String.CreateString(System.SByte*, System.Int32, System.Int32, System.Text.Encoding)")] public extern unsafe String(sbyte* value, int startIndex, int length, Encoding enc); +#if PROJECTN [DependencyReductionRoot] - private static unsafe string Ctor(sbyte* value, int startIndex, int length, Encoding enc) +#endif +#if !CORECLR + static +#endif + private unsafe string Ctor(sbyte* value, int startIndex, int length, Encoding enc) { if (enc == null) return new string(value, startIndex, length); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); + if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); @@ -315,40 +272,44 @@ namespace System byte* pStart = (byte*)(value + startIndex); if (pStart < value) { - // overflow check + if (length == 0) + return Empty; + + throw new ArgumentNullException(nameof(value)); + } + + byte* pStart = (byte*)(value + startIndex); + + // overflow check + if (pStart < value) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR); - } - byte[] copyOfValue = new byte[length]; - fixed (byte* pCopyOfValue = copyOfValue) - { - try - { - Buffer.Memcpy(dest: pCopyOfValue, src: pStart, len: length); - } - catch (Exception) - { - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_PartialWCHAR); - } - } - - return enc.GetString(copyOfValue); + return enc.GetString(new ReadOnlySpan(pStart, length)); } [MethodImplAttribute(MethodImplOptions.InternalCall)] [PreserveDependency("System.String.CreateString(System.Char, System.Int32)")] public extern String(char c, int count); - [System.Runtime.CompilerServices.DependencyReductionRoot] - private static String Ctor(char c, int count) +#if PROJECTN + [DependencyReductionRoot] +#endif +#if !CORECLR + static +#endif + private string Ctor(char c, int count) { - if (count > 0) + if (count <= 0) { - String result = FastAllocateString(count); + if (count == 0) + return Empty; + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount); + } - if (c == '\0') - return result; // Fast path null char string + string result = FastAllocateString(count); + if (c != '\0') // Fast path null char string + { unsafe { fixed (char* dest = &result._firstChar) @@ -375,56 +336,49 @@ namespace System ((char*)dmem)[0] = c; } } - return result; } - else if (count == 0) - return String.Empty; - else - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount); + return result; } [MethodImplAttribute(MethodImplOptions.InternalCall)] [PreserveDependency("System.String.CreateString(System.ReadOnlySpan`1)")] public extern String(ReadOnlySpan value); +#if PROJECTN [DependencyReductionRoot] - private unsafe static string Ctor(ReadOnlySpan value) +#endif +#if !CORECLR + static +#endif + private unsafe string Ctor(ReadOnlySpan value) { if (value.Length == 0) - { return Empty; - } string result = FastAllocateString(value.Length); fixed (char* dest = &result._firstChar, src = &MemoryMarshal.GetReference(value)) - { wstrcpy(dest, src, value.Length); - } return result; } public static string Create(int length, TState state, SpanAction action) { if (action == null) - { throw new ArgumentNullException(nameof(action)); - } - if (length > 0) + if (length <= 0) { - string result = FastAllocateString(length); - action(new Span(ref result.GetRawStringData(), length), state); - return result; + if (length == 0) + return Empty; + throw new ArgumentOutOfRangeException(nameof(length)); } - if (length == 0) - { - return Empty; - } - - throw new ArgumentOutOfRangeException(nameof(length)); + string result = FastAllocateString(length); + action(new Span(ref result.GetRawStringData(), length), state); + return result; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator ReadOnlySpan(string value) => value != null ? new ReadOnlySpan(ref value.GetRawStringData(), value.Length) : default; @@ -433,22 +387,14 @@ namespace System return this; } - public static unsafe String Copy(String str) + public static unsafe string Copy(string str) { if (str == null) - { throw new ArgumentNullException(nameof(str)); - } - int length = str.Length; - - String result = FastAllocateString(length); - - fixed (char* dest = &result._firstChar) - fixed (char* src = &str._firstChar) - { - wstrcpy(dest, src, length); - } + string result = FastAllocateString(str.Length); + fixed (char* dest = &result._firstChar, src = &str._firstChar) + wstrcpy(dest, src, str.Length); return result; } @@ -457,7 +403,7 @@ namespace System // sourceIndex + count - 1 to the character array buffer, beginning // at destinationIndex. // - unsafe public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) + public unsafe void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) throw new ArgumentNullException(nameof(destination)); @@ -470,94 +416,72 @@ namespace System if (destinationIndex > destination.Length - count || destinationIndex < 0) throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_IndexCount); - // Note: fixed does not like empty arrays - if (count > 0) - { - fixed (char* src = &_firstChar) - fixed (char* dest = destination) - wstrcpy(dest + destinationIndex, src + sourceIndex, count); - } + fixed (char* src = &_firstChar, dest = destination) + wstrcpy(dest + destinationIndex, src + sourceIndex, count); } // Returns the entire string as an array of characters. - unsafe public char[] ToCharArray() + public unsafe char[] ToCharArray() { - // Huge performance improvement for short strings by doing this. - int length = Length; - if (length > 0) - { - char[] chars = new char[length]; - fixed (char* src = &_firstChar) - fixed (char* dest = &chars[0]) - { - wstrcpy(dest, src, length); - } - return chars; - } - return Array.Empty(); + if (Length == 0) + return Array.Empty(); + + char[] chars = new char[Length]; + fixed (char* src = &_firstChar, dest = &chars[0]) + wstrcpy(dest, src, Length); + return chars; } // Returns a substring of this string as an array of characters. // - unsafe public char[] ToCharArray(int startIndex, int length) + public unsafe char[] ToCharArray(int startIndex, int length) { // Range check everything. if (startIndex < 0 || startIndex > Length || startIndex > Length - length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); - if (length < 0) - throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index); - if (length > 0) + if (length <= 0) { - char[] chars = new char[length]; - fixed (char* src = &_firstChar) - fixed (char* dest = &chars[0]) - { - wstrcpy(dest, src + startIndex, length); - } - return chars; + if (length == 0) + return Array.Empty(); + throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index); } - return Array.Empty(); + + char[] chars = new char[length]; + fixed (char* src = &_firstChar, dest = &chars[0]) + wstrcpy(dest, src + startIndex, length); + return chars; } - public static bool IsNullOrEmpty(String value) + [NonVersionable] + public static bool IsNullOrEmpty(string value) { - return (value == null || value.Length == 0); + // Using 0u >= (uint)value.Length rather than + // value.Length == 0 as it will elide the bounds check to + // the first char: value[0] if that is performed following the test + // for the same test cost. + // Ternary operator returning true/false prevents redundant asm generation: + // https://github.com/dotnet/coreclr/issues/914 + return (value == null || 0u >= (uint)value.Length) ? true : false; } - public static bool IsNullOrWhiteSpace(String value) + public static bool IsNullOrWhiteSpace(string value) { if (value == null) return true; for (int i = 0; i < value.Length; i++) { - if (!Char.IsWhiteSpace(value[i])) return false; + if (!char.IsWhiteSpace(value[i])) return false; } return true; } - // Gets the length of this string - // - /// This is a EE implemented function so that the JIT can recognise is specially - /// and eliminate checks on character fetchs in a loop like: - /// for(int i = 0; i < str.Length; i++) str[i] - /// The actually code generated for this will be one instruction and will be inlined. - // - // Spec#: Add postcondition in a contract assembly. Potential perf problem. - public int Length - { - get { return _stringLength; } - } - - internal ref char GetRawStringData() - { - return ref _firstChar; - } + internal ref char GetRawStringData() => ref _firstChar; // Helper for encodings so they can talk to our buffer directly // stringLength must be the exact size we'll expect - unsafe internal static String CreateStringFromEncoding( + internal static unsafe string CreateStringFromEncoding( byte* bytes, int byteLength, Encoding encoding) { Debug.Assert(bytes != null); @@ -570,9 +494,9 @@ namespace System // They gave us an empty string if they needed one // 0 bytelength might be possible if there's something in an encoder if (stringLength == 0) - return String.Empty; + return Empty; - String s = FastAllocateString(stringLength); + string s = FastAllocateString(stringLength); fixed (char* pTempChars = &s._firstChar) { int doubleCheck = encoding.GetChars(bytes, byteLength, pTempChars, stringLength, null); @@ -600,13 +524,13 @@ namespace System // Returns this string. - public override String ToString() + public override string ToString() { return this; } // Returns this string. - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return this; } @@ -641,6 +565,9 @@ namespace System } #if !BIT64 + // The following code is (somewhat surprisingly!) significantly faster than a naive loop, + // at least on x86 and the current jit. + // The loop condition below works because if "end[0] & end[1]" is non-zero, that means // neither operand can have been zero. If is zero, we have to look at the operands individually, // but we hope this going to fairly rare. @@ -676,7 +603,7 @@ namespace System // NOTE: We can access a ulong a time since the ptr is aligned, // and therefore we're only accessing the same word/page. (See notes // for the 32-bit version above.) - + const ulong MagicMask = 0x7fff7fff7fff7fff; while (true) @@ -715,6 +642,14 @@ namespace System int count = (int)(end - ptr); +#if BIT64 + // Check for overflow + if (ptr + count != end) + throw new ArgumentException(SR.Arg_MustBeNullTerminatedString); +#else + Debug.Assert(ptr + count == end); +#endif + return count; } @@ -787,7 +722,7 @@ namespace System return Convert.ToDouble(this, provider); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this, provider); } @@ -797,7 +732,7 @@ namespace System return Convert.ToDateTime(this, provider); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } @@ -811,16 +746,38 @@ namespace System public bool IsNormalized(NormalizationForm normalizationForm) { +#if CORECLR + if (this.IsFastSort()) + { + // If its FastSort && one of the 4 main forms, then its already normalized + if (normalizationForm == NormalizationForm.FormC || + normalizationForm == NormalizationForm.FormKC || + normalizationForm == NormalizationForm.FormD || + normalizationForm == NormalizationForm.FormKD) + return true; + } +#endif return Normalization.IsNormalized(this, normalizationForm); } - public String Normalize() + public string Normalize() { return Normalize(NormalizationForm.FormC); } - public String Normalize(NormalizationForm normalizationForm) + public string Normalize(NormalizationForm normalizationForm) { +#if CORECLR + if (this.IsAscii()) + { + // If its FastSort && one of the 4 main forms, then its already normalized + if (normalizationForm == NormalizationForm.FormC || + normalizationForm == NormalizationForm.FormKC || + normalizationForm == NormalizationForm.FormD || + normalizationForm == NormalizationForm.FormKD) + return this; + } +#endif return Normalization.Normalize(this, normalizationForm); } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/StringComparer.cs b/external/corert/src/System.Private.CoreLib/shared/System/StringComparer.cs index de311e91d1..47731cb782 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/StringComparer.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/StringComparer.cs @@ -114,10 +114,10 @@ namespace System if (x == null) return -1; if (y == null) return 1; - String sa = x as String; + string sa = x as string; if (sa != null) { - String sb = y as String; + string sb = y as string; if (sb != null) { return Compare(sa, sb); @@ -133,15 +133,15 @@ namespace System throw new ArgumentException(SR.Argument_ImplementIComparable); } - public new bool Equals(Object x, Object y) + public new bool Equals(object x, object y) { if (x == y) return true; if (x == null || y == null) return false; - String sa = x as String; + string sa = x as string; if (sa != null) { - String sb = y as String; + string sb = y as string; if (sb != null) { return Equals(sa, sb); @@ -165,8 +165,8 @@ namespace System return obj.GetHashCode(); } - public abstract int Compare(String x, String y); - public abstract bool Equals(String x, String y); + public abstract int Compare(string x, string y); + public abstract bool Equals(string x, string y); public abstract int GetHashCode(string obj); } @@ -293,7 +293,7 @@ namespace System { return false; } - return (string.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0); + return string.Equals(x, y, StringComparison.OrdinalIgnoreCase); } return x.Equals(y); } @@ -307,7 +307,7 @@ namespace System if (_ignoreCase) { - return TextInfo.GetHashCodeOrdinalIgnoreCase(obj); + return CompareInfo.GetIgnoreCaseHash(obj); } return obj.GetHashCode(); @@ -375,7 +375,7 @@ namespace System { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); } - return TextInfo.GetHashCodeOrdinalIgnoreCase(obj); + return CompareInfo.GetIgnoreCaseHash(obj); } public void GetObjectData(SerializationInfo info, StreamingContext context) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/StringSpanHelpers.cs b/external/corert/src/System.Private.CoreLib/shared/System/StringSpanHelpers.cs deleted file mode 100644 index 9ddcc94503..0000000000 --- a/external/corert/src/System.Private.CoreLib/shared/System/StringSpanHelpers.cs +++ /dev/null @@ -1,142 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Globalization; - -namespace System -{ - /// Helpers for string-like operations on spans of chars. - internal static class StringSpanHelpers - { - // TODO https://github.com/dotnet/corefx/issues/21395: Provide public, efficient implementations - - public static bool Equals(this ReadOnlySpan left, ReadOnlySpan right, StringComparison comparisonType) => - comparisonType == StringComparison.Ordinal ? Equals(left, right) : - comparisonType == StringComparison.OrdinalIgnoreCase ? EqualsOrdinalIgnoreCase(left, right) : - throw new ArgumentOutOfRangeException(nameof(comparisonType)); - - public static bool Equals(this ReadOnlySpan left, string right) => - Equals(left, right.AsSpan()); - - public static bool Equals(this ReadOnlySpan left, ReadOnlySpan right) - { - if (left.Length != right.Length) - { - return false; - } - - for (int i = 0; i < left.Length; i++) - { - if (left[i] != right[i]) - { - return false; - } - } - - return true; - } - -#if MONO - internal -#endif - static bool EqualsOrdinalIgnoreCase(this ReadOnlySpan left, ReadOnlySpan right) - { - if (left.Length != right.Length) - { - return false; - } - - for (int i = 0; i < left.Length; i++) - { - char x = left[i], y = right[i]; - if (x != y && - TextInfo.ToUpperAsciiInvariant(x) != TextInfo.ToUpperAsciiInvariant(y)) - { - return false; - } - } - - return true; - } - - public static int IndexOf(this ReadOnlySpan source, char value) => - IndexOf(source, value, 0); - - public static int IndexOf(this ReadOnlySpan source, char value, int startIndex) - { - for (int i = startIndex; i < source.Length; i++) - { - if (source[i] == value) - { - return i; - } - } - - return -1; - } - - public static bool Contains(this ReadOnlySpan source, char value) - { - for (int i = 0; i < source.Length; i++) - { - if (source[i] == value) - { - return true; - } - } - - return false; - } - - public static ReadOnlySpan Remove(this ReadOnlySpan source, int startIndex, int count) - { - if (startIndex < 0) - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount); - if (count > source.Length - startIndex) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_IndexCount); - - if (count == 0) - { - return source; - } - - int newLength = source.Length - count; - if (newLength == 0) - { - return ReadOnlySpan.Empty; - } - - Span result = new char[newLength]; - source.Slice(0, startIndex).CopyTo(result); - source.Slice(startIndex + count).CopyTo(result.Slice(startIndex)); - return result; - } - - // Returns the index of the last occurrence of a specified character in the current instance. - public static int LastIndexOf(this ReadOnlySpan source, char value) - { - if (source.Length == 0) - return -1; - - for (int i = source.Length - 1; i >= 0; i--) - { - if (source[i] == value) - return i; - } - - return -1; - } - - public static void CheckStringComparison(StringComparison comparisonType) - { - // Single comparison to check if comparisonType is within [CurrentCulture .. OrdinalIgnoreCase] - if ((uint)(comparisonType - StringComparison.CurrentCulture) > (StringComparison.OrdinalIgnoreCase - StringComparison.CurrentCulture)) - { - throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); - } - } - } -} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/SystemException.cs b/external/corert/src/System.Private.CoreLib/shared/System/SystemException.cs index b7e8e42175..9a1daf2104 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/SystemException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/SystemException.cs @@ -16,13 +16,13 @@ namespace System HResult = HResults.COR_E_SYSTEM; } - public SystemException(String message) + public SystemException(string message) : base(message) { HResult = HResults.COR_E_SYSTEM; } - public SystemException(String message, Exception innerException) + public SystemException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_SYSTEM; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/ASCIIEncoding.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/ASCIIEncoding.cs index e89943a192..217d934677 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/ASCIIEncoding.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/ASCIIEncoding.cs @@ -31,7 +31,7 @@ namespace System.Text { } - internal override void SetDefaultFallbacks() + internal sealed override void SetDefaultFallbacks() { // For ASCIIEncoding we just use default replacement fallback this.encoderFallback = EncoderFallback.ReplacementFallback; @@ -59,13 +59,13 @@ namespace System.Text { // Validate input parameters if (chars == null) - throw new ArgumentNullException("chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) - throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input, return 0, avoid fixed empty array problem if (count == 0) @@ -81,11 +81,11 @@ namespace System.Text // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetByteCount(String chars) + public override unsafe int GetByteCount(string chars) { // Validate input if (chars==null) - throw new ArgumentNullException("chars"); + throw new ArgumentNullException(nameof(chars)); fixed (char* pChars = chars) return GetByteCount(pChars, chars.Length, null); @@ -100,34 +100,42 @@ namespace System.Text { // Validate Parameters if (chars == null) - throw new ArgumentNullException("chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) - throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); // Call it with empty encoder return GetByteCount(chars, count, null); } + public override unsafe int GetByteCount(ReadOnlySpan chars) + { + fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) + { + return GetByteCount(charsPtr, chars.Length, encoder: null); + } + } + // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding - public override unsafe int GetBytes(String chars, int charIndex, int charCount, + public override unsafe int GetBytes(string chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); + throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCount); + throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) - throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); int byteCount = bytes.Length - byteIndex; @@ -154,16 +162,16 @@ namespace System.Text { // Validate parameters if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); + throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) - throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); // If nothing to encode return 0 if (charCount == 0) @@ -186,14 +194,23 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); return GetBytes(chars, charCount, bytes, byteCount, null); } + public override unsafe int GetBytes(ReadOnlySpan chars, Span bytes) + { + fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) + fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) + { + return GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length, encoder: null); + } + } + // Returns the number of characters produced by decoding a range of bytes // in a byte array. // @@ -206,13 +223,13 @@ namespace System.Text { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input just return 0, fixed doesn't like 0 length arrays if (count == 0) @@ -232,14 +249,22 @@ namespace System.Text { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) - throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); return GetCharCount(bytes, count, null); } + public override unsafe int GetCharCount(ReadOnlySpan bytes) + { + fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) + { + return GetCharCount(bytesPtr, bytes.Length, decoder: null); + } + } + // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding @@ -250,16 +275,16 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if ( bytes.Length - byteIndex < byteCount) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) - throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); // If no input, return 0 & avoid fixed problem if (byteCount == 0) @@ -282,14 +307,23 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); return GetChars(bytes, byteCount, chars, charCount, null); } + public override unsafe int GetChars(ReadOnlySpan bytes, Span chars) + { + fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) + fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) + { + return GetChars(bytesPtr, bytes.Length, charsPtr, chars.Length, decoder: null); + } + } + // Returns a string containing the decoded representation of a range of // bytes in a byte array. // @@ -298,24 +332,24 @@ namespace System.Text // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe String GetString(byte[] bytes, int byteIndex, int byteCount) + public override unsafe string GetString(byte[] bytes, int byteIndex, int byteCount) { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid problems with empty input buffer - if (byteCount == 0) return String.Empty; + if (byteCount == 0) return string.Empty; fixed (byte* pBytes = bytes) - return String.CreateStringFromEncoding( + return string.CreateStringFromEncoding( pBytes + byteIndex, byteCount, this); } @@ -326,7 +360,7 @@ namespace System.Text // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption - internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder) + internal sealed override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative"); @@ -348,7 +382,7 @@ namespace System.Text if (encoder != null) { charLeftOver = encoder._charLeftOver; - Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; @@ -400,7 +434,7 @@ namespace System.Text // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { - Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); + Debug.Assert(char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); Debug.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder"); // Since left over char was a surrogate, it'll have to be fallen back. @@ -460,8 +494,8 @@ namespace System.Text return byteCount; } - internal override unsafe int GetBytes(char* chars, int charCount, - byte* bytes, int byteCount, EncoderNLS encoder) + internal sealed override unsafe int GetBytes( + char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null"); @@ -502,7 +536,7 @@ namespace System.Text fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); } - Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetBytes]leftover character should be high surrogate"); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert @@ -676,7 +710,7 @@ namespace System.Text } // This is internal and called by something else, - internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) + internal sealed override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already Debug.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null"); @@ -748,8 +782,8 @@ namespace System.Text return charCount; } - internal override unsafe int GetChars(byte* bytes, int byteCount, - char* chars, int charCount, DecoderNLS decoder) + internal sealed override unsafe int GetChars( + byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null"); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/Decoder.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/Decoder.cs index b827648fc1..b4a7575ba6 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/Decoder.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/Decoder.cs @@ -134,7 +134,7 @@ namespace System.Text public virtual unsafe int GetCharCount(ReadOnlySpan bytes, bool flush) { - fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) + fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return GetCharCount(bytesPtr, bytes.Length, flush); } @@ -227,8 +227,8 @@ namespace System.Text public virtual unsafe int GetChars(ReadOnlySpan bytes, Span chars, bool flush) { - fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) - fixed (char* charsPtr = &MemoryMarshal.GetReference(chars)) + fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) + fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) { return GetChars(bytesPtr, bytes.Length, charsPtr, chars.Length, flush); } @@ -341,8 +341,8 @@ namespace System.Text public virtual unsafe void Convert(ReadOnlySpan bytes, Span chars, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { - fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) - fixed (char* charsPtr = &MemoryMarshal.GetReference(chars)) + fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) + fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) { Convert(bytesPtr, bytes.Length, charsPtr, chars.Length, flush, out bytesUsed, out charsUsed, out completed); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs index 30c817c91a..8c62730c26 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs @@ -38,7 +38,7 @@ namespace System.Text } } - public override bool Equals(Object value) + public override bool Equals(object value) { InternalDecoderBestFitFallback that = value as InternalDecoderBestFitFallback; if (that != null) @@ -63,15 +63,15 @@ namespace System.Text private InternalDecoderBestFitFallback _oFallback; // Private object for locking instead of locking on a public type for SQL reliability work. - private static Object s_InternalSyncObject; - private static Object InternalSyncObject + private static object s_InternalSyncObject; + private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { - Object o = new Object(); - Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); + object o = new object(); + Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs index 8bfc1f32d3..56c004714f 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs @@ -29,7 +29,7 @@ namespace System.Text } } - public override bool Equals(Object value) + public override bool Equals(object value) { DecoderExceptionFallback that = value as DecoderExceptionFallback; if (that != null) @@ -112,19 +112,19 @@ namespace System.Text HResult = HResults.COR_E_ARGUMENT; } - public DecoderFallbackException(String message) + public DecoderFallbackException(string message) : base(message) { HResult = HResults.COR_E_ARGUMENT; } - public DecoderFallbackException(String message, Exception innerException) + public DecoderFallbackException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_ARGUMENT; } - public DecoderFallbackException(String message, byte[] bytesUnknown, int index) + public DecoderFallbackException(string message, byte[] bytesUnknown, int index) : base(message) { _bytesUnknown = bytesUnknown; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderFallback.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderFallback.cs index 11b9539b5c..fff8ad1d7b 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderFallback.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderFallback.cs @@ -104,9 +104,9 @@ namespace System.Text while ((ch = GetNextChar()) != 0) { // Make sure no mixed up surrogates - if (Char.IsSurrogate(ch)) + if (char.IsSurrogate(ch)) { - if (Char.IsHighSurrogate(ch)) + if (char.IsHighSurrogate(ch)) { // High Surrogate if (bHighSurrogate) @@ -159,9 +159,9 @@ namespace System.Text while ((ch = GetNextChar()) != 0) { // Make sure no mixed up surrogates - if (Char.IsSurrogate(ch)) + if (char.IsSurrogate(ch)) { - if (Char.IsHighSurrogate(ch)) + if (char.IsHighSurrogate(ch)) { // High Surrogate if (bHighSurrogate) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs index 422b80bb2f..a97baf05cb 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs @@ -9,14 +9,14 @@ namespace System.Text public sealed class DecoderReplacementFallback : DecoderFallback { // Our variables - private String _strDefault; + private string _strDefault; // Construction. Default replacement fallback uses no best fit and ? replacement string public DecoderReplacementFallback() : this("?") { } - public DecoderReplacementFallback(String replacement) + public DecoderReplacementFallback(string replacement) { if (replacement == null) throw new ArgumentNullException(nameof(replacement)); @@ -26,10 +26,10 @@ namespace System.Text for (int i = 0; i < replacement.Length; i++) { // Found a surrogate? - if (Char.IsSurrogate(replacement, i)) + if (char.IsSurrogate(replacement, i)) { // High or Low? - if (Char.IsHighSurrogate(replacement, i)) + if (char.IsHighSurrogate(replacement, i)) { // if already had a high one, stop if (bFoundHigh) @@ -60,7 +60,7 @@ namespace System.Text _strDefault = replacement; } - public String DefaultString + public string DefaultString { get { @@ -82,7 +82,7 @@ namespace System.Text } } - public override bool Equals(Object value) + public override bool Equals(object value) { DecoderReplacementFallback that = value as DecoderReplacementFallback; if (that != null) @@ -103,7 +103,7 @@ namespace System.Text public sealed class DecoderReplacementFallbackBuffer : DecoderFallbackBuffer { // Store our default string - private String _strDefault; + private string _strDefault; private int _fallbackCount = -1; private int _fallbackIndex = -1; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/Encoder.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/Encoder.cs index fb1bdb8038..df7d51203f 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/Encoder.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/Encoder.cs @@ -132,7 +132,7 @@ namespace System.Text public virtual unsafe int GetByteCount(ReadOnlySpan chars, bool flush) { - fixed (char* charsPtr = &MemoryMarshal.GetReference(chars)) + fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) { return GetByteCount(charsPtr, chars.Length, flush); } @@ -221,8 +221,8 @@ namespace System.Text public virtual unsafe int GetBytes(ReadOnlySpan chars, Span bytes, bool flush) { - fixed (char* charsPtr = &MemoryMarshal.GetReference(chars)) - fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) + fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) + fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length, flush); } @@ -335,8 +335,8 @@ namespace System.Text public virtual unsafe void Convert(ReadOnlySpan chars, Span bytes, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { - fixed (char* charsPtr = &MemoryMarshal.GetReference(chars)) - fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) + fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) + fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { Convert(charsPtr, chars.Length, bytesPtr, bytes.Length, flush, out charsUsed, out bytesUsed, out completed); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs index 7f3be2a7a6..4aab3f62a3 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs @@ -38,7 +38,7 @@ namespace System.Text } } - public override bool Equals(Object value) + public override bool Equals(object value) { InternalEncoderBestFitFallback that = value as InternalEncoderBestFitFallback; if (that != null) @@ -63,15 +63,15 @@ namespace System.Text private int _iSize; // Private object for locking instead of locking on a public type for SQL reliability work. - private static Object s_InternalSyncObject; - private static Object InternalSyncObject + private static object s_InternalSyncObject; + private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { - Object o = new Object(); - Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); + object o = new object(); + Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } @@ -113,12 +113,12 @@ namespace System.Text public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { // Double check input surrogate pair - if (!Char.IsHighSurrogate(charUnknownHigh)) + if (!char.IsHighSurrogate(charUnknownHigh)) throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF)); - if (!Char.IsLowSurrogate(charUnknownLow)) + if (!char.IsLowSurrogate(charUnknownLow)) throw new ArgumentOutOfRangeException(nameof(charUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs index 66de1940f6..92afcf701a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs @@ -28,7 +28,7 @@ namespace System.Text } } - public override bool Equals(Object value) + public override bool Equals(object value) { EncoderExceptionFallback that = value as EncoderExceptionFallback; if (that != null) @@ -57,18 +57,18 @@ namespace System.Text public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { - if (!Char.IsHighSurrogate(charUnknownHigh)) + if (!char.IsHighSurrogate(charUnknownHigh)) { throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF)); } - if (!Char.IsLowSurrogate(charUnknownLow)) + if (!char.IsLowSurrogate(charUnknownLow)) { throw new ArgumentOutOfRangeException(nameof(charUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); } - int iTemp = Char.ConvertToUtf32(charUnknownHigh, charUnknownLow); + int iTemp = char.ConvertToUtf32(charUnknownHigh, charUnknownLow); // Fall back our char throw new EncoderFallbackException( @@ -111,34 +111,34 @@ namespace System.Text HResult = HResults.COR_E_ARGUMENT; } - public EncoderFallbackException(String message) + public EncoderFallbackException(string message) : base(message) { HResult = HResults.COR_E_ARGUMENT; } - public EncoderFallbackException(String message, Exception innerException) + public EncoderFallbackException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_ARGUMENT; } internal EncoderFallbackException( - String message, char charUnknown, int index) : base(message) + string message, char charUnknown, int index) : base(message) { _charUnknown = charUnknown; _index = index; } internal EncoderFallbackException( - String message, char charUnknownHigh, char charUnknownLow, int index) : base(message) + string message, char charUnknownHigh, char charUnknownLow, int index) : base(message) { - if (!Char.IsHighSurrogate(charUnknownHigh)) + if (!char.IsHighSurrogate(charUnknownHigh)) { throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF)); } - if (!Char.IsLowSurrogate(charUnknownLow)) + if (!char.IsLowSurrogate(charUnknownLow)) { throw new ArgumentOutOfRangeException(nameof(CharUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderFallback.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderFallback.cs index d860a02a76..f98b15e078 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderFallback.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderFallback.cs @@ -142,7 +142,7 @@ namespace System.Text int index = (int)(chars - charStart) - 1; // See if it was a high surrogate - if (Char.IsHighSurrogate(ch)) + if (char.IsHighSurrogate(ch)) { // See if there's a low surrogate to go with it if (chars >= this.charEnd) @@ -165,11 +165,11 @@ namespace System.Text { // Might have a low surrogate char cNext = *chars; - if (Char.IsLowSurrogate(cNext)) + if (char.IsLowSurrogate(cNext)) { // If already falling back then fail if (bFallingBack && iRecursionCount++ > iMaxRecursion) - ThrowLastCharRecursive(Char.ConvertToUtf32(ch, cNext)); + ThrowLastCharRecursive(char.ConvertToUtf32(ch, cNext)); // Next is a surrogate, add it as surrogate pair, and increment chars chars++; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs index a1d0bbcd95..760c280fde 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs @@ -11,14 +11,14 @@ namespace System.Text public sealed class EncoderReplacementFallback : EncoderFallback { // Our variables - private String _strDefault; + private string _strDefault; // Construction. Default replacement fallback uses no best fit and ? replacement string public EncoderReplacementFallback() : this("?") { } - public EncoderReplacementFallback(String replacement) + public EncoderReplacementFallback(string replacement) { // Must not be null if (replacement == null) @@ -29,10 +29,10 @@ namespace System.Text for (int i = 0; i < replacement.Length; i++) { // Found a surrogate? - if (Char.IsSurrogate(replacement, i)) + if (char.IsSurrogate(replacement, i)) { // High or Low? - if (Char.IsHighSurrogate(replacement, i)) + if (char.IsHighSurrogate(replacement, i)) { // if already had a high one, stop if (bFoundHigh) @@ -63,7 +63,7 @@ namespace System.Text _strDefault = replacement; } - public String DefaultString + public string DefaultString { get { @@ -85,7 +85,7 @@ namespace System.Text } } - public override bool Equals(Object value) + public override bool Equals(object value) { EncoderReplacementFallback that = value as EncoderReplacementFallback; if (that != null) @@ -106,7 +106,7 @@ namespace System.Text public sealed class EncoderReplacementFallbackBuffer : EncoderFallbackBuffer { // Store our default string - private String _strDefault; + private string _strDefault; private int _fallbackCount = -1; private int _fallbackIndex = -1; @@ -127,7 +127,7 @@ namespace System.Text // If we're recursive we may still have something in our buffer that makes this a surrogate if (char.IsHighSurrogate(charUnknown) && _fallbackCount >= 0 && char.IsLowSurrogate(_strDefault[_fallbackIndex + 1])) - ThrowLastCharRecursive(Char.ConvertToUtf32(charUnknown, _strDefault[_fallbackIndex + 1])); + ThrowLastCharRecursive(char.ConvertToUtf32(charUnknown, _strDefault[_fallbackIndex + 1])); // Nope, just one character ThrowLastCharRecursive(unchecked((int)charUnknown)); @@ -144,18 +144,18 @@ namespace System.Text public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { // Double check input surrogate pair - if (!Char.IsHighSurrogate(charUnknownHigh)) + if (!char.IsHighSurrogate(charUnknownHigh)) throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF)); - if (!Char.IsLowSurrogate(charUnknownLow)) + if (!char.IsLowSurrogate(charUnknownLow)) throw new ArgumentOutOfRangeException(nameof(charUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. if (_fallbackCount >= 1) - ThrowLastCharRecursive(Char.ConvertToUtf32(charUnknownHigh, charUnknownLow)); + ThrowLastCharRecursive(char.ConvertToUtf32(charUnknownHigh, charUnknownLow)); // Go ahead and get our fallback _fallbackCount = _strDefault.Length; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/Encoding.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/Encoding.cs index e469180ce6..005f08afd7 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/Encoding.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/Encoding.cs @@ -325,7 +325,7 @@ namespace System.Text // Returns an Encoding object for a given name or a given code page value. // - public static Encoding GetEncoding(String name) + public static Encoding GetEncoding(string name) { Encoding baseEncoding = EncodingProvider.GetEncodingFromProvider(name); if (baseEncoding != null) @@ -342,7 +342,7 @@ namespace System.Text // Returns an Encoding object for a given name or a given code page value. // - public static Encoding GetEncoding(String name, + public static Encoding GetEncoding(string name, EncoderFallback encoderFallback, DecoderFallback decoderFallback) { Encoding baseEncoding = EncodingProvider.GetEncodingFromProvider(name, encoderFallback, decoderFallback); @@ -386,7 +386,7 @@ namespace System.Text // Returns the name for this encoding that can be used with mail agent body tags. // If the encoding may not be used, the string is empty. - public virtual String BodyName + public virtual string BodyName { get { @@ -443,7 +443,7 @@ namespace System.Text } } #else - public virtual String EncodingName + public virtual string EncodingName { get { @@ -454,7 +454,7 @@ namespace System.Text // Returns the name for this encoding that can be used with mail agent header // tags. If the encoding may not be used, the string is empty. - public virtual String HeaderName + public virtual string HeaderName { get { @@ -467,7 +467,7 @@ namespace System.Text } // Returns the IANA preferred name for this encoding. - public virtual String WebName + public virtual string WebName { get { @@ -603,7 +603,7 @@ namespace System.Text } - public virtual Object Clone() + public virtual object Clone() { Encoding newEncoding = (Encoding)this.MemberwiseClone(); @@ -646,7 +646,7 @@ namespace System.Text return GetByteCount(chars, 0, chars.Length); } - public virtual int GetByteCount(String s) + public virtual int GetByteCount(string s) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -713,7 +713,7 @@ namespace System.Text public virtual unsafe int GetByteCount(ReadOnlySpan chars) { - fixed (char* charsPtr = &MemoryMarshal.GetReference(chars)) + fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) { return GetByteCount(charsPtr, chars.Length); } @@ -767,7 +767,7 @@ namespace System.Text // Returns a byte array containing the encoded representation of the given // string. // - public virtual byte[] GetBytes(String s) + public virtual byte[] GetBytes(string s) { if (s == null) throw new ArgumentNullException(nameof(s), @@ -817,7 +817,7 @@ namespace System.Text } } - public virtual int GetBytes(String s, int charIndex, int charCount, + public virtual int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null) @@ -895,8 +895,8 @@ namespace System.Text public virtual unsafe int GetBytes(ReadOnlySpan chars, Span bytes) { - fixed (char* charsPtr = &MemoryMarshal.GetReference(chars)) - fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) + fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) + fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length); } @@ -945,7 +945,7 @@ namespace System.Text public virtual unsafe int GetCharCount(ReadOnlySpan bytes) { - fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) + fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return GetCharCount(bytesPtr, bytes.Length); } @@ -1057,8 +1057,8 @@ namespace System.Text public virtual unsafe int GetChars(ReadOnlySpan bytes, Span chars) { - fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) - fixed (char* charsPtr = &MemoryMarshal.GetReference(chars)) + fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) + fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) { return GetChars(bytesPtr, bytes.Length, charsPtr, chars.Length); } @@ -1082,14 +1082,14 @@ namespace System.Text if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); - return String.CreateStringFromEncoding(bytes, byteCount, this); + return string.CreateStringFromEncoding(bytes, byteCount, this); } public unsafe string GetString(ReadOnlySpan bytes) { - fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) + fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { - return GetString(bytesPtr, bytes.Length); + return string.CreateStringFromEncoding(bytesPtr, bytes.Length, this); } } @@ -1184,7 +1184,7 @@ namespace System.Text // Returns a string containing the decoded representation of a given byte // array. // - public virtual String GetString(byte[] bytes) + public virtual string GetString(byte[] bytes) { if (bytes == null) throw new ArgumentNullException(nameof(bytes), @@ -1198,9 +1198,9 @@ namespace System.Text // // Internally we override this for performance // - public virtual String GetString(byte[] bytes, int index, int count) + public virtual string GetString(byte[] bytes, int index, int count) { - return new String(GetChars(bytes, index, count)); + return new string(GetChars(bytes, index, count)); } // Returns an encoding for Unicode format. The returned encoding will be @@ -1241,7 +1241,7 @@ namespace System.Text private static Encoding BigEndianUTF32 => UTF32Encoding.s_bigEndianDefault; - public override bool Equals(Object value) + public override bool Equals(object value) { Encoding that = value as Encoding; if (that != null) @@ -1325,7 +1325,7 @@ namespace System.Text _encoding = encoding; } - public Object GetRealObject(StreamingContext context) + public object GetRealObject(StreamingContext context) { throw new PlatformNotSupportedException(); } @@ -1390,7 +1390,7 @@ namespace System.Text _encoding = encoding; } - public Object GetRealObject(StreamingContext context) + public object GetRealObject(StreamingContext context) { throw new PlatformNotSupportedException(); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs index 99995f759b..8e71e58fab 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs @@ -53,7 +53,7 @@ namespace System.Text return Encoding.GetEncoding(iCodePage); } - public override bool Equals(Object value) + public override bool Equals(object value) { EncodingInfo that = value as EncodingInfo; if (that != null) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/EncodingNLS.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/EncodingNLS.cs index d5de9e553a..e6fa0627d3 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/EncodingNLS.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/EncodingNLS.cs @@ -40,13 +40,13 @@ namespace System.Text { // Validate input parameters if (chars == null) - throw new ArgumentNullException("chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) - throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input, return 0, avoid fixed empty array problem if (count == 0) @@ -61,11 +61,11 @@ namespace System.Text // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetByteCount(String s) + public override unsafe int GetByteCount(string s) { // Validate input if (s==null) - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(s)); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); @@ -78,10 +78,10 @@ namespace System.Text { // Validate Parameters if (chars == null) - throw new ArgumentNullException("chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) - throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); // Call it with empty encoder return GetByteCount(chars, count, null); @@ -91,20 +91,20 @@ namespace System.Text // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding - public override unsafe int GetBytes(String s, int charIndex, int charCount, + public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) - throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array); + throw new ArgumentNullException((s == null ? nameof(s) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (s.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount); + throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) - throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); int byteCount = bytes.Length - byteIndex; @@ -130,16 +130,16 @@ namespace System.Text { // Validate parameters if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); + throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) - throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) @@ -160,10 +160,10 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); return GetBytes(chars, charCount, bytes, byteCount, null); } @@ -179,13 +179,13 @@ namespace System.Text { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input just return 0, fixed doesn't like 0 length arrays if (count == 0) @@ -203,10 +203,10 @@ namespace System.Text { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) - throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); return GetCharCount(bytes, count, null); } @@ -220,16 +220,16 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if ( bytes.Length - byteIndex < byteCount) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) - throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); // If no input, return 0 & avoid fixed problem if (byteCount == 0) @@ -250,10 +250,10 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); return GetChars(bytes, byteCount, chars, charCount, null); } @@ -265,23 +265,23 @@ namespace System.Text // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe String GetString(byte[] bytes, int index, int count) + public override unsafe string GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid problems with empty input buffer - if (count == 0) return String.Empty; + if (count == 0) return string.Empty; fixed (byte* pBytes = bytes) - return String.CreateStringFromEncoding( + return string.CreateStringFromEncoding( pBytes + index, count, this); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs index ce8c3e0208..4d15eea01a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs @@ -130,7 +130,7 @@ namespace System.Text return null; } - private static Object s_InternalSyncObject = new Object(); + private static object s_InternalSyncObject = new object(); private static volatile EncodingProvider[] s_providers; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/Latin1Encoding.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/Latin1Encoding.cs index 335eb76e3c..736fff5d26 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/Latin1Encoding.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/Latin1Encoding.cs @@ -11,7 +11,7 @@ namespace System.Text // Latin1Encoding is a simple override to optimize the GetString version of Latin1Encoding. // because of the best fit cases we can't do this when encoding the string, only when decoding // - internal class Latin1Encoding : EncodingNLS + internal sealed class Latin1Encoding : EncodingNLS { // Used by Encoding.Latin1 for lazy initialization // The initialization code will not be run until a static member of the class is referenced @@ -42,7 +42,7 @@ namespace System.Text if (encoder != null) { charLeftOver = encoder._charLeftOver; - Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), "[Latin1Encoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; @@ -164,7 +164,7 @@ namespace System.Text { charLeftOver = encoder._charLeftOver; fallback = encoder.Fallback as EncoderReplacementFallback; - Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), "[Latin1Encoding.GetBytes]leftover character should be high surrogate"); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/StringBuilder.Debug.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/StringBuilder.Debug.cs new file mode 100644 index 0000000000..a62c4777ad --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/StringBuilder.Debug.cs @@ -0,0 +1,37 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; + +namespace System.Text +{ + public sealed partial class StringBuilder + { + private void ShowChunks(int maxChunksToShow = 10) + { + int count = 0; + StringBuilder head = this, current = this; + while (current != null) + { + if (count < maxChunksToShow) + { + count++; + } + else + { + head = head.m_ChunkPrevious; + } + current = current.m_ChunkPrevious; + } + current = head; + string[] chunks = new string[count]; + for (int i = count; i > 0; i--) + { + chunks[i - 1] = new string(current.m_ChunkChars).Replace('\0', '.'); + current = current.m_ChunkPrevious; + } + Debug.WriteLine('|' + string.Join('|', chunks) + '|'); + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs deleted file mode 100644 index a7804c3991..0000000000 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs +++ /dev/null @@ -1,2438 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Text; -using System.Runtime; -using System.Runtime.Serialization; -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Runtime.Versioning; -using System.Security; -using System.Threading; -using System.Globalization; -using System.Diagnostics; -using System.Collections.Generic; - -namespace System.Text -{ - // This class represents a mutable string. It is convenient for situations in - // which it is desirable to modify a string, perhaps by removing, replacing, or - // inserting characters, without creating a new String subsequent to - // each modification. - // - // The methods contained within this class do not return a new StringBuilder - // object unless specified otherwise. This class may be used in conjunction with the String - // class to carry out modifications upon strings. - [Serializable] - [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public sealed partial class StringBuilder : ISerializable - { - // A StringBuilder is internally represented as a linked list of blocks each of which holds - // a chunk of the string. It turns out string as a whole can also be represented as just a chunk, - // so that is what we do. - - /// - /// The character buffer for this chunk. - /// - internal char[] m_ChunkChars; - - /// - /// The chunk that logically precedes this chunk. - /// - internal StringBuilder m_ChunkPrevious; - - /// - /// The number of characters in this chunk. - /// This is the number of elements in that are in use, from the start of the buffer. - /// - internal int m_ChunkLength; - - /// - /// The logical offset of this chunk's characters in the string it is a part of. - /// This is the sum of the number of characters in preceding blocks. - /// - internal int m_ChunkOffset; - - /// - /// The maximum capacity this builder is allowed to have. - /// - internal int m_MaxCapacity; - - /// - /// The default capacity of a . - /// - internal const int DefaultCapacity = 16; - - private const string CapacityField = "Capacity"; // Do not rename (binary serialization) - private const string MaxCapacityField = "m_MaxCapacity"; // Do not rename (binary serialization) - private const string StringValueField = "m_StringValue"; // Do not rename (binary serialization) - private const string ThreadIDField = "m_currentThread"; // Do not rename (binary serialization) - - // We want to keep chunk arrays out of large object heap (< 85K bytes ~ 40K chars) to be sure. - // Making the maximum chunk size big means less allocation code called, but also more waste - // in unused characters and slower inserts / replaces (since you do need to slide characters over - // within a buffer). - internal const int MaxChunkSize = 8000; - - /// - /// Initializes a new instance of the class. - /// - public StringBuilder() - { - m_MaxCapacity = int.MaxValue; - m_ChunkChars = new char[DefaultCapacity]; - } - - /// - /// Initializes a new instance of the class. - /// - /// The initial capacity of this builder. - public StringBuilder(int capacity) - : this(capacity, int.MaxValue) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The initial contents of this builder. - public StringBuilder(string value) - : this(value, DefaultCapacity) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The initial contents of this builder. - /// The initial capacity of this builder. - public StringBuilder(string value, int capacity) - : this(value, 0, value?.Length ?? 0, capacity) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The initial contents of this builder. - /// The index to start in . - /// The number of characters to read in . - /// The initial capacity of this builder. - public StringBuilder(string value, int startIndex, int length, int capacity) - { - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity), SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(capacity))); - } - if (length < 0) - { - throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(length))); - } - if (startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); - } - - if (value == null) - { - value = string.Empty; - } - if (startIndex > value.Length - length) - { - throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength); - } - - m_MaxCapacity = int.MaxValue; - if (capacity == 0) - { - capacity = DefaultCapacity; - } - capacity = Math.Max(capacity, length); - - m_ChunkChars = new char[capacity]; - m_ChunkLength = length; - - unsafe - { - fixed (char* sourcePtr = value) - { - ThreadSafeCopy(sourcePtr + startIndex, m_ChunkChars, 0, length); - } - } - } - - /// - /// Initializes a new instance of the class. - /// - /// The initial capacity of this builder. - /// The maximum capacity of this builder. - public StringBuilder(int capacity, int maxCapacity) - { - if (capacity > maxCapacity) - { - throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity); - } - if (maxCapacity < 1) - { - throw new ArgumentOutOfRangeException(nameof(maxCapacity), SR.ArgumentOutOfRange_SmallMaxCapacity); - } - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity), SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(capacity))); - } - - if (capacity == 0) - { - capacity = Math.Min(DefaultCapacity, maxCapacity); - } - - m_MaxCapacity = maxCapacity; - m_ChunkChars = new char[capacity]; - } - - private StringBuilder(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - - int persistedCapacity = 0; - string persistedString = null; - int persistedMaxCapacity = Int32.MaxValue; - bool capacityPresent = false; - - // Get the data - SerializationInfoEnumerator enumerator = info.GetEnumerator(); - while (enumerator.MoveNext()) - { - switch (enumerator.Name) - { - case MaxCapacityField: - persistedMaxCapacity = info.GetInt32(MaxCapacityField); - break; - case StringValueField: - persistedString = info.GetString(StringValueField); - break; - case CapacityField: - persistedCapacity = info.GetInt32(CapacityField); - capacityPresent = true; - break; - default: - // Ignore other fields for forwards-compatibility. - break; - } - } - - // Check values and set defaults - if (persistedString == null) - { - persistedString = string.Empty; - } - if (persistedMaxCapacity < 1 || persistedString.Length > persistedMaxCapacity) - { - throw new SerializationException(SR.Serialization_StringBuilderMaxCapacity); - } - - if (!capacityPresent) - { - // StringBuilder in V1.X did not persist the Capacity, so this is a valid legacy code path. - persistedCapacity = Math.Min(Math.Max(DefaultCapacity, persistedString.Length), persistedMaxCapacity); - } - - if (persistedCapacity < 0 || persistedCapacity < persistedString.Length || persistedCapacity > persistedMaxCapacity) - { - throw new SerializationException(SR.Serialization_StringBuilderCapacity); - } - - // Assign - m_MaxCapacity = persistedMaxCapacity; - m_ChunkChars = new char[persistedCapacity]; - persistedString.CopyTo(0, m_ChunkChars, 0, persistedString.Length); - m_ChunkLength = persistedString.Length; - m_ChunkPrevious = null; - AssertInvariants(); - } - - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - - AssertInvariants(); - info.AddValue(MaxCapacityField, m_MaxCapacity); - info.AddValue(CapacityField, Capacity); - info.AddValue(StringValueField, ToString()); - // Note: persist "m_currentThread" to be compatible with old versions - info.AddValue(ThreadIDField, 0); - } - - [System.Diagnostics.Conditional("DEBUG")] - private void AssertInvariants() - { - Debug.Assert(m_ChunkOffset + m_ChunkChars.Length >= m_ChunkOffset, "The length of the string is greater than int.MaxValue."); - - StringBuilder currentBlock = this; - int maxCapacity = this.m_MaxCapacity; - for (;;) - { - // All blocks have the same max capacity. - Debug.Assert(currentBlock.m_MaxCapacity == maxCapacity); - Debug.Assert(currentBlock.m_ChunkChars != null); - - Debug.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length); - Debug.Assert(currentBlock.m_ChunkLength >= 0); - Debug.Assert(currentBlock.m_ChunkOffset >= 0); - - StringBuilder prevBlock = currentBlock.m_ChunkPrevious; - if (prevBlock == null) - { - Debug.Assert(currentBlock.m_ChunkOffset == 0); - break; - } - // There are no gaps in the blocks. - Debug.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength); - currentBlock = prevBlock; - } - } - - public int Capacity - { - get { return m_ChunkChars.Length + m_ChunkOffset; } - set - { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NegativeCapacity); - } - if (value > MaxCapacity) - { - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_Capacity); - } - if (value < Length) - { - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); - } - - if (Capacity != value) - { - int newLen = value - m_ChunkOffset; - char[] newArray = new char[newLen]; - Array.Copy(m_ChunkChars, 0, newArray, 0, m_ChunkLength); - m_ChunkChars = newArray; - } - } - } - - /// - /// Gets the maximum capacity this builder is allowed to have. - /// - public int MaxCapacity => m_MaxCapacity; - - /// - /// Ensures that the capacity of this builder is at least the specified value. - /// - /// The new capacity for this builder. - /// - /// If is less than or equal to the current capacity of - /// this builder, the capacity remains unchanged. - /// - public int EnsureCapacity(int capacity) - { - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity); - } - - if (Capacity < capacity) - Capacity = capacity; - return Capacity; - } - - public override String ToString() - { - AssertInvariants(); - - if (Length == 0) - { - return string.Empty; - } - - string result = string.FastAllocateString(Length); - StringBuilder chunk = this; - unsafe - { - fixed (char* destinationPtr = result) - { - do - { - if (chunk.m_ChunkLength > 0) - { - // Copy these into local variables so that they are stable even in the presence of race conditions - char[] sourceArray = chunk.m_ChunkChars; - int chunkOffset = chunk.m_ChunkOffset; - int chunkLength = chunk.m_ChunkLength; - - // Check that we will not overrun our boundaries. - if ((uint)(chunkLength + chunkOffset) <= (uint)result.Length && (uint)chunkLength <= (uint)sourceArray.Length) - { - fixed (char* sourcePtr = &sourceArray[0]) - string.wstrcpy(destinationPtr + chunkOffset, sourcePtr, chunkLength); - } - else - { - throw new ArgumentOutOfRangeException(nameof(chunkLength), SR.ArgumentOutOfRange_Index); - } - } - chunk = chunk.m_ChunkPrevious; - } - while (chunk != null); - - return result; - } - } - } - - /// - /// Creates a string from a substring of this builder. - /// - /// The index to start in this builder. - /// The number of characters to read in this builder. - public string ToString(int startIndex, int length) - { - int currentLength = this.Length; - if (startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); - } - if (startIndex > currentLength) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndexLargerThanLength); - } - if (length < 0) - { - throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); - } - if (startIndex > currentLength - length) - { - throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength); - } - - AssertInvariants(); - string result = string.FastAllocateString(length); - unsafe - { - fixed (char* destinationPtr = result) - { - this.CopyTo(startIndex, new Span(destinationPtr, length), length); - return result; - } - } - } - - public StringBuilder Clear() - { - this.Length = 0; - return this; - } - - /// - /// Gets or sets the length of this builder. - /// - public int Length - { - get - { - return m_ChunkOffset + m_ChunkLength; - } - set - { - //If the new length is less than 0 or greater than our Maximum capacity, bail. - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NegativeLength); - } - - if (value > MaxCapacity) - { - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); - } - - int originalCapacity = Capacity; - - if (value == 0 && m_ChunkPrevious == null) - { - m_ChunkLength = 0; - m_ChunkOffset = 0; - Debug.Assert(Capacity >= originalCapacity); - return; - } - - int delta = value - Length; - if (delta > 0) - { - // Pad ourselves with null characters. - Append('\0', delta); - } - else - { - StringBuilder chunk = FindChunkForIndex(value); - if (chunk != this) - { - // We crossed a chunk boundary when reducing the Length. We must replace this middle-chunk with a new larger chunk, - // to ensure the original capacity is preserved. - int newLen = originalCapacity - chunk.m_ChunkOffset; - char[] newArray = new char[newLen]; - - Debug.Assert(newLen > chunk.m_ChunkChars.Length, "The new chunk should be larger than the one it is replacing."); - Array.Copy(chunk.m_ChunkChars, 0, newArray, 0, chunk.m_ChunkLength); - - m_ChunkChars = newArray; - m_ChunkPrevious = chunk.m_ChunkPrevious; - m_ChunkOffset = chunk.m_ChunkOffset; - } - m_ChunkLength = value - chunk.m_ChunkOffset; - AssertInvariants(); - } - Debug.Assert(Capacity >= originalCapacity); - } - } - - [IndexerName("Chars")] - public char this[int index] - { - get - { - StringBuilder chunk = this; - for (;;) - { - int indexInBlock = index - chunk.m_ChunkOffset; - if (indexInBlock >= 0) - { - if (indexInBlock >= chunk.m_ChunkLength) - { - throw new IndexOutOfRangeException(); - } - return chunk.m_ChunkChars[indexInBlock]; - } - chunk = chunk.m_ChunkPrevious; - if (chunk == null) - { - throw new IndexOutOfRangeException(); - } - } - } - set - { - StringBuilder chunk = this; - for (;;) - { - int indexInBlock = index - chunk.m_ChunkOffset; - if (indexInBlock >= 0) - { - if (indexInBlock >= chunk.m_ChunkLength) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); - } - chunk.m_ChunkChars[indexInBlock] = value; - return; - } - chunk = chunk.m_ChunkPrevious; - if (chunk == null) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); - } - } - } - } - - /// - /// Appends a character 0 or more times to the end of this builder. - /// - /// The character to append. - /// The number of times to append . - public StringBuilder Append(char value, int repeatCount) - { - if (repeatCount < 0) - { - throw new ArgumentOutOfRangeException(nameof(repeatCount), SR.ArgumentOutOfRange_NegativeCount); - } - - if (repeatCount == 0) - { - return this; - } - - // this is where we can check if the repeatCount will put us over m_MaxCapacity - // We are doing the check here to prevent the corruption of the StringBuilder. - int newLength = Length + repeatCount; - if (newLength > m_MaxCapacity || newLength < repeatCount) - { - throw new ArgumentOutOfRangeException(nameof(repeatCount), SR.ArgumentOutOfRange_LengthGreaterThanCapacity); - } - - int index = m_ChunkLength; - while (repeatCount > 0) - { - if (index < m_ChunkChars.Length) - { - m_ChunkChars[index++] = value; - --repeatCount; - } - else - { - m_ChunkLength = index; - ExpandByABlock(repeatCount); - Debug.Assert(m_ChunkLength == 0); - index = 0; - } - } - - m_ChunkLength = index; - AssertInvariants(); - return this; - } - - /// - /// Appends a range of characters to the end of this builder. - /// - /// The characters to append. - /// The index to start in . - /// The number of characters to read in . - public StringBuilder Append(char[] value, int startIndex, int charCount) - { - if (startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_GenericPositive); - } - if (charCount < 0) - { - throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GenericPositive); - } - - if (value == null) - { - if (startIndex == 0 && charCount == 0) - { - return this; - } - - throw new ArgumentNullException(nameof(value)); - } - if (charCount > value.Length - startIndex) - { - throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_Index); - } - - if (charCount == 0) - { - return this; - } - - unsafe - { - fixed (char* valueChars = &value[startIndex]) - { - Append(valueChars, charCount); - return this; - } - } - } - - - /// - /// Appends a string to the end of this builder. - /// - /// The string to append. - public StringBuilder Append(String value) - { - if (value != null) - { - // We could have just called AppendHelper here; this is a hand-specialization of that code. - char[] chunkChars = m_ChunkChars; - int chunkLength = m_ChunkLength; - int valueLen = value.Length; - int newCurrentIndex = chunkLength + valueLen; - - if (newCurrentIndex < chunkChars.Length) // Use strictly < to avoid issues if count == 0, newIndex == length - { - if (valueLen <= 2) - { - if (valueLen > 0) - chunkChars[chunkLength] = value[0]; - if (valueLen > 1) - chunkChars[chunkLength + 1] = value[1]; - } - else - { - unsafe - { - fixed (char* valuePtr = value) - fixed (char* destPtr = &chunkChars[chunkLength]) - { - string.wstrcpy(destPtr, valuePtr, valueLen); - } - } - } - - m_ChunkLength = newCurrentIndex; - } - else - { - AppendHelper(value); - } - } - - return this; - } - - // We put this fixed in its own helper to avoid the cost of zero-initing `valueChars` in the - // case we don't actually use it. - private void AppendHelper(string value) - { - unsafe - { - fixed (char* valueChars = value) - { - Append(valueChars, value.Length); - } - } - } - - /// - /// Appends part of a string to the end of this builder. - /// - /// The string to append. - /// The index to start in . - /// The number of characters to read in . - public StringBuilder Append(string value, int startIndex, int count) - { - if (startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GenericPositive); - } - - if (value == null) - { - if (startIndex == 0 && count == 0) - { - return this; - } - throw new ArgumentNullException(nameof(value)); - } - - if (count == 0) - { - return this; - } - - if (startIndex > value.Length - count) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); - } - - unsafe - { - fixed (char* valueChars = value) - { - Append(valueChars + startIndex, count); - return this; - } - } - } - - public StringBuilder Append(StringBuilder value) - { - if (value != null && value.Length != 0) - { - return AppendCore(value, 0, value.Length); - } - return this; - } - - public StringBuilder Append(StringBuilder value, int startIndex, int count) - { - if (startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); - } - - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GenericPositive); - } - - if (value == null) - { - if (startIndex == 0 && count == 0) - { - return this; - } - throw new ArgumentNullException(nameof(value)); - } - - if (count == 0) - { - return this; - } - - if (count > value.Length - startIndex) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); - } - - return AppendCore(value, startIndex, count); - } - - private StringBuilder AppendCore(StringBuilder value, int startIndex, int count) - { - if (value == this) - return Append(value.ToString(startIndex, count)); - - int newLength = Length + count; - - if ((uint)newLength > (uint)m_MaxCapacity) - { - throw new ArgumentOutOfRangeException(nameof(Capacity), SR.ArgumentOutOfRange_Capacity); - } - - while (count > 0) - { - int length = Math.Min(m_ChunkChars.Length - m_ChunkLength, count); - if (length == 0) - { - ExpandByABlock(count); - length = Math.Min(m_ChunkChars.Length - m_ChunkLength, count); - } - value.CopyTo(startIndex, new Span(m_ChunkChars, m_ChunkLength, length), length); - - m_ChunkLength += length; - startIndex += length; - count -= length; - } - - return this; - } - - public StringBuilder AppendLine() => Append(Environment.NewLine); - - public StringBuilder AppendLine(string value) - { - Append(value); - return Append(Environment.NewLine); - } - - public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) - { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } - - if (destinationIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(destinationIndex))); - } - - if (destinationIndex > destination.Length - count) - { - throw new ArgumentException(SR.ArgumentOutOfRange_OffsetOut); - } - - CopyTo(sourceIndex, new Span(destination).Slice(destinationIndex), count); - } - - public void CopyTo(int sourceIndex, Span destination, int count) - { - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.Arg_NegativeArgCount); - } - - if ((uint)sourceIndex > (uint)Length) - { - throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index); - } - - if (sourceIndex > Length - count) - { - throw new ArgumentException(SR.Arg_LongerThanSrcString); - } - - AssertInvariants(); - - StringBuilder chunk = this; - int sourceEndIndex = sourceIndex + count; - int curDestIndex = count; - while (count > 0) - { - int chunkEndIndex = sourceEndIndex - chunk.m_ChunkOffset; - if (chunkEndIndex >= 0) - { - chunkEndIndex = Math.Min(chunkEndIndex, chunk.m_ChunkLength); - - int chunkCount = count; - int chunkStartIndex = chunkEndIndex - count; - if (chunkStartIndex < 0) - { - chunkCount += chunkStartIndex; - chunkStartIndex = 0; - } - curDestIndex -= chunkCount; - count -= chunkCount; - - // We ensure that chunkStartIndex + chunkCount are within range of m_chunkChars as well as - // ensuring that curDestIndex + chunkCount are within range of destination - ThreadSafeCopy(chunk.m_ChunkChars, chunkStartIndex, destination, curDestIndex, chunkCount); - } - chunk = chunk.m_ChunkPrevious; - } - } - - /// - /// Inserts a string 0 or more times into this builder at the specified position. - /// - /// The index to insert in this builder. - /// The string to insert. - /// The number of times to insert the string. - public StringBuilder Insert(int index, String value, int count) - { - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } - - int currentLength = Length; - if ((uint)index > (uint)currentLength) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); - } - - if (string.IsNullOrEmpty(value) || count == 0) - { - return this; - } - - // Ensure we don't insert more chars than we can hold, and we don't - // have any integer overflow in our new length. - long insertingChars = (long)value.Length * count; - if (insertingChars > MaxCapacity - this.Length) - { - throw new OutOfMemoryException(); - } - Debug.Assert(insertingChars + this.Length < int.MaxValue); - - StringBuilder chunk; - int indexInChunk; - MakeRoom(index, (int)insertingChars, out chunk, out indexInChunk, false); - unsafe - { - fixed (char* valuePtr = value) - { - while (count > 0) - { - ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, valuePtr, value.Length); - --count; - } - - return this; - } - } - } - - /// - /// Removes a range of characters from this builder. - /// - /// - /// This method does not reduce the capacity of this builder. - /// - public StringBuilder Remove(int startIndex, int length) - { - if (length < 0) - { - throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); - } - - if (startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); - } - - if (length > Length - startIndex) - { - throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index); - } - - if (Length == length && startIndex == 0) - { - Length = 0; - return this; - } - - if (length > 0) - { - StringBuilder chunk; - int indexInChunk; - Remove(startIndex, length, out chunk, out indexInChunk); - } - - return this; - } - - public StringBuilder Append(bool value) => Append(value.ToString()); - - public StringBuilder Append(char value) - { - if (m_ChunkLength < m_ChunkChars.Length) - { - m_ChunkChars[m_ChunkLength++] = value; - } - else - { - Append(value, 1); - } - - return this; - } - - [CLSCompliant(false)] - public StringBuilder Append(sbyte value) => AppendSpanFormattable(value); - - public StringBuilder Append(byte value) => AppendSpanFormattable(value); - - public StringBuilder Append(short value) => AppendSpanFormattable(value); - - public StringBuilder Append(int value) => AppendSpanFormattable(value); - - public StringBuilder Append(long value) => AppendSpanFormattable(value); - - public StringBuilder Append(float value) => AppendSpanFormattable(value); - - public StringBuilder Append(double value) => AppendSpanFormattable(value); - - public StringBuilder Append(decimal value) => AppendSpanFormattable(value); - - [CLSCompliant(false)] - public StringBuilder Append(ushort value) => AppendSpanFormattable(value); - - [CLSCompliant(false)] - public StringBuilder Append(uint value) => AppendSpanFormattable(value); - - [CLSCompliant(false)] - public StringBuilder Append(ulong value) => AppendSpanFormattable(value); - - private StringBuilder AppendSpanFormattable(T value) where T : ISpanFormattable - { - if (value.TryFormat(RemainingCurrentChunk, out int charsWritten, format: default, provider: null)) - { - m_ChunkLength += charsWritten; - return this; - } - - return Append(value.ToString()); - } - - public StringBuilder Append(object value) => (value == null) ? this : Append(value.ToString()); - - public StringBuilder Append(char[] value) - { - if (value?.Length > 0) - { - unsafe - { - fixed (char* valueChars = &value[0]) - { - Append(valueChars, value.Length); - } - } - } - return this; - } - - public StringBuilder Append(ReadOnlySpan value) - { - if (value.Length > 0) - { - unsafe - { - fixed (char* valueChars = &MemoryMarshal.GetReference(value)) - { - Append(valueChars, value.Length); - } - } - } - return this; - } - - #region AppendJoin - - public unsafe StringBuilder AppendJoin(string separator, params object[] values) - { - separator = separator ?? string.Empty; - fixed (char* pSeparator = separator) - { - return AppendJoinCore(pSeparator, separator.Length, values); - } - } - - public unsafe StringBuilder AppendJoin(string separator, IEnumerable values) - { - separator = separator ?? string.Empty; - fixed (char* pSeparator = separator) - { - return AppendJoinCore(pSeparator, separator.Length, values); - } - } - - public unsafe StringBuilder AppendJoin(string separator, params string[] values) - { - separator = separator ?? string.Empty; - fixed (char* pSeparator = separator) - { - return AppendJoinCore(pSeparator, separator.Length, values); - } - } - - public unsafe StringBuilder AppendJoin(char separator, params object[] values) - { - return AppendJoinCore(&separator, 1, values); - } - - public unsafe StringBuilder AppendJoin(char separator, IEnumerable values) - { - return AppendJoinCore(&separator, 1, values); - } - - public unsafe StringBuilder AppendJoin(char separator, params string[] values) - { - return AppendJoinCore(&separator, 1, values); - } - - private unsafe StringBuilder AppendJoinCore(char* separator, int separatorLength, IEnumerable values) - { - Debug.Assert(separator != null); - Debug.Assert(separatorLength >= 0); - - if (values == null) - { - ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); - } - - using (IEnumerator en = values.GetEnumerator()) - { - if (!en.MoveNext()) - { - return this; - } - - var value = en.Current; - if (value != null) - { - Append(value.ToString()); - } - - while (en.MoveNext()) - { - Append(separator, separatorLength); - value = en.Current; - if (value != null) - { - Append(value.ToString()); - } - } - } - return this; - } - - private unsafe StringBuilder AppendJoinCore(char* separator, int separatorLength, T[] values) - { - if (values == null) - { - ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); - } - - if (values.Length == 0) - { - return this; - } - - if (values[0] != null) - { - Append(values[0].ToString()); - } - - for (int i = 1; i < values.Length; i++) - { - Append(separator, separatorLength); - if (values[i] != null) - { - Append(values[i].ToString()); - } - } - return this; - } - - #endregion - - public StringBuilder Insert(int index, String value) - { - if ((uint)index > (uint)Length) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); - } - - if (value != null) - { - unsafe - { - fixed (char* sourcePtr = value) - Insert(index, sourcePtr, value.Length); - } - } - return this; - } - - public StringBuilder Insert(int index, bool value) => Insert(index, value.ToString(), 1); - - [CLSCompliant(false)] - public StringBuilder Insert(int index, sbyte value) => Insert(index, value.ToString(), 1); - - public StringBuilder Insert(int index, byte value) => Insert(index, value.ToString(), 1); - - public StringBuilder Insert(int index, short value) => Insert(index, value.ToString(), 1); - - public StringBuilder Insert(int index, char value) - { - unsafe - { - Insert(index, &value, 1); - } - return this; - } - - public StringBuilder Insert(int index, char[] value) - { - if ((uint)index > (uint)Length) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); - } - - if (value != null) - Insert(index, value, 0, value.Length); - return this; - } - - public StringBuilder Insert(int index, char[] value, int startIndex, int charCount) - { - int currentLength = Length; - if ((uint)index > (uint)currentLength) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); - } - - if (value == null) - { - if (startIndex == 0 && charCount == 0) - { - return this; - } - throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String); - } - - if (startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); - } - - if (charCount < 0) - { - throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GenericPositive); - } - - if (startIndex > value.Length - charCount) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); - } - - if (charCount > 0) - { - unsafe - { - fixed (char* sourcePtr = &value[startIndex]) - Insert(index, sourcePtr, charCount); - } - } - return this; - } - - public StringBuilder Insert(int index, int value) => Insert(index, value.ToString(), 1); - - public StringBuilder Insert(int index, long value) => Insert(index, value.ToString(), 1); - - public StringBuilder Insert(int index, float value) => Insert(index, value.ToString(), 1); - - public StringBuilder Insert(int index, double value) => Insert(index, value.ToString(), 1); - - public StringBuilder Insert(int index, decimal value) => Insert(index, value.ToString(), 1); - - [CLSCompliant(false)] - public StringBuilder Insert(int index, ushort value) => Insert(index, value.ToString(), 1); - - [CLSCompliant(false)] - public StringBuilder Insert(int index, uint value) => Insert(index, value.ToString(), 1); - - [CLSCompliant(false)] - public StringBuilder Insert(int index, ulong value) => Insert(index, value.ToString(), 1); - - public StringBuilder Insert(int index, Object value) => (value == null) ? this : Insert(index, value.ToString(), 1); - - public StringBuilder Insert(int index, ReadOnlySpan value) - { - if ((uint)index > (uint)Length) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); - } - - if (value.Length > 0) - { - unsafe - { - fixed (char* sourcePtr = &MemoryMarshal.GetReference(value)) - Insert(index, sourcePtr, value.Length); - } - } - return this; - } - - public StringBuilder AppendFormat(String format, Object arg0) => AppendFormatHelper(null, format, new ParamsArray(arg0)); - - public StringBuilder AppendFormat(String format, Object arg0, Object arg1) => AppendFormatHelper(null, format, new ParamsArray(arg0, arg1)); - - public StringBuilder AppendFormat(String format, Object arg0, Object arg1, Object arg2) => AppendFormatHelper(null, format, new ParamsArray(arg0, arg1, arg2)); - - public StringBuilder AppendFormat(String format, params Object[] args) - { - if (args == null) - { - // To preserve the original exception behavior, throw an exception about format if both - // args and format are null. The actual null check for format is in AppendFormatHelper. - string paramName = (format == null) ? nameof(format) : nameof(args); - throw new ArgumentNullException(paramName); - } - - return AppendFormatHelper(null, format, new ParamsArray(args)); - } - - public StringBuilder AppendFormat(IFormatProvider provider, String format, Object arg0) => AppendFormatHelper(provider, format, new ParamsArray(arg0)); - - public StringBuilder AppendFormat(IFormatProvider provider, String format, Object arg0, Object arg1) => AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1)); - - public StringBuilder AppendFormat(IFormatProvider provider, String format, Object arg0, Object arg1, Object arg2) => AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1, arg2)); - - public StringBuilder AppendFormat(IFormatProvider provider, String format, params Object[] args) - { - if (args == null) - { - // To preserve the original exception behavior, throw an exception about format if both - // args and format are null. The actual null check for format is in AppendFormatHelper. - string paramName = (format == null) ? nameof(format) : nameof(args); - throw new ArgumentNullException(paramName); - } - - return AppendFormatHelper(provider, format, new ParamsArray(args)); - } - - private static void FormatError() - { - throw new FormatException(SR.Format_InvalidString); - } - - // Undocumented exclusive limits on the range for Argument Hole Index and Argument Hole Alignment. - private const int IndexLimit = 1000000; // Note: 0 <= ArgIndex < IndexLimit - private const int WidthLimit = 1000000; // Note: -WidthLimit < ArgAlign < WidthLimit - - internal StringBuilder AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args) - { - if (format == null) - { - throw new ArgumentNullException(nameof(format)); - } - - int pos = 0; - int len = format.Length; - char ch = '\x0'; - StringBuilder unescapedItemFormat = null; - - ICustomFormatter cf = null; - if (provider != null) - { - cf = (ICustomFormatter)provider.GetFormat(typeof(ICustomFormatter)); - } - - while (true) - { - while (pos < len) - { - ch = format[pos]; - - pos++; - // Is it a closing brace? - if (ch == '}') - { - // Check next character (if there is one) to see if it is escaped. eg }} - if (pos < len && format[pos] == '}') - pos++; - else - // Otherwise treat it as an error (Mismatched closing brace) - FormatError(); - } - // Is it a opening brace? - if (ch == '{') - { - // Check next character (if there is one) to see if it is escaped. eg {{ - if (pos < len && format[pos] == '{') - pos++; - else - { - // Otherwise treat it as the opening brace of an Argument Hole. - pos--; - break; - } - } - // If it neither then treat the character as just text. - Append(ch); - } - - // - // Start of parsing of Argument Hole. - // Argument Hole ::= { Index (, WS* Alignment WS*)? (: Formatting)? } - // - if (pos == len) break; - - // - // Start of parsing required Index parameter. - // Index ::= ('0'-'9')+ WS* - // - pos++; - // If reached end of text then error (Unexpected end of text) - // or character is not a digit then error (Unexpected Character) - if (pos == len || (ch = format[pos]) < '0' || ch > '9') FormatError(); - int index = 0; - do - { - index = index * 10 + ch - '0'; - pos++; - // If reached end of text then error (Unexpected end of text) - if (pos == len) FormatError(); - ch = format[pos]; - // so long as character is digit and value of the index is less than 1000000 ( index limit ) - } - while (ch >= '0' && ch <= '9' && index < IndexLimit); - - // If value of index is not within the range of the arguments passed in then error (Index out of range) - if (index >= args.Length) throw new FormatException(SR.Format_IndexOutOfRange); - - // Consume optional whitespace. - while (pos < len && (ch = format[pos]) == ' ') pos++; - // End of parsing index parameter. - - // - // Start of parsing of optional Alignment - // Alignment ::= comma WS* minus? ('0'-'9')+ WS* - // - bool leftJustify = false; - int width = 0; - // Is the character a comma, which indicates the start of alignment parameter. - if (ch == ',') - { - pos++; - - // Consume Optional whitespace - while (pos < len && format[pos] == ' ') pos++; - - // If reached the end of the text then error (Unexpected end of text) - if (pos == len) FormatError(); - - // Is there a minus sign? - ch = format[pos]; - if (ch == '-') - { - // Yes, then alignment is left justified. - leftJustify = true; - pos++; - // If reached end of text then error (Unexpected end of text) - if (pos == len) FormatError(); - ch = format[pos]; - } - - // If current character is not a digit then error (Unexpected character) - if (ch < '0' || ch > '9') FormatError(); - // Parse alignment digits. - do - { - width = width * 10 + ch - '0'; - pos++; - // If reached end of text then error. (Unexpected end of text) - if (pos == len) FormatError(); - ch = format[pos]; - // So long a current character is a digit and the value of width is less than 100000 ( width limit ) - } - while (ch >= '0' && ch <= '9' && width < WidthLimit); - // end of parsing Argument Alignment - } - - // Consume optional whitespace - while (pos < len && (ch = format[pos]) == ' ') pos++; - - // - // Start of parsing of optional formatting parameter. - // - Object arg = args[index]; - String itemFormat = null; - ReadOnlySpan itemFormatSpan = default; // used if itemFormat is null - // Is current character a colon? which indicates start of formatting parameter. - if (ch == ':') - { - pos++; - int startPos = pos; - - while (true) - { - // If reached end of text then error. (Unexpected end of text) - if (pos == len) FormatError(); - ch = format[pos]; - pos++; - - // Is character a opening or closing brace? - if (ch == '}' || ch == '{') - { - if (ch == '{') - { - // Yes, is next character also a opening brace, then treat as escaped. eg {{ - if (pos < len && format[pos] == '{') - pos++; - else - // Error Argument Holes can not be nested. - FormatError(); - } - else - { - // Yes, is next character also a closing brace, then treat as escaped. eg }} - if (pos < len && format[pos] == '}') - pos++; - else - { - // No, then treat it as the closing brace of an Arg Hole. - pos--; - break; - } - } - - // Reaching here means the brace has been escaped - // so we need to build up the format string in segments - if (unescapedItemFormat == null) - { - unescapedItemFormat = new StringBuilder(); - } - unescapedItemFormat.Append(format, startPos, pos - startPos - 1); - startPos = pos; - } - } - - if (unescapedItemFormat == null || unescapedItemFormat.Length == 0) - { - if (startPos != pos) - { - // There was no brace escaping, extract the item format as a single string - itemFormatSpan = format.AsSpan().Slice(startPos, pos - startPos); - } - } - else - { - unescapedItemFormat.Append(format, startPos, pos - startPos); - itemFormatSpan = itemFormat = unescapedItemFormat.ToString(); - unescapedItemFormat.Clear(); - } - } - // If current character is not a closing brace then error. (Unexpected Character) - if (ch != '}') FormatError(); - // Construct the output for this arg hole. - pos++; - String s = null; - if (cf != null) - { - if (itemFormatSpan.Length != 0 && itemFormat == null) - { - itemFormat = new string(itemFormatSpan); - } - s = cf.Format(itemFormat, arg, provider); - } - - if (s == null) - { - // If arg is ISpanFormattable and the beginning doesn't need padding, - // try formatting it into the remaining current chunk. - if (arg is ISpanFormattable spanFormattableArg && - (leftJustify || width == 0) && - spanFormattableArg.TryFormat(RemainingCurrentChunk, out int charsWritten, itemFormatSpan, provider)) - { - m_ChunkLength += charsWritten; - - // Pad the end, if needed. - int padding = width - charsWritten; - if (leftJustify && padding > 0) Append(' ', padding); - - // Continue to parse other characters. - continue; - } - - // Otherwise, fallback to trying IFormattable or calling ToString. - if (arg is IFormattable formattableArg) - { - if (itemFormatSpan.Length != 0 && itemFormat == null) - { - itemFormat = new string(itemFormatSpan); - } - s = formattableArg.ToString(itemFormat, provider); - } - else if (arg != null) - { - s = arg.ToString(); - } - } - // Append it to the final output of the Format String. - if (s == null) s = String.Empty; - int pad = width - s.Length; - if (!leftJustify && pad > 0) Append(' ', pad); - Append(s); - if (leftJustify && pad > 0) Append(' ', pad); - // Continue to parse other characters. - } - return this; - } - - /// - /// Replaces all instances of one string with another in this builder. - /// - /// The string to replace. - /// The string to replace with. - /// - /// If is null, instances of - /// are removed from this builder. - /// - public StringBuilder Replace(String oldValue, String newValue) => Replace(oldValue, newValue, 0, Length); - - /// - /// Determines if the contents of this builder are equal to the contents of another builder. - /// - /// The other builder. - public bool Equals(StringBuilder sb) - { - if (sb == null) - return false; - if (Capacity != sb.Capacity || MaxCapacity != sb.MaxCapacity || Length != sb.Length) - return false; - if (sb == this) - return true; - - StringBuilder thisChunk = this; - int thisChunkIndex = thisChunk.m_ChunkLength; - StringBuilder sbChunk = sb; - int sbChunkIndex = sbChunk.m_ChunkLength; - for (;;) - { - --thisChunkIndex; - --sbChunkIndex; - - while (thisChunkIndex < 0) - { - thisChunk = thisChunk.m_ChunkPrevious; - if (thisChunk == null) - break; - thisChunkIndex = thisChunk.m_ChunkLength + thisChunkIndex; - } - - while (sbChunkIndex < 0) - { - sbChunk = sbChunk.m_ChunkPrevious; - if (sbChunk == null) - break; - sbChunkIndex = sbChunk.m_ChunkLength + sbChunkIndex; - } - - if (thisChunkIndex < 0) - return sbChunkIndex < 0; - if (sbChunkIndex < 0) - return false; - if (thisChunk.m_ChunkChars[thisChunkIndex] != sbChunk.m_ChunkChars[sbChunkIndex]) - return false; - } - } - - /// - /// Determines if the contents of this builder are equal to the contents of ReadOnlySpan. - /// - /// The ReadOnlySpan{char}. - public bool Equals(ReadOnlySpan value) - { - if (value.Length != Length) - return false; - - StringBuilder sbChunk = this; - int offset = 0; - - do - { - int chunk_length = sbChunk.m_ChunkLength; - offset += chunk_length; - - ReadOnlySpan chunk = new ReadOnlySpan(sbChunk.m_ChunkChars, 0, chunk_length); - - if (!chunk.Equals(value.Slice(value.Length - offset, chunk_length))) - return false; - - sbChunk = sbChunk.m_ChunkPrevious; - } while (sbChunk != null); - - Debug.Assert(offset == Length); - return true; - } - - /// - /// Replaces all instances of one string with another in part of this builder. - /// - /// The string to replace. - /// The string to replace with. - /// The index to start in this builder. - /// The number of characters to read in this builder. - /// - /// If is null, instances of - /// are removed from this builder. - /// - public StringBuilder Replace(String oldValue, String newValue, int startIndex, int count) - { - int currentLength = Length; - if ((uint)startIndex > (uint)currentLength) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); - } - if (count < 0 || startIndex > currentLength - count) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Index); - } - if (oldValue == null) - { - throw new ArgumentNullException(nameof(oldValue)); - } - if (oldValue.Length == 0) - { - throw new ArgumentException(SR.Argument_EmptyName, nameof(oldValue)); - } - - newValue = newValue ?? string.Empty; - - int deltaLength = newValue.Length - oldValue.Length; - - int[] replacements = null; // A list of replacement positions in a chunk to apply - int replacementsCount = 0; - - // Find the chunk, indexInChunk for the starting point - StringBuilder chunk = FindChunkForIndex(startIndex); - int indexInChunk = startIndex - chunk.m_ChunkOffset; - while (count > 0) - { - // Look for a match in the chunk,indexInChunk pointer - if (StartsWith(chunk, indexInChunk, count, oldValue)) - { - // Push it on the replacements array (with growth), we will do all replacements in a - // given chunk in one operation below (see ReplaceAllInChunk) so we don't have to slide - // many times. - if (replacements == null) - { - replacements = new int[5]; - } - else if (replacementsCount >= replacements.Length) - { - Array.Resize(ref replacements, replacements.Length * 3 / 2 + 4); // Grow by ~1.5x, but more in the begining - } - replacements[replacementsCount++] = indexInChunk; - indexInChunk += oldValue.Length; - count -= oldValue.Length; - } - else - { - indexInChunk++; - --count; - } - - if (indexInChunk >= chunk.m_ChunkLength || count == 0) // Have we moved out of the current chunk? - { - // Replacing mutates the blocks, so we need to convert to a logical index and back afterwards. - int index = indexInChunk + chunk.m_ChunkOffset; - int indexBeforeAdjustment = index; - - // See if we accumulated any replacements, if so apply them. - ReplaceAllInChunk(replacements, replacementsCount, chunk, oldValue.Length, newValue); - // The replacement has affected the logical index. Adjust it. - index += ((newValue.Length - oldValue.Length) * replacementsCount); - replacementsCount = 0; - - chunk = FindChunkForIndex(index); - indexInChunk = index - chunk.m_ChunkOffset; - Debug.Assert(chunk != null || count == 0, "Chunks ended prematurely!"); - } - } - - AssertInvariants(); - return this; - } - - /// - /// Replaces all instances of one character with another in this builder. - /// - /// The character to replace. - /// The character to replace with. - public StringBuilder Replace(char oldChar, char newChar) - { - return Replace(oldChar, newChar, 0, Length); - } - - /// - /// Replaces all instances of one character with another in this builder. - /// - /// The character to replace. - /// The character to replace with. - /// The index to start in this builder. - /// The number of characters to read in this builder. - public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count) - { - int currentLength = Length; - if ((uint)startIndex > (uint)currentLength) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); - } - - if (count < 0 || startIndex > currentLength - count) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Index); - } - - int endIndex = startIndex + count; - StringBuilder chunk = this; - - for (;;) - { - int endIndexInChunk = endIndex - chunk.m_ChunkOffset; - int startIndexInChunk = startIndex - chunk.m_ChunkOffset; - if (endIndexInChunk >= 0) - { - int curInChunk = Math.Max(startIndexInChunk, 0); - int endInChunk = Math.Min(chunk.m_ChunkLength, endIndexInChunk); - while (curInChunk < endInChunk) - { - if (chunk.m_ChunkChars[curInChunk] == oldChar) - chunk.m_ChunkChars[curInChunk] = newChar; - curInChunk++; - } - } - if (startIndexInChunk >= 0) - break; - chunk = chunk.m_ChunkPrevious; - } - - AssertInvariants(); - return this; - } - - /// - /// Appends a character buffer to this builder. - /// - /// The pointer to the start of the buffer. - /// The number of characters in the buffer. - [CLSCompliant(false)] - public unsafe StringBuilder Append(char* value, int valueCount) - { - // We don't check null value as this case will throw null reference exception anyway - if (valueCount < 0) - { - throw new ArgumentOutOfRangeException(nameof(valueCount), SR.ArgumentOutOfRange_NegativeCount); - } - - // this is where we can check if the valueCount will put us over m_MaxCapacity - // We are doing the check here to prevent the corruption of the StringBuilder. - int newLength = Length + valueCount; - if (newLength > m_MaxCapacity || newLength < valueCount) - { - throw new ArgumentOutOfRangeException(nameof(valueCount), SR.ArgumentOutOfRange_LengthGreaterThanCapacity); - } - - // This case is so common we want to optimize for it heavily. - int newIndex = valueCount + m_ChunkLength; - if (newIndex <= m_ChunkChars.Length) - { - ThreadSafeCopy(value, m_ChunkChars, m_ChunkLength, valueCount); - m_ChunkLength = newIndex; - } - else - { - // Copy the first chunk - int firstLength = m_ChunkChars.Length - m_ChunkLength; - if (firstLength > 0) - { - ThreadSafeCopy(value, m_ChunkChars, m_ChunkLength, firstLength); - m_ChunkLength = m_ChunkChars.Length; - } - - // Expand the builder to add another chunk. - int restLength = valueCount - firstLength; - ExpandByABlock(restLength); - Debug.Assert(m_ChunkLength == 0, "A new block was not created."); - - // Copy the second chunk - ThreadSafeCopy(value + firstLength, m_ChunkChars, 0, restLength); - m_ChunkLength = restLength; - } - AssertInvariants(); - return this; - } - - /// - /// Inserts a character buffer into this builder at the specified position. - /// - /// The index to insert in this builder. - /// The pointer to the start of the buffer. - /// The number of characters in the buffer. - private unsafe void Insert(int index, char* value, int valueCount) - { - if ((uint)index > (uint)Length) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); - } - - if (valueCount > 0) - { - StringBuilder chunk; - int indexInChunk; - MakeRoom(index, valueCount, out chunk, out indexInChunk, false); - ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, value, valueCount); - } - } - - /// - /// Replaces strings at specified indices with a new string in a chunk. - /// - /// The list of indices, relative to the beginning of the chunk, to remove at. - /// The number of replacements to make. - /// The source chunk. - /// The number of characters to remove at each replacement. - /// The string to insert at each replacement. - /// - /// This routine is very efficient because it does replacements in bulk. - /// - private void ReplaceAllInChunk(int[] replacements, int replacementsCount, StringBuilder sourceChunk, int removeCount, string value) - { - if (replacementsCount <= 0) - { - return; - } - - unsafe - { - fixed (char* valuePtr = value) - { - // calculate the total amount of extra space or space needed for all the replacements. - int delta = (value.Length - removeCount) * replacementsCount; - - StringBuilder targetChunk = sourceChunk; // the target as we copy chars down - int targetIndexInChunk = replacements[0]; - - // Make the room needed for all the new characters if needed. - if (delta > 0) - MakeRoom(targetChunk.m_ChunkOffset + targetIndexInChunk, delta, out targetChunk, out targetIndexInChunk, true); - // We made certain that characters after the insertion point are not moved, - int i = 0; - for (;;) - { - // Copy in the new string for the ith replacement - ReplaceInPlaceAtChunk(ref targetChunk, ref targetIndexInChunk, valuePtr, value.Length); - int gapStart = replacements[i] + removeCount; - i++; - if (i >= replacementsCount) - { - break; - } - - int gapEnd = replacements[i]; - Debug.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer. Should not happen"); - Debug.Assert(gapStart <= gapEnd, "negative gap size"); - Debug.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big"); - if (delta != 0) // can skip the sliding of gaps if source an target string are the same size. - { - // Copy the gap data between the current replacement and the next replacement - fixed (char* sourcePtr = &sourceChunk.m_ChunkChars[gapStart]) - ReplaceInPlaceAtChunk(ref targetChunk, ref targetIndexInChunk, sourcePtr, gapEnd - gapStart); - } - else - { - targetIndexInChunk += gapEnd - gapStart; - Debug.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk"); - } - } - - // Remove extra space if necessary. - if (delta < 0) - Remove(targetChunk.m_ChunkOffset + targetIndexInChunk, -delta, out targetChunk, out targetIndexInChunk); - } - } - } - - /// - /// Returns a value indicating whether a substring of a builder starts with a specified prefix. - /// - /// The chunk in which the substring starts. - /// The index in at which the substring starts. - /// The logical count of the substring. - /// The prefix. - private bool StartsWith(StringBuilder chunk, int indexInChunk, int count, string value) - { - for (int i = 0; i < value.Length; i++) - { - if (count == 0) - { - return false; - } - - if (indexInChunk >= chunk.m_ChunkLength) - { - chunk = Next(chunk); - if (chunk == null) - return false; - indexInChunk = 0; - } - - if (value[i] != chunk.m_ChunkChars[indexInChunk]) - { - return false; - } - - indexInChunk++; - --count; - } - - return true; - } - - /// - /// Replaces characters at a specified location with the contents of a character buffer. - /// This function is the logical equivalent of memcpy. - /// - /// - /// The chunk in which to start replacing characters. - /// Receives the chunk in which character replacement ends. - /// - /// - /// The index in to start replacing characters at. - /// Receives the index at which character replacement ends. - /// - /// The pointer to the start of the character buffer. - /// The number of characters in the buffer. - unsafe private void ReplaceInPlaceAtChunk(ref StringBuilder chunk, ref int indexInChunk, char* value, int count) - { - if (count != 0) - { - for (;;) - { - int lengthInChunk = chunk.m_ChunkLength - indexInChunk; - Debug.Assert(lengthInChunk >= 0, "Index isn't in the chunk."); - - int lengthToCopy = Math.Min(lengthInChunk, count); - ThreadSafeCopy(value, chunk.m_ChunkChars, indexInChunk, lengthToCopy); - - // Advance the index. - indexInChunk += lengthToCopy; - if (indexInChunk >= chunk.m_ChunkLength) - { - chunk = Next(chunk); - indexInChunk = 0; - } - count -= lengthToCopy; - if (count == 0) - { - break; - } - value += lengthToCopy; - } - } - } - - /// - /// This method prevents out-of-bounds writes in the case a different thread updates a field in the builder just before a copy begins. - /// All interesting variables are copied out of the heap into the parameters of this method, and then bounds checks are run. - /// - private static unsafe void ThreadSafeCopy(char* sourcePtr, char[] destination, int destinationIndex, int count) - { - if (count > 0) - { - if ((uint)destinationIndex <= (uint)destination.Length && (destinationIndex + count) <= destination.Length) - { - fixed (char* destinationPtr = &destination[destinationIndex]) - string.wstrcpy(destinationPtr, sourcePtr, count); - } - else - { - throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_Index); - } - } - } - - private static unsafe void ThreadSafeCopy(char[] source, int sourceIndex, Span destination, int destinationIndex, int count) - { - if (count > 0) - { - if ((uint)sourceIndex > (uint)source.Length || count > source.Length - sourceIndex) - { - throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index); - } - - if ((uint)destinationIndex > (uint)destination.Length || count > destination.Length - destinationIndex) - { - throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_Index); - } - - fixed (char* sourcePtr = &source[sourceIndex]) - fixed (char* destinationPtr = &MemoryMarshal.GetReference(destination)) - string.wstrcpy(destinationPtr + destinationIndex, sourcePtr, count); - } - } - - /// - /// Gets the chunk corresponding to the logical index in this builder. - /// - /// The logical index in this builder. - /// - /// After calling this method, you can obtain the actual index within the chunk by - /// subtracting from . - /// - private StringBuilder FindChunkForIndex(int index) - { - Debug.Assert(0 <= index && index <= Length); - - StringBuilder result = this; - while (result.m_ChunkOffset > index) - { - result = result.m_ChunkPrevious; - } - - Debug.Assert(result != null); - return result; - } - - /// - /// Gets the chunk corresponding to the logical byte index in this builder. - /// - /// The logical byte index in this builder. - private StringBuilder FindChunkForByte(int byteIndex) - { - Debug.Assert(0 <= byteIndex && byteIndex <= Length * sizeof(char)); - - StringBuilder result = this; - while (result.m_ChunkOffset * sizeof(char) > byteIndex) - { - result = result.m_ChunkPrevious; - } - - Debug.Assert(result != null); - return result; - } - - /// Gets a span representing the remaining space available in the current chunk. - private Span RemainingCurrentChunk - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => new Span(m_ChunkChars, m_ChunkLength, m_ChunkChars.Length - m_ChunkLength); - } - - /// - /// Finds the chunk that logically succeeds the specified chunk. - /// - /// The chunk whose successor should be found. - /// - /// Each chunk only stores the pointer to its logical predecessor, so this routine has to start - /// from the 'this' pointer (which is assumed to represent the whole StringBuilder) and work its - /// way down until it finds the specified chunk (which is O(n)). Thus, it is more expensive than - /// a field fetch. - /// - private StringBuilder Next(StringBuilder chunk) => chunk == this ? null : FindChunkForIndex(chunk.m_ChunkOffset + chunk.m_ChunkLength); - - /// - /// Transfers the character buffer from this chunk to a new chunk, and allocates a new buffer with a minimum size for this chunk. - /// - /// The minimum size of the new buffer to be allocated for this chunk. - /// - /// This method requires that the current chunk is full. Otherwise, there's no point in shifting the characters over. - /// It also assumes that 'this' is the last chunk in the linked list. - /// - private void ExpandByABlock(int minBlockCharCount) - { - Debug.Assert(Capacity == Length, nameof(ExpandByABlock) + " should only be called when there is no space left."); - Debug.Assert(minBlockCharCount > 0); - - AssertInvariants(); - - if ((minBlockCharCount + Length) > m_MaxCapacity || minBlockCharCount + Length < minBlockCharCount) - { - throw new ArgumentOutOfRangeException("requiredLength", SR.ArgumentOutOfRange_SmallCapacity); - } - - // - We always need to make the new chunk at least as big as was requested (`minBlockCharCount`). - // - We'd also prefer to make it at least at big as the current length (thus doubling capacity). - // - But this is only up to a maximum, so we stay in the small object heap, and never allocate - // really big chunks even if the string gets really big. - int newBlockLength = Math.Max(minBlockCharCount, Math.Min(Length, MaxChunkSize)); - - // Move all of the data from this chunk to a new one, via a few O(1) pointer adjustments. - // Then, have this chunk point to the new one as its predecessor. - m_ChunkPrevious = new StringBuilder(this); - m_ChunkOffset += m_ChunkLength; - m_ChunkLength = 0; - - // Check for integer overflow (logical buffer size > int.MaxValue) - if (m_ChunkOffset + newBlockLength < newBlockLength) - { - m_ChunkChars = null; - throw new OutOfMemoryException(); - } - m_ChunkChars = new char[newBlockLength]; - - AssertInvariants(); - } - - /// - /// Creates a new chunk with fields copied from an existing chunk. - /// - /// The chunk from which to copy fields. - /// - /// - /// This method runs in O(1) time. It does not copy data within the character buffer - /// holds, but copies the reference to the character buffer itself - /// (plus a few other fields). - /// - /// - /// Callers are expected to update subsequently to point to this - /// chunk as its predecessor. - /// - /// - private StringBuilder(StringBuilder from) - { - m_ChunkLength = from.m_ChunkLength; - m_ChunkOffset = from.m_ChunkOffset; - m_ChunkChars = from.m_ChunkChars; - m_ChunkPrevious = from.m_ChunkPrevious; - m_MaxCapacity = from.m_MaxCapacity; - - AssertInvariants(); - } - - /// - /// Creates a gap at a logical index with the specified count. - /// - /// The logical index in this builder. - /// The number of characters in the gap. - /// Receives the chunk containing the gap. - /// The index in that points to the gap. - /// - /// - If true, then room must be made by inserting a chunk before the current chunk. - /// - If false, then room can be made by shifting characters ahead of - /// in this block forward by provided the characters will still fit in - /// the current chunk after being shifted. - /// - Providing false does not make a difference most of the time, but it can matter when someone - /// inserts lots of small strings at a position in the buffer. - /// - /// - /// - /// Since chunks do not contain references to their successors, it is not always possible for us to make room - /// by inserting space after in case this chunk runs out of space. Thus, we make room - /// by inserting space before the specified index, and having logical indices refer to new locations by the end - /// of this method. - /// - /// - /// can be used in conjunction with this method to fill in the newly created gap. - /// - /// - private void MakeRoom(int index, int count, out StringBuilder chunk, out int indexInChunk, bool doNotMoveFollowingChars) - { - AssertInvariants(); - Debug.Assert(count > 0); - Debug.Assert(index >= 0); - - if (count + Length > m_MaxCapacity || count + Length < count) - { - throw new ArgumentOutOfRangeException("requiredLength", SR.ArgumentOutOfRange_SmallCapacity); - } - - chunk = this; - while (chunk.m_ChunkOffset > index) - { - chunk.m_ChunkOffset += count; - chunk = chunk.m_ChunkPrevious; - } - indexInChunk = index - chunk.m_ChunkOffset; - - // Cool, we have some space in this block, and we don't have to copy much to get at it, so go ahead and use it. - // This typically happens when someone repeatedly inserts small strings at a spot (usually the absolute front) of the buffer. - if (!doNotMoveFollowingChars && chunk.m_ChunkLength <= DefaultCapacity * 2 && chunk.m_ChunkChars.Length - chunk.m_ChunkLength >= count) - { - for (int i = chunk.m_ChunkLength; i > indexInChunk; ) - { - --i; - chunk.m_ChunkChars[i + count] = chunk.m_ChunkChars[i]; - } - chunk.m_ChunkLength += count; - return; - } - - // Allocate space for the new chunk, which will go before the current one. - StringBuilder newChunk = new StringBuilder(Math.Max(count, DefaultCapacity), chunk.m_MaxCapacity, chunk.m_ChunkPrevious); - newChunk.m_ChunkLength = count; - - // Copy the head of the current buffer to the new buffer. - int copyCount1 = Math.Min(count, indexInChunk); - if (copyCount1 > 0) - { - unsafe - { - fixed (char* chunkCharsPtr = &chunk.m_ChunkChars[0]) - { - ThreadSafeCopy(chunkCharsPtr, newChunk.m_ChunkChars, 0, copyCount1); - - // Slide characters over in the current buffer to make room. - int copyCount2 = indexInChunk - copyCount1; - if (copyCount2 >= 0) - { - ThreadSafeCopy(chunkCharsPtr + copyCount1, chunk.m_ChunkChars, 0, copyCount2); - indexInChunk = copyCount2; - } - } - } - } - - // Wire in the new chunk. - chunk.m_ChunkPrevious = newChunk; - chunk.m_ChunkOffset += count; - if (copyCount1 < count) - { - chunk = newChunk; - indexInChunk = copyCount1; - } - - AssertInvariants(); - } - - /// - /// Used by to allocate another chunk. - /// - /// The size of the character buffer for this chunk. - /// The maximum capacity, to be stored in this chunk. - /// The predecessor of this chunk. - private StringBuilder(int size, int maxCapacity, StringBuilder previousBlock) - { - Debug.Assert(size > 0); - Debug.Assert(maxCapacity > 0); - - m_ChunkChars = new char[size]; - m_MaxCapacity = maxCapacity; - m_ChunkPrevious = previousBlock; - if (previousBlock != null) - { - m_ChunkOffset = previousBlock.m_ChunkOffset + previousBlock.m_ChunkLength; - } - - AssertInvariants(); - } - - /// - /// Removes a specified number of characters beginning at a logical index in this builder. - /// - /// The logical index in this builder to start removing characters. - /// The number of characters to remove. - /// Receives the new chunk containing the logical index. - /// - /// Receives the new index in that is associated with the logical index. - /// - private void Remove(int startIndex, int count, out StringBuilder chunk, out int indexInChunk) - { - AssertInvariants(); - Debug.Assert(startIndex >= 0 && startIndex < Length); - - int endIndex = startIndex + count; - - // Find the chunks for the start and end of the block to delete. - chunk = this; - StringBuilder endChunk = null; - int endIndexInChunk = 0; - for (;;) - { - if (endIndex - chunk.m_ChunkOffset >= 0) - { - if (endChunk == null) - { - endChunk = chunk; - endIndexInChunk = endIndex - endChunk.m_ChunkOffset; - } - if (startIndex - chunk.m_ChunkOffset >= 0) - { - indexInChunk = startIndex - chunk.m_ChunkOffset; - break; - } - } - else - { - chunk.m_ChunkOffset -= count; - } - chunk = chunk.m_ChunkPrevious; - } - Debug.Assert(chunk != null, "We fell off the beginning of the string!"); - - int copyTargetIndexInChunk = indexInChunk; - int copyCount = endChunk.m_ChunkLength - endIndexInChunk; - if (endChunk != chunk) - { - copyTargetIndexInChunk = 0; - // Remove the characters after `startIndex` to the end of the chunk. - chunk.m_ChunkLength = indexInChunk; - - // Remove the characters in chunks between the start and the end chunk. - endChunk.m_ChunkPrevious = chunk; - endChunk.m_ChunkOffset = chunk.m_ChunkOffset + chunk.m_ChunkLength; - - // If the start is 0, then we can throw away the whole start chunk. - if (indexInChunk == 0) - { - endChunk.m_ChunkPrevious = chunk.m_ChunkPrevious; - chunk = endChunk; - } - } - endChunk.m_ChunkLength -= (endIndexInChunk - copyTargetIndexInChunk); - - // SafeCritical: We ensure that `endIndexInChunk + copyCount` is within range of `m_ChunkChars`, and - // also ensure that `copyTargetIndexInChunk + copyCount` is within the chunk. - - // Remove any characters in the end chunk, by sliding the characters down. - if (copyTargetIndexInChunk != endIndexInChunk) // Sometimes no move is necessary - { - ThreadSafeCopy(endChunk.m_ChunkChars, endIndexInChunk, endChunk.m_ChunkChars, copyTargetIndexInChunk, copyCount); - } - - Debug.Assert(chunk != null, "We fell off the beginning of the string!"); - AssertInvariants(); - } - } -} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs.REMOVED.git-id new file mode 100644 index 0000000000..6d277cf683 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs.REMOVED.git-id @@ -0,0 +1 @@ +99021e2dda3f0dd62f44ec5c0d2364ee74d32911 \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/StringBuilderCache.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/StringBuilderCache.cs new file mode 100644 index 0000000000..e699cc27cc --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/StringBuilderCache.cs @@ -0,0 +1,62 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Text +{ + /// Provide a cached reusable instance of stringbuilder per thread. + internal static class StringBuilderCache + { + // The value 360 was chosen in discussion with performance experts as a compromise between using + // as litle memory per thread as possible and still covering a large part of short-lived + // StringBuilder creations on the startup path of VS designers. + private const int MaxBuilderSize = 360; + private const int DefaultCapacity = 16; // == StringBuilder.DefaultCapacity + + // WARNING: We allow diagnostic tools to directly inspect this member (t_cachedInstance). + // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. + // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. + // Get in touch with the diagnostics team if you have questions. + [ThreadStatic] + private static StringBuilder t_cachedInstance; + + /// Get a StringBuilder for the specified capacity. + /// If a StringBuilder of an appropriate size is cached, it will be returned and the cache emptied. + public static StringBuilder Acquire(int capacity = DefaultCapacity) + { + if (capacity <= MaxBuilderSize) + { + StringBuilder sb = t_cachedInstance; + if (sb != null) + { + // Avoid stringbuilder block fragmentation by getting a new StringBuilder + // when the requested size is larger than the current capacity + if (capacity <= sb.Capacity) + { + t_cachedInstance = null; + sb.Clear(); + return sb; + } + } + } + return new StringBuilder(capacity); + } + + /// Place the specified builder in the cache if it is not too big. + public static void Release(StringBuilder sb) + { + if (sb.Capacity <= MaxBuilderSize) + { + t_cachedInstance = sb; + } + } + + /// ToString() the stringbuilder, Release it to the cache, and return the resulting string. + public static string GetStringAndRelease(StringBuilder sb) + { + string result = sb.ToString(); + Release(sb); + return result; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs index 7828775ea0..86169e6b16 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs @@ -103,13 +103,13 @@ namespace System.Text { // Validate input parameters if (chars == null) - throw new ArgumentNullException("chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) - throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input, return 0, avoid fixed empty array problem if (count == 0) @@ -125,11 +125,11 @@ namespace System.Text // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetByteCount(String s) + public override unsafe int GetByteCount(string s) { // Validate input if (s==null) - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(s)); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); @@ -144,10 +144,10 @@ namespace System.Text { // Validate Parameters if (chars == null) - throw new ArgumentNullException("chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) - throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); // Call it with empty encoder return GetByteCount(chars, count, null); @@ -158,20 +158,20 @@ namespace System.Text // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding - public override unsafe int GetBytes(String s, int charIndex, int charCount, + public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) - throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array); + throw new ArgumentNullException((s == null ? nameof(s) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (s.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount); + throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) - throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); int byteCount = bytes.Length - byteIndex; @@ -198,16 +198,16 @@ namespace System.Text { // Validate parameters if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); + throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) - throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) @@ -230,10 +230,10 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); return GetBytes(chars, charCount, bytes, byteCount, null); } @@ -250,13 +250,13 @@ namespace System.Text { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input just return 0, fixed doesn't like 0 length arrays. if (count == 0) @@ -276,10 +276,10 @@ namespace System.Text { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) - throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); return GetCharCount(bytes, count, null); } @@ -294,16 +294,16 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if ( bytes.Length - byteIndex < byteCount) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) - throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); // If no input, return 0 & avoid fixed problem if (byteCount == 0) @@ -326,10 +326,10 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); return GetChars(bytes, byteCount, chars, charCount, null); } @@ -342,23 +342,23 @@ namespace System.Text // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe String GetString(byte[] bytes, int index, int count) + public override unsafe string GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid problems with empty input buffer - if (count == 0) return String.Empty; + if (count == 0) return string.Empty; fixed (byte* pBytes = bytes) - return String.CreateStringFromEncoding( + return string.CreateStringFromEncoding( pBytes + index, count, this); } @@ -417,7 +417,7 @@ namespace System.Text // // In previous char, we encounter a high surrogate, so we are expecting a low surrogate here. // - if (Char.IsLowSurrogate(ch)) + if (char.IsLowSurrogate(ch)) { // They're all legal highSurrogate = '\0'; @@ -447,7 +447,7 @@ namespace System.Text } // Do we have another high surrogate? - if (Char.IsHighSurrogate(ch)) + if (char.IsHighSurrogate(ch)) { // // We'll have a high surrogate to check next time. @@ -457,7 +457,7 @@ namespace System.Text } // Check for illegal characters - if (Char.IsLowSurrogate(ch)) + if (char.IsLowSurrogate(ch)) { // We have a leading low surrogate, do the fallback charsForFallback = chars; @@ -552,7 +552,7 @@ namespace System.Text // // In previous char, we encountered a high surrogate, so we are expecting a low surrogate here. // - if (Char.IsLowSurrogate(ch)) + if (char.IsLowSurrogate(ch)) { // Is it a legal one? uint iTemp = GetSurrogate(highSurrogate, ch); @@ -616,7 +616,7 @@ namespace System.Text } // Do we have another high surrogate?, if so remember it - if (Char.IsHighSurrogate(ch)) + if (char.IsHighSurrogate(ch)) { // // We'll have a high surrogate to check next time. @@ -626,7 +626,7 @@ namespace System.Text } // Check for illegal characters (low surrogate) - if (Char.IsLowSurrogate(ch)) + if (char.IsLowSurrogate(ch)) { // We have a leading low surrogate, do the fallback charsForFallback = chars; @@ -1159,7 +1159,7 @@ namespace System.Text _emitUTF32ByteOrderMark ? (_bigEndian ? s_bigEndianPreamble : s_littleEndianPreamble) : Array.Empty(); - public override bool Equals(Object value) + public override bool Equals(object value) { UTF32Encoding that = value as UTF32Encoding; if (that != null) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs index 0246c28915..5c51c81076 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs @@ -14,17 +14,17 @@ namespace System.Text { public class UTF7Encoding : Encoding { - private const String base64Chars = + private const string base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // 0123456789111111111122222222223333333333444444444455555555556666 // 012345678901234567890123456789012345678901234567890123 // These are the characters that can be directly encoded in UTF7. - private const String directChars = + private const string directChars = "\t\n\r '(),-./0123456789:?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // These are the characters that can be optionally directly encoded in UTF7. - private const String optionalChars = + private const string optionalChars = "!\"#$%&*;<=>@[]^_`{|}"; // Used by Encoding.UTF7 for lazy initialization @@ -88,16 +88,16 @@ namespace System.Text } // We go ahead and set this because Encoding expects it, however nothing can fall back in UTF7. - internal override void SetDefaultFallbacks() + internal sealed override void SetDefaultFallbacks() { // UTF7 had an odd decoderFallback behavior, and the Encoder fallback // is irrelevant because we encode surrogates individually and never check for unmatched ones // (so nothing can fallback during encoding) - this.encoderFallback = new EncoderReplacementFallback(String.Empty); + this.encoderFallback = new EncoderReplacementFallback(string.Empty); this.decoderFallback = new DecoderUTF7Fallback(); } - public override bool Equals(Object value) + public override bool Equals(object value) { UTF7Encoding that = value as UTF7Encoding; if (that != null) @@ -133,13 +133,13 @@ namespace System.Text { // Validate input parameters if (chars == null) - throw new ArgumentNullException("chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) - throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input, return 0, avoid fixed empty array problem if (count == 0) @@ -159,7 +159,7 @@ namespace System.Text { // Validate input if (s==null) - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(s)); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); @@ -174,10 +174,10 @@ namespace System.Text { // Validate Parameters if (chars == null) - throw new ArgumentNullException("chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) - throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); // Call it with empty encoder return GetByteCount(chars, count, null); @@ -192,16 +192,16 @@ namespace System.Text byte[] bytes, int byteIndex) { if (s == null || bytes == null) - throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array); + throw new ArgumentNullException((s == null ? nameof(s) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (s.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount); + throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) - throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); int byteCount = bytes.Length - byteIndex; @@ -228,16 +228,16 @@ namespace System.Text { // Validate parameters if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); + throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) - throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) @@ -260,10 +260,10 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); return GetBytes(chars, charCount, bytes, byteCount, null); } @@ -280,13 +280,13 @@ namespace System.Text { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input just return 0, fixed doesn't like 0 length arrays. if (count == 0) @@ -306,10 +306,10 @@ namespace System.Text { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) - throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); return GetCharCount(bytes, count, null); } @@ -324,16 +324,16 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if ( bytes.Length - byteIndex < byteCount) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) - throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); // If no input, return 0 & avoid fixed problem if (byteCount == 0) @@ -356,10 +356,10 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); return GetChars(bytes, byteCount, chars, charCount, null); } @@ -372,23 +372,23 @@ namespace System.Text // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe String GetString(byte[] bytes, int index, int count) + public override unsafe string GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid problems with empty input buffer - if (count == 0) return String.Empty; + if (count == 0) return string.Empty; fixed (byte* pBytes = bytes) - return String.CreateStringFromEncoding( + return string.CreateStringFromEncoding( pBytes + index, count, this); } @@ -396,7 +396,7 @@ namespace System.Text // End of standard methods copied from EncodingNLS.cs // - internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder) + internal sealed override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder) { Debug.Assert(chars != null, "[UTF7Encoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UTF7Encoding.GetByteCount]count >=0"); @@ -405,8 +405,8 @@ namespace System.Text return GetBytes(chars, count, null, 0, baseEncoder); } - internal override unsafe int GetBytes(char* chars, int charCount, - byte* bytes, int byteCount, EncoderNLS baseEncoder) + internal sealed override unsafe int GetBytes( + char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS baseEncoder) { Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetBytes]byteCount >=0"); Debug.Assert(chars != null, "[UTF7Encoding.GetBytes]chars!=null"); @@ -545,7 +545,7 @@ namespace System.Text return buffer.Count; } - internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) + internal sealed override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { Debug.Assert(count >= 0, "[UTF7Encoding.GetCharCount]count >=0"); Debug.Assert(bytes != null, "[UTF7Encoding.GetCharCount]bytes!=null"); @@ -554,8 +554,8 @@ namespace System.Text return GetChars(bytes, count, null, 0, baseDecoder); } - internal override unsafe int GetChars(byte* bytes, int byteCount, - char* chars, int charCount, DecoderNLS baseDecoder) + internal sealed override unsafe int GetChars( + byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetChars]byteCount >=0"); Debug.Assert(bytes != null, "[UTF7Encoding.GetChars]bytes!=null"); @@ -873,7 +873,7 @@ namespace System.Text } } - public override bool Equals(Object value) + public override bool Equals(object value) { DecoderUTF7Fallback that = value as DecoderUTF7Fallback; if (that != null) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs.REMOVED.git-id index add73271c0..25d9b92bb2 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs.REMOVED.git-id +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs.REMOVED.git-id @@ -1 +1 @@ -67f87c9b09cea24711f13de237cd53a00386c382 \ No newline at end of file +c9e51f661e0edf5adf2f135a2439cb39d934449a \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs index 342bf53d62..6a27d2c855 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs @@ -6,11 +6,17 @@ // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused. // +// This define can be used to turn off the fast loops. Useful for finding whether +// the problem is fastloop-specific. +#define FASTLOOP + using System; using System.Globalization; using System.Diagnostics; using System.Runtime.InteropServices; +using Internal.Runtime.CompilerServices; + namespace System.Text { public class UnicodeEncoding : Encoding @@ -23,15 +29,14 @@ namespace System.Text private static readonly byte[] s_bigEndianPreamble = new byte[2] { 0xfe, 0xff }; private static readonly byte[] s_littleEndianPreamble = new byte[2] { 0xff, 0xfe }; - internal bool isThrowException = false; + private bool isThrowException = false; - internal bool bigEndian = false; - internal bool byteOrderMark = true; + private bool bigEndian = false; + private bool byteOrderMark = true; // Unicode version 2.0 character size in bytes public const int CharSize = 2; - public UnicodeEncoding() : this(false, true) { @@ -56,7 +61,7 @@ namespace System.Text SetDefaultFallbacks(); } - internal override void SetDefaultFallbacks() + internal sealed override void SetDefaultFallbacks() { // For UTF-X encodings, we use a replacement fallback with an empty string if (this.isThrowException) @@ -89,13 +94,13 @@ namespace System.Text { // Validate input parameters if (chars == null) - throw new ArgumentNullException("chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) - throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input, return 0, avoid fixed empty array problem if (count == 0) @@ -111,11 +116,11 @@ namespace System.Text // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetByteCount(String s) + public override unsafe int GetByteCount(string s) { // Validate input if (s==null) - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(s)); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); @@ -130,10 +135,10 @@ namespace System.Text { // Validate Parameters if (chars == null) - throw new ArgumentNullException("chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) - throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); // Call it with empty encoder return GetByteCount(chars, count, null); @@ -144,20 +149,20 @@ namespace System.Text // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding - public override unsafe int GetBytes(String s, int charIndex, int charCount, + public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) - throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array); + throw new ArgumentNullException((s == null ? nameof(s) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (s.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount); + throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) - throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); int byteCount = bytes.Length - byteIndex; @@ -184,16 +189,16 @@ namespace System.Text { // Validate parameters if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); + throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) - throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) @@ -216,10 +221,10 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); return GetBytes(chars, charCount, bytes, byteCount, null); } @@ -236,13 +241,13 @@ namespace System.Text { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input just return 0, fixed doesn't like 0 length arrays if (count == 0) @@ -262,10 +267,10 @@ namespace System.Text { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) - throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); return GetCharCount(bytes, count, null); } @@ -280,16 +285,16 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if ( bytes.Length - byteIndex < byteCount) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) - throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); + throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); // If no input, return 0 & avoid fixed problem if (byteCount == 0) @@ -312,10 +317,10 @@ namespace System.Text { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); return GetChars(bytes, byteCount, chars, charCount, null); } @@ -332,19 +337,19 @@ namespace System.Text { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); + throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) - throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); + throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid problems with empty input buffer - if (count == 0) return String.Empty; + if (count == 0) return string.Empty; fixed (byte* pBytes = bytes) - return String.CreateStringFromEncoding( + return string.CreateStringFromEncoding( pBytes + index, count, this); } @@ -352,7 +357,7 @@ namespace System.Text // End of standard methods copied from EncodingNLS.cs // - internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) + internal sealed override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { Debug.Assert(chars != null, "[UnicodeEncoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0"); @@ -372,11 +377,6 @@ namespace System.Text bool wasHereBefore = false; - // Need -1 to check 2 at a time. If we have an even #, longChars will go - // from longEnd - 1/2 long to longEnd + 1/2 long. If we're odd, longChars - // will go from longEnd - 1 long to longEnd. (Might not get to use this) - ulong* longEnd = (ulong*)(charEnd - 3); - // For fallback we may need a fallback buffer EncoderFallbackBuffer fallbackBuffer = null; char* charsForFallback; @@ -410,19 +410,21 @@ namespace System.Text if (ch == 0) { // No fallback, maybe we can do it fast -#if !NO_FAST_UNICODE_LOOP -#if BIGENDIAN // If endianess is backwards then each pair of bytes would be backwards. - if ( bigEndian && +#if FASTLOOP + // If endianess is backwards then each pair of bytes would be backwards. + if ( (bigEndian ^ BitConverter.IsLittleEndian) && +#if BIT64 + (unchecked((long)chars) & 7) == 0 && #else - if (!bigEndian && -#endif // BIGENDIAN - -#if BIT64 // 64 bit CPU needs to be long aligned for this to work. - charLeftOver == 0 && (unchecked((long)chars) & 7) == 0) -#else - charLeftOver == 0 && (unchecked((int)chars) & 3) == 0) + (unchecked((int)chars) & 3) == 0 && #endif + charLeftOver == 0) { + // Need -1 to check 2 at a time. If we have an even #, longChars will go + // from longEnd - 1/2 long to longEnd + 1/2 long. If we're odd, longChars + // will go from longEnd - 1 long to longEnd. (Might not get to use this) + ulong* longEnd = (ulong*)(charEnd - 3); + // Need new char* so we can check 4 at a time ulong* longChars = (ulong*)chars; @@ -453,11 +455,8 @@ namespace System.Text // If they happen to be high/low/high/low, we may as well continue. Check the next // bit to see if its set (low) or not (high) in the right pattern -#if BIGENDIAN - if (((0xfc00fc00fc00fc00 & *longChars) ^ 0xd800dc00d800dc00) != 0) -#else - if (((0xfc00fc00fc00fc00 & *longChars) ^ 0xdc00d800dc00d800) != 0) -#endif + if ((0xfc00fc00fc00fc00 & *longChars) != + (BitConverter.IsLittleEndian ? (ulong)0xdc00d800dc00d800 : (ulong)0xd800dc00d800dc00)) { // Either there weren't 4 surrogates, or the 0x0400 bit was set when a high // was hoped for or the 0x0400 bit wasn't set where a low was hoped for. @@ -480,7 +479,7 @@ namespace System.Text if (chars >= charEnd) break; } -#endif // !NO_FAST_UNICODE_LOOP +#endif // FASTLOOP // No fallback, just get next char ch = *chars; @@ -651,8 +650,8 @@ namespace System.Text return byteCount; } - internal override unsafe int GetBytes(char* chars, int charCount, - byte* bytes, int byteCount, EncoderNLS encoder) + internal sealed override unsafe int GetBytes( + char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { Debug.Assert(chars != null, "[UnicodeEncoding.GetBytes]chars!=null"); Debug.Assert(byteCount >= 0, "[UnicodeEncoding.GetBytes]byteCount >=0"); @@ -700,17 +699,14 @@ namespace System.Text if (ch == 0) { // No fallback, maybe we can do it fast -#if !NO_FAST_UNICODE_LOOP -#if BIGENDIAN // If endianess is backwards then each pair of bytes would be backwards. - if ( bigEndian && +#if FASTLOOP + // If endianess is backwards then each pair of bytes would be backwards. + if ( (bigEndian ^ BitConverter.IsLittleEndian) && +#if BIT64 + (unchecked((long)chars) & 7) == 0 && #else - if (!bigEndian && -#endif // BIGENDIAN -#if BIT64 // 64 bit CPU needs to be long aligned for this to work, 32 bit CPU needs to be 32 bit aligned - (unchecked((long)chars) & 7) == 0 && (unchecked((long)bytes) & 7) == 0 && -#else - (unchecked((int)chars) & 3) == 0 && (unchecked((int)bytes) & 3) == 0 && -#endif // BIT64 + (unchecked((int)chars) & 3) == 0 && +#endif charLeftOver == 0) { // Need -1 to check 2 at a time. If we have an even #, longChars will go @@ -752,11 +748,8 @@ namespace System.Text // If they happen to be high/low/high/low, we may as well continue. Check the next // bit to see if its set (low) or not (high) in the right pattern -#if BIGENDIAN - if (((0xfc00fc00fc00fc00 & *longChars) ^ 0xd800dc00d800dc00) != 0) -#else - if (((0xfc00fc00fc00fc00 & *longChars) ^ 0xdc00d800dc00d800) != 0) -#endif + if ((0xfc00fc00fc00fc00 & *longChars) != + (BitConverter.IsLittleEndian ? (ulong)0xdc00d800dc00d800 : (ulong)0xd800dc00d800dc00)) { // Either there weren't 4 surrogates, or the 0x0400 bit was set when a high // was hoped for or the 0x0400 bit wasn't set where a low was hoped for. @@ -771,7 +764,7 @@ namespace System.Text // else all < 0x8000 so we can use them // We can use these 4 chars. - *longBytes = *longChars; + Unsafe.WriteUnaligned(longBytes, *longChars); longChars++; longBytes++; } @@ -782,66 +775,7 @@ namespace System.Text if (chars >= charEnd) break; } - // Not aligned, but maybe we can still be somewhat faster - // Also somehow this optimizes the above loop? It seems to cause something above - // to get enregistered, but I haven't figured out how to make that happen without this loop. - else if ((charLeftOver == 0) && -#if BIGENDIAN - bigEndian && -#else - !bigEndian && -#endif // BIGENDIAN - -#if BIT64 - (unchecked((long)chars) & 7) != (unchecked((long)bytes) & 7) && // Only do this if chars & bytes are out of line, otherwise faster loop will be faster next time -#else - (unchecked((int)chars) & 3) != (unchecked((int)bytes) & 3) && // Only do this if chars & bytes are out of line, otherwise faster loop will be faster next time -#endif // BIT64 - (unchecked((int)(bytes)) & 1) == 0) - { - // # to use - long iCount = ((byteEnd - bytes) >> 1 < charEnd - chars) ? - (byteEnd - bytes) >> 1 : charEnd - chars; - - // Need new char* - char* charOut = ((char*)bytes); // a char* for our output - char* tempEnd = chars + iCount - 1; // Our end pointer - - while (chars < tempEnd) - { - if (*chars >= (char)0xd800 && *chars <= (char)0xdfff) - { - // break for fallback for low surrogate - if (*chars >= 0xdc00) - break; - - // break if next one's not a low surrogate (will do fallback) - if (*(chars + 1) < 0xdc00 || *(chars + 1) > 0xdfff) - break; - - // They both exist, use them - } - // If 2nd char is surrogate & this one isn't then only add one - else if (*(chars + 1) >= (char)0xd800 && *(chars + 1) <= 0xdfff) - { - *charOut = *chars; - charOut++; - chars++; - continue; - } - - *charOut = *chars; - *(charOut + 1) = *(chars + 1); - charOut += 2; - chars += 2; - } - - bytes = (byte*)charOut; - - if (chars >= charEnd) - break; - } -#endif // !NO_FAST_UNICODE_LOOP +#endif // FASTLOOP // No fallback, just get next char ch = *chars; @@ -1070,13 +1004,10 @@ namespace System.Text encoder == null || !encoder._throwOnOverflow, "[UnicodeEncoding.GetBytes]Expected empty fallback buffer if not converting"); - // We used to copy it fast, but this doesn't check for surrogates - // System.IO.__UnmanagedMemoryStream.memcpyimpl(bytes, (byte*)chars, usedByteCount); - return (int)(bytes - byteStart); } - internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) + internal sealed override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { Debug.Assert(bytes != null, "[UnicodeEncoding.GetCharCount]bytes!=null"); Debug.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0"); @@ -1093,11 +1024,6 @@ namespace System.Text // Start by assuming same # of chars as bytes int charCount = count >> 1; - // Need -1 to check 2 at a time. If we have an even #, longBytes will go - // from longEnd - 1/2 long to longEnd + 1/2 long. If we're odd, longBytes - // will go from longEnd - 1 long to longEnd. (Might not get to use this) - ulong* longEnd = (ulong*)(byteEnd - 7); - // For fallback we may need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; @@ -1126,19 +1052,20 @@ namespace System.Text { // If we're aligned then maybe we can do it fast // That'll hurt if we're unaligned because we'll always test but never be aligned -#if !NO_FAST_UNICODE_LOOP -#if BIGENDIAN - if (bigEndian && -#else // BIGENDIAN - if (!bigEndian && -#endif // BIGENDIAN -#if BIT64 // win64 has to be long aligned +#if FASTLOOP + if ((bigEndian ^ BitConverter.IsLittleEndian) && +#if BIT64 (unchecked((long)bytes) & 7) == 0 && #else (unchecked((int)bytes) & 3) == 0 && #endif // BIT64 lastByte == -1 && lastChar == 0) { + // Need -1 to check 2 at a time. If we have an even #, longBytes will go + // from longEnd - 1/2 long to longEnd + 1/2 long. If we're odd, longBytes + // will go from longEnd - 1 long to longEnd. (Might not get to use this) + ulong* longEnd = (ulong*)(byteEnd - 7); + // Need new char* so we can check 4 at a time ulong* longBytes = (ulong*)bytes; @@ -1169,11 +1096,8 @@ namespace System.Text // If they happen to be high/low/high/low, we may as well continue. Check the next // bit to see if its set (low) or not (high) in the right pattern -#if BIGENDIAN - if (((0xfc00fc00fc00fc00 & *longBytes) ^ 0xd800dc00d800dc00) != 0) -#else - if (((0xfc00fc00fc00fc00 & *longBytes) ^ 0xdc00d800dc00d800) != 0) -#endif + if ((0xfc00fc00fc00fc00 & *longBytes) != + (BitConverter.IsLittleEndian ? (ulong)0xdc00d800dc00d800 : (ulong)0xd800dc00d800dc00)) { // Either there weren't 4 surrogates, or the 0x0400 bit was set when a high // was hoped for or the 0x0400 bit wasn't set where a low was hoped for. @@ -1196,7 +1120,7 @@ namespace System.Text if (bytes >= byteEnd) break; } -#endif // !NO_FAST_UNICODE_LOOP +#endif // FASTLOOP // Get 1st byte if (lastByte < 0) @@ -1410,8 +1334,8 @@ namespace System.Text return charCount; } - internal override unsafe int GetChars(byte* bytes, int byteCount, - char* chars, int charCount, DecoderNLS baseDecoder) + internal sealed override unsafe int GetChars( + byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { Debug.Assert(chars != null, "[UnicodeEncoding.GetChars]chars!=null"); Debug.Assert(byteCount >= 0, "[UnicodeEncoding.GetChars]byteCount >=0"); @@ -1449,17 +1373,13 @@ namespace System.Text { // If we're aligned then maybe we can do it fast // That'll hurt if we're unaligned because we'll always test but never be aligned -#if !NO_FAST_UNICODE_LOOP -#if BIGENDIAN - if (bigEndian && -#else // BIGENDIAN - if (!bigEndian && -#endif // BIGENDIAN -#if BIT64 // win64 has to be long aligned - (unchecked((long)chars) & 7) == 0 && (unchecked((long)bytes) & 7) == 0 && +#if FASTLOOP + if ((bigEndian ^ BitConverter.IsLittleEndian) && +#if BIT64 + (unchecked((long)chars) & 7) == 0 && #else - (unchecked((int)chars) & 3) == 0 && (unchecked((int)bytes) & 3) == 0 && -#endif // BIT64 + (unchecked((int)chars) & 3) == 0 && +#endif lastByte == -1 && lastChar == 0) { // Need -1 to check 2 at a time. If we have an even #, longChars will go @@ -1501,11 +1421,8 @@ namespace System.Text // If they happen to be high/low/high/low, we may as well continue. Check the next // bit to see if its set (low) or not (high) in the right pattern -#if BIGENDIAN - if (((0xfc00fc00fc00fc00 & *longBytes) ^ 0xd800dc00d800dc00) != 0) -#else - if (((0xfc00fc00fc00fc00 & *longBytes) ^ 0xdc00d800dc00d800) != 0) -#endif + if ((0xfc00fc00fc00fc00 & *longBytes) != + (BitConverter.IsLittleEndian ? (ulong)0xdc00d800dc00d800 : (ulong)0xd800dc00d800dc00)) { // Either there weren't 4 surrogates, or the 0x0400 bit was set when a high // was hoped for or the 0x0400 bit wasn't set where a low was hoped for. @@ -1520,7 +1437,7 @@ namespace System.Text // else all < 0x8000 so we can use them // We can use these 4 chars. - *longChars = *longBytes; + Unsafe.WriteUnaligned(longChars, *longBytes); longBytes++; longChars++; } @@ -1531,7 +1448,7 @@ namespace System.Text if (bytes >= byteEnd) break; } -#endif // !NO_FAST_UNICODE_LOOP +#endif // FASTLOOP // Get 1st byte if (lastByte < 0) @@ -1840,9 +1757,6 @@ namespace System.Text decoder.lastByte = lastByte; } - // Used to do this the old way - // System.IO.__UnmanagedMemoryStream.memcpyimpl((byte*)chars, bytes, byteCount); - // Shouldn't have anything in fallback buffer for GetChars // (don't have to check _throwOnOverflow for count or chars) Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, @@ -1875,7 +1789,7 @@ namespace System.Text else return new byte[2] { 0xff, 0xfe }; } - return Array.Empty(); + return Array.Empty(); } public override ReadOnlySpan Preamble => @@ -1928,7 +1842,7 @@ namespace System.Text } - public override bool Equals(Object value) + public override bool Equals(object value) { UnicodeEncoding that = value as UnicodeEncoding; if (that != null) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Text/ValueStringBuilder.cs b/external/corert/src/System.Private.CoreLib/shared/System/Text/ValueStringBuilder.cs index 18d5648672..74b5dacf97 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Text/ValueStringBuilder.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Text/ValueStringBuilder.cs @@ -9,7 +9,7 @@ using System.Runtime.InteropServices; namespace System.Text { - internal ref struct ValueStringBuilder + internal ref partial struct ValueStringBuilder { private char[] _arrayToReturnToPool; private Span _chars; @@ -22,11 +22,19 @@ namespace System.Text _pos = 0; } + public ValueStringBuilder(int initialCapacity) + { + _arrayToReturnToPool = ArrayPool.Shared.Rent(initialCapacity); + _chars = _arrayToReturnToPool; + _pos = 0; + } + public int Length { get => _pos; set { + Debug.Assert(value >= 0); Debug.Assert(value <= _chars.Length); _pos = value; } @@ -40,7 +48,30 @@ namespace System.Text Grow(capacity - _chars.Length); } - public ref char GetPinnableReference() => ref MemoryMarshal.GetReference(_chars); + /// + /// Get a pinnable reference to the builder. + /// Does not ensure there is a null char after + /// This overload is pattern matched in the C# 7.3+ compiler so you can omit + /// the explicit method call, and write eg "fixed (char* c = builder)" + /// + public ref char GetPinnableReference() + { + return ref MemoryMarshal.GetReference(_chars); + } + + /// + /// Get a pinnable reference to the builder. + /// + /// Ensures that the builder has a null char after + public ref char GetPinnableReference(bool terminate) + { + if (terminate) + { + EnsureCapacity(Length + 1); + _chars[Length] = '\0'; + } + return ref MemoryMarshal.GetReference(_chars); + } public ref char this[int index] { @@ -53,12 +84,31 @@ namespace System.Text public override string ToString() { - var s = new string(_chars.Slice(0, _pos)); + var s = _chars.Slice(0, _pos).ToString(); Dispose(); return s; } + /// Returns the underlying storage of the builder. + public Span RawChars => _chars; + + /// + /// Returns a span around the contents of the builder. + /// + /// Ensures that the builder has a null char after + public ReadOnlySpan AsSpan(bool terminate) + { + if (terminate) + { + EnsureCapacity(Length + 1); + _chars[Length] = '\0'; + } + return _chars.Slice(0, _pos); + } + public ReadOnlySpan AsSpan() => _chars.Slice(0, _pos); + public ReadOnlySpan AsSpan(int start) => _chars.Slice(start, _pos - start); + public ReadOnlySpan AsSpan(int start, int length) => _chars.Slice(start, length); public bool TryCopyTo(Span destination, out int charsWritten) { @@ -93,7 +143,7 @@ namespace System.Text public void Append(char c) { int pos = _pos; - if (pos < _chars.Length) + if ((uint)pos < (uint)_chars.Length) { _chars[pos] = c; _pos = pos + 1; @@ -108,7 +158,7 @@ namespace System.Text public void Append(string s) { int pos = _pos; - if (s.Length == 1 && pos < _chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc. + if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc. { _chars[pos] = s[0]; _pos = pos + 1; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/AbandonedMutexException.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/AbandonedMutexException.cs index c7e604f33d..bd504dd27a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Threading/AbandonedMutexException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/AbandonedMutexException.cs @@ -27,13 +27,13 @@ namespace System.Threading HResult = HResults.COR_E_ABANDONEDMUTEX; } - public AbandonedMutexException(String message) + public AbandonedMutexException(string message) : base(message) { HResult = HResults.COR_E_ABANDONEDMUTEX; } - public AbandonedMutexException(String message, Exception inner) + public AbandonedMutexException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_ABANDONEDMUTEX; @@ -46,14 +46,14 @@ namespace System.Threading SetupException(location, handle); } - public AbandonedMutexException(String message, int location, WaitHandle handle) + public AbandonedMutexException(string message, int location, WaitHandle handle) : base(message) { HResult = HResults.COR_E_ABANDONEDMUTEX; SetupException(location, handle); } - public AbandonedMutexException(String message, Exception inner, int location, WaitHandle handle) + public AbandonedMutexException(string message, Exception inner, int location, WaitHandle handle) : base(message, inner) { HResult = HResults.COR_E_ABANDONEDMUTEX; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/AsyncLocal.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/AsyncLocal.cs index 3531265bec..12d6502432 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Threading/AsyncLocal.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/AsyncLocal.cs @@ -61,7 +61,7 @@ namespace System.Threading get { object obj = ExecutionContext.GetLocalValue(this); - return (obj == null) ? default(T) : (T)obj; + return (obj == null) ? default : (T)obj; } set { @@ -72,8 +72,8 @@ namespace System.Threading void IAsyncLocal.OnValueChanged(object previousValueObj, object currentValueObj, bool contextChanged) { Debug.Assert(m_valueChangedHandler != null); - T previousValue = previousValueObj == null ? default(T) : (T)previousValueObj; - T currentValue = currentValueObj == null ? default(T) : (T)currentValueObj; + T previousValue = previousValueObj == null ? default : (T)previousValueObj; + T currentValue = currentValueObj == null ? default : (T)currentValueObj; m_valueChangedHandler(new AsyncLocalValueChangedArgs(previousValue, currentValue, contextChanged)); } } @@ -86,19 +86,18 @@ namespace System.Threading void OnValueChanged(object previousValue, object currentValue, bool contextChanged); } - public struct AsyncLocalValueChangedArgs + public readonly struct AsyncLocalValueChangedArgs { - public T PreviousValue { get; private set; } - public T CurrentValue { get; private set; } + public T PreviousValue { get; } + public T CurrentValue { get; } // // If the value changed because we changed to a different ExecutionContext, this is true. If it changed // because someone set the Value property, this is false. // - public bool ThreadContextChanged { get; private set; } + public bool ThreadContextChanged { get; } internal AsyncLocalValueChangedArgs(T previousValue, T currentValue, bool contextChanged) - : this() { PreviousValue = previousValue; CurrentValue = currentValue; @@ -114,7 +113,7 @@ namespace System.Threading internal interface IAsyncLocalValueMap { bool TryGetValue(IAsyncLocal key, out object value); - IAsyncLocalValueMap Set(IAsyncLocal key, object value); + IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent); } // @@ -124,14 +123,31 @@ namespace System.Threading { public static IAsyncLocalValueMap Empty { get; } = new EmptyAsyncLocalValueMap(); - // Instance without any key/value pairs. Used as a singleton/ - internal sealed class EmptyAsyncLocalValueMap : IAsyncLocalValueMap + public static bool IsEmpty(IAsyncLocalValueMap asyncLocalValueMap) { - public IAsyncLocalValueMap Set(IAsyncLocal key, object value) + Debug.Assert(asyncLocalValueMap != null); + Debug.Assert(asyncLocalValueMap == Empty || asyncLocalValueMap.GetType() != typeof(EmptyAsyncLocalValueMap)); + + return asyncLocalValueMap == Empty; + } + + public static IAsyncLocalValueMap Create(IAsyncLocal key, object value, bool treatNullValueAsNonexistent) + { + // If the value isn't null or a null value may not be treated as nonexistent, then create a new one-element map + // to store the key/value pair. Otherwise, use the empty map. + return value != null || !treatNullValueAsNonexistent ? + new OneElementAsyncLocalValueMap(key, value) : + Empty; + } + + // Instance without any key/value pairs. Used as a singleton/ + private sealed class EmptyAsyncLocalValueMap : IAsyncLocalValueMap + { + public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent) { - // If the value isn't null, then create a new one-element map to store - // the key/value pair. If it is null, then we're still empty. - return value != null ? + // If the value isn't null or a null value may not be treated as nonexistent, then create a new one-element map + // to store the key/value pair. Otherwise, use the empty map. + return value != null || !treatNullValueAsNonexistent ? new OneElementAsyncLocalValueMap(key, value) : (IAsyncLocalValueMap)this; } @@ -144,7 +160,7 @@ namespace System.Threading } // Instance with one key/value pair. - internal sealed class OneElementAsyncLocalValueMap : IAsyncLocalValueMap + private sealed class OneElementAsyncLocalValueMap : IAsyncLocalValueMap { private readonly IAsyncLocal _key1; private readonly object _value1; @@ -154,21 +170,20 @@ namespace System.Threading _key1 = key; _value1 = value; } - public IAsyncLocalValueMap Set(IAsyncLocal key, object value) + public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent) { - if (value != null) + if (value != null || !treatNullValueAsNonexistent) { - // The value is non-null. If the key matches one already contained in this map, - // then create a new one-element map with the updated value, otherwise create - // a two-element map with the additional key/value. + // If the key matches one already contained in this map, then create a new one-element map with the updated + // value, otherwise create a two-element map with the additional key/value. return ReferenceEquals(key, _key1) ? new OneElementAsyncLocalValueMap(key, value) : (IAsyncLocalValueMap)new TwoElementAsyncLocalValueMap(_key1, _value1, key, value); } else { - // The value is null. If the key exists in this map, remove it by downgrading to an empty map. - // Otherwise, there's nothing to add or remove, so just return this map. + // If the key exists in this map, remove it by downgrading to an empty map. Otherwise, there's nothing to + // add or remove, so just return this map. return ReferenceEquals(key, _key1) ? Empty : (IAsyncLocalValueMap)this; @@ -202,13 +217,12 @@ namespace System.Threading _key2 = key2; _value2 = value2; } - public IAsyncLocalValueMap Set(IAsyncLocal key, object value) + public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent) { - if (value != null) + if (value != null || !treatNullValueAsNonexistent) { - // The value is non-null. If the key matches one already contained in this map, - // then create a new two-element map with the updated value, otherwise create - // a three-element map with the additional key/value. + // If the key matches one already contained in this map, then create a new two-element map with the updated + // value, otherwise create a three-element map with the additional key/value. return ReferenceEquals(key, _key1) ? new TwoElementAsyncLocalValueMap(key, value, _key2, _value2) : ReferenceEquals(key, _key2) ? new TwoElementAsyncLocalValueMap(_key1, _value1, key, value) : @@ -216,8 +230,8 @@ namespace System.Threading } else { - // The value is null. If the key exists in this map, remove it by downgrading to a one-element map - // without the key. Otherwise, there's nothing to add or remove, so just return this map. + // If the key exists in this map, remove it by downgrading to a one-element map without the key. Otherwise, + // there's nothing to add or remove, so just return this map. return ReferenceEquals(key, _key1) ? new OneElementAsyncLocalValueMap(_key2, _value2) : ReferenceEquals(key, _key2) ? new OneElementAsyncLocalValueMap(_key1, _value1) : @@ -258,12 +272,12 @@ namespace System.Threading _key3 = key3; _value3 = value3; } - public IAsyncLocalValueMap Set(IAsyncLocal key, object value) + public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent) { - if (value != null) + if (value != null || !treatNullValueAsNonexistent) { - // The value is non-null. If the key matches one already contained in this map, - // then create a new three-element map with the updated value. + // If the key matches one already contained in this map, then create a new three-element map with the + // updated value. if (ReferenceEquals(key, _key1)) return new ThreeElementAsyncLocalValueMap(key, value, _key2, _value2, _key3, _value3); if (ReferenceEquals(key, _key2)) return new ThreeElementAsyncLocalValueMap(_key1, _value1, key, value, _key3, _value3); if (ReferenceEquals(key, _key3)) return new ThreeElementAsyncLocalValueMap(_key1, _value1, _key2, _value2, key, value); @@ -279,8 +293,8 @@ namespace System.Threading } else { - // The value is null. If the key exists in this map, remove it by downgrading to a two-element map - // without the key. Otherwise, there's nothing to add or remove, so just return this map. + // If the key exists in this map, remove it by downgrading to a two-element map without the key. Otherwise, + // there's nothing to add or remove, so just return this map. return ReferenceEquals(key, _key1) ? new TwoElementAsyncLocalValueMap(_key2, _value2, _key3, _value3) : ReferenceEquals(key, _key2) ? new TwoElementAsyncLocalValueMap(_key1, _value1, _key3, _value3) : @@ -332,17 +346,18 @@ namespace System.Threading _keyValues[index] = new KeyValuePair(key, value); } - public IAsyncLocalValueMap Set(IAsyncLocal key, object value) + public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent) { // Find the key in this map. for (int i = 0; i < _keyValues.Length; i++) { if (ReferenceEquals(key, _keyValues[i].Key)) { - // The key is in the map. If the value isn't null, then create a new map of the same - // size that has all of the same pairs, with this new key/value pair overwriting the old. - if (value != null) + // The key is in the map. + if (value != null || !treatNullValueAsNonexistent) { + // Create a new map of the same size that has all of the same pairs, with this new key/value pair + // overwriting the old. var multi = new MultiElementAsyncLocalValueMap(_keyValues.Length); Array.Copy(_keyValues, 0, multi._keyValues, 0, _keyValues.Length); multi._keyValues[i] = new KeyValuePair(key, value); @@ -350,8 +365,8 @@ namespace System.Threading } else if (_keyValues.Length == 4) { - // The value is null, and we only have four elements, one of which we're removing, - // so downgrade to a three-element map, without the matching element. + // We only have four elements, one of which we're removing, so downgrade to a three-element map, + // without the matching element. return i == 0 ? new ThreeElementAsyncLocalValueMap(_keyValues[1].Key, _keyValues[1].Value, _keyValues[2].Key, _keyValues[2].Value, _keyValues[3].Key, _keyValues[3].Value) : i == 1 ? new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[2].Key, _keyValues[2].Value, _keyValues[3].Key, _keyValues[3].Value) : @@ -360,8 +375,8 @@ namespace System.Threading } else { - // The value is null, and we have enough elements remaining to warrant a multi map. - // Create a new one and copy all of the elements from this one, except the one to be removed. + // We have enough elements remaining to warrant a multi map. Create a new one and copy all of the + // elements from this one, except the one to be removed. var multi = new MultiElementAsyncLocalValueMap(_keyValues.Length - 1); if (i != 0) Array.Copy(_keyValues, 0, multi._keyValues, 0, i); if (i != _keyValues.Length - 1) Array.Copy(_keyValues, i + 1, multi._keyValues, i, _keyValues.Length - i - 1); @@ -372,9 +387,9 @@ namespace System.Threading // The key does not already exist in this map. - // If the value is null, then we can simply return this same map, as there's nothing to add or remove. - if (value == null) + if (value == null && treatNullValueAsNonexistent) { + // We can simply return this same map, as there's nothing to add or remove. return this; } @@ -418,14 +433,14 @@ namespace System.Threading { public ManyElementAsyncLocalValueMap(int capacity) : base(capacity) { } - public IAsyncLocalValueMap Set(IAsyncLocal key, object value) + public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent) { int count = Count; bool containsKey = ContainsKey(key); // If the value being set exists, create a new many map, copy all of the elements from this one, // and then store the new key/value pair into it. This is the most common case. - if (value != null) + if (value != null || !treatNullValueAsNonexistent) { var map = new ManyElementAsyncLocalValueMap(count + (containsKey ? 0 : 1)); foreach (KeyValuePair pair in this) @@ -436,15 +451,14 @@ namespace System.Threading return map; } - // Otherwise, the value is null, which means null is being stored into an AsyncLocal.Value. - // Since there's no observable difference at the API level between storing null and the key - // not existing at all, we can downgrade to a smaller map rather than storing null. + // Otherwise, the value is null and a null value may be treated as nonexistent. We can downgrade to a smaller + // map rather than storing null. // If the key is contained in this map, we're going to create a new map that's one pair smaller. if (containsKey) { // If the new count would be within range of a multi map instead of a many map, - // downgrade to the many map, which uses less memory and is faster to access. + // downgrade to the multi map, which uses less memory and is faster to access. // Otherwise, just create a new many map that's missing this key. if (count == MultiElementAsyncLocalValueMap.MaxMultiElements + 1) { @@ -475,8 +489,8 @@ namespace System.Threading } } - // We were storing null, but the key wasn't in the map, so there's nothing to change. - // Just return this instance. + // We were storing null and a null value may be treated as nonexistent, but the key wasn't in the map, so + // there's nothing to change. Just return this instance. return this; } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/CancellationToken.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/CancellationToken.cs similarity index 70% rename from external/corert/src/System.Private.CoreLib/src/System/Threading/CancellationToken.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Threading/CancellationToken.cs index fdca71f462..68e6971a54 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/CancellationToken.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/CancellationToken.cs @@ -2,16 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -//////////////////////////////////////////////////////////////////////////////// - -#pragma warning disable 0420 // turn off 'a reference to a volatile field will not be treated as volatile' during CAS. - - using System.Diagnostics; -using System.Diagnostics.Private; -using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Threading @@ -42,10 +33,10 @@ namespace System.Threading // The backing TokenSource. // if null, it implicitly represents the same thing as new CancellationToken(false). // When required, it will be instantiated to reflect this. - private readonly CancellationTokenSource m_source; + private readonly CancellationTokenSource _source; //!! warning. If more fields are added, the assumptions in CreateLinkedToken may no longer be valid - /* Properties */ + private readonly static Action s_actionToActionObjShunt = obj => ((Action)obj)(); /// /// Returns an empty CancellationToken value. @@ -53,10 +44,7 @@ namespace System.Threading /// /// The value returned by this property will be non-cancelable by default. /// - public static CancellationToken None - { - get { return default(CancellationToken); } - } + public static CancellationToken None => default; /// /// Gets whether cancellation has been requested for this token. @@ -65,7 +53,7 @@ namespace System.Threading /// /// /// This property indicates whether cancellation has been requested for this token, - /// either through the token initially being construted in a canceled state, or through + /// either through the token initially being constructed in a canceled state, or through /// calling Cancel /// on the token's associated . /// @@ -77,13 +65,7 @@ namespace System.Threading /// particularly in situations where related objects are being canceled concurrently. /// /// - public bool IsCancellationRequested - { - get - { - return m_source != null && m_source.IsCancellationRequested; - } - } + public bool IsCancellationRequested => _source != null && _source.IsCancellationRequested; /// /// Gets whether this token is capable of being in the canceled state. @@ -93,13 +75,7 @@ namespace System.Threading /// into a canceled state, meaning that will never /// return true. /// - public bool CanBeCanceled - { - get - { - return m_source != null && m_source.CanBeCanceled; - } - } + public bool CanBeCanceled => _source != null; /// /// Gets a that is signaled when the token is canceled. @@ -111,7 +87,7 @@ namespace System.Threading /// /// The associated CancellationTokenSource has been disposed. - public WaitHandle WaitHandle => (m_source ?? CancellationTokenSource.InternalGetStaticSource(false)).WaitHandle; + public WaitHandle WaitHandle => (_source ?? CancellationTokenSource.s_neverCanceledSource).WaitHandle; // public CancellationToken() // this constructor is implicit for structs @@ -120,10 +96,7 @@ namespace System.Threading /// /// Internal constructor only a CancellationTokenSource should create a CancellationToken /// - internal CancellationToken(CancellationTokenSource source) - { - m_source = source; - } + internal CancellationToken(CancellationTokenSource source) => _source = source; /// /// Initializes the CancellationToken. @@ -138,22 +111,8 @@ namespace System.Threading /// If is true, /// both and will be true. /// - public CancellationToken(bool canceled) : - this() + public CancellationToken(bool canceled) : this(canceled ? CancellationTokenSource.s_canceledSource : null) { - if (canceled) - m_source = CancellationTokenSource.InternalGetStaticSource(canceled); - } - - /* Methods */ - - - private static readonly Action s_ActionToActionObjShunt = new Action(ActionToActionObjShunt); - private static void ActionToActionObjShunt(object obj) - { - Action action = obj as Action; - Debug.Assert(action != null, "Expected an Action here"); - action(); } /// @@ -165,25 +124,21 @@ namespace System.Threading /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// + /// + /// The current ExecutionContext, if one exists, will be captured + /// along with the delegate and will be used when executing it. + /// /// /// The delegate to be executed when the CancellationToken is canceled. /// The instance that can - /// be used to deregister the callback. + /// be used to unregister the callback. /// is null. - /// The associated CancellationTokenSource has been disposed. - public CancellationTokenRegistration Register(Action callback) - { - if (callback == null) - throw new ArgumentNullException(nameof(callback)); - - return Register( - s_ActionToActionObjShunt, - callback, - false, // useSync=false - true // useExecutionContext=true - ); - } + public CancellationTokenRegistration Register(Action callback) => + Register( + s_actionToActionObjShunt, + callback ?? throw new ArgumentNullException(nameof(callback)), + useSynchronizationContext: false, + useExecutionContext: true); /// /// Registers a delegate that will be called when this @@ -195,26 +150,24 @@ namespace System.Threading /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// + /// + /// The current ExecutionContext, if one exists, will be captured + /// along with the delegate and will be used when executing it. + /// /// /// The delegate to be executed when the CancellationToken is canceled. /// A Boolean value that indicates whether to capture /// the current SynchronizationContext and use it /// when invoking the . /// The instance that can - /// be used to deregister the callback. + /// be used to unregister the callback. /// is null. - public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext) - { - if (callback == null) - throw new ArgumentNullException(nameof(callback)); - - return Register( - s_ActionToActionObjShunt, - callback, + public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext) => + Register( + s_actionToActionObjShunt, + callback ?? throw new ArgumentNullException(nameof(callback)), useSynchronizationContext, - true // useExecutionContext=true - ); - } + useExecutionContext: true); /// /// Registers a delegate that will be called when this @@ -226,24 +179,18 @@ namespace System.Threading /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// + /// + /// The current ExecutionContext, if one exists, will be captured + /// along with the delegate and will be used when executing it. + /// /// /// The delegate to be executed when the CancellationToken is canceled. /// The state to pass to the when the delegate is invoked. This may be null. /// The instance that can - /// be used to deregister the callback. + /// be used to unregister the callback. /// is null. - public CancellationTokenRegistration Register(Action callback, Object state) - { - if (callback == null) - throw new ArgumentNullException(nameof(callback)); - - return Register( - callback, - state, - false, // useSync=false - true // useExecutionContext=true - ); - } + public CancellationTokenRegistration Register(Action callback, object state) => + Register(callback, state, useSynchronizationContext: false, useExecutionContext: true); /// /// Registers a delegate that will be called when this @@ -266,31 +213,17 @@ namespace System.Threading /// the current SynchronizationContext and use it /// when invoking the . /// The instance that can - /// be used to deregister the callback. + /// be used to unregister the callback. /// is null. /// The associated CancellationTokenSource has been disposed. - public CancellationTokenRegistration Register(Action callback, Object state, bool useSynchronizationContext) - { - return Register( - callback, - state, - useSynchronizationContext, - true // useExecutionContext=true - ); - } + public CancellationTokenRegistration Register(Action callback, object state, bool useSynchronizationContext) => + Register(callback, state, useSynchronizationContext, useExecutionContext: true); // helper for internal registration needs that don't require an EC capture (e.g. creating linked token sources, or registering unstarted TPL tasks) // has a handy signature, and skips capturing execution context. - internal CancellationTokenRegistration InternalRegisterWithoutEC(Action callback, Object state) - { - return Register( - callback, - state, - false, // useSyncContext=false - false // useExecutionContext=false - ); - } + internal CancellationTokenRegistration InternalRegisterWithoutEC(Action callback, object state) => + Register(callback, state, useSynchronizationContext: false, useExecutionContext: false); /// /// Registers a delegate that will be called when this @@ -309,37 +242,25 @@ namespace System.Threading /// the current SynchronizationContext and use it /// when invoking the . /// The instance that can - /// be used to deregister the callback. + /// be used to unregister the callback. /// is null. /// The associated CancellationTokenSource has been disposed. +#if CORECLR + private +#else [MethodImpl(MethodImplOptions.NoInlining)] - public CancellationTokenRegistration Register(Action callback, Object state, bool useSynchronizationContext, bool useExecutionContext) + public +#endif + CancellationTokenRegistration Register(Action callback, object state, bool useSynchronizationContext, bool useExecutionContext) { if (callback == null) throw new ArgumentNullException(nameof(callback)); - if (CanBeCanceled == false) - { - return new CancellationTokenRegistration(); // nothing to do for tokens than can never reach the canceled state. Give them a dummy registration. - } - - // Capture sync/execution contexts if required. - // Note: Only capture sync/execution contexts if IsCancellationRequested = false - // as we know that if it is true that the callback will just be called synchronously. - - SynchronizationContext capturedSyncContext = null; - ExecutionContext capturedExecutionContext = null; - if (!IsCancellationRequested) - { - if (useSynchronizationContext) - capturedSyncContext = SynchronizationContext.Current; - if (useExecutionContext) - capturedExecutionContext = ExecutionContext.Capture(); - } - - // Register the callback with the source. - return m_source.InternalRegister(callback, state, capturedSyncContext, capturedExecutionContext); + CancellationTokenSource source = _source; + return source != null ? + source.InternalRegister(callback, state, useSynchronizationContext ? SynchronizationContext.Current : null, useExecutionContext ? ExecutionContext.Capture() : null) : + default; // Nothing to do for tokens than can never reach the canceled state. Give back a dummy registration. } /// @@ -351,30 +272,7 @@ namespace System.Threading /// True if the instances are equal; otherwise, false. Two tokens are equal if they are associated /// with the same CancellationTokenSource or if they were both constructed /// from public CancellationToken constructors and their values are equal. - public bool Equals(CancellationToken other) - { - //if both sources are null, then both tokens represent the Empty token. - if (m_source == null && other.m_source == null) - { - return true; - } - - // one is null but other has inflated the default source - // these are only equal if the inflated one is the staticSource(false) - if (m_source == null) - { - return other.m_source == CancellationTokenSource.InternalGetStaticSource(false); - } - - if (other.m_source == null) - { - return m_source == CancellationTokenSource.InternalGetStaticSource(false); - } - - // general case, we check if the sources are identical - - return m_source == other.m_source; - } + public bool Equals(CancellationToken other) => _source == other._source; /// /// Determines whether the current CancellationToken instance is equal to the @@ -387,30 +285,13 @@ namespace System.Threading /// from public CancellationToken constructors and their values are equal. /// An associated CancellationTokenSource has been disposed. - public override bool Equals(Object other) - { - if (other is CancellationToken) - { - return Equals((CancellationToken)other); - } - - return false; - } + public override bool Equals(object other) => other is CancellationToken && Equals((CancellationToken)other); /// /// Serves as a hash function for a CancellationToken. /// /// A hash code for the current CancellationToken instance. - public override Int32 GetHashCode() - { - if (m_source == null) - { - // link to the common source so that we have a source to interrogate. - return CancellationTokenSource.InternalGetStaticSource(false).GetHashCode(); - } - - return m_source.GetHashCode(); - } + public override int GetHashCode() => (_source ?? CancellationTokenSource.s_neverCanceledSource).GetHashCode(); /// /// Determines whether two CancellationToken instances are equal. @@ -420,10 +301,7 @@ namespace System.Threading /// True if the instances are equal; otherwise, false. /// An associated CancellationTokenSource has been disposed. - public static bool operator ==(CancellationToken left, CancellationToken right) - { - return left.Equals(right); - } + public static bool operator ==(CancellationToken left, CancellationToken right) => left.Equals(right); /// /// Determines whether two CancellationToken instances are not equal. @@ -433,10 +311,7 @@ namespace System.Threading /// True if the instances are not equal; otherwise, false. /// An associated CancellationTokenSource has been disposed. - public static bool operator !=(CancellationToken left, CancellationToken right) - { - return !left.Equals(right); - } + public static bool operator !=(CancellationToken left, CancellationToken right) => !left.Equals(right); /// /// Throws a OperationCanceledException if @@ -458,22 +333,8 @@ namespace System.Threading ThrowOperationCanceledException(); } - // Throw an ODE if this CancellationToken's source is disposed. - internal void ThrowIfSourceDisposed() - { - if ((m_source != null) && m_source.IsDisposed) - ThrowObjectDisposedException(); - } - // Throws an OCE; separated out to enable better inlining of ThrowIfCancellationRequested - private void ThrowOperationCanceledException() - { + private void ThrowOperationCanceledException() => throw new OperationCanceledException(SR.OperationCanceled, this); - } - - private static void ThrowObjectDisposedException() - { - throw new ObjectDisposedException(null, SR.CancellationToken_SourceDisposed); - } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.Windows.cs new file mode 100644 index 0000000000..2da53b2b80 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.Windows.cs @@ -0,0 +1,93 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.IO; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace System.Threading +{ + public partial class EventWaitHandle + { + private const uint AccessRights = (uint)Interop.Kernel32.MAXIMUM_ALLOWED | Interop.Kernel32.SYNCHRONIZE | Interop.Kernel32.EVENT_MODIFY_STATE; + + private EventWaitHandle(SafeWaitHandle handle) + { + SafeWaitHandle = handle; + } + + private void CreateEventCore(bool initialState, EventResetMode mode, string name, out bool createdNew) + { +#if !PLATFORM_WINDOWS + if (name != null) + throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); +#endif + uint eventFlags = initialState ? Interop.Kernel32.CREATE_EVENT_INITIAL_SET : 0; + if (mode == EventResetMode.ManualReset) + eventFlags |= (uint)Interop.Kernel32.CREATE_EVENT_MANUAL_RESET; + + SafeWaitHandle handle = Interop.Kernel32.CreateEventEx(IntPtr.Zero, name, eventFlags, AccessRights); + + int errorCode = Marshal.GetLastWin32Error(); + if (handle.IsInvalid) + { + handle.SetHandleAsInvalid(); + if (name != null && name.Length != 0 && errorCode == Interop.Errors.ERROR_INVALID_HANDLE) + throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); + + throw Win32Marshal.GetExceptionForWin32Error(errorCode, name); + } + createdNew = errorCode != Interop.Errors.ERROR_ALREADY_EXISTS; + SafeWaitHandle = handle; + } + + private static OpenExistingResult OpenExistingWorker(string name, out EventWaitHandle result) + { +#if PLATFORM_WINDOWS + if (name == null) + throw new ArgumentNullException(nameof(name)); + if (name.Length == 0) + throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); + + result = null; + SafeWaitHandle myHandle = Interop.Kernel32.OpenEvent(AccessRights, false, name); + + if (myHandle.IsInvalid) + { + int errorCode = Marshal.GetLastWin32Error(); + + if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.Errors.ERROR_INVALID_NAME) + return OpenExistingResult.NameNotFound; + if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND) + return OpenExistingResult.PathNotFound; + if (name != null && name.Length != 0 && errorCode == Interop.Errors.ERROR_INVALID_HANDLE) + return OpenExistingResult.NameInvalid; + + throw Win32Marshal.GetExceptionForWin32Error(errorCode, name); + } + result = new EventWaitHandle(myHandle); + return OpenExistingResult.Success; +#else + throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); +#endif + } + + public bool Reset() + { + bool res = Interop.Kernel32.ResetEvent(_waitHandle); + if (!res) + throw Win32Marshal.GetExceptionForLastWin32Error(); + return res; + } + + public bool Set() + { + bool res = Interop.Kernel32.SetEvent(_waitHandle); + if (!res) + throw Win32Marshal.GetExceptionForLastWin32Error(); + return res; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.cs new file mode 100644 index 0000000000..4cd733b9bd --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.cs @@ -0,0 +1,51 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.IO; + +namespace System.Threading +{ + public partial class EventWaitHandle : WaitHandle + { + public EventWaitHandle(bool initialState, EventResetMode mode) : + this(initialState, mode, null, out _) + { + } + + public EventWaitHandle(bool initialState, EventResetMode mode, string name) : + this(initialState, mode, name, out _) + { + } + + public EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew) + { + if (mode != EventResetMode.AutoReset && mode != EventResetMode.ManualReset) + throw new ArgumentException(SR.Argument_InvalidFlag, nameof(mode)); + + CreateEventCore(initialState, mode, name, out createdNew); + } + + public static EventWaitHandle OpenExisting(string name) + { + EventWaitHandle result; + switch (OpenExistingWorker(name, out result)) + { + case OpenExistingResult.NameNotFound: + throw new WaitHandleCannotBeOpenedException(); + case OpenExistingResult.NameInvalid: + throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); + case OpenExistingResult.PathNotFound: + throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, name)); + default: + return result; + } + } + + public static bool TryOpenExisting(string name, out EventWaitHandle result) + { + return OpenExistingWorker(name, out result) == OpenExistingResult.Success; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs index 9f27c6dcb4..694514ef07 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs @@ -19,11 +19,12 @@ using Thread = Internal.Runtime.Augments.RuntimeThread; namespace System.Threading { - public delegate void ContextCallback(Object state); + public delegate void ContextCallback(object state); public sealed class ExecutionContext : IDisposable, ISerializable { internal static readonly ExecutionContext Default = new ExecutionContext(isDefault: true); + internal static readonly ExecutionContext DefaultFlowSuppressed = new ExecutionContext(AsyncLocalValueMap.Empty, Array.Empty(), isFlowSuppressed: true); private readonly IAsyncLocalValueMap m_localValues; private readonly IAsyncLocal[] m_localChangeNotifications; @@ -63,15 +64,14 @@ namespace System.Threading { Debug.Assert(isFlowSuppressed != m_isFlowSuppressed); - if (!isFlowSuppressed && - (m_localValues == null || - m_localValues.GetType() == typeof(AsyncLocalValueMap.EmptyAsyncLocalValueMap)) - ) + if (m_localValues == null || AsyncLocalValueMap.IsEmpty(m_localValues)) { - return null; // implies the default context + return isFlowSuppressed ? + DefaultFlowSuppressed : + null; // implies the default context } - // Flow suppressing a Default context will have null values, set them to Empty - return new ExecutionContext(m_localValues ?? AsyncLocalValueMap.Empty, m_localChangeNotifications ?? Array.Empty(), isFlowSuppressed); + + return new ExecutionContext(m_localValues, m_localChangeNotifications, isFlowSuppressed); } public static AsyncFlowControl SuppressFlow() @@ -112,7 +112,7 @@ namespace System.Threading internal bool IsDefault => m_isDefault; - public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state) + public static void Run(ExecutionContext executionContext, ContextCallback callback, object state) { // Note: ExecutionContext.Run is an extremely hot function and used by every await, ThreadPool execution, etc. if (executionContext == null) @@ -123,7 +123,7 @@ namespace System.Threading RunInternal(executionContext, callback, state); } - internal static void RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) + internal static void RunInternal(ExecutionContext executionContext, ContextCallback callback, object state) { // Note: ExecutionContext.RunInternal is an extremely hot function and used by every await, ThreadPool execution, etc. // Note: Manual enregistering may be addressed by "Exception Handling Write Through Optimization" @@ -321,19 +321,26 @@ namespace System.Threading return; } + // Regarding 'treatNullValueAsNonexistent: !needChangeNotifications' below: + // - When change notifications are not necessary for this IAsyncLocal, there is no observable difference between + // storing a null value and removing the IAsyncLocal from 'm_localValues' + // - When change notifications are necessary for this IAsyncLocal, the IAsyncLocal's absence in 'm_localValues' + // indicates that this is the first value change for the IAsyncLocal and it needs to be registered for change + // notifications. So in this case, a null value must be stored in 'm_localValues' to indicate that the IAsyncLocal + // is already registered for change notifications. IAsyncLocal[] newChangeNotifications = null; IAsyncLocalValueMap newValues; bool isFlowSuppressed = false; if (current != null) { isFlowSuppressed = current.m_isFlowSuppressed; - newValues = current.m_localValues.Set(local, newValue); + newValues = current.m_localValues.Set(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications); newChangeNotifications = current.m_localChangeNotifications; } else { // First AsyncLocal - newValues = new AsyncLocalValueMap.OneElementAsyncLocalValueMap(local, newValue); + newValues = AsyncLocalValueMap.Create(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications); } // @@ -359,7 +366,7 @@ namespace System.Threading } Thread.CurrentThread.ExecutionContext = - (!isFlowSuppressed && newValues.GetType() == typeof(AsyncLocalValueMap.EmptyAsyncLocalValueMap)) ? + (!isFlowSuppressed && AsyncLocalValueMap.IsEmpty(newValues)) ? null : // No values, return to Default context new ExecutionContext(newValues, newChangeNotifications, isFlowSuppressed); diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/ManualResetEventSlim.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/ManualResetEventSlim.cs new file mode 100644 index 0000000000..dc65f6f168 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/ManualResetEventSlim.cs @@ -0,0 +1,759 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; + +namespace System.Threading +{ + // ManualResetEventSlim wraps a manual-reset event internally with a little bit of + // spinning. When an event will be set imminently, it is often advantageous to avoid + // a 4k+ cycle context switch in favor of briefly spinning. Therefore we layer on to + // a brief amount of spinning that should, on the average, make using the slim event + // cheaper than using Win32 events directly. This can be reset manually, much like + // a Win32 manual-reset would be. + // + // Notes: + // We lazily allocate the Win32 event internally. Therefore, the caller should + // always call Dispose to clean it up, just in case. This API is a no-op of the + // event wasn't allocated, but if it was, ensures that the event goes away + // eagerly, instead of waiting for finalization. + + /// + /// Provides a slimmed down version of . + /// + /// + /// All public and protected members of are thread-safe and may be used + /// concurrently from multiple threads, with the exception of Dispose, which + /// must only be used when all other operations on the have + /// completed, and Reset, which should only be used when no other threads are + /// accessing the event. + /// + [DebuggerDisplay("Set = {IsSet}")] + public class ManualResetEventSlim : IDisposable + { + // These are the default spin counts we use on single-proc and MP machines. + private const int DEFAULT_SPIN_SP = 1; + + private volatile object m_lock; + // A lock used for waiting and pulsing. Lazily initialized via EnsureLockObjectCreated() + + private volatile ManualResetEvent m_eventObj; // A true Win32 event used for waiting. + + // -- State -- // + //For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant. + private volatile int m_combinedState; //ie a uint. Used for the state items listed below. + + //1-bit for signalled state + private const int SignalledState_BitMask = unchecked((int)0x80000000);//1000 0000 0000 0000 0000 0000 0000 0000 + private const int SignalledState_ShiftCount = 31; + + //1-bit for disposed state + private const int Dispose_BitMask = unchecked((int)0x40000000);//0100 0000 0000 0000 0000 0000 0000 0000 + + //11-bits for m_spinCount + private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); //0011 1111 1111 1000 0000 0000 0000 0000 + private const int SpinCountState_ShiftCount = 19; + private const int SpinCountState_MaxValue = (1 << 11) - 1; //2047 + + //19-bits for m_waiters. This allows support of 512K threads waiting which should be ample + private const int NumWaitersState_BitMask = unchecked((int)0x0007FFFF); // 0000 0000 0000 0111 1111 1111 1111 1111 + private const int NumWaitersState_ShiftCount = 0; + private const int NumWaitersState_MaxValue = (1 << 19) - 1; //512K-1 + // ----------- // + +#if DEBUG + private static int s_nextId; // The next id that will be given out. + private int m_id = Interlocked.Increment(ref s_nextId); // A unique id for debugging purposes only. + private long m_lastSetTime; + private long m_lastResetTime; +#endif + + /// + /// Gets the underlying object for this . + /// + /// The underlying event object fore this . + /// + /// Accessing this property forces initialization of an underlying event object if one hasn't + /// already been created. To simply wait on this , + /// the public Wait methods should be preferred. + /// + public WaitHandle WaitHandle + { + get + { + ThrowIfDisposed(); + if (m_eventObj == null) + { + // Lazily initialize the event object if needed. + LazyInitializeEvent(); + } + + return m_eventObj; + } + } + + /// + /// Gets whether the event is set. + /// + /// true if the event has is set; otherwise, false. + public bool IsSet + { + get + { + return 0 != ExtractStatePortion(m_combinedState, SignalledState_BitMask); + } + + private set + { + UpdateStateAtomically(((value) ? 1 : 0) << SignalledState_ShiftCount, SignalledState_BitMask); + } + } + + /// + /// Gets the number of spin waits that will be occur before falling back to a true wait. + /// + public int SpinCount + { + get + { + return ExtractStatePortionAndShiftRight(m_combinedState, SpinCountState_BitMask, SpinCountState_ShiftCount); + } + + private set + { + Debug.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); + Debug.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); + // Don't worry about thread safety because it's set one time from the constructor + m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount); + } + } + + /// + /// How many threads are waiting. + /// + private int Waiters + { + get + { + return ExtractStatePortionAndShiftRight(m_combinedState, NumWaitersState_BitMask, NumWaitersState_ShiftCount); + } + + set + { + //setting to <0 would indicate an internal flaw, hence Assert is appropriate. + Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error."); + + // it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here. + if (value >= NumWaitersState_MaxValue) + throw new InvalidOperationException(string.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue)); + + UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask); + } + } + + //----------------------------------------------------------------------------------- + // Constructs a new event, optionally specifying the initial state and spin count. + // The defaults are that the event is unsignaled and some reasonable default spin. + // + + /// + /// Initializes a new instance of the + /// class with an initial state of nonsignaled. + /// + public ManualResetEventSlim() + : this(false) + { + } + + /// + /// Initializes a new instance of the + /// class with a boolean value indicating whether to set the initial state to signaled. + /// + /// true to set the initial state signaled; false to set the initial state + /// to nonsignaled. + public ManualResetEventSlim(bool initialState) + { + // Specify the default spin count, and use default spin if we're + // on a multi-processor machine. Otherwise, we won't. + Initialize(initialState, SpinWait.SpinCountforSpinBeforeWait); + } + + /// + /// Initializes a new instance of the + /// class with a Boolean value indicating whether to set the initial state to signaled and a specified + /// spin count. + /// + /// true to set the initial state to signaled; false to set the initial state + /// to nonsignaled. + /// The number of spin waits that will occur before falling back to a true + /// wait. + /// is less than + /// 0 or greater than the maximum allowed value. + public ManualResetEventSlim(bool initialState, int spinCount) + { + if (spinCount < 0) + { + throw new ArgumentOutOfRangeException(nameof(spinCount)); + } + + if (spinCount > SpinCountState_MaxValue) + { + throw new ArgumentOutOfRangeException( + nameof(spinCount), + string.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue)); + } + + // We will suppress default spin because the user specified a count. + Initialize(initialState, spinCount); + } + + /// + /// Initializes the internal state of the event. + /// + /// Whether the event is set initially or not. + /// The spin count that decides when the event will block. + private void Initialize(bool initialState, int spinCount) + { + m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0; + //the spinCount argument has been validated by the ctors. + //but we now sanity check our predefined constants. + Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); + Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); + + SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount; + } + + /// + /// Helper to ensure the lock object is created before first use. + /// + private void EnsureLockObjectCreated() + { + if (m_lock != null) + return; + + object newObj = new object(); + Interlocked.CompareExchange(ref m_lock, newObj, null); // failure is benign. Someone else set the value. + } + + /// + /// This method lazily initializes the event object. It uses CAS to guarantee that + /// many threads racing to call this at once don't result in more than one event + /// being stored and used. The event will be signaled or unsignaled depending on + /// the state of the thin-event itself, with synchronization taken into account. + /// + /// True if a new event was created and stored, false otherwise. + private bool LazyInitializeEvent() + { + bool preInitializeIsSet = IsSet; + ManualResetEvent newEventObj = new ManualResetEvent(preInitializeIsSet); + + // We have to CAS this in case we are racing with another thread. We must + // guarantee only one event is actually stored in this field. + if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null) + { + // Someone else set the value due to a race condition. Destroy the garbage event. + newEventObj.Dispose(); + + return false; + } + else + { + // Now that the event is published, verify that the state hasn't changed since + // we snapped the preInitializeState. Another thread could have done that + // between our initial observation above and here. The barrier incurred from + // the CAS above (in addition to m_state being volatile) prevents this read + // from moving earlier and being collapsed with our original one. + bool currentIsSet = IsSet; + if (currentIsSet != preInitializeIsSet) + { + Debug.Assert(currentIsSet, + "The only safe concurrent transition is from unset->set: detected set->unset."); + + // We saw it as unsignaled, but it has since become set. + lock (newEventObj) + { + // If our event hasn't already been disposed of, we must set it. + if (m_eventObj == newEventObj) + { + newEventObj.Set(); + } + } + } + + return true; + } + } + + /// + /// Sets the state of the event to signaled, which allows one or more threads waiting on the event to + /// proceed. + /// + public void Set() + { + Set(false); + } + + /// + /// Private helper to actually perform the Set. + /// + /// Indicates whether we are calling Set() during cancellation. + /// The object has been canceled. + private void Set(bool duringCancellation) + { + // We need to ensure that IsSet=true does not get reordered past the read of m_eventObj + // This would be a legal movement according to the .NET memory model. + // The code is safe as IsSet involves an Interlocked.CompareExchange which provides a full memory barrier. + IsSet = true; + + // If there are waiting threads, we need to pulse them. + if (Waiters > 0) + { + Debug.Assert(m_lock != null); //if waiters>0, then m_lock has already been created. + lock (m_lock) + { + Monitor.PulseAll(m_lock); + } + } + + ManualResetEvent eventObj = m_eventObj; + + //Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly + //It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic + + if (eventObj != null && !duringCancellation) + { + // We must surround this call to Set in a lock. The reason is fairly subtle. + // Sometimes a thread will issue a Wait and wake up after we have set m_state, + // but before we have gotten around to setting m_eventObj (just below). That's + // because Wait first checks m_state and will only access the event if absolutely + // necessary. However, the coding pattern { event.Wait(); event.Dispose() } is + // quite common, and we must support it. If the waiter woke up and disposed of + // the event object before the setter has finished, however, we would try to set a + // now-disposed Win32 event. Crash! To deal with this race condition, we use a lock to + // protect access to the event object when setting and disposing of it. We also + // double-check that the event has not become null in the meantime when in the lock. + + lock (eventObj) + { + if (m_eventObj != null) + { + // If somebody is waiting, we must set the event. + m_eventObj.Set(); + } + } + } + +#if DEBUG + m_lastSetTime = DateTime.UtcNow.Ticks; +#endif + } + + /// + /// Sets the state of the event to nonsignaled, which causes threads to block. + /// + /// + /// Unlike most of the members of , is not + /// thread-safe and may not be used concurrently with other members of this instance. + /// + public void Reset() + { + ThrowIfDisposed(); + // If there's an event, reset it. + if (m_eventObj != null) + { + m_eventObj.Reset(); + } + + // There is a race condition here. If another thread Sets the event, we will get into a state + // where m_state will be unsignaled, yet the Win32 event object will have been signaled. + // This could cause waiting threads to wake up even though the event is in an + // unsignaled state. This is fine -- those that are calling Reset concurrently are + // responsible for doing "the right thing" -- e.g. rechecking the condition and + // resetting the event manually. + + // And finally set our state back to unsignaled. + IsSet = false; + +#if DEBUG + m_lastResetTime = DateTime.UtcNow.Ticks; +#endif + } + + /// + /// Blocks the current thread until the current is set. + /// + /// + /// The maximum number of waiters has been exceeded. + /// + /// + /// The caller of this method blocks indefinitely until the current instance is set. The caller will + /// return immediately if the event is currently in a set state. + /// + public void Wait() + { + Wait(Timeout.Infinite, new CancellationToken()); + } + + /// + /// Blocks the current thread until the current receives a signal, + /// while observing a . + /// + /// The to + /// observe. + /// + /// The maximum number of waiters has been exceeded. + /// + /// was + /// canceled. + /// + /// The caller of this method blocks indefinitely until the current instance is set. The caller will + /// return immediately if the event is currently in a set state. + /// + public void Wait(CancellationToken cancellationToken) + { + Wait(Timeout.Infinite, cancellationToken); + } + + /// + /// Blocks the current thread until the current is set, using a + /// to measure the time interval. + /// + /// A that represents the number of milliseconds + /// to wait, or a that represents -1 milliseconds to wait indefinitely. + /// + /// true if the was set; otherwise, + /// false. + /// is a negative + /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater + /// than . + /// + /// The maximum number of waiters has been exceeded. + /// + public bool Wait(TimeSpan timeout) + { + long totalMilliseconds = (long)timeout.TotalMilliseconds; + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) + { + throw new ArgumentOutOfRangeException(nameof(timeout)); + } + + return Wait((int)totalMilliseconds, new CancellationToken()); + } + + /// + /// Blocks the current thread until the current is set, using a + /// to measure the time interval, while observing a . + /// + /// A that represents the number of milliseconds + /// to wait, or a that represents -1 milliseconds to wait indefinitely. + /// + /// The to + /// observe. + /// true if the was set; otherwise, + /// false. + /// is a negative + /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater + /// than . + /// was canceled. + /// + /// The maximum number of waiters has been exceeded. + /// + public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) + { + long totalMilliseconds = (long)timeout.TotalMilliseconds; + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) + { + throw new ArgumentOutOfRangeException(nameof(timeout)); + } + + return Wait((int)totalMilliseconds, cancellationToken); + } + + /// + /// Blocks the current thread until the current is set, using a + /// 32-bit signed integer to measure the time interval. + /// + /// The number of milliseconds to wait, or (-1) to wait indefinitely. + /// true if the was set; otherwise, + /// false. + /// is a + /// negative number other than -1, which represents an infinite time-out. + /// + /// The maximum number of waiters has been exceeded. + /// + public bool Wait(int millisecondsTimeout) + { + return Wait(millisecondsTimeout, new CancellationToken()); + } + + /// + /// Blocks the current thread until the current is set, using a + /// 32-bit signed integer to measure the time interval, while observing a . + /// + /// The number of milliseconds to wait, or (-1) to wait indefinitely. + /// The to + /// observe. + /// true if the was set; otherwise, + /// false. + /// is a + /// negative number other than -1, which represents an infinite time-out. + /// + /// The maximum number of waiters has been exceeded. + /// + /// was canceled. + public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) + { + ThrowIfDisposed(); + cancellationToken.ThrowIfCancellationRequested(); // an early convenience check + + if (millisecondsTimeout < -1) + { + throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout)); + } + + if (!IsSet) + { + if (millisecondsTimeout == 0) + { + // For 0-timeouts, we just return immediately. + return false; + } + + + // We spin briefly before falling back to allocating and/or waiting on a true event. + uint startTime = 0; + bool bNeedTimeoutAdjustment = false; + int realMillisecondsTimeout = millisecondsTimeout; //this will be adjusted if necessary. + + if (millisecondsTimeout != Timeout.Infinite) + { + // We will account for time spent spinning, so that we can decrement it from our + // timeout. In most cases the time spent in this section will be negligible. But + // we can't discount the possibility of our thread being switched out for a lengthy + // period of time. The timeout adjustments only take effect when and if we actually + // decide to block in the kernel below. + + startTime = TimeoutHelper.GetTime(); + bNeedTimeoutAdjustment = true; + } + + // Spin + int spinCount = SpinCount; + var spinner = new SpinWait(); + while (spinner.Count < spinCount) + { + spinner.SpinOnce(SpinWait.Sleep1ThresholdForLongSpinBeforeWait); + + if (IsSet) + { + return true; + } + + if (spinner.Count >= 100 && spinner.Count % 10 == 0) // check the cancellation token if the user passed a very large spin count + cancellationToken.ThrowIfCancellationRequested(); + } + + // Now enter the lock and wait. + EnsureLockObjectCreated(); + + // We must register and unregister the token outside of the lock, to avoid deadlocks. + using (cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCallback, this)) + { + lock (m_lock) + { + // Loop to cope with spurious wakeups from other waits being canceled + while (!IsSet) + { + // If our token was canceled, we must throw and exit. + cancellationToken.ThrowIfCancellationRequested(); + + //update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled) + if (bNeedTimeoutAdjustment) + { + realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout); + if (realMillisecondsTimeout <= 0) + return false; + } + + // There is a race condition that Set will fail to see that there are waiters as Set does not take the lock, + // so after updating waiters, we must check IsSet again. + // Also, we must ensure there cannot be any reordering of the assignment to Waiters and the + // read from IsSet. This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange + // operation which provides a full memory barrier. + // If we see IsSet=false, then we are guaranteed that Set() will see that we are + // waiting and will pulse the monitor correctly. + + Waiters = Waiters + 1; + + if (IsSet) //This check must occur after updating Waiters. + { + Waiters--; //revert the increment. + return true; + } + + // Now finally perform the wait. + try + { + // ** the actual wait ** + if (!Monitor.Wait(m_lock, realMillisecondsTimeout)) + return false; //return immediately if the timeout has expired. + } + finally + { + // Clean up: we're done waiting. + Waiters = Waiters - 1; + } + // Now just loop back around, and the right thing will happen. Either: + // 1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait) + // or 2. the wait was successful. (the loop will break) + } + } + } + } // automatically disposes (and unregisters) the callback + + return true; //done. The wait was satisfied. + } + + /// + /// Releases all resources used by the current instance of . + /// + /// + /// Unlike most of the members of , is not + /// thread-safe and may not be used concurrently with other members of this instance. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// When overridden in a derived class, releases the unmanaged resources used by the + /// , and optionally releases the managed resources. + /// + /// true to release both managed and unmanaged resources; + /// false to release only unmanaged resources. + /// + /// Unlike most of the members of , is not + /// thread-safe and may not be used concurrently with other members of this instance. + /// + protected virtual void Dispose(bool disposing) + { + if ((m_combinedState & Dispose_BitMask) != 0) + return; // already disposed + + m_combinedState |= Dispose_BitMask; //set the dispose bit + if (disposing) + { + // We will dispose of the event object. We do this under a lock to protect + // against the race condition outlined in the Set method above. + ManualResetEvent eventObj = m_eventObj; + if (eventObj != null) + { + lock (eventObj) + { + eventObj.Dispose(); + m_eventObj = null; + } + } + } + } + + /// + /// Throw ObjectDisposedException if the MRES is disposed + /// + private void ThrowIfDisposed() + { + if ((m_combinedState & Dispose_BitMask) != 0) + throw new ObjectDisposedException(SR.ManualResetEventSlim_Disposed); + } + + /// + /// Private helper method to wake up waiters when a cancellationToken gets canceled. + /// + private static Action s_cancellationTokenCallback = new Action(CancellationTokenCallback); + private static void CancellationTokenCallback(object obj) + { + ManualResetEventSlim mre = obj as ManualResetEventSlim; + Debug.Assert(mre != null, "Expected a ManualResetEventSlim"); + Debug.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use. + lock (mre.m_lock) + { + Monitor.PulseAll(mre.m_lock); // awaken all waiters + } + } + + /// + /// Private helper method for updating parts of a bit-string state value. + /// Mainly called from the IsSet and Waiters properties setters + /// + /// + /// Note: the parameter types must be int as CompareExchange cannot take a Uint + /// + /// The new value + /// The mask used to set the bits + private void UpdateStateAtomically(int newBits, int updateBitsMask) + { + SpinWait sw = new SpinWait(); + + Debug.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask."); + + do + { + int oldState = m_combinedState; // cache the old value for testing in CAS + + // Procedure:(1) zero the updateBits. eg oldState = [11111111] flag= [00111000] newState = [11000111] + // then (2) map in the newBits. eg [11000111] newBits=00101000, newState=[11101111] + int newState = (oldState & ~updateBitsMask) | newBits; + + if (Interlocked.CompareExchange(ref m_combinedState, newState, oldState) == oldState) + { + return; + } + + sw.SpinOnce(); + } while (true); + } + + /// + /// Private helper method - performs Mask and shift, particular helpful to extract a field from a packed word. + /// eg ExtractStatePortionAndShiftRight(0x12345678, 0xFF000000, 24) => 0x12, ie extracting the top 8-bits as a simple integer + /// + /// ?? is there a common place to put this rather than being private to MRES? + /// + /// + /// + /// + /// + private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount) + { + //convert to uint before shifting so that right-shift does not replicate the sign-bit, + //then convert back to int. + return unchecked((int)(((uint)(state & mask)) >> rightBitShiftCount)); + } + + /// + /// Performs a Mask operation, but does not perform the shift. + /// This is acceptable for boolean values for which the shift is unnecessary + /// eg (val & Mask) != 0 is an appropriate way to extract a boolean rather than using + /// ((val & Mask) >> shiftAmount) == 1 + /// + /// ?? is there a common place to put this rather than being private to MRES? + /// + /// + /// + private static int ExtractStatePortion(int state, int mask) + { + return state & mask; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/Mutex.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Mutex.Windows.cs new file mode 100644 index 0000000000..212eb9dc31 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Mutex.Windows.cs @@ -0,0 +1,100 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.IO; +using Microsoft.Win32; +using Microsoft.Win32.SafeHandles; +using System.Runtime.InteropServices; +using System.Diagnostics; + +namespace System.Threading +{ + /// + /// Synchronization primitive that can also be used for interprocess synchronization + /// + public sealed partial class Mutex : WaitHandle + { + private const uint AccessRights = + (uint)Interop.Kernel32.MAXIMUM_ALLOWED | Interop.Kernel32.SYNCHRONIZE | Interop.Kernel32.MUTEX_MODIFY_STATE; + + private void CreateMutexCore(bool initiallyOwned, string name, out bool createdNew) + { + uint mutexFlags = initiallyOwned ? Interop.Kernel32.CREATE_MUTEX_INITIAL_OWNER : 0; + SafeWaitHandle mutexHandle = Interop.Kernel32.CreateMutexEx(IntPtr.Zero, name, mutexFlags, AccessRights); + int errorCode = Marshal.GetLastWin32Error(); + + if (mutexHandle.IsInvalid) + { + mutexHandle.SetHandleAsInvalid(); +#if !PLATFORM_WINDOWS + if (errorCode == Interop.Errors.ERROR_FILENAME_EXCED_RANGE) + // On Unix, length validation is done by CoreCLR's PAL after converting to utf-8 + throw new ArgumentException(SR.Argument_WaitHandleNameTooLong, nameof(name)); +#endif + if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE) + throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); + + throw Win32Marshal.GetExceptionForWin32Error(errorCode, name); + } + + createdNew = errorCode != Interop.Errors.ERROR_ALREADY_EXISTS; + SafeWaitHandle = mutexHandle; + } + + private static OpenExistingResult OpenExistingWorker(string name, out Mutex result) + { + if (name == null) + { + throw new ArgumentNullException(nameof(name)); + } + + if (name.Length == 0) + { + throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); + } + + result = null; + // To allow users to view & edit the ACL's, call OpenMutex + // with parameters to allow us to view & edit the ACL. This will + // fail if we don't have permission to view or edit the ACL's. + // If that happens, ask for less permissions. + SafeWaitHandle myHandle = Interop.Kernel32.OpenMutex(AccessRights, false, name); + + if (myHandle.IsInvalid) + { + int errorCode = Marshal.GetLastWin32Error(); +#if !PLATFORM_WINDOWS + if (errorCode == Interop.Errors.ERROR_FILENAME_EXCED_RANGE) + { + // On Unix, length validation is done by CoreCLR's PAL after converting to utf-8 + throw new ArgumentException(SR.Argument_WaitHandleNameTooLong, nameof(name)); + } +#endif + if (Interop.Errors.ERROR_FILE_NOT_FOUND == errorCode || Interop.Errors.ERROR_INVALID_NAME == errorCode) + return OpenExistingResult.NameNotFound; + if (Interop.Errors.ERROR_PATH_NOT_FOUND == errorCode) + return OpenExistingResult.PathNotFound; + if (Interop.Errors.ERROR_INVALID_HANDLE == errorCode) + return OpenExistingResult.NameInvalid; + + // this is for passed through Win32Native Errors + throw Win32Marshal.GetExceptionForWin32Error(errorCode, name); + } + + result = new Mutex(myHandle); + return OpenExistingResult.Success; + } + + // Note: To call ReleaseMutex, you must have an ACL granting you + // MUTEX_MODIFY_STATE rights (0x0001). The other interesting value + // in a Mutex's ACL is MUTEX_ALL_ACCESS (0x1F0001). + public void ReleaseMutex() + { + if (!Interop.Kernel32.ReleaseMutex(_waitHandle)) + { + throw new ApplicationException(SR.Arg_SynchronizationLockException); + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/Mutex.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Mutex.cs new file mode 100644 index 0000000000..d85242892d --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Mutex.cs @@ -0,0 +1,62 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.IO; +using Microsoft.Win32; +using Microsoft.Win32.SafeHandles; +using System.Runtime.InteropServices; +using System.Diagnostics; + +namespace System.Threading +{ + /// + /// Synchronization primitive that can also be used for interprocess synchronization + /// + public sealed partial class Mutex : WaitHandle + { + public Mutex(bool initiallyOwned, string name, out bool createdNew) + { + CreateMutexCore(initiallyOwned, name, out createdNew); + } + + public Mutex(bool initiallyOwned, string name) + { + CreateMutexCore(initiallyOwned, name, out _); + } + + public Mutex(bool initiallyOwned) + { + CreateMutexCore(initiallyOwned, null, out _); + } + + public Mutex() + { + CreateMutexCore(false, null, out _); + } + + private Mutex(SafeWaitHandle handle) + { + SafeWaitHandle = handle; + } + + public static Mutex OpenExisting(string name) + { + switch (OpenExistingWorker(name, out Mutex result)) + { + case OpenExistingResult.NameNotFound: + throw new WaitHandleCannotBeOpenedException(); + case OpenExistingResult.NameInvalid: + throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); + case OpenExistingResult.PathNotFound: + throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, name)); + + default: + return result; + } + } + + public static bool TryOpenExisting(string name, out Mutex result) => + OpenExistingWorker(name, out result) == OpenExistingResult.Success; + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/NativeOverlapped.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/NativeOverlapped.cs similarity index 100% rename from external/corert/src/System.Private.CoreLib/src/System/Threading/NativeOverlapped.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Threading/NativeOverlapped.cs diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/ReaderWriterLockSlim.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/ReaderWriterLockSlim.cs index 45175488e7..9424fbd5b4 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Threading/ReaderWriterLockSlim.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/ReaderWriterLockSlim.cs @@ -241,7 +241,7 @@ namespace System.Threading public TimeoutTracker(TimeSpan timeout) { long ltm = (long)timeout.TotalMilliseconds; - if (ltm < -1 || ltm > (long)Int32.MaxValue) + if (ltm < -1 || ltm > (long)int.MaxValue) throw new ArgumentOutOfRangeException(nameof(timeout)); _total = (int)ltm; if (_total != -1 && _total != 0) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/Semaphore.Windows.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Semaphore.Windows.cs new file mode 100644 index 0000000000..8a14f5ef38 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Semaphore.Windows.cs @@ -0,0 +1,88 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.Win32.SafeHandles; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; + +namespace System.Threading +{ + public sealed partial class Semaphore + { + private const uint AccessRights = (uint)Interop.Kernel32.MAXIMUM_ALLOWED | Interop.Kernel32.SYNCHRONIZE | Interop.Kernel32.SEMAPHORE_MODIFY_STATE; + + private Semaphore(SafeWaitHandle handle) + { + SafeWaitHandle = handle; + } + + private void CreateSemaphoreCore(int initialCount, int maximumCount, string name, out bool createdNew) + { + Debug.Assert(initialCount >= 0); + Debug.Assert(maximumCount >= 1); + Debug.Assert(initialCount <= maximumCount); + +#if !PLATFORM_WINDOWS + if (name != null) + throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); +#endif + SafeWaitHandle myHandle = Interop.Kernel32.CreateSemaphoreEx(IntPtr.Zero, initialCount, maximumCount, name, 0, AccessRights); + + int errorCode = Marshal.GetLastWin32Error(); + if (myHandle.IsInvalid) + { + if (name != null && name.Length != 0 && errorCode == Interop.Errors.ERROR_INVALID_HANDLE) + throw new WaitHandleCannotBeOpenedException( + SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); + + throw Win32Marshal.GetExceptionForLastWin32Error(); + } + createdNew = errorCode != Interop.Errors.ERROR_ALREADY_EXISTS; + this.SafeWaitHandle = myHandle; + } + + private static OpenExistingResult OpenExistingWorker(string name, out Semaphore result) + { +#if PLATFORM_WINDOWS + if (name == null) + throw new ArgumentNullException(nameof(name)); + if (name.Length == 0) + throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); + + // Pass false to OpenSemaphore to prevent inheritedHandles + SafeWaitHandle myHandle = Interop.Kernel32.OpenSemaphore(AccessRights, false, name); + + if (myHandle.IsInvalid) + { + result = null; + int errorCode = Marshal.GetLastWin32Error(); + + if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.Errors.ERROR_INVALID_NAME) + return OpenExistingResult.NameNotFound; + if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND) + return OpenExistingResult.PathNotFound; + if (name != null && name.Length != 0 && errorCode == Interop.Errors.ERROR_INVALID_HANDLE) + return OpenExistingResult.NameInvalid; + // this is for passed through NativeMethods Errors + throw Win32Marshal.GetExceptionForLastWin32Error(); + } + + result = new Semaphore(myHandle); + return OpenExistingResult.Success; +#else + throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); +#endif + } + + private int ReleaseCore(int releaseCount) + { + int previousCount; + if (!Interop.Kernel32.ReleaseSemaphore(SafeWaitHandle, releaseCount, out previousCount)) + throw new SemaphoreFullException(); + + return previousCount; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Semaphore.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs similarity index 55% rename from external/corert/src/System.Private.CoreLib/src/System/Threading/Semaphore.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs index 9e7a7796a4..6014fcd1c8 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Semaphore.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs @@ -2,60 +2,36 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.IO; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; +using System.IO; using System.Runtime.InteropServices; -using System.Threading; -using System.Runtime.Versioning; namespace System.Threading { public sealed partial class Semaphore : WaitHandle { // creates a nameless semaphore object - // Win32 only takes maximum count of Int32.MaxValue - public Semaphore(int initialCount, int maximumCount) + // Win32 only takes maximum count of int.MaxValue + public Semaphore(int initialCount, int maximumCount) : this(initialCount, maximumCount, null) { } + + public Semaphore(int initialCount, int maximumCount, string name) : + this(initialCount, maximumCount, name, out _) { - VerifyCounts(initialCount, maximumCount); - - bool createdNew; - CreateSemaphoreCore(initialCount, maximumCount, null, out createdNew); - } - - public Semaphore(int initialCount, int maximumCount, string name) - { - VerifyCounts(initialCount, maximumCount); - VerifyNameForCreate(name); - - bool createdNew; - CreateSemaphoreCore(initialCount, maximumCount, name, out createdNew); } public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew) - { - VerifyCounts(initialCount, maximumCount); - VerifyNameForCreate(name); - - CreateSemaphoreCore(initialCount, maximumCount, name, out createdNew); - } - - private static void VerifyCounts(int initialCount, int maximumCount) { if (initialCount < 0) - { - throw new ArgumentOutOfRangeException(nameof(initialCount), SR.ArgumentOutOfRange_NeedNonNegNumRequired); - } + throw new ArgumentOutOfRangeException(nameof(initialCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (maximumCount < 1) - { - throw new ArgumentOutOfRangeException(nameof(maximumCount), SR.ArgumentOutOfRange_NeedNonNegNumRequired); - } + throw new ArgumentOutOfRangeException(nameof(maximumCount), SR.ArgumentOutOfRange_NeedPosNum); if (initialCount > maximumCount) - { throw new ArgumentException(SR.Argument_SemaphoreInitialMaximum); - } + + CreateSemaphoreCore(initialCount, maximumCount, name, out createdNew); } public static Semaphore OpenExisting(string name) @@ -77,40 +53,15 @@ namespace System.Threading public static bool TryOpenExisting(string name, out Semaphore result) => OpenExistingWorker(name, out result) == OpenExistingResult.Success; - // increase the count on a semaphore, returns previous count public int Release() => ReleaseCore(1); // increase the count on a semaphore, returns previous count public int Release(int releaseCount) { if (releaseCount < 1) - { - throw new ArgumentOutOfRangeException(nameof(releaseCount), SR.ArgumentOutOfRange_NeedNonNegNumRequired); - } + throw new ArgumentOutOfRangeException(nameof(releaseCount), SR.ArgumentOutOfRange_NeedNonNegNum); return ReleaseCore(releaseCount); } - - private int ReleaseCore(int releaseCount) - { - // The field value is modifiable via the public property, save it locally - // to ensure that one instance is used in all places in this method - SafeWaitHandle waitHandle = _waitHandle; - if (waitHandle == null) - { - ThrowInvalidHandleException(); - } - - waitHandle.DangerousAddRef(); - try - { - return ReleaseCore(waitHandle.DangerousGetHandle(), releaseCount); - } - finally - { - waitHandle.DangerousRelease(); - } - } } } - diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/SemaphoreFullException.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/SemaphoreFullException.cs index 18558b19e0..a6cff781df 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Threading/SemaphoreFullException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/SemaphoreFullException.cs @@ -15,11 +15,11 @@ namespace System.Threading { } - public SemaphoreFullException(String message) : base(message) + public SemaphoreFullException(string message) : base(message) { } - public SemaphoreFullException(String message, Exception innerException) : base(message, innerException) + public SemaphoreFullException(string message, Exception innerException) : base(message, innerException) { } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/SemaphoreSlim.cs similarity index 87% rename from external/corert/src/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Threading/SemaphoreSlim.cs index ba2c0ecd97..83f5f1d282 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/SemaphoreSlim.cs @@ -1,23 +1,14 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ -// -// - -// -// A lightweight semahore class that contains the basic semaphore functions plus some useful functions like interrupt -// and wait handle exposing to allow waiting on multiple semaphores. -// -// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +using System; +using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading.Tasks; -// The class will be part of the current System.Threading namespace - namespace System.Threading { /// @@ -52,11 +43,16 @@ namespace System.Threading // The number of synchronously waiting threads, it is set to zero in the constructor and increments before blocking the // threading and decrements it back after that. It is used as flag for the release call to know if there are // waiting threads in the monitor or not. - private volatile int m_waitCount; + private int m_waitCount; + + /// + /// This is used to help prevent waking more waiters than necessary. It's not perfect and sometimes more waiters than + /// necessary may still be woken, see . + /// + private int m_countOfWaitersPulsedToWake; // Dummy object used to in lock statements to protect the semaphore count, wait handle and cancelation - private Lock m_lock; - private Condition m_condition; + private object m_lockObj; // Act as the semaphore wait handle, it's lazily initialized if needed, the first WaitHandle call initialize it // and wait an release sets and resets it respectively as long as it is not null @@ -70,13 +66,13 @@ namespace System.Threading // A pre-completed task with Result==true private static readonly Task s_trueTask = - new Task(false, true, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default(CancellationToken)); + new Task(false, true, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default); // A pre-completed task with Result==false private readonly static Task s_falseTask = - new Task(false, false, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default(CancellationToken)); + new Task(false, false, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default); // No maximum constant - private const int NO_MAXIMUM = Int32.MaxValue; + private const int NO_MAXIMUM = int.MaxValue; // Task in a linked list of asynchronous waiters private sealed class TaskNode : Task, IThreadPoolWorkItem @@ -89,6 +85,9 @@ namespace System.Threading bool setSuccessfully = TrySetResult(true); Debug.Assert(setSuccessfully, "Should have been able to complete task"); } +#if CORECLR + void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { /* nop */ } +#endif } #endregion @@ -127,7 +126,7 @@ namespace System.Threading return m_waitHandle; //lock the count to avoid multiple threads initializing the handle if it is null - using (LockHolder.Hold(m_lock)) + lock (m_lockObj) { if (m_waitHandle == null) { @@ -183,8 +182,7 @@ namespace System.Threading } m_maxCount = maxCount; - m_lock = new Lock(); - m_condition = new Condition(m_lock); + m_lockObj = new object(); m_currentCount = initialCount; } @@ -233,8 +231,8 @@ namespace System.Threading public bool Wait(TimeSpan timeout) { // Validate the timeout - Int64 totalMilliseconds = (Int64)timeout.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) + long totalMilliseconds = (long)timeout.TotalMilliseconds; + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new System.ArgumentOutOfRangeException( nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); @@ -263,8 +261,8 @@ namespace System.Threading public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { // Validate the timeout - Int64 totalMilliseconds = (Int64)timeout.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) + long totalMilliseconds = (long)timeout.TotalMilliseconds; + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new System.ArgumentOutOfRangeException( nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); @@ -333,27 +331,38 @@ namespace System.Threading bool lockTaken = false; //Register for cancellation outside of the main lock. - //NOTE: Register/deregister inside the lock can deadlock as different lock acquisition orders could + //NOTE: Register/unregister inside the lock can deadlock as different lock acquisition orders could // occur for (1)this.m_lockObj and (2)cts.internalLock CancellationTokenRegistration cancellationTokenRegistration = cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCanceledEventHandler, this); try { - // Perf: first spin wait for the count to be positive, but only up to the first planned yield. - // This additional amount of spinwaiting in addition - // to Monitor.Enter()’s spinwaiting has shown measurable perf gains in test scenarios. - // - SpinWait spin = new SpinWait(); - while (m_currentCount == 0 && !spin.NextSpinWillYield) + // Perf: first spin wait for the count to be positive. + // This additional amount of spinwaiting in addition + // to Monitor.Enter()’s spinwaiting has shown measurable perf gains in test scenarios. + if (m_currentCount == 0) { - spin.SpinOnce(); + // Monitor.Enter followed by Monitor.Wait is much more expensive than waiting on an event as it involves another + // spin, contention, etc. The usual number of spin iterations that would otherwise be used here is increased to + // lessen that extra expense of doing a proper wait. + int spinCount = SpinWait.SpinCountforSpinBeforeWait * 4; + + var spinner = new SpinWait(); + while (spinner.Count < spinCount) + { + spinner.SpinOnce(sleep1Threshold: -1); + + if (m_currentCount != 0) + { + break; + } + } } // entering the lock and incrementing waiters must not suffer a thread-abort, else we cannot // clean up m_waitCount correctly, which may lead to deadlock due to non-woken waiters. try { } finally { - m_lock.Acquire(); - lockTaken = true; + Monitor.Enter(m_lockObj, ref lockTaken); if (lockTaken) { m_waitCount++; @@ -422,7 +431,7 @@ namespace System.Threading if (lockTaken) { m_waitCount--; - m_lock.Release(); + Monitor.Exit(m_lockObj); } // Unregister the cancellation callback. @@ -439,13 +448,13 @@ namespace System.Threading } /// - /// Local helper function, waits on the monitor until the monitor recieves signal or the + /// Local helper function, waits on the monitor until the monitor receives signal or the /// timeout is expired /// /// The maximum timeout /// The start ticks to calculate the elapsed time /// The CancellationToken to observe. - /// true if the monitor recieved a signal, false if the timeout expired + /// true if the monitor received a signal, false if the timeout expired private bool WaitUntilCountOrTimeout(int millisecondsTimeout, uint startTime, CancellationToken cancellationToken) { int remainingWaitMilliseconds = Timeout.Infinite; @@ -466,7 +475,20 @@ namespace System.Threading } } // ** the actual wait ** - if (!m_condition.Wait(remainingWaitMilliseconds)) + bool waitSuccessful = Monitor.Wait(m_lockObj, remainingWaitMilliseconds); + + // This waiter has woken up and this needs to be reflected in the count of waiters pulsed to wake. Since we + // don't have thread-specific pulse state, there is not enough information to tell whether this thread woke up + // because it was pulsed. For instance, this thread may have timed out and may have been waiting to reacquire + // the lock before returning from Monitor.Wait, in which case we don't know whether this thread got pulsed. So + // in any woken case, decrement the count if possible. As such, timeouts could cause more waiters to wake than + // necessary. + if (m_countOfWaitersPulsedToWake != 0) + { + --m_countOfWaitersPulsedToWake; + } + + if (!waitSuccessful) { return false; } @@ -481,7 +503,7 @@ namespace System.Threading /// A task that will complete when the semaphore has been entered. public Task WaitAsync() { - return WaitAsync(Timeout.Infinite, default(CancellationToken)); + return WaitAsync(Timeout.Infinite, default); } /// @@ -518,7 +540,7 @@ namespace System.Threading /// public Task WaitAsync(int millisecondsTimeout) { - return WaitAsync(millisecondsTimeout, default(CancellationToken)); + return WaitAsync(millisecondsTimeout, default); } /// @@ -546,7 +568,7 @@ namespace System.Threading /// public Task WaitAsync(TimeSpan timeout) { - return WaitAsync(timeout, default(CancellationToken)); + return WaitAsync(timeout, default); } /// @@ -568,8 +590,8 @@ namespace System.Threading public Task WaitAsync(TimeSpan timeout, CancellationToken cancellationToken) { // Validate the timeout - Int64 totalMilliseconds = (Int64)timeout.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) + long totalMilliseconds = (long)timeout.TotalMilliseconds; + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new System.ArgumentOutOfRangeException( nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); @@ -610,9 +632,9 @@ namespace System.Threading // Bail early for cancellation if (cancellationToken.IsCancellationRequested) - return Task.FromCancellation(cancellationToken); + return Task.FromCanceled(cancellationToken); - using (LockHolder.Hold(m_lock)) + lock (m_lockObj) { // If there are counts available, allow this waiter to succeed. if (m_currentCount > 0) @@ -644,7 +666,7 @@ namespace System.Threading /// The created task. private TaskNode CreateAndAddAsyncWaiter() { - Debug.Assert(m_lock.IsAcquired, "Requires the lock be held"); + Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held"); // Create the task var task = new TaskNode(); @@ -674,7 +696,7 @@ namespace System.Threading private bool RemoveAsyncWaiter(TaskNode task) { Debug.Assert(task != null, "Expected non-null task"); - Debug.Assert(m_lock.IsAcquired, "Requires the lock be held"); + Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held"); // Is the task in the list? To be in the list, either it's the head or it has a predecessor that's in the list. bool wasInList = m_asyncHead == task || task.Prev != null; @@ -700,14 +722,14 @@ namespace System.Threading private async Task WaitUntilCountOrTimeoutAsync(TaskNode asyncWaiter, int millisecondsTimeout, CancellationToken cancellationToken) { Debug.Assert(asyncWaiter != null, "Waiter should have been constructed"); - Debug.Assert(m_lock.IsAcquired, "Requires the lock be held"); + Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held"); // Wait until either the task is completed, timeout occurs, or cancellation is requested. // We need to ensure that the Task.Delay task is appropriately cleaned up if the await // completes due to the asyncWaiter completing, so we use our own token that we can explicitly // cancel, and we chain the caller's supplied token into it. using (var cts = cancellationToken.CanBeCanceled ? - CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, default(CancellationToken)) : + CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, default) : new CancellationTokenSource()) { var waitCompleted = Task.WhenAny(asyncWaiter, Task.Delay(millisecondsTimeout, cts.Token)); @@ -722,7 +744,7 @@ namespace System.Threading // If the await completed synchronously, we still hold the lock. If it didn't, // we no longer hold the lock. As such, acquire it. - using (LockHolder.Hold(m_lock)) + lock (m_lockObj) { // Remove the task from the list. If we're successful in doing so, // we know that no one else has tried to complete this waiter yet, @@ -773,7 +795,7 @@ namespace System.Threading } int returnCount; - using (LockHolder.Hold(m_lock)) + lock (m_lockObj) { // Read the m_currentCount into a local variable to avoid unnecessary volatile accesses inside the lock. int currentCount = m_currentCount; @@ -788,13 +810,27 @@ namespace System.Threading // Increment the count by the actual release count currentCount += releaseCount; - // Signal to any synchronous waiters + // Signal to any synchronous waiters, taking into account how many waiters have previously been pulsed to wake + // but have not yet woken int waitCount = m_waitCount; - - int waitersToNotify = Math.Min(releaseCount, waitCount); - for (int i = 0; i < waitersToNotify; i++) + Debug.Assert(m_countOfWaitersPulsedToWake <= waitCount); + int waitersToNotify = Math.Min(currentCount, waitCount) - m_countOfWaitersPulsedToWake; + if (waitersToNotify > 0) { - m_condition.SignalOne(); + // Ideally, limiting to a maximum of releaseCount would not be necessary and could be an assert instead, but + // since WaitUntilCountOrTimeout() does not have enough information to tell whether a woken thread was + // pulsed, it's possible for m_countOfWaitersPulsedToWake to be less than the number of threads that have + // actually been pulsed to wake. + if (waitersToNotify > releaseCount) + { + waitersToNotify = releaseCount; + } + + m_countOfWaitersPulsedToWake += waitersToNotify; + for (int i = 0; i < waitersToNotify; i++) + { + Monitor.Pulse(m_lockObj); + } } // Now signal to any asynchronous waiters, if there are any. While we've already @@ -861,7 +897,7 @@ namespace System.Threading /// true to release both managed and unmanaged resources; /// false to release only unmanaged resources. /// - /// Unlike most of the members of , is not + /// Unlike most of the members of , is not /// thread-safe and may not be used concurrently with other members of this instance. /// protected virtual void Dispose(bool disposing) @@ -873,15 +909,12 @@ namespace System.Threading m_waitHandle.Dispose(); m_waitHandle = null; } - m_lock = null; - m_condition = null; + m_lockObj = null; m_asyncHead = null; m_asyncTail = null; } } - - /// /// Private helper method to wake up waiters when a cancellationToken gets canceled. /// @@ -890,9 +923,9 @@ namespace System.Threading { SemaphoreSlim semaphore = obj as SemaphoreSlim; Debug.Assert(semaphore != null, "Expected a SemaphoreSlim"); - using (LockHolder.Hold(semaphore.m_lock)) + lock (semaphore.m_lockObj) { - semaphore.m_condition.SignalAll(); //wake up all waiters. + Monitor.PulseAll(semaphore.m_lockObj); //wake up all waiters. } } @@ -902,15 +935,11 @@ namespace System.Threading /// private void CheckDispose() { - if (m_lock == null) + if (m_lockObj == null) { throw new ObjectDisposedException(null, SR.SemaphoreSlim_Disposed); } } - /// - /// local helper function to retrieve the exception string message from the resource file - /// - /// The key string #endregion } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/SendOrPostCallback.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/SendOrPostCallback.cs index 6692d35ab2..b96914ab2c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Threading/SendOrPostCallback.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/SendOrPostCallback.cs @@ -4,5 +4,5 @@ namespace System.Threading { - public delegate void SendOrPostCallback(Object state); + public delegate void SendOrPostCallback(object state); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/SpinLock.cs similarity index 78% rename from external/corert/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Threading/SpinLock.cs index f949896e2c..2b0610539d 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/SpinLock.cs @@ -12,12 +12,8 @@ // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; -using System.Runtime.InteropServices; using System.Runtime.CompilerServices; -using Internal.Runtime.Augments; -using Internal.Threading.Tracing; - namespace System.Threading { /// @@ -66,35 +62,28 @@ namespace System.Threading // // There are several masks and constants below for convenience. - private volatile int m_owner; - - // The multiplier factor for the each spinning iteration - // This number has been chosen after trying different numbers on different CPUs (4, 8 and 16 ) and this provided the best results - private const int SPINNING_FACTOR = 100; + private volatile int _owner; // After how many yields, call Sleep(1) private const int SLEEP_ONE_FREQUENCY = 40; - // After how many yields, call Sleep(0) - private const int SLEEP_ZERO_FREQUENCY = 10; - // After how many yields, check the timeout private const int TIMEOUT_CHECK_FREQUENCY = 10; // Thr thread tracking disabled mask - private const int LOCK_ID_DISABLE_MASK = unchecked((int)0x80000000); //1000 0000 0000 0000 0000 0000 0000 0000 + private const int LOCK_ID_DISABLE_MASK = unchecked((int)0x80000000); // 1000 0000 0000 0000 0000 0000 0000 0000 //the lock is held by some thread, but we don't know which - private const int LOCK_ANONYMOUS_OWNED = 0x1; //0000 0000 0000 0000 0000 0000 0000 0001 + private const int LOCK_ANONYMOUS_OWNED = 0x1; // 0000 0000 0000 0000 0000 0000 0000 0001 // Waiters mask if the thread tracking is disabled - private const int WAITERS_MASK = ~(LOCK_ID_DISABLE_MASK | 1); //0111 1111 1111 1111 1111 1111 1111 1110 + private const int WAITERS_MASK = ~(LOCK_ID_DISABLE_MASK | 1); // 0111 1111 1111 1111 1111 1111 1111 1110 // The Thread tacking is disabled and the lock bit is set, used in Enter fast path to make sure the id is disabled and lock is available - private const int ID_DISABLED_AND_ANONYMOUS_OWNED = unchecked((int)0x80000001); //1000 0000 0000 0000 0000 0000 0000 0001 + private const int ID_DISABLED_AND_ANONYMOUS_OWNED = unchecked((int)0x80000001); // 1000 0000 0000 0000 0000 0000 0000 0001 // If the thread is unowned if: - // m_owner zero and the threa tracking is enabled + // m_owner zero and the thread tracking is enabled // m_owner & LOCK_ANONYMOUS_OWNED = zero and the thread tracking is disabled private const int LOCK_UNOWNED = 0; @@ -104,7 +93,7 @@ namespace System.Threading private static int MAXIMUM_WAITERS = WAITERS_MASK; [MethodImpl(MethodImplOptions.AggressiveInlining)] - private int CompareExchange(ref int location, int value, int comparand, ref bool success) + private static int CompareExchange(ref int location, int value, int comparand, ref bool success) { int result = Interlocked.CompareExchange(ref location, value, comparand); success = (result == comparand); @@ -122,10 +111,10 @@ namespace System.Threading /// purposes. public SpinLock(bool enableThreadOwnerTracking) { - m_owner = LOCK_UNOWNED; + _owner = LOCK_UNOWNED; if (!enableThreadOwnerTracking) { - m_owner |= LOCK_ID_DISABLE_MASK; + _owner |= LOCK_ID_DISABLE_MASK; Debug.Assert(!IsThreadOwnerTrackingEnabled, "property should be false by now"); } } @@ -159,11 +148,11 @@ namespace System.Threading /// public void Enter(ref bool lockTaken) { - //Try to keep the code and branching in this method as small as possible in order to inline the method - int observedOwner = m_owner; - if (lockTaken || //invalid parameter - (observedOwner & ID_DISABLED_AND_ANONYMOUS_OWNED) != LOCK_ID_DISABLE_MASK || //thread tracking is enabled or the lock is already acquired - CompareExchange(ref m_owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) //acquiring the lock failed + // Try to keep the code and branching in this method as small as possible in order to inline the method + int observedOwner = _owner; + if (lockTaken || // invalid parameter + (observedOwner & ID_DISABLED_AND_ANONYMOUS_OWNED) != LOCK_ID_DISABLE_MASK || // thread tracking is enabled or the lock is already acquired + CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) //acquiring the lock failed ContinueTryEnter(Timeout.Infinite, ref lockTaken); // Then try the slow path if any of the above conditions is met } @@ -187,7 +176,7 @@ namespace System.Threading /// public void TryEnter(ref bool lockTaken) { - int observedOwner = m_owner; + int observedOwner = _owner; if (((observedOwner & LOCK_ID_DISABLE_MASK) == 0) | lockTaken) { // Thread tracking enabled or invalid arg. Take slow path. @@ -201,7 +190,7 @@ namespace System.Threading else { // Lock wasn't held; try to acquire it. - CompareExchange(ref m_owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken); + CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken); } } @@ -234,7 +223,7 @@ namespace System.Threading public void TryEnter(TimeSpan timeout, ref bool lockTaken) { // Validate the timeout - Int64 totalMilliseconds = (Int64)timeout.TotalMilliseconds; + long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new System.ArgumentOutOfRangeException( @@ -269,18 +258,18 @@ namespace System.Threading /// a negative number other than -1, which represents an infinite time-out. public void TryEnter(int millisecondsTimeout, ref bool lockTaken) { - int observedOwner = m_owner; + int observedOwner = _owner; if (millisecondsTimeout < -1 || //invalid parameter lockTaken || //invalid parameter (observedOwner & ID_DISABLED_AND_ANONYMOUS_OWNED) != LOCK_ID_DISABLE_MASK || //thread tracking is enabled or the lock is already acquired - CompareExchange(ref m_owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) // acquiring the lock failed + CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) // acquiring the lock failed ContinueTryEnter(millisecondsTimeout, ref lockTaken); // The call the slow pth } /// /// Try acquire the lock with long path, this is usually called after the first path in Enter and /// TryEnter failed The reason for short path is to make it inline in the run time which improves the - /// performance. This method assumed that the parameter are validated in Enter ir TryENter method + /// performance. This method assumed that the parameter are validated in Enter or TryEnter method. /// /// The timeout milliseconds /// The lockTaken param @@ -290,7 +279,7 @@ namespace System.Threading if (lockTaken) { lockTaken = false; - throw new System.ArgumentException(SR.SpinLock_TryReliableEnter_ArgumentException); + throw new ArgumentException(SR.SpinLock_TryReliableEnter_ArgumentException); } if (millisecondsTimeout < -1) @@ -305,11 +294,6 @@ namespace System.Threading startTime = TimeoutHelper.GetTime(); } - if (SpinLockTrace.Enabled) - { - SpinLockTrace.SpinLock_FastPathFailed(m_owner); - } - if (IsThreadOwnerTrackingEnabled) { // Slow path for enabled thread tracking mode @@ -332,10 +316,10 @@ namespace System.Threading //***Step 1, take the lock or update the waiters // try to acquire the lock directly if possible or update the waiters count - observedOwner = m_owner; + observedOwner = _owner; if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED) { - if (CompareExchange(ref m_owner, observedOwner | 1, observedOwner, ref lockTaken) == observedOwner) + if (CompareExchange(ref _owner, observedOwner | 1, observedOwner, ref lockTaken) == observedOwner) { // Acquired lock return; @@ -352,89 +336,50 @@ namespace System.Threading // Did not acquire lock as owned and timeout is 0 so fail fast return; } - else //failed to acquire the lock,then try to update the waiters. If the waiters count reached the maximum, jsut break the loop to avoid overflow + else //failed to acquire the lock, then try to update the waiters. If the waiters count reached the maximum, just break the loop to avoid overflow { if ((observedOwner & WAITERS_MASK) != MAXIMUM_WAITERS) - turn = (Interlocked.Add(ref m_owner, 2) & WAITERS_MASK) >> 1; + { + // This can still overflow, but maybe there will never be that many waiters + turn = (Interlocked.Add(ref _owner, 2) & WAITERS_MASK) >> 1; + } } - //***Step 2. Spinning - //lock acquired failed and waiters updated - int processorCount = PlatformHelper.ProcessorCount; - if (turn < processorCount) + // lock acquired failed and waiters updated + + //*** Step 2, Spinning and Yielding + var spinner = new SpinWait(); + if (turn > PlatformHelper.ProcessorCount) { - int processFactor = 1; - for (int i = 1; i <= turn * SPINNING_FACTOR; i++) - { - RuntimeThread.SpinWait((turn + i) * SPINNING_FACTOR * processFactor); - if (processFactor < processorCount) - processFactor++; - observedOwner = m_owner; - if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED) - { - int newOwner = (observedOwner & WAITERS_MASK) == 0 ? // Gets the number of waiters, if zero - observedOwner | 1 // don't decrement it. just set the lock bit, it is zzero because a previous call of Exit(false) ehich corrupted the waiters - : (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit - Debug.Assert((newOwner & WAITERS_MASK) >= 0); - - if (CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner) - { - return; - } - } - } - - // Check the timeout. - if (millisecondsTimeout != Timeout.Infinite && TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0) - { - DecrementWaiters(); - return; - } + spinner.Count = SpinWait.YieldThreshold; } - - //*** Step 3, Yielding - //Sleep(1) every 50 yields - int yieldsoFar = 0; while (true) { - observedOwner = m_owner; + spinner.SpinOnce(SLEEP_ONE_FREQUENCY); + + observedOwner = _owner; if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED) { int newOwner = (observedOwner & WAITERS_MASK) == 0 ? // Gets the number of waiters, if zero - observedOwner | 1 // don't decrement it. just set the lock bit, it is zzero because a previous call of Exit(false) ehich corrupted the waiters + observedOwner | 1 // don't decrement it. just set the lock bit, it is zero because a previous call of Exit(false) which corrupted the waiters : (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit Debug.Assert((newOwner & WAITERS_MASK) >= 0); - if (CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner) + if (CompareExchange(ref _owner, newOwner, observedOwner, ref lockTaken) == observedOwner) { return; } } - if (yieldsoFar % SLEEP_ONE_FREQUENCY == 0) + if (spinner.Count % TIMEOUT_CHECK_FREQUENCY == 0) { - RuntimeThread.Sleep(1); - } - else if (yieldsoFar % SLEEP_ZERO_FREQUENCY == 0) - { - RuntimeThread.Sleep(0); - } - else - { - RuntimeThread.Yield(); - } - - if (yieldsoFar % TIMEOUT_CHECK_FREQUENCY == 0) - { - //Check the timeout. + // Check the timeout. if (millisecondsTimeout != Timeout.Infinite && TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0) { DecrementWaiters(); return; } } - - yieldsoFar++; } } @@ -446,9 +391,9 @@ namespace System.Threading SpinWait spinner = new SpinWait(); while (true) { - int observedOwner = m_owner; + int observedOwner = _owner; if ((observedOwner & WAITERS_MASK) == 0) return; // don't decrement the waiters if it's corrupted by previous call of Exit(false) - if (Interlocked.CompareExchange(ref m_owner, observedOwner - 2, observedOwner) == observedOwner) + if (Interlocked.CompareExchange(ref _owner, observedOwner - 2, observedOwner) == observedOwner) { Debug.Assert(!IsThreadOwnerTrackingEnabled); // Make sure the waiters never be negative which will cause the thread tracking bit to be flipped break; @@ -467,8 +412,8 @@ namespace System.Threading int lockUnowned = 0; // We are using thread IDs to mark ownership. Snap the thread ID and check for recursion. // We also must or the ID enablement bit, to ensure we propagate when we CAS it in. - int m_newOwner = Environment.CurrentManagedThreadId; - if (m_owner == m_newOwner) + int newOwner = Environment.CurrentManagedThreadId; + if (_owner == newOwner) { // We don't allow lock recursion. throw new LockRecursionException(SR.SpinLock_TryEnter_LockRecursionException); @@ -486,9 +431,9 @@ namespace System.Threading // Test before trying to CAS, to avoid acquiring the line exclusively unnecessarily. - if (m_owner == lockUnowned) + if (_owner == lockUnowned) { - if (CompareExchange(ref m_owner, m_newOwner, lockUnowned, ref lockTaken) == lockUnowned) + if (CompareExchange(ref _owner, newOwner, lockUnowned, ref lockTaken) == lockUnowned) { return; } @@ -508,7 +453,7 @@ namespace System.Threading /// /// /// The default overload of provides the same behavior as if calling using true as the argument, but Exit() could be slightly faster than Exit(true). + /// cref="Exit(bool)"/> using true as the argument, but Exit() could be slightly faster than Exit(true). /// /// /// Thread ownership tracking is enabled, and the current thread is not the owner of this lock. @@ -516,10 +461,10 @@ namespace System.Threading public void Exit() { //This is the fast path for the thread tracking is disabled, otherwise go to the slow path - if ((m_owner & LOCK_ID_DISABLE_MASK) == 0) + if ((_owner & LOCK_ID_DISABLE_MASK) == 0) ExitSlowPath(true); else - Interlocked.Decrement(ref m_owner); + Interlocked.Decrement(ref _owner); } /// @@ -530,7 +475,7 @@ namespace System.Threading /// publish the exit operation to other threads. /// /// - /// Calling with the argument set to + /// Calling with the argument set to /// true will improve the fairness of the lock at the expense of some performance. The default /// overload behaves as if specifying true for . @@ -540,16 +485,18 @@ namespace System.Threading /// public void Exit(bool useMemoryBarrier) { - // This is the fast path for the thread tracking is diabled and not to use memory barrier, otherwise go to the slow path - // The reason not to add else statement if the usememorybarrier is that it will add more barnching in the code and will prevent + // This is the fast path for the thread tracking is disabled and not to use memory barrier, otherwise go to the slow path + // The reason not to add else statement if the usememorybarrier is that it will add more branching in the code and will prevent // method inlining, so this is optimized for useMemoryBarrier=false and Exit() overload optimized for useMemoryBarrier=true. - int tmpOwner = m_owner; + int tmpOwner = _owner; if ((tmpOwner & LOCK_ID_DISABLE_MASK) != 0 & !useMemoryBarrier) { - m_owner = tmpOwner & (~LOCK_ANONYMOUS_OWNED); + _owner = tmpOwner & (~LOCK_ANONYMOUS_OWNED); } else + { ExitSlowPath(useMemoryBarrier); + } } /// @@ -561,28 +508,33 @@ namespace System.Threading /// private void ExitSlowPath(bool useMemoryBarrier) { - bool threadTrackingEnabled = (m_owner & LOCK_ID_DISABLE_MASK) == 0; + bool threadTrackingEnabled = (_owner & LOCK_ID_DISABLE_MASK) == 0; if (threadTrackingEnabled && !IsHeldByCurrentThread) { - throw new System.Threading.SynchronizationLockException( - SR.SpinLock_Exit_SynchronizationLockException); + throw new SynchronizationLockException(SR.SpinLock_Exit_SynchronizationLockException); } if (useMemoryBarrier) { if (threadTrackingEnabled) - Interlocked.Exchange(ref m_owner, LOCK_UNOWNED); + { + Interlocked.Exchange(ref _owner, LOCK_UNOWNED); + } else - Interlocked.Decrement(ref m_owner); + { + Interlocked.Decrement(ref _owner); + } } else { if (threadTrackingEnabled) - m_owner = LOCK_UNOWNED; + { + _owner = LOCK_UNOWNED; + } else { - int tmpOwner = m_owner; - m_owner = tmpOwner & (~LOCK_ANONYMOUS_OWNED); + int tmpOwner = _owner; + _owner = tmpOwner & (~LOCK_ANONYMOUS_OWNED); } } } @@ -595,9 +547,9 @@ namespace System.Threading get { if (IsThreadOwnerTrackingEnabled) - return m_owner != LOCK_UNOWNED; + return _owner != LOCK_UNOWNED; - return (m_owner & LOCK_ANONYMOUS_OWNED) != LOCK_UNOWNED; + return (_owner & LOCK_ANONYMOUS_OWNED) != LOCK_UNOWNED; } } @@ -623,15 +575,12 @@ namespace System.Threading { throw new InvalidOperationException(SR.SpinLock_IsHeldByCurrentThread); } - return ((m_owner & (~LOCK_ID_DISABLE_MASK)) == Environment.CurrentManagedThreadId); + return ((_owner & (~LOCK_ID_DISABLE_MASK)) == Environment.CurrentManagedThreadId); } } /// Gets whether thread ownership tracking is enabled for this instance. - public bool IsThreadOwnerTrackingEnabled - { - get { return (m_owner & LOCK_ID_DISABLE_MASK) == 0; } - } + public bool IsThreadOwnerTrackingEnabled => (_owner & LOCK_ID_DISABLE_MASK) == 0; #region Debugger proxy class /// @@ -640,7 +589,7 @@ namespace System.Threading internal class SystemThreading_SpinLockDebugView { // SpinLock object - private SpinLock m_spinLock; + private SpinLock _spinLock; /// /// SystemThreading_SpinLockDebugView constructor @@ -649,7 +598,7 @@ namespace System.Threading public SystemThreading_SpinLockDebugView(SpinLock spinLock) { // Note that this makes a copy of the SpinLock (struct). It doesn't hold a reference to it. - m_spinLock = spinLock; + _spinLock = spinLock; } /// @@ -661,7 +610,7 @@ namespace System.Threading { try { - return m_spinLock.IsHeldByCurrentThread; + return _spinLock.IsHeldByCurrentThread; } catch (InvalidOperationException) { @@ -677,9 +626,9 @@ namespace System.Threading { get { - if (m_spinLock.IsThreadOwnerTrackingEnabled) + if (_spinLock.IsThreadOwnerTrackingEnabled) { - return m_spinLock.m_owner; + return _spinLock._owner; } else { @@ -692,10 +641,7 @@ namespace System.Threading /// /// Gets whether the lock is currently held by any thread or not. /// - public bool IsHeld - { - get { return m_spinLock.IsHeld; } - } + public bool IsHeld => _spinLock.IsHeld; } #endregion diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/SpinWait.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/SpinWait.cs index 414ad1852f..54857c322c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Threading/SpinWait.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/SpinWait.cs @@ -88,7 +88,16 @@ namespace System.Threading /// for here. /// internal static readonly int SpinCountforSpinBeforeWait = PlatformHelper.IsSingleProcessor ? 1 : 35; - internal const int Sleep1ThresholdForSpinBeforeWait = 40; // should be greater than SpinCountforSpinBeforeWait + + /// + /// Typically, Sleep(1) should not be issued for a spin-wait before a proper wait because it is usually more beneficial + /// to just issue the proper wait. For longer spin-waits (when the spin count is configurable), this value may be used as + /// a threshold for issuing Sleep(1). + /// + /// + /// Should be greater than so that Sleep(1) would not be used by default. + /// + internal const int Sleep1ThresholdForLongSpinBeforeWait = 40; // The number of times we've spun already. private int _count; @@ -127,12 +136,42 @@ namespace System.Threading /// public void SpinOnce() { - SpinOnce(DefaultSleep1Threshold); + SpinOnceCore(DefaultSleep1Threshold); } - internal void SpinOnce(int sleep1Threshold) + /// + /// Performs a single spin. + /// + /// + /// A minimum spin count after which Thread.Sleep(1) may be used. A value of -1 may be used to + /// disable the use of Thread.Sleep(1). + /// + /// + /// is less than -1. + /// + /// + /// This is typically called in a loop, and may change in behavior based on the number of times a + /// has been called thus far on this instance. + /// + public void SpinOnce(int sleep1Threshold) { - Debug.Assert(sleep1Threshold >= YieldThreshold || PlatformHelper.IsSingleProcessor); // so that NextSpinWillYield behaves as requested + if (sleep1Threshold < -1) + { + throw new ArgumentOutOfRangeException(nameof(sleep1Threshold), sleep1Threshold, SR.ArgumentOutOfRange_NeedNonNegOrNegative1); + } + + if (sleep1Threshold >= 0 && sleep1Threshold < YieldThreshold) + { + sleep1Threshold = YieldThreshold; + } + + SpinOnceCore(sleep1Threshold); + } + + private void SpinOnceCore(int sleep1Threshold) + { + Debug.Assert(sleep1Threshold >= -1); + Debug.Assert(sleep1Threshold < 0 || sleep1Threshold >= YieldThreshold); // (_count - YieldThreshold) % 2 == 0: The purpose of this check is to interleave Thread.Yield/Sleep(0) with // Thread.SpinWait. Otherwise, the following issues occur: @@ -145,7 +184,7 @@ namespace System.Threading // contention), they may switch between one another, delaying work that can make progress. if (( _count >= YieldThreshold && - (_count >= sleep1Threshold || (_count - YieldThreshold) % 2 == 0) + ((_count >= sleep1Threshold && sleep1Threshold >= 0) || (_count - YieldThreshold) % 2 == 0) ) || PlatformHelper.IsSingleProcessor) { @@ -164,7 +203,7 @@ namespace System.Threading // configured to use the (default) coarse-grained system timer. // - if (_count >= sleep1Threshold) + if (_count >= sleep1Threshold && sleep1Threshold >= 0) { RuntimeThread.Sleep(1); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/SynchronizationLockException.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/SynchronizationLockException.cs index e050e1539d..3b5d31f3c0 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Threading/SynchronizationLockException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/SynchronizationLockException.cs @@ -26,13 +26,13 @@ namespace System.Threading HResult = HResults.COR_E_SYNCHRONIZATIONLOCK; } - public SynchronizationLockException(String message) + public SynchronizationLockException(string message) : base(message) { HResult = HResults.COR_E_SYNCHRONIZATIONLOCK; } - public SynchronizationLockException(String message, Exception innerException) + public SynchronizationLockException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_SYNCHRONIZATIONLOCK; diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs similarity index 95% rename from external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs index b30ff63db4..baf0a5025e 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs @@ -5,7 +5,6 @@ // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // - // // A pair of schedulers that together support concurrent (reader) / exclusive (writer) // task scheduling. Using just the exclusive scheduler can be used to simulate a serial @@ -19,6 +18,8 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using Thread = Internal.Runtime.Augments.RuntimeThread; + namespace System.Threading.Tasks { /// @@ -39,10 +40,10 @@ namespace System.Threading.Tasks private readonly TaskScheduler m_underlyingTaskScheduler; /// /// The maximum number of tasks allowed to run concurrently. This only applies to concurrent tasks, - /// since exlusive tasks are inherently limited to 1. + /// since exclusive tasks are inherently limited to 1. /// private readonly int m_maxConcurrencyLevel; - /// The maximum number of tasks we can process before recyling our runner tasks. + /// The maximum number of tasks we can process before recycling our runner tasks. private readonly int m_maxItemsPerTask; /// /// If positive, it represents the number of concurrently running concurrent tasks. @@ -61,10 +62,10 @@ namespace System.Threading.Tasks /// Default MaxItemsPerTask to use for processing if none is specified. private const int DEFAULT_MAXITEMSPERTASK = UNLIMITED_PROCESSING; /// Default MaxConcurrencyLevel is the processor count if not otherwise specified. - private static Int32 DefaultMaxConcurrencyLevel { get { return Environment.ProcessorCount; } } + private static int DefaultMaxConcurrencyLevel { get { return Environment.ProcessorCount; } } /// Gets the sync obj used to protect all state on this instance. - private readonly Lock ValueLock = new Lock(); + private object ValueLock { get { return m_threadProcessingMode; } } /// /// Initializes the ConcurrentExclusiveSchedulerPair. @@ -115,8 +116,8 @@ namespace System.Threading.Tasks // Treat UNLIMITED_PROCESSING/-1 for both MCL and MIPT as the biggest possible value so that we don't // have to special case UNLIMITED_PROCESSING later on in processing. - if (m_maxConcurrencyLevel == UNLIMITED_PROCESSING) m_maxConcurrencyLevel = Int32.MaxValue; - if (m_maxItemsPerTask == UNLIMITED_PROCESSING) m_maxItemsPerTask = Int32.MaxValue; + if (m_maxConcurrencyLevel == UNLIMITED_PROCESSING) m_maxConcurrencyLevel = int.MaxValue; + if (m_maxItemsPerTask == UNLIMITED_PROCESSING) m_maxItemsPerTask = int.MaxValue; // Create the concurrent/exclusive schedulers for this pair m_exclusiveTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, 1, ProcessingMode.ProcessingExclusiveTask); @@ -130,7 +131,7 @@ namespace System.Threading.Tasks /// public void Complete() { - using (LockHolder.Hold(ValueLock)) + lock (ValueLock) { if (!CompletionRequested) { @@ -210,19 +211,21 @@ namespace System.Threading.Tasks cs.m_completionQueued = true; ThreadPool.QueueUserWorkItem(state => { - var localCs = (CompletionState)state; // don't use 'cs', as it'll force a closure - Debug.Assert(!localCs.Task.IsCompleted, "Completion should only happen once."); + var localThis = (ConcurrentExclusiveSchedulerPair)state; + Debug.Assert(!localThis.m_completionState.Task.IsCompleted, "Completion should only happen once."); - var exceptions = localCs.m_exceptions; + List exceptions = localThis.m_completionState.m_exceptions; bool success = (exceptions != null && exceptions.Count > 0) ? - localCs.TrySetException(exceptions) : - localCs.TrySetResult(default(VoidTaskResult)); + localThis.m_completionState.TrySetException(exceptions) : + localThis.m_completionState.TrySetResult(default); Debug.Assert(success, "Expected to complete completion task."); - }, cs); + + localThis.m_threadProcessingMode.Dispose(); + }, this); } } - /// Initiatites scheduler shutdown due to a worker task faulting.. + /// Initiates scheduler shutdown due to a worker task faulting. /// The faulted worker task that's initiating the shutdown. private void FaultWithTask(Task faultedTask) { @@ -232,7 +235,7 @@ namespace System.Threading.Tasks // Store the faulted task's exceptions var cs = EnsureCompletionStateInitialized(); - if (cs.m_exceptions == null) cs.m_exceptions = new LowLevelListWithIList(); + if (cs.m_exceptions == null) cs.m_exceptions = new List(); cs.m_exceptions.AddRange(faultedTask.Exception.InnerExceptions); // Now that we're doomed, request completion @@ -292,7 +295,7 @@ namespace System.Threading.Tasks try { processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessExclusiveTasks(), this, - default(CancellationToken), GetCreationOptionsForTask(fairly)); + default, GetCreationOptionsForTask(fairly)); processingTask.Start(m_underlyingTaskScheduler); // When we call Start, if the underlying scheduler throws in QueueTask, TPL will fault the task and rethrow // the exception. To deal with that, we need a reference to the task object, so that we can observe its exception. @@ -319,7 +322,7 @@ namespace System.Threading.Tasks try { processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessConcurrentTasks(), this, - default(CancellationToken), GetCreationOptionsForTask(fairly)); + default, GetCreationOptionsForTask(fairly)); processingTask.Start(m_underlyingTaskScheduler); // See above logic for why we use new + Start rather than StartNew } catch @@ -372,7 +375,7 @@ namespace System.Threading.Tasks "Somehow we ended up escaping exclusive mode."); m_threadProcessingMode.Value = ProcessingMode.NotCurrentlyProcessing; - using (LockHolder.Hold(ValueLock)) + lock (ValueLock) { // When this task was launched, we tracked it by setting m_processingCount to WRITER_IN_PROGRESS. // now reset it to 0. Then check to see whether there's more processing to be done. @@ -419,7 +422,7 @@ namespace System.Threading.Tasks // before entering the loop an exclusive task arrives. If we didn't execute at // least one task, we would have spent all of the overhead to launch a // task but with none of the benefit. There's of course also an inherent - // race here with regards to exclusive tasks arriving, and we're ok with + // race condition here with regards to exclusive tasks arriving, and we're ok with // executing one more concurrent task than we should before giving priority to exclusive tasks. if (!m_exclusiveTaskScheduler.m_tasks.IsEmpty) break; } @@ -431,7 +434,7 @@ namespace System.Threading.Tasks "Somehow we ended up escaping concurrent mode."); m_threadProcessingMode.Value = ProcessingMode.NotCurrentlyProcessing; - using (LockHolder.Hold(ValueLock)) + lock (ValueLock) { // When this task was launched, we tracked it with a positive processing count; // decrement that count. Then check to see whether there's more processing to be done. @@ -461,7 +464,7 @@ namespace System.Threading.Tasks /// Whether completion processing has been queued. internal bool m_completionQueued; /// Unrecoverable exceptions incurred while processing. - internal LowLevelListWithIList m_exceptions; + internal List m_exceptions; } /// @@ -512,7 +515,7 @@ namespace System.Threading.Tasks protected internal override void QueueTask(Task task) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); - using (LockHolder.Hold(m_pair.ValueLock)) + lock (m_pair.ValueLock) { // If the scheduler has already had completion requested, no new work is allowed to be scheduled if (m_pair.CompletionRequested) throw new InvalidOperationException(GetType().ToString()); @@ -557,7 +560,7 @@ namespace System.Threading.Tasks // since it'll only allow inlining if it can find the task in the local queue). // As such, if we're not on a thread pool thread, we know for sure the // task won't be inlined, so let's not even try. - if (isDefaultScheduler && taskWasPreviouslyQueued && !ThreadPool.IsThreadPoolThread) + if (isDefaultScheduler && taskWasPreviouslyQueued && !Thread.CurrentThread.IsThreadPoolThread) { return false; } @@ -612,6 +615,7 @@ namespace System.Threading.Tasks var ignored = t.Exception; throw; } + finally { t.Dispose(); } } /// Shim used to invoke this.TryExecuteTask(task). @@ -705,15 +709,15 @@ namespace System.Threading.Tasks } } - /// Asserts that a given Lock object is either held or not held. - /// The Lock object to check. + /// Asserts that a given synchronization object is either held or not held. + /// The monitor to check. /// Whether we want to assert that it's currently held or not held. [Conditional("DEBUG")] - private static void ContractAssertMonitorStatus(Lock syncObj, bool held) + private static void ContractAssertMonitorStatus(object syncObj, bool held) { - Debug.Assert(syncObj != null, "The Lock object to check must be provided."); + Debug.Assert(syncObj != null, "The monitor object to check must be provided."); #if !MONO - Debug.Assert(syncObj.IsAcquired == held, "The locking scheme was not correctly followed."); + Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed."); #endif } @@ -726,16 +730,14 @@ namespace System.Threading.Tasks /// The options to use. internal static TaskCreationOptions GetCreationOptionsForTask(bool isReplacementReplica = false) { - TaskCreationOptions options = - TaskCreationOptions.DenyChildAttach; - + TaskCreationOptions options = TaskCreationOptions.DenyChildAttach; if (isReplacementReplica) options |= TaskCreationOptions.PreferFairness; return options; } /// Provides an enumeration that represents the current state of the scheduler pair. [Flags] - internal enum ProcessingMode : byte + private enum ProcessingMode : byte { /// The scheduler pair is currently dormant, with no work scheduled. NotCurrentlyProcessing = 0x0, diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskCanceledException.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskCanceledException.cs index a6ec030452..c3ee31a53c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskCanceledException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskCanceledException.cs @@ -53,6 +53,18 @@ namespace System.Threading.Tasks { } + /// + /// Initializes a new instance of the + /// class with a specified error message, a reference to the inner exception that is the cause of + /// this exception, and the that triggered the cancellation. + /// + /// The error message that explains the reason for the exception. + /// The exception that is the cause of the current exception. + /// The that triggered the cancellation. + public TaskCanceledException(string message, Exception innerException, CancellationToken token) : base(message, innerException, token) + { + } + /// /// Initializes a new instance of the class /// with a reference to the that has been canceled. diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskCompletionSource.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskCompletionSource.cs index 992e9db767..11ba26d89d 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskCompletionSource.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskCompletionSource.cs @@ -315,7 +315,7 @@ namespace System.Threading.Tasks /// The was disposed. public bool TrySetCanceled() { - return TrySetCanceled(default(CancellationToken)); + return TrySetCanceled(default); } // Enables a token to be stored into the canceled task diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/ValueTask.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/ValueTask.cs index 18e4a27a49..4d6a759605 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/ValueTask.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/Tasks/ValueTask.cs @@ -14,17 +14,59 @@ using Internal.Runtime.CompilerServices; namespace System.Threading.Tasks { + // TYPE SAFETY WARNING: + // This code uses Unsafe.As to cast _obj. This is done in order to minimize the costs associated with + // casting _obj to a variety of different types that can be stored in a ValueTask, e.g. Task + // vs IValueTaskSource. Previous attempts at this were faulty due to using a separate field + // to store information about the type of the object in _obj; this is faulty because if the ValueTask + // is stored into a field, concurrent read/writes can result in tearing the _obj from the type information + // stored in a separate field. This means we can rely only on the _obj field to determine how to handle + // it. As such, the pattern employed is to copy _obj into a local obj, and then check it for null and + // type test against Task/Task. Since the ValueTask can only be constructed with null, Task, + // or IValueTaskSource, we can then be confident in knowing that if it doesn't match one of those values, + // it must be an IValueTaskSource, and we can use Unsafe.As. This could be defeated by other unsafe means, + // like private reflection or using Unsafe.As manually, but at that point you're already doing things + // that can violate type safety; we only care about getting correct behaviors when using "safe" code. + // There are still other race conditions in user's code that can result in errors, but such errors don't + // cause ValueTask to violate type safety. + /// Provides an awaitable result of an asynchronous operation. /// - /// s are meant to be directly awaited. To do more complicated operations with them, a - /// should be extracted using . Such operations might include caching an instance to be awaited later, - /// registering multiple continuations with a single operation, awaiting the same task multiple times, and using combinators over - /// multiple operations. + /// instances are meant to be directly awaited. To do more complicated operations with them, a + /// should be extracted using . Such operations might include caching a task instance to be awaited later, + /// registering multiple continuations with a single task, awaiting the same task multiple times, and using combinators over + /// multiple operations: + /// + /// + /// Once the result of a instance has been retrieved, do not attempt to retrieve it again. + /// instances may be backed by instances that are reusable, and such + /// instances may use the act of retrieving the instances result as a notification that the instance may now be reused for + /// a different operation. Attempting to then reuse that same results in undefined behavior. + /// + /// + /// Do not attempt to add multiple continuations to the same . While this might work if the + /// wraps a T or a , it may not work if the + /// was constructed from an . + /// + /// + /// Some operations that return a may invalidate it based on some subsequent operation being performed. + /// Unless otherwise documented, assume that a should be awaited prior to performing any additional operations + /// on the instance from which it was retrieved. + /// + /// /// [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder))] [StructLayout(LayoutKind.Auto)] public readonly struct ValueTask : IEquatable { + /// A task canceled using `new CancellationToken(true)`. + private static readonly Task s_canceledTask = +#if netstandard + Task.Delay(Timeout.Infinite, new CancellationToken(canceled: true)); +#else + Task.FromCanceled(new CancellationToken(canceled: true)); +#endif + /// A successfully completed task. internal static Task CompletedTask #if netstandard { get; } = Task.Delay(0); @@ -34,10 +76,11 @@ namespace System.Threading.Tasks /// null if representing a successful synchronous completion, otherwise a or a . internal readonly object _obj; - /// Flags providing additional details about the ValueTask's contents and behavior. - internal readonly ValueTaskFlags _flags; /// Opaque value passed through to the . internal readonly short _token; + /// true to continue on the capture context; otherwise, true. + /// Stored in the rather than in the configured awaiter to utilize otherwise padding space. + internal readonly bool _continueOnCapturedContext; // An instance created with the default ctor (a zero init'd struct) represents a synchronously, successfully completed operation. @@ -53,7 +96,7 @@ namespace System.Threading.Tasks _obj = task; - _flags = ValueTaskFlags.ObjectIsTask; + _continueOnCapturedContext = true; _token = 0; } @@ -71,51 +114,15 @@ namespace System.Threading.Tasks _obj = source; _token = token; - _flags = 0; + _continueOnCapturedContext = true; } - /// Non-verified initialization of the struct to the specified values. - /// The object. - /// The token. - /// The flags. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private ValueTask(object obj, short token, ValueTaskFlags flags) + private ValueTask(object obj, short token, bool continueOnCapturedContext) { _obj = obj; _token = token; - _flags = flags; - } - - /// Gets whether the contination should be scheduled to the current context. - internal bool ContinueOnCapturedContext - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => (_flags & ValueTaskFlags.AvoidCapturedContext) == 0; - } - - /// Gets whether the object in the field is a . - internal bool ObjectIsTask - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => (_flags & ValueTaskFlags.ObjectIsTask) != 0; - } - - /// Returns the stored in . This uses . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal Task UnsafeGetTask() - { - Debug.Assert(ObjectIsTask); - Debug.Assert(_obj is Task); - return Unsafe.As(_obj); - } - - /// Returns the stored in . This uses . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal IValueTaskSource UnsafeGetValueTaskSource() - { - Debug.Assert(!ObjectIsTask); - Debug.Assert(_obj is IValueTaskSource); - return Unsafe.As(_obj); + _continueOnCapturedContext = continueOnCapturedContext; } /// Returns the hash code for this instance. @@ -144,18 +151,26 @@ namespace System.Threading.Tasks /// It will either return the wrapped task object if one exists, or it'll /// manufacture a new task object to represent the result. /// - public Task AsTask() => - _obj == null ? ValueTask.CompletedTask : - ObjectIsTask ? UnsafeGetTask() : - GetTaskForValueTaskSource(); + public Task AsTask() + { + object obj = _obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + return + obj == null ? CompletedTask : + obj as Task ?? + GetTaskForValueTaskSource(Unsafe.As(obj)); + } /// Gets a that may be used at any point in the future. public ValueTask Preserve() => _obj == null ? this : new ValueTask(AsTask()); /// Creates a to represent the . - private Task GetTaskForValueTaskSource() + /// + /// The is passed in rather than reading and casting + /// so that the caller can pass in an object it's already validated. + /// + private Task GetTaskForValueTaskSource(IValueTaskSource t) { - IValueTaskSource t = UnsafeGetValueTaskSource(); ValueTaskSourceStatus status = t.GetStatus(_token); if (status != ValueTaskSourceStatus.Pending) { @@ -164,7 +179,7 @@ namespace System.Threading.Tasks // Propagate any exceptions that may have occurred, then return // an already successfully completed task. t.GetResult(_token); - return ValueTask.CompletedTask; + return CompletedTask; // If status is Faulted or Canceled, GetResult should throw. But // we can't guarantee every implementation will do the "right thing". @@ -175,22 +190,15 @@ namespace System.Threading.Tasks { if (status == ValueTaskSourceStatus.Canceled) { -#if netstandard - var tcs = new TaskCompletionSource(); - tcs.TrySetCanceled(); - return tcs.Task; -#else +#if !netstandard if (exc is OperationCanceledException oce) { var task = new Task(); task.TrySetCanceled(oce.CancellationToken, oce); return task; } - else - { - return Task.FromCanceled(new CancellationToken(true)); - } #endif + return s_canceledTask; } else { @@ -205,7 +213,7 @@ namespace System.Threading.Tasks } } - var m = new ValueTaskSourceTask(t, _token); + var m = new ValueTaskSourceAsTask(t, _token); return #if netstandard m.Task; @@ -215,7 +223,7 @@ namespace System.Threading.Tasks } /// Type used to create a to represent a . - private sealed class ValueTaskSourceTask : + private sealed class ValueTaskSourceAsTask : #if netstandard TaskCompletionSource #else @@ -224,7 +232,7 @@ namespace System.Threading.Tasks { private static readonly Action s_completionAction = state => { - if (!(state is ValueTaskSourceTask vtst) || + if (!(state is ValueTaskSourceAsTask vtst) || !(vtst._source is IValueTaskSource source)) { // This could only happen if the IValueTaskSource passed the wrong state @@ -270,7 +278,7 @@ namespace System.Threading.Tasks /// The token to pass through to operations on private readonly short _token; - public ValueTaskSourceTask(IValueTaskSource source, short token) + public ValueTaskSourceAsTask(IValueTaskSource source, short token) { _token = token; _source = source; @@ -282,30 +290,73 @@ namespace System.Threading.Tasks public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => _obj == null || (ObjectIsTask ? UnsafeGetTask().IsCompleted : UnsafeGetValueTaskSource().GetStatus(_token) != ValueTaskSourceStatus.Pending); + get + { + object obj = _obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj == null) + { + return true; + } + + if (obj is Task t) + { + return t.IsCompleted; + } + + return Unsafe.As(obj).GetStatus(_token) != ValueTaskSourceStatus.Pending; + } } /// Gets whether the represents a successfully completed operation. public bool IsCompletedSuccessfully { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => - _obj == null || - (ObjectIsTask ? + get + { + object obj = _obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj == null) + { + return true; + } + + if (obj is Task t) + { + return #if netstandard - UnsafeTask.Status == TaskStatus.RanToCompletion : + t.Status == TaskStatus.RanToCompletion; #else - UnsafeGetTask().IsCompletedSuccessfully : + t.IsCompletedSuccessfully; #endif - UnsafeGetValueTaskSource().GetStatus(_token) == ValueTaskSourceStatus.Succeeded); + } + + return Unsafe.As(obj).GetStatus(_token) == ValueTaskSourceStatus.Succeeded; + } } /// Gets whether the represents a failed operation. public bool IsFaulted { - get => - _obj != null && - (ObjectIsTask ? UnsafeGetTask().IsFaulted : UnsafeGetValueTaskSource().GetStatus(_token) == ValueTaskSourceStatus.Faulted); + get + { + object obj = _obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj == null) + { + return false; + } + + if (obj is Task t) + { + return t.IsFaulted; + } + + return Unsafe.As(obj).GetStatus(_token) == ValueTaskSourceStatus.Faulted; + } } /// Gets whether the represents a canceled operation. @@ -316,9 +367,23 @@ namespace System.Threading.Tasks /// public bool IsCanceled { - get => - _obj != null && - (ObjectIsTask ? UnsafeGetTask().IsCanceled : UnsafeGetValueTaskSource().GetStatus(_token) == ValueTaskSourceStatus.Canceled); + get + { + object obj = _obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj == null) + { + return false; + } + + if (obj is Task t) + { + return t.IsCanceled; + } + + return Unsafe.As(obj).GetStatus(_token) == ValueTaskSourceStatus.Canceled; + } } /// Throws the exception that caused the to fail. If it completed successfully, nothing is thrown. @@ -326,19 +391,22 @@ namespace System.Threading.Tasks [StackTraceHidden] internal void ThrowIfCompletedUnsuccessfully() { - if (_obj != null) + object obj = _obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj != null) { - if (ObjectIsTask) + if (obj is Task t) { #if netstandard - UnsafeTask.GetAwaiter().GetResult(); + t.GetAwaiter().GetResult(); #else - TaskAwaiter.ValidateEnd(UnsafeGetTask()); + TaskAwaiter.ValidateEnd(t); #endif } else { - UnsafeGetValueTaskSource().GetResult(_token); + Unsafe.As(obj).GetResult(_token); } } } @@ -351,34 +419,51 @@ namespace System.Threading.Tasks /// true to attempt to marshal the continuation back to the captured context; otherwise, false. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) - { - // TODO: Simplify once https://github.com/dotnet/coreclr/pull/16138 is fixed. - bool avoidCapture = !continueOnCapturedContext; - return new ConfiguredValueTaskAwaitable(new ValueTask(_obj, _token, _flags | Unsafe.As(ref avoidCapture))); - } + public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) => + new ConfiguredValueTaskAwaitable(new ValueTask(_obj, _token, continueOnCapturedContext)); } /// Provides a value type that can represent a synchronously available value or a task object. /// Specifies the type of the result. /// - /// s are meant to be directly awaited. To do more complicated operations with them, a - /// should be extracted using or . Such operations might include caching an instance to - /// be awaited later, registering multiple continuations with a single operation, awaiting the same task multiple times, and using - /// combinators over multiple operations. + /// instances are meant to be directly awaited. To do more complicated operations with them, a + /// should be extracted using . Such operations might include caching a task instance to be awaited later, + /// registering multiple continuations with a single task, awaiting the same task multiple times, and using combinators over + /// multiple operations: + /// + /// + /// Once the result of a instance has been retrieved, do not attempt to retrieve it again. + /// instances may be backed by instances that are reusable, and such + /// instances may use the act of retrieving the instances result as a notification that the instance may now be reused for + /// a different operation. Attempting to then reuse that same results in undefined behavior. + /// + /// + /// Do not attempt to add multiple continuations to the same . While this might work if the + /// wraps a T or a , it may not work if the + /// was constructed from an . + /// + /// + /// Some operations that return a may invalidate it based on some subsequent operation being performed. + /// Unless otherwise documented, assume that a should be awaited prior to performing any additional operations + /// on the instance from which it was retrieved. + /// + /// /// [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder<>))] [StructLayout(LayoutKind.Auto)] public readonly struct ValueTask : IEquatable> { + /// A task canceled using `new CancellationToken(true)`. Lazily created only when first needed. + private static Task s_canceledTask; /// null if has the result, otherwise a or a . internal readonly object _obj; /// The result to be used if the operation completed successfully synchronously. internal readonly TResult _result; - /// Flags providing additional details about the ValueTask's contents and behavior. - internal readonly ValueTaskFlags _flags; /// Opaque value passed through to the . internal readonly short _token; + /// true to continue on the captured context; otherwise, false. + /// Stored in the rather than in the configured awaiter to utilize otherwise padding space. + internal readonly bool _continueOnCapturedContext; // An instance created with the default ctor (a zero init'd struct) represents a synchronously, successfully completed operation // with a result of default(TResult). @@ -391,7 +476,7 @@ namespace System.Threading.Tasks _result = result; _obj = null; - _flags = 0; + _continueOnCapturedContext = true; _token = 0; } @@ -408,7 +493,7 @@ namespace System.Threading.Tasks _obj = task; _result = default; - _flags = ValueTaskFlags.ObjectIsTask; + _continueOnCapturedContext = true; _token = 0; } @@ -427,54 +512,23 @@ namespace System.Threading.Tasks _token = token; _result = default; - _flags = 0; + _continueOnCapturedContext = true; } /// Non-verified initialization of the struct to the specified values. /// The object. /// The result. /// The token. - /// The flags. + /// true to continue on captured context; otherwise, false. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private ValueTask(object obj, TResult result, short token, ValueTaskFlags flags) + private ValueTask(object obj, TResult result, short token, bool continueOnCapturedContext) { _obj = obj; _result = result; _token = token; - _flags = flags; + _continueOnCapturedContext = continueOnCapturedContext; } - /// Gets whether the contination should be scheduled to the current context. - internal bool ContinueOnCapturedContext - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => (_flags & ValueTaskFlags.AvoidCapturedContext) == 0; - } - - /// Gets whether the object in the field is a . - internal bool ObjectIsTask - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => (_flags & ValueTaskFlags.ObjectIsTask) != 0; - } - - /// Returns the stored in . This uses . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal Task UnsafeGetTask() - { - Debug.Assert(ObjectIsTask); - Debug.Assert(_obj is Task); - return Unsafe.As>(_obj); - } - - /// Returns the stored in . This uses . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal IValueTaskSource UnsafeGetValueTaskSource() - { - Debug.Assert(!ObjectIsTask); - Debug.Assert(_obj is IValueTaskSource); - return Unsafe.As>(_obj); - } /// Returns the hash code for this instance. public override int GetHashCode() => @@ -508,23 +562,39 @@ namespace System.Threading.Tasks /// It will either return the wrapped task object if one exists, or it'll /// manufacture a new task object to represent the result. /// - public Task AsTask() => - _obj == null ? + public Task AsTask() + { + object obj = _obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj == null) + { + return #if netstandard - Task.FromResult(_result) : + Task.FromResult(_result); #else - AsyncTaskMethodBuilder.GetTaskForResult(_result) : + AsyncTaskMethodBuilder.GetTaskForResult(_result); #endif - ObjectIsTask ? UnsafeGetTask() : - GetTaskForValueTaskSource(); + } + + if (obj is Task t) + { + return t; + } + + return GetTaskForValueTaskSource(Unsafe.As>(obj)); + } /// Gets a that may be used at any point in the future. public ValueTask Preserve() => _obj == null ? this : new ValueTask(AsTask()); /// Creates a to represent the . - private Task GetTaskForValueTaskSource() + /// + /// The is passed in rather than reading and casting + /// so that the caller can pass in an object it's already validated. + /// + private Task GetTaskForValueTaskSource(IValueTaskSource t) { - IValueTaskSource t = UnsafeGetValueTaskSource(); ValueTaskSourceStatus status = t.GetStatus(_token); if (status != ValueTaskSourceStatus.Pending) { @@ -548,22 +618,29 @@ namespace System.Threading.Tasks { if (status == ValueTaskSourceStatus.Canceled) { -#if netstandard - var tcs = new TaskCompletionSource(); - tcs.TrySetCanceled(); - return tcs.Task; -#else +#if !netstandard if (exc is OperationCanceledException oce) { var task = new Task(); task.TrySetCanceled(oce.CancellationToken, oce); return task; } - else - { - return Task.FromCanceled(new CancellationToken(true)); - } #endif + + Task canceledTask = s_canceledTask; + if (canceledTask == null) + { +#if netstandard + var tcs = new TaskCompletionSource(); + tcs.TrySetCanceled(); + canceledTask = tcs.Task; +#else + canceledTask = Task.FromCanceled(new CancellationToken(true)); +#endif + // Benign race condition to initialize cached task, as identity doesn't matter. + s_canceledTask = canceledTask; + } + return canceledTask; } else { @@ -578,7 +655,7 @@ namespace System.Threading.Tasks } } - var m = new ValueTaskSourceTask(t, _token); + var m = new ValueTaskSourceAsTask(t, _token); return #if netstandard m.Task; @@ -588,7 +665,7 @@ namespace System.Threading.Tasks } /// Type used to create a to represent a . - private sealed class ValueTaskSourceTask : + private sealed class ValueTaskSourceAsTask : #if netstandard TaskCompletionSource #else @@ -597,7 +674,7 @@ namespace System.Threading.Tasks { private static readonly Action s_completionAction = state => { - if (!(state is ValueTaskSourceTask vtst) || + if (!(state is ValueTaskSourceAsTask vtst) || !(vtst._source is IValueTaskSource source)) { // This could only happen if the IValueTaskSource passed the wrong state @@ -642,7 +719,7 @@ namespace System.Threading.Tasks /// The token to pass through to operations on private readonly short _token; - public ValueTaskSourceTask(IValueTaskSource source, short token) + public ValueTaskSourceAsTask(IValueTaskSource source, short token) { _source = source; _token = token; @@ -654,30 +731,73 @@ namespace System.Threading.Tasks public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => _obj == null || (ObjectIsTask ? UnsafeGetTask().IsCompleted : UnsafeGetValueTaskSource().GetStatus(_token) != ValueTaskSourceStatus.Pending); + get + { + object obj = _obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj == null) + { + return true; + } + + if (obj is Task t) + { + return t.IsCompleted; + } + + return Unsafe.As>(obj).GetStatus(_token) != ValueTaskSourceStatus.Pending; + } } /// Gets whether the represents a successfully completed operation. public bool IsCompletedSuccessfully { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => - _obj == null || - (ObjectIsTask ? + get + { + object obj = _obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj == null) + { + return true; + } + + if (obj is Task t) + { + return #if netstandard - UnsafeTask.Status == TaskStatus.RanToCompletion : + t.Status == TaskStatus.RanToCompletion; #else - UnsafeGetTask().IsCompletedSuccessfully : + t.IsCompletedSuccessfully; #endif - UnsafeGetValueTaskSource().GetStatus(_token) == ValueTaskSourceStatus.Succeeded); + } + + return Unsafe.As>(obj).GetStatus(_token) == ValueTaskSourceStatus.Succeeded; + } } /// Gets whether the represents a failed operation. public bool IsFaulted { - get => - _obj != null && - (ObjectIsTask ? UnsafeGetTask().IsFaulted : UnsafeGetValueTaskSource().GetStatus(_token) == ValueTaskSourceStatus.Faulted); + get + { + object obj = _obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj == null) + { + return false; + } + + if (obj is Task t) + { + return t.IsFaulted; + } + + return Unsafe.As>(obj).GetStatus(_token) == ValueTaskSourceStatus.Faulted; + } } /// Gets whether the represents a canceled operation. @@ -688,9 +808,23 @@ namespace System.Threading.Tasks /// public bool IsCanceled { - get => - _obj != null && - (ObjectIsTask ? UnsafeGetTask().IsCanceled : UnsafeGetValueTaskSource().GetStatus(_token) == ValueTaskSourceStatus.Canceled); + get + { + object obj = _obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj == null) + { + return false; + } + + if (obj is Task t) + { + return t.IsCanceled; + } + + return Unsafe.As>(obj).GetStatus(_token) == ValueTaskSourceStatus.Canceled; + } } /// Gets the result. @@ -699,23 +833,25 @@ namespace System.Threading.Tasks [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - if (_obj == null) + object obj = _obj; + Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); + + if (obj == null) { return _result; } - if (ObjectIsTask) + if (obj is Task t) { #if netstandard - return UnsafeTask.GetAwaiter().GetResult(); + return t.GetAwaiter().GetResult(); #else - Task t = UnsafeGetTask(); TaskAwaiter.ValidateEnd(t); return t.ResultOnSuccess; #endif } - return UnsafeGetValueTaskSource().GetResult(_token); + return Unsafe.As>(obj).GetResult(_token); } } @@ -728,12 +864,8 @@ namespace System.Threading.Tasks /// true to attempt to marshal the continuation back to the captured context; otherwise, false. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) - { - // TODO: Simplify once https://github.com/dotnet/coreclr/pull/16138 is fixed. - bool avoidCapture = !continueOnCapturedContext; - return new ConfiguredValueTaskAwaitable(new ValueTask(_obj, _result, _token, _flags | Unsafe.As(ref avoidCapture))); - } + public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) => + new ConfiguredValueTaskAwaitable(new ValueTask(_obj, _result, _token, continueOnCapturedContext)); /// Gets a string-representation of this . public override string ToString() @@ -750,26 +882,4 @@ namespace System.Threading.Tasks return string.Empty; } } - - /// Internal flags used in the implementation of and . - [Flags] - internal enum ValueTaskFlags : byte - { - /// - /// Indicates that context (e.g. SynchronizationContext) should not be captured when adding - /// a continuation. - /// - /// - /// The value here must be 0x1, to match the value of a true Boolean reinterpreted as a byte. - /// This only has meaning when awaiting a ValueTask, with ConfigureAwait creating a new - /// ValueTask setting or not setting this flag appropriately. - /// - AvoidCapturedContext = 0x1, - - /// - /// Indicates that the ValueTask's object field stores a Task. This is used to avoid - /// a type check on whatever is stored in the object field. - /// - ObjectIsTask = 0x2 - } -} \ No newline at end of file +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadInterruptedException.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/ThreadInterruptedException.cs similarity index 61% rename from external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadInterruptedException.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Threading/ThreadInterruptedException.cs index 8a10cc9c99..13fa1e91bc 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadInterruptedException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/ThreadInterruptedException.cs @@ -2,45 +2,44 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: An exception class to indicate that the thread was interrupted -** from a waiting state. -** -** -=============================================================================*/ - using System.Runtime.Serialization; namespace System.Threading { + /// + /// An exception class to indicate that the thread was interrupted from a waiting state. + /// [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public class ThreadInterruptedException : SystemException { - public ThreadInterruptedException() - : base(SR.Threading_ThreadInterrupted) + public ThreadInterruptedException() : base( +#if CORECLR + GetMessageFromNativeResources(ExceptionMessageKind.ThreadInterrupted) +#else + SR.Threading_ThreadInterrupted +#endif + ) { HResult = HResults.COR_E_THREADINTERRUPTED; } - public ThreadInterruptedException(String message) + public ThreadInterruptedException(string message) : base(message) { HResult = HResults.COR_E_THREADINTERRUPTED; } - public ThreadInterruptedException(String message, Exception innerException) + public ThreadInterruptedException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_THREADINTERRUPTED; } - protected ThreadInterruptedException(SerializationInfo info, StreamingContext context) - : base(info, context) + protected ThreadInterruptedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } -} +} \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/ThreadLocal.cs similarity index 80% rename from external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs rename to external/corert/src/System.Private.CoreLib/shared/System/Threading/ThreadLocal.cs index 0a8c845acf..9f4beae9cf 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/ThreadLocal.cs @@ -1,24 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#pragma warning disable 0420 -// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ -// -// +using System.Collections.Generic; +using System.Diagnostics; -// // A class that provides a simple, lightweight implementation of thread-local lazy-initialization, where a value is initialized once per accessing // thread; this provides an alternative to using a ThreadStatic static variable and having // to check the variable prior to every access to see if it's been initialized. -// -// -// -// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- - -using System.Diagnostics; -using System.Diagnostics.Private; -using System.Collections.Generic; namespace System.Threading { @@ -38,15 +27,13 @@ namespace System.Threading public class ThreadLocal : IDisposable { // a delegate that returns the created value, if null the created value will be default(T) - private Func m_valueFactory; + private Func _valueFactory; - // // ts_slotArray is a table of thread-local values for all ThreadLocal instances // // So, when a thread reads ts_slotArray, it gets back an array of *all* ThreadLocal values for this thread and this T. - // The slot relevant to this particular ThreadLocal instance is determined by the m_idComplement instance field stored in + // The slot relevant to this particular ThreadLocal instance is determined by the _idComplement instance field stored in // the ThreadLocal instance. - // [ThreadStatic] private static LinkedSlotVolatile[] ts_slotArray; @@ -56,22 +43,22 @@ namespace System.Threading // Slot ID of this ThreadLocal<> instance. We store a bitwise complement of the ID (that is ~ID), which allows us to distinguish // between the case when ID is 0 and an incompletely initialized object, either due to a thread abort in the constructor, or // possibly due to a memory model issue in user code. - private int m_idComplement; + private int _idComplement; // This field is set to true when the constructor completes. That is helpful for recognizing whether a constructor // threw an exception - either due to invalid argument or due to a thread abort. Finally, the field is set to false // when the instance is disposed. - private volatile bool m_initialized; + private volatile bool _initialized; // IdManager assigns and reuses slot IDs. Additionally, the object is also used as a global lock. private static IdManager s_idManager = new IdManager(); // A linked list of all values associated with this ThreadLocal instance. // We create a dummy head node. That allows us to remove any (non-dummy) node without having to locate the m_linkedSlot field. - private LinkedSlot m_linkedSlot = new LinkedSlot(null); + private LinkedSlot _linkedSlot = new LinkedSlot(null); // Whether the Values property is supported - private bool m_trackAllValues; + private bool _trackAllValues; /// /// Initializes the instance. @@ -132,19 +119,19 @@ namespace System.Threading private void Initialize(Func valueFactory, bool trackAllValues) { - m_valueFactory = valueFactory; - m_trackAllValues = trackAllValues; + _valueFactory = valueFactory; + _trackAllValues = trackAllValues; - // Assign the ID and mark the instance as initialized. To avoid leaking IDs, we assign the ID and set m_initialized + // Assign the ID and mark the instance as initialized. To avoid leaking IDs, we assign the ID and set _initialized // in a finally block, to avoid a thread abort in between the two statements. try { } finally { - m_idComplement = ~s_idManager.GetId(); + _idComplement = ~s_idManager.GetId(); - // As the last step, mark the instance as fully initialized. (Otherwise, if m_initialized=false, we know that an exception + // As the last step, mark the instance as fully initialized. (Otherwise, if _initialized=false, we know that an exception // occurred in the constructor.) - m_initialized = true; + _initialized = true; } } @@ -184,23 +171,23 @@ namespace System.Threading { int id; - using (LockHolder.Hold(s_idManager.m_lock)) + lock (s_idManager) { - id = ~m_idComplement; - m_idComplement = 0; + id = ~_idComplement; + _idComplement = 0; - if (id < 0 || !m_initialized) + if (id < 0 || !_initialized) { - Debug.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized"); + Debug.Assert(id >= 0 || !_initialized, "expected id >= 0 if initialized"); // Handle double Dispose calls or disposal of an instance whose constructor threw an exception. return; } - m_initialized = false; + _initialized = false; - for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next) + for (LinkedSlot linkedSlot = _linkedSlot._next; linkedSlot != null; linkedSlot = linkedSlot._next) { - LinkedSlotVolatile[] slotArray = linkedSlot.SlotArray; + LinkedSlotVolatile[] slotArray = linkedSlot._slotArray; if (slotArray == null) { @@ -209,15 +196,15 @@ namespace System.Threading } // Remove the reference from the LinkedSlot to the slot table. - linkedSlot.SlotArray = null; + linkedSlot._slotArray = null; // And clear the references from the slot table to the linked slot and the value so that // both can get garbage collected. - slotArray[id].Value.Value = default(T); + slotArray[id].Value._value = default; slotArray[id].Value = null; } } - m_linkedSlot = null; + _linkedSlot = null; s_idManager.ReturnId(id); } @@ -266,7 +253,7 @@ namespace System.Threading { LinkedSlotVolatile[] slotArray = ts_slotArray; LinkedSlot slot; - int id = ~m_idComplement; + int id = ~_idComplement; // // Attempt to get the value using the fast path @@ -275,7 +262,7 @@ namespace System.Threading && id >= 0 // Is the ID non-negative (i.e., instance is not disposed)? && id < slotArray.Length // Is the table large enough? && (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID? - && m_initialized // Has the instance *still* not been disposed (important for races with Dispose)? + && _initialized // Has the instance *still* not been disposed (important for a race condition with Dispose)? ) { // We verified that the instance has not been disposed *after* we got a reference to the slot. @@ -283,7 +270,7 @@ namespace System.Threading // // Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read // will not be reordered before the read of slotArray[id]. - return slot.Value; + return slot._value; } return GetValueSlow(); @@ -292,16 +279,14 @@ namespace System.Threading { LinkedSlotVolatile[] slotArray = ts_slotArray; LinkedSlot slot; - int id = ~m_idComplement; + int id = ~_idComplement; - // // Attempt to set the value using the fast path - // if (slotArray != null // Has the slot array been initialized? && id >= 0 // Is the ID non-negative (i.e., instance is not disposed)? && id < slotArray.Length // Is the table large enough? && (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID? - && m_initialized // Has the instance *still* not been disposed (important for races with Dispose)? + && _initialized // Has the instance *still* not been disposed (important for a race condition with Dispose)? ) { // We verified that the instance has not been disposed *after* we got a reference to the slot. @@ -309,7 +294,7 @@ namespace System.Threading // // Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read // will not be reordered before the read of slotArray[id]. - slot.Value = value; + slot._value = value; } else { @@ -321,23 +306,23 @@ namespace System.Threading private T GetValueSlow() { // If the object has been disposed, the id will be -1. - int id = ~m_idComplement; + int id = ~_idComplement; if (id < 0) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } - //Debugger.NotifyOfCrossThreadDependency(); + Debugger.NotifyOfCrossThreadDependency(); // Determine the initial value T value; - if (m_valueFactory == null) + if (_valueFactory == null) { - value = default(T); + value = default; } else { - value = m_valueFactory(); + value = _valueFactory(); if (IsValueCreated) { @@ -352,7 +337,7 @@ namespace System.Threading private void SetValueSlow(T value, LinkedSlotVolatile[] slotArray) { - int id = ~m_idComplement; + int id = ~_idComplement; // If the object has been disposed, id will be -1. if (id < 0) @@ -364,7 +349,7 @@ namespace System.Threading if (slotArray == null) { slotArray = new LinkedSlotVolatile[GetNewTableSize(id + 1)]; - ts_finalizationHelper = new FinalizationHelper(slotArray, m_trackAllValues); + ts_finalizationHelper = new FinalizationHelper(slotArray, _trackAllValues); ts_slotArray = slotArray; } @@ -393,12 +378,12 @@ namespace System.Threading // if this ThreadLocal instance was disposed on another thread and another ThreadLocal instance was // created, we definitely won't assign the value into the wrong instance. - if (!m_initialized) + if (!_initialized) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } - slot.Value = value; + slot._value = value; } } @@ -411,32 +396,30 @@ namespace System.Threading var linkedSlot = new LinkedSlot(slotArray); // Insert the LinkedSlot into the linked list maintained by this ThreadLocal<> instance and into the slot array - using (LockHolder.Hold(s_idManager.m_lock)) + lock (s_idManager) { // Check that the instance has not been disposed. It is important to check this under a lock, since // Dispose also executes under a lock. - if (!m_initialized) + if (!_initialized) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } - LinkedSlot firstRealNode = m_linkedSlot.Next; + LinkedSlot firstRealNode = _linkedSlot._next; - // // Insert linkedSlot between nodes m_linkedSlot and firstRealNode. - // (m_linkedSlot is the dummy head node that should always be in the front.) - // - linkedSlot.Next = firstRealNode; - linkedSlot.Previous = m_linkedSlot; - linkedSlot.Value = value; + // (_linkedSlot is the dummy head node that should always be in the front.) + linkedSlot._next = firstRealNode; + linkedSlot._previous = _linkedSlot; + linkedSlot._value = value; if (firstRealNode != null) { - firstRealNode.Previous = linkedSlot; + firstRealNode._previous = linkedSlot; } - m_linkedSlot.Next = linkedSlot; + _linkedSlot._next = linkedSlot; - // Assigning the slot under a lock prevents a race with Dispose (dispose also acquires the lock). + // Assigning the slot under a lock prevents a race condition with Dispose (dispose also acquires the lock). // Otherwise, it would be possible that the ThreadLocal instance is disposed, another one gets created // with the same ID, and the write would go to the wrong instance. slotArray[id].Value = linkedSlot; @@ -453,7 +436,7 @@ namespace System.Threading { get { - if (!m_trackAllValues) + if (!_trackAllValues) { throw new InvalidOperationException(SR.ThreadLocal_ValuesNotAvailable); } @@ -465,21 +448,21 @@ namespace System.Threading } /// Gets all of the threads' values in a list. - private LowLevelListWithIList GetValuesAsList() + private List GetValuesAsList() { - LowLevelListWithIList valueList = new LowLevelListWithIList(); - int id = ~m_idComplement; + List valueList = new List(); + int id = ~_idComplement; if (id == -1) { return null; } // Walk over the linked list of slots and gather the values associated with this ThreadLocal instance. - for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next) + for (LinkedSlot linkedSlot = _linkedSlot._next; linkedSlot != null; linkedSlot = linkedSlot._next) { // We can safely read linkedSlot.Value. Even if this ThreadLocal has been disposed in the meantime, the LinkedSlot // objects will never be assigned to another ThreadLocal instance. - valueList.Add(linkedSlot.Value); + valueList.Add(linkedSlot._value); } return valueList; @@ -491,7 +474,7 @@ namespace System.Threading get { int count = 0; - for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next) + for (LinkedSlot linkedSlot = _linkedSlot._next; linkedSlot != null; linkedSlot = linkedSlot._next) { count++; } @@ -509,7 +492,7 @@ namespace System.Threading { get { - int id = ~m_idComplement; + int id = ~_idComplement; if (id < 0) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); @@ -528,17 +511,17 @@ namespace System.Threading get { LinkedSlotVolatile[] slotArray = ts_slotArray; - int id = ~m_idComplement; + int id = ~_idComplement; LinkedSlot slot; - if (slotArray == null || id >= slotArray.Length || (slot = slotArray[id].Value) == null || !m_initialized) - return default(T); - return slot.Value; + if (slotArray == null || id >= slotArray.Length || (slot = slotArray[id].Value) == null || !_initialized) + return default; + return slot._value; } } /// Gets the values of all threads that accessed the ThreadLocal<T>. - internal IList ValuesForDebugDisplay // same as Values property, but doesn't throw if disposed + internal List ValuesForDebugDisplay // same as Values property, but doesn't throw if disposed { get { return GetValuesAsList(); } } @@ -560,14 +543,14 @@ namespace System.Threading // Dispose could use a stale SlotArray reference and clear out a slot in the old array only, while // the value continues to be referenced from the new (larger) array. // - using (LockHolder.Hold(s_idManager.m_lock)) + lock (s_idManager) { for (int i = 0; i < table.Length; i++) { LinkedSlot linkedSlot = table[i].Value; - if (linkedSlot != null && linkedSlot.SlotArray != null) + if (linkedSlot != null && linkedSlot._slotArray != null) { - linkedSlot.SlotArray = newTable; + linkedSlot._slotArray = newTable; newTable[i] = table[i]; } } @@ -576,14 +559,12 @@ namespace System.Threading table = newTable; } - private const int MaxArrayLength = int.MaxValue; - /// /// Chooses the next larger table size /// private static int GetNewTableSize(int minSize) { - if ((uint)minSize > MaxArrayLength) + if ((uint)minSize > Array.MaxArrayLength) { // Intentionally return a value that will result in an OutOfMemoryException return int.MaxValue; @@ -594,13 +575,13 @@ namespace System.Threading // Round up the size to the next power of 2 // // The algorithm takes three steps: - // input -> subtract one -> propagate 1-bits to the right -> add one + // input -> subtract one -> propagate 1-bits to the right -> add one // // Let's take a look at the 3 steps in both interesting cases: where the input // is (Example 1) and isn't (Example 2) a power of 2. // - // Example 1: 100000 -> 011111 -> 011111 -> 100000 - // Example 2: 011010 -> 011001 -> 011111 -> 100000 + // Example 1: 100000 -> 011111 -> 011111 -> 100000 + // Example 2: 011010 -> 011001 -> 011111 -> 100000 // int newSize = minSize; @@ -618,9 +599,9 @@ namespace System.Threading newSize++; // Don't set newSize to more than Array.MaxArrayLength - if ((uint)newSize > MaxArrayLength) + if ((uint)newSize > Array.MaxArrayLength) { - newSize = MaxArrayLength; + newSize = Array.MaxArrayLength; } return newSize; @@ -630,7 +611,7 @@ namespace System.Threading /// A wrapper struct used as LinkedSlotVolatile[] - an array of LinkedSlot instances, but with volatile semantics /// on array accesses. /// - internal struct LinkedSlotVolatile + private struct LinkedSlotVolatile { internal volatile LinkedSlot Value; } @@ -643,24 +624,24 @@ namespace System.Threading /// 1. If SlotArray is not null, the value is in SlotArray.Table[id] /// 2. If SlotArray is null, the value is in FinalValue. /// - internal sealed class LinkedSlot + private sealed class LinkedSlot { internal LinkedSlot(LinkedSlotVolatile[] slotArray) { - SlotArray = slotArray; + _slotArray = slotArray; } // The next LinkedSlot for this ThreadLocal<> instance - internal volatile LinkedSlot Next; + internal volatile LinkedSlot _next; // The previous LinkedSlot for this ThreadLocal<> instance - internal volatile LinkedSlot Previous; + internal volatile LinkedSlot _previous; // The SlotArray that stores this LinkedSlot at SlotArray.Table[id]. - internal volatile LinkedSlotVolatile[] SlotArray; + internal volatile LinkedSlotVolatile[] _slotArray; // The value for this slot. - internal T Value; + internal T _value; } /// @@ -669,34 +650,32 @@ namespace System.Threading private class IdManager { // The next ID to try - private int m_nextIdToTry = 0; + private int _nextIdToTry = 0; // Stores whether each ID is free or not. Additionally, the object is also used as a lock for the IdManager. - private LowLevelList m_freeIds = new LowLevelList(); - - internal Lock m_lock = new Lock(); + private List _freeIds = new List(); internal int GetId() { - using (LockHolder.Hold(m_lock)) + lock (_freeIds) { - int availableId = m_nextIdToTry; - while (availableId < m_freeIds.Count) + int availableId = _nextIdToTry; + while (availableId < _freeIds.Count) { - if (m_freeIds[availableId]) { break; } + if (_freeIds[availableId]) { break; } availableId++; } - if (availableId == m_freeIds.Count) + if (availableId == _freeIds.Count) { - m_freeIds.Add(false); + _freeIds.Add(false); } else { - m_freeIds[availableId] = false; + _freeIds[availableId] = false; } - m_nextIdToTry = availableId + 1; + _nextIdToTry = availableId + 1; return availableId; } @@ -705,10 +684,10 @@ namespace System.Threading // Return an ID to the pool internal void ReturnId(int id) { - using (LockHolder.Hold(m_lock)) + lock (_freeIds) { - m_freeIds[id] = true; - if (id < m_nextIdToTry) m_nextIdToTry = id; + _freeIds[id] = true; + if (id < _nextIdToTry) _nextIdToTry = id; } } } @@ -717,7 +696,7 @@ namespace System.Threading /// A class that facilitates ThreadLocal cleanup after a thread exits. /// /// After a thread with an associated thread-local table has exited, the FinalizationHelper - /// is reponsible for removing back-references to the table. Since an instance of FinalizationHelper + /// is responsible for removing back-references to the table. Since an instance of FinalizationHelper /// is only referenced from a single thread-local slot, the FinalizationHelper will be GC'd once /// the thread has exited. /// @@ -725,15 +704,15 @@ namespace System.Threading /// (all those LinkedSlot instances can be found by following references from the table slots) and /// releases the table so that it can get GC'd. /// - internal class FinalizationHelper + private class FinalizationHelper { internal LinkedSlotVolatile[] SlotArray; - private bool m_trackAllValues; + private bool _trackAllValues; internal FinalizationHelper(LinkedSlotVolatile[] slotArray, bool trackAllValues) { SlotArray = slotArray; - m_trackAllValues = trackAllValues; + _trackAllValues = trackAllValues; } ~FinalizationHelper() @@ -750,25 +729,25 @@ namespace System.Threading continue; } - if (m_trackAllValues) + if (_trackAllValues) { // Set the SlotArray field to null to release the slot array. - linkedSlot.SlotArray = null; + linkedSlot._slotArray = null; } else { // Remove the LinkedSlot from the linked list. Once the FinalizationHelper is done, all back-references to // the table will be have been removed, and so the table can get GC'd. - using (LockHolder.Hold(s_idManager.m_lock)) + lock (s_idManager) { - if (linkedSlot.Next != null) + if (linkedSlot._next != null) { - linkedSlot.Next.Previous = linkedSlot.Previous; + linkedSlot._next._previous = linkedSlot._previous; } // Since the list uses a dummy head node, the Previous reference should never be null. - Debug.Assert(linkedSlot.Previous != null); - linkedSlot.Previous.Next = linkedSlot.Next; + Debug.Assert(linkedSlot._previous != null); + linkedSlot._previous._next = linkedSlot._next; } } } @@ -781,37 +760,22 @@ namespace System.Threading internal sealed class SystemThreading_ThreadLocalDebugView { //The ThreadLocal object being viewed. - private readonly ThreadLocal m_tlocal; + private readonly ThreadLocal _tlocal; /// Constructs a new debugger view object for the provided ThreadLocal object. /// A ThreadLocal object to browse in the debugger. public SystemThreading_ThreadLocalDebugView(ThreadLocal tlocal) { - m_tlocal = tlocal; + _tlocal = tlocal; } /// Returns whether the ThreadLocal object is initialized or not. - public bool IsValueCreated - { - get { return m_tlocal.IsValueCreated; } - } + public bool IsValueCreated => _tlocal.IsValueCreated; /// Returns the value of the ThreadLocal object. - public T Value - { - get - { - return m_tlocal.ValueForDebugDisplay; - } - } + public T Value => _tlocal.ValueForDebugDisplay; /// Return all values for all threads that have accessed this instance. - public IList Values - { - get - { - return m_tlocal.ValuesForDebugDisplay; - } - } + public List Values => _tlocal.ValuesForDebugDisplay; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/ThreadStateException.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/ThreadStateException.cs index 6fc06a8516..d9ba48dfc8 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Threading/ThreadStateException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/ThreadStateException.cs @@ -26,13 +26,13 @@ namespace System.Threading HResult = HResults.COR_E_THREADSTATE; } - public ThreadStateException(String message) + public ThreadStateException(string message) : base(message) { HResult = HResults.COR_E_THREADSTATE; } - public ThreadStateException(String message, Exception innerException) + public ThreadStateException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_THREADSTATE; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/TimeoutHelper.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/TimeoutHelper.cs index c96a4d00d6..dd3291281e 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Threading/TimeoutHelper.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/TimeoutHelper.cs @@ -7,16 +7,16 @@ using System.Diagnostics; namespace System.Threading { /// - /// A helper class to capture a start time using Environment.TickCout as a time in milliseconds, also updates a given timeout bu subtracting the current time from - /// the start time + /// A helper class to capture a start time using as a time in milliseconds. + /// Also updates a given timeout by subtracting the current time from the start time. /// internal static class TimeoutHelper { /// - /// Returns the Environment.TickCount as a start time in milliseconds as a uint, TickCount tools over from positive to negative every ~ 25 days - /// then ~25 days to back to positive again, uint is sued to ignore the sign and double the range to 50 days + /// Returns as a start time in milliseconds as a . + /// rolls over from positive to negative every ~25 days, then ~25 days to back to positive again. + /// is used to ignore the sign and double the range to 50 days. /// - /// public static uint GetTime() { return (uint)Environment.TickCount; @@ -27,7 +27,7 @@ namespace System.Threading /// /// The first time (in milliseconds) observed when the wait started /// The original wait timeout in milliseconds - /// The new wait time in milliseconds, -1 if the time expired + /// The new wait time in milliseconds, or -1 if the time expired public static int UpdateTimeOut(uint startTime, int originalWaitMillisecondsTimeout) { // The function must be called in case the time out is not infinite @@ -42,7 +42,7 @@ namespace System.Threading } // Subtract the elapsed time from the current wait time - int currentWaitTimeout = originalWaitMillisecondsTimeout - (int)elapsedMilliseconds; ; + int currentWaitTimeout = originalWaitMillisecondsTimeout - (int)elapsedMilliseconds; if (currentWaitTimeout <= 0) { return 0; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs b/external/corert/src/System.Private.CoreLib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs index e60e46d2be..60821542b5 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs @@ -15,12 +15,12 @@ namespace System.Threading HResult = HResults.COR_E_WAITHANDLECANNOTBEOPENED; } - public WaitHandleCannotBeOpenedException(String message) : base(message) + public WaitHandleCannotBeOpenedException(string message) : base(message) { HResult = HResults.COR_E_WAITHANDLECANNOTBEOPENED; } - public WaitHandleCannotBeOpenedException(String message, Exception innerException) : base(message, innerException) + public WaitHandleCannotBeOpenedException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_WAITHANDLECANNOTBEOPENED; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/TimeSpan.cs b/external/corert/src/System.Private.CoreLib/shared/System/TimeSpan.cs index 4293ed505b..10bdb331bb 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/TimeSpan.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/TimeSpan.cs @@ -28,13 +28,13 @@ namespace System // an appropriate custom ILMarshaler to keep WInRT interop scenarios enabled. // [Serializable] - public struct TimeSpan : IComparable, IComparable, IEquatable, IFormattable, ISpanFormattable + public readonly struct TimeSpan : IComparable, IComparable, IEquatable, IFormattable, ISpanFormattable { public const long TicksPerMillisecond = 10000; private const double MillisecondsPerTick = 1.0 / TicksPerMillisecond; public const long TicksPerSecond = TicksPerMillisecond * 1000; // 10,000,000 - private const double SecondsPerTick = 1.0 / TicksPerSecond; // 0.0001 + private const double SecondsPerTick = 1.0 / TicksPerSecond; // 0.0000001 public const long TicksPerMinute = TicksPerSecond * 60; // 600,000,000 private const double MinutesPerTick = 1.0 / TicksPerMinute; // 1.6666666666667e-9 @@ -50,22 +50,22 @@ namespace System private const int MillisPerHour = MillisPerMinute * 60; // 3,600,000 private const int MillisPerDay = MillisPerHour * 24; // 86,400,000 - internal const long MaxSeconds = Int64.MaxValue / TicksPerSecond; - internal const long MinSeconds = Int64.MinValue / TicksPerSecond; + internal const long MaxSeconds = long.MaxValue / TicksPerSecond; + internal const long MinSeconds = long.MinValue / TicksPerSecond; - internal const long MaxMilliSeconds = Int64.MaxValue / TicksPerMillisecond; - internal const long MinMilliSeconds = Int64.MinValue / TicksPerMillisecond; + internal const long MaxMilliSeconds = long.MaxValue / TicksPerMillisecond; + internal const long MinMilliSeconds = long.MinValue / TicksPerMillisecond; internal const long TicksPerTenthSecond = TicksPerMillisecond * 100; public static readonly TimeSpan Zero = new TimeSpan(0); - public static readonly TimeSpan MaxValue = new TimeSpan(Int64.MaxValue); - public static readonly TimeSpan MinValue = new TimeSpan(Int64.MinValue); + public static readonly TimeSpan MaxValue = new TimeSpan(long.MaxValue); + public static readonly TimeSpan MinValue = new TimeSpan(long.MinValue); // internal so that DateTime doesn't have to call an extra get // method for some arithmetic operations. - internal long _ticks; // Do not rename (binary serialization) + internal readonly long _ticks; // Do not rename (binary serialization) public TimeSpan(long ticks) { @@ -84,7 +84,7 @@ namespace System public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) { - Int64 totalMilliSeconds = ((Int64)days * 3600 * 24 + (Int64)hours * 3600 + (Int64)minutes * 60 + seconds) * 1000 + milliseconds; + long totalMilliSeconds = ((long)days * 3600 * 24 + (long)hours * 3600 + (long)minutes * 60 + seconds) * 1000 + milliseconds; if (totalMilliSeconds > MaxMilliSeconds || totalMilliSeconds < MinMilliSeconds) throw new ArgumentOutOfRangeException(null, SR.Overflow_TimeSpanTooLong); _ticks = (long)totalMilliSeconds * TicksPerMillisecond; @@ -178,7 +178,7 @@ namespace System } // Returns a value less than zero if this object - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) return 1; if (!(value is TimeSpan)) @@ -209,7 +209,7 @@ namespace System return new TimeSpan(_ticks >= 0 ? _ticks : -_ticks); } - public override bool Equals(Object value) + public override bool Equals(object value) { if (value is TimeSpan) { @@ -240,11 +240,11 @@ namespace System private static TimeSpan Interval(double value, int scale) { - if (Double.IsNaN(value)) + if (double.IsNaN(value)) throw new ArgumentException(SR.Arg_CannotBeNaN); double tmp = value * scale; double millis = tmp + (value >= 0 ? 0.5 : -0.5); - if ((millis > Int64.MaxValue / TicksPerMillisecond) || (millis < Int64.MinValue / TicksPerMillisecond)) + if ((millis > long.MaxValue / TicksPerMillisecond) || (millis < long.MinValue / TicksPerMillisecond)) throw new OverflowException(SR.Overflow_TimeSpanTooLong); return new TimeSpan((long)millis * TicksPerMillisecond); } @@ -305,18 +305,18 @@ namespace System // See System.Globalization.TimeSpanParse and System.Globalization.TimeSpanFormat #region ParseAndFormat - private static void ValidateStyles(TimeSpanStyles style, String parameterName) + private static void ValidateStyles(TimeSpanStyles style, string parameterName) { if (style != TimeSpanStyles.None && style != TimeSpanStyles.AssumeNegative) throw new ArgumentException(SR.Argument_InvalidTimeSpanStyles, parameterName); } - public static TimeSpan Parse(String s) + public static TimeSpan Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); /* Constructs a TimeSpan from a string. Leading and trailing white space characters are allowed. */ return TimeSpanParse.Parse(s, null); } - public static TimeSpan Parse(String input, IFormatProvider formatProvider) + public static TimeSpan Parse(string input, IFormatProvider formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return TimeSpanParse.Parse(input, formatProvider); @@ -325,18 +325,18 @@ namespace System { return TimeSpanParse.Parse(input, formatProvider); } - public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider) + public static TimeSpan ParseExact(string input, string format, IFormatProvider formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); return TimeSpanParse.ParseExact(input, format, formatProvider, TimeSpanStyles.None); } - public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider) + public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None); } - public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles) + public static TimeSpan ParseExact(string input, string format, IFormatProvider formatProvider, TimeSpanStyles styles) { ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); @@ -349,7 +349,7 @@ namespace System ValidateStyles(styles, nameof(styles)); return TimeSpanParse.ParseExact(input, format, formatProvider, styles); } - public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles) + public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles) { ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); @@ -360,11 +360,11 @@ namespace System ValidateStyles(styles, nameof(styles)); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles); } - public static Boolean TryParse(String s, out TimeSpan result) + public static bool TryParse(string s, out TimeSpan result) { if (s == null) { - result = default(TimeSpan); + result = default; return false; } return TimeSpanParse.TryParse(s, null, out result); @@ -374,11 +374,11 @@ namespace System return TimeSpanParse.TryParse(s, null, out result); } - public static Boolean TryParse(String input, IFormatProvider formatProvider, out TimeSpan result) + public static bool TryParse(string input, IFormatProvider formatProvider, out TimeSpan result) { if (input == null) { - result = default(TimeSpan); + result = default; return false; } return TimeSpanParse.TryParse(input, formatProvider, out result); @@ -387,7 +387,7 @@ namespace System { return TimeSpanParse.TryParse(input, formatProvider, out result); } - public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, out TimeSpan result) + public static bool TryParseExact(string input, string format, IFormatProvider formatProvider, out TimeSpan result) { if (input == null || format == null) { @@ -401,11 +401,11 @@ namespace System { return TimeSpanParse.TryParseExact(input, format, formatProvider, TimeSpanStyles.None, out result); } - public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, out TimeSpan result) + public static bool TryParseExact(string input, string[] formats, IFormatProvider formatProvider, out TimeSpan result) { if (input == null) { - result = default(TimeSpan); + result = default; return false; } return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result); @@ -415,7 +415,7 @@ namespace System return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result); } - public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) + public static bool TryParseExact(string input, string format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); if (input == null || format == null) @@ -432,12 +432,12 @@ namespace System ValidateStyles(styles, nameof(styles)); return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result); } - public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) + public static bool TryParseExact(string input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); if (input == null) { - result = default(TimeSpan); + result = default; return false; } return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result); @@ -448,15 +448,15 @@ namespace System ValidateStyles(styles, nameof(styles)); return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result); } - public override String ToString() + public override string ToString() { - return TimeSpanFormat.Format(this, null, null); + return TimeSpanFormat.FormatC(this); } - public String ToString(String format) + public string ToString(string format) { return TimeSpanFormat.Format(this, format, null); } - public String ToString(String format, IFormatProvider formatProvider) + public string ToString(string format, IFormatProvider formatProvider) { return TimeSpanFormat.Format(this, format, formatProvider); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/TimeZone.cs b/external/corert/src/System.Private.CoreLib/shared/System/TimeZone.cs index d4059babfc..010db8090f 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/TimeZone.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/TimeZone.cs @@ -32,15 +32,15 @@ namespace System private static volatile TimeZone currentTimeZone = null; // Private object for locking instead of locking on a public type for SQL reliability work. - private static Object s_InternalSyncObject; - private static Object InternalSyncObject + private static object s_InternalSyncObject; + private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { - Object o = new Object(); - Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); + object o = new object(); + Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } @@ -87,12 +87,12 @@ namespace System } } - public abstract String StandardName + public abstract string StandardName { get; } - public abstract String DaylightName + public abstract string DaylightName { get; } @@ -129,8 +129,8 @@ namespace System { return time; } - Boolean isAmbiguousLocalDst = false; - Int64 offset = ((CurrentSystemTimeZone)(TimeZone.CurrentTimeZone)).GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst); + bool isAmbiguousLocalDst = false; + long offset = ((CurrentSystemTimeZone)(TimeZone.CurrentTimeZone)).GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst); return new DateTime(time.Ticks + offset, DateTimeKind.Local, isAmbiguousLocalDst); } @@ -247,7 +247,7 @@ namespace System ambiguousEnd = startTime - daylightTimes.Delta; } - Boolean isDst = false; + bool isDst = false; if (startTime > endTime) { // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year. diff --git a/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.AdjustmentRule.cs b/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.AdjustmentRule.cs index 0e949a30ec..aceb7b90fb 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.AdjustmentRule.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.AdjustmentRule.cs @@ -11,6 +11,8 @@ namespace System [Serializable] public sealed class AdjustmentRule : IEquatable, ISerializable, IDeserializationCallback { + private static readonly TimeSpan DaylightDeltaAdjustment = TimeSpan.FromHours(24.0); + private static readonly TimeSpan MaxDaylightDelta = TimeSpan.FromHours(12.0); private readonly DateTime _dateStart; private readonly DateTime _dateEnd; private readonly TimeSpan _daylightDelta; @@ -39,8 +41,8 @@ namespace System internal bool HasDaylightSaving => DaylightDelta != TimeSpan.Zero || - (DaylightTransitionStart != default(TransitionTime) && DaylightTransitionStart.TimeOfDay != DateTime.MinValue) || - (DaylightTransitionEnd != default(TransitionTime) && DaylightTransitionEnd.TimeOfDay != DateTime.MinValue.AddMilliseconds(1)); + (DaylightTransitionStart != default && DaylightTransitionStart.TimeOfDay != DateTime.MinValue) || + (DaylightTransitionEnd != default && DaylightTransitionEnd.TimeOfDay != DateTime.MinValue.AddMilliseconds(1)); public bool Equals(AdjustmentRule other) => other != null && @@ -100,6 +102,7 @@ namespace System TimeSpan baseUtcOffsetDelta, bool noDaylightTransitions) { + AdjustDaylightDeltaToExpectedRange(ref daylightDelta, ref baseUtcOffsetDelta); return new AdjustmentRule( dateStart, dateEnd, @@ -186,6 +189,26 @@ namespace System } } + /// + /// Ensures the daylight delta is within [-12, 12] hours + /// > + private static void AdjustDaylightDeltaToExpectedRange(ref TimeSpan daylightDelta, ref TimeSpan baseUtcOffsetDelta) + { + if (daylightDelta > MaxDaylightDelta) + { + daylightDelta -= DaylightDeltaAdjustment; + baseUtcOffsetDelta += DaylightDeltaAdjustment; + } + else if (daylightDelta < -MaxDaylightDelta) + { + daylightDelta += DaylightDeltaAdjustment; + baseUtcOffsetDelta -= DaylightDeltaAdjustment; + } + + System.Diagnostics.Debug.Assert(daylightDelta <= MaxDaylightDelta && daylightDelta >= -MaxDaylightDelta, + "DaylightDelta should not ever be more than 24h"); + } + void IDeserializationCallback.OnDeserialization(object sender) { // OnDeserialization is called after each instance of this class is deserialized. diff --git a/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Unix.cs b/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Unix.cs index 410eaf3ff1..5645c2a389 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Unix.cs @@ -384,8 +384,8 @@ namespace System string symlinkPath = Interop.Sys.ReadLink(tzFilePath); if (symlinkPath != null) { - // Use Path.Combine to resolve links that contain a relative path (e.g. /etc/localtime). - symlinkPath = Path.Combine(tzFilePath, symlinkPath); + // symlinkPath can be relative path, use Path to get the full absolute path. + symlinkPath = Path.GetFullPath(symlinkPath, Path.GetDirectoryName(tzFilePath)); string timeZoneDirectory = GetTimeZoneDirectory(); if (symlinkPath.StartsWith(timeZoneDirectory, StringComparison.Ordinal)) @@ -398,7 +398,7 @@ namespace System } /// - /// Enumerate files + /// Enumerate files /// private static IEnumerable EnumerateFilesRecursively(string path) { @@ -595,6 +595,7 @@ namespace System } catch (ArgumentException) { } catch (InvalidTimeZoneException) { } + try { return new TimeZoneInfo(rawData, id, dstDisabled: true); // create a TimeZoneInfo instance from the TZif data w/o DST support @@ -602,7 +603,6 @@ namespace System catch (ArgumentException) { } catch (InvalidTimeZoneException) { } } - return null; } @@ -866,7 +866,7 @@ namespace System index++; } - if (index == 0) + if (rulesList.Count == 0 && index < dts.Length) { TZifType transitionType = TZif_GetEarlyDateTransitionType(transitionTypes); DateTime endTransitionDate = dts[index]; @@ -883,6 +883,12 @@ namespace System default(TransitionTime), baseUtcDelta, noDaylightTransitions: true); + + if (!IsValidAdjustmentRuleOffest(timeZoneBaseUtcOffset, r)) + { + NormalizeAdjustmentRuleOffset(timeZoneBaseUtcOffset, ref r); + } + rulesList.Add(r); } else if (index < dts.Length) @@ -920,6 +926,12 @@ namespace System default(TransitionTime), baseUtcDelta, noDaylightTransitions: true); + + if (!IsValidAdjustmentRuleOffest(timeZoneBaseUtcOffset, r)) + { + NormalizeAdjustmentRuleOffset(timeZoneBaseUtcOffset, ref r); + } + rulesList.Add(r); } else @@ -932,8 +944,14 @@ namespace System if (!string.IsNullOrEmpty(futureTransitionsPosixFormat)) { AdjustmentRule r = TZif_CreateAdjustmentRuleForPosixFormat(futureTransitionsPosixFormat, startTransitionDate, timeZoneBaseUtcOffset); + if (r != null) { + if (!IsValidAdjustmentRuleOffest(timeZoneBaseUtcOffset, r)) + { + NormalizeAdjustmentRuleOffset(timeZoneBaseUtcOffset, ref r); + } + rulesList.Add(r); } } @@ -954,6 +972,12 @@ namespace System default(TransitionTime), baseUtcDelta, noDaylightTransitions: true); + + if (!IsValidAdjustmentRuleOffest(timeZoneBaseUtcOffset, r)) + { + NormalizeAdjustmentRuleOffset(timeZoneBaseUtcOffset, ref r); + } + rulesList.Add(r); } } @@ -1012,17 +1036,15 @@ namespace System /// private static AdjustmentRule TZif_CreateAdjustmentRuleForPosixFormat(string posixFormat, DateTime startTransitionDate, TimeSpan timeZoneBaseUtcOffset) { - string standardName; - string standardOffset; - string daylightSavingsName; - string daylightSavingsOffset; - string start; - string startTime; - string end; - string endTime; - - if (TZif_ParsePosixFormat(posixFormat, out standardName, out standardOffset, out daylightSavingsName, - out daylightSavingsOffset, out start, out startTime, out end, out endTime)) + if (TZif_ParsePosixFormat(posixFormat, + out ReadOnlySpan standardName, + out ReadOnlySpan standardOffset, + out ReadOnlySpan daylightSavingsName, + out ReadOnlySpan daylightSavingsOffset, + out ReadOnlySpan start, + out ReadOnlySpan startTime, + out ReadOnlySpan end, + out ReadOnlySpan endTime)) { // a valid posixFormat has at least standardName and standardOffset @@ -1033,7 +1055,7 @@ namespace System baseOffset = TZif_CalculateTransitionOffsetFromBase(baseOffset, timeZoneBaseUtcOffset); // having a daylightSavingsName means there is a DST rule - if (!string.IsNullOrEmpty(daylightSavingsName)) + if (!daylightSavingsName.IsEmpty) { TimeSpan? parsedDaylightSavings = TZif_ParseOffsetString(daylightSavingsOffset); TimeSpan daylightSavingsTimeSpan; @@ -1079,16 +1101,16 @@ namespace System return null; } - private static TimeSpan? TZif_ParseOffsetString(string offset) + private static TimeSpan? TZif_ParseOffsetString(ReadOnlySpan offset) { TimeSpan? result = null; - if (!string.IsNullOrEmpty(offset)) + if (offset.Length > 0) { bool negative = offset[0] == '-'; if (negative || offset[0] == '+') { - offset = offset.Substring(1); + offset = offset.Slice(1); } // Try parsing just hours first. @@ -1117,9 +1139,40 @@ namespace System return result; } - private static TransitionTime TZif_CreateTransitionTimeFromPosixRule(string date, string time) + private static DateTime ParseTimeOfDay(ReadOnlySpan time) { - if (string.IsNullOrEmpty(date)) + DateTime timeOfDay; + TimeSpan? timeOffset = TZif_ParseOffsetString(time); + if (timeOffset.HasValue) + { + // This logic isn't correct and can't be corrected until https://github.com/dotnet/corefx/issues/2618 is fixed. + // Some time zones use time values like, "26", "144", or "-2". + // This allows the week to sometimes be week 4 and sometimes week 5 in the month. + // For now, strip off any 'days' in the offset, and just get the time of day correct + timeOffset = new TimeSpan(timeOffset.Value.Hours, timeOffset.Value.Minutes, timeOffset.Value.Seconds); + if (timeOffset.Value < TimeSpan.Zero) + { + timeOfDay = new DateTime(1, 1, 2, 0, 0, 0); + } + else + { + timeOfDay = new DateTime(1, 1, 1, 0, 0, 0); + } + + timeOfDay += timeOffset.Value; + } + else + { + // default to 2AM. + timeOfDay = new DateTime(1, 1, 1, 2, 0, 0); + } + + return timeOfDay; + } + + private static TransitionTime TZif_CreateTransitionTimeFromPosixRule(ReadOnlySpan date, ReadOnlySpan time) + { + if (date.IsEmpty) { return default(TransitionTime); } @@ -1135,72 +1188,115 @@ namespace System DayOfWeek day; if (!TZif_ParseMDateRule(date, out month, out week, out day)) { - throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_UnparseablePosixMDateString, date)); + throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_UnparseablePosixMDateString, date.ToString())); } - DateTime timeOfDay; - TimeSpan? timeOffset = TZif_ParseOffsetString(time); - if (timeOffset.HasValue) - { - // This logic isn't correct and can't be corrected until https://github.com/dotnet/corefx/issues/2618 is fixed. - // Some time zones use time values like, "26", "144", or "-2". - // This allows the week to sometimes be week 4 and sometimes week 5 in the month. - // For now, strip off any 'days' in the offset, and just get the time of day correct - timeOffset = new TimeSpan(timeOffset.Value.Hours, timeOffset.Value.Minutes, timeOffset.Value.Seconds); - if (timeOffset.Value < TimeSpan.Zero) - { - timeOfDay = new DateTime(1, 1, 2, 0, 0, 0); - } - else - { - timeOfDay = new DateTime(1, 1, 1, 0, 0, 0); - } - - timeOfDay += timeOffset.Value; - } - else - { - // default to 2AM. - timeOfDay = new DateTime(1, 1, 1, 2, 0, 0); - } - - return TransitionTime.CreateFloatingDateRule(timeOfDay, month, week, day); + return TransitionTime.CreateFloatingDateRule(ParseTimeOfDay(time), month, week, day); } else { - // Jn - // This specifies the Julian day, with n between 1 and 365.February 29 is never counted, even in leap years. + if (date[0] != 'J') + { + // should be n Julian day format which we don't support. + // + // This specifies the Julian day, with n between 0 and 365. February 29 is counted in leap years. + // + // n would be a relative number from the begining of the year. which should handle if the + // the year is a leap year or not. + // + // In leap year, n would be counted as: + // + // 0 30 31 59 60 90 335 365 + // |-------Jan--------|-------Feb--------|-------Mar--------|....|-------Dec--------| + // + // while in non leap year we'll have + // + // 0 30 31 58 59 89 334 364 + // |-------Jan--------|-------Feb--------|-------Mar--------|....|-------Dec--------| + // + // + // For example if n is specified as 60, this means in leap year the rule will start at Mar 1, + // while in non leap year the rule will start at Mar 2. + // + // If we need to support n format, we'll have to have a floating adjustment rule support this case. - // n - // This specifies the Julian day, with n between 0 and 365.February 29 is counted in leap years. + throw new InvalidTimeZoneException(SR.InvalidTimeZone_NJulianDayNotSupported); + } - // These two rules cannot be expressed with the current AdjustmentRules - // One of them *could* be supported if we relaxed the TransitionTime validation rules, and allowed - // "IsFixedDateRule = true, Month = 0, Day = n" to mean the nth day of the year, picking one of the rules above - - throw new InvalidTimeZoneException(SR.InvalidTimeZone_JulianDayNotSupported); + // Julian day + TZif_ParseJulianDay(date, out int month, out int day); + return TransitionTime.CreateFixedDateRule(ParseTimeOfDay(time), month, day); } } + /// + /// Parses a string like Jn or n into month and day values. + /// + /// + /// true if the parsing succeeded; otherwise, false. + /// + private static void TZif_ParseJulianDay(ReadOnlySpan date, out int month, out int day) + { + // Jn + // This specifies the Julian day, with n between 1 and 365.February 29 is never counted, even in leap years. + Debug.Assert(!date.IsEmpty); + Debug.Assert(date[0] == 'J'); + month = day = 0; + + int index = 1; + + if (index >= date.Length || ((uint)(date[index] - '0') > '9'-'0')) + { + throw new InvalidTimeZoneException(SR.InvalidTimeZone_InvalidJulianDay); + } + + int julianDay = 0; + + do + { + julianDay = julianDay * 10 + (int) (date[index] - '0'); + index++; + } while (index < date.Length && ((uint)(date[index] - '0') <= '9'-'0')); + + int[] days = GregorianCalendarHelper.DaysToMonth365; + + if (julianDay == 0 || julianDay > days[days.Length - 1]) + { + throw new InvalidTimeZoneException(SR.InvalidTimeZone_InvalidJulianDay); + } + + int i = 1; + while (i < days.Length && julianDay > days[i]) + { + i++; + } + + Debug.Assert(i > 0 && i < days.Length); + + month = i; + day = julianDay - days[i - 1]; + } + /// /// Parses a string like Mm.w.d into month, week and DayOfWeek values. /// /// /// true if the parsing succeeded; otherwise, false. /// - private static bool TZif_ParseMDateRule(string dateRule, out int month, out int week, out DayOfWeek dayOfWeek) + private static bool TZif_ParseMDateRule(ReadOnlySpan dateRule, out int month, out int week, out DayOfWeek dayOfWeek) { if (dateRule[0] == 'M') { - int firstDotIndex = dateRule.IndexOf('.'); - if (firstDotIndex > 0) + int monthWeekDotIndex = dateRule.IndexOf('.'); + if (monthWeekDotIndex > 0) { - int secondDotIndex = dateRule.IndexOf('.', firstDotIndex + 1); - if (secondDotIndex > 0) + ReadOnlySpan weekDaySpan = dateRule.Slice(monthWeekDotIndex + 1); + int weekDayDotIndex = weekDaySpan.IndexOf('.'); + if (weekDayDotIndex > 0) { - if (int.TryParse(dateRule.AsSpan().Slice(1, firstDotIndex - 1), out month) && - int.TryParse(dateRule.AsSpan().Slice(firstDotIndex + 1, secondDotIndex - firstDotIndex - 1), out week) && - int.TryParse(dateRule.AsSpan().Slice(secondDotIndex + 1), out int day)) + if (int.TryParse(dateRule.Slice(1, monthWeekDotIndex - 1), out month) && + int.TryParse(weekDaySpan.Slice(0, weekDayDotIndex), out week) && + int.TryParse(weekDaySpan.Slice(weekDayDotIndex + 1), out int day)) { dayOfWeek = (DayOfWeek)day; return true; @@ -1216,15 +1312,15 @@ namespace System } private static bool TZif_ParsePosixFormat( - string posixFormat, - out string standardName, - out string standardOffset, - out string daylightSavingsName, - out string daylightSavingsOffset, - out string start, - out string startTime, - out string end, - out string endTime) + ReadOnlySpan posixFormat, + out ReadOnlySpan standardName, + out ReadOnlySpan standardOffset, + out ReadOnlySpan daylightSavingsName, + out ReadOnlySpan daylightSavingsOffset, + out ReadOnlySpan start, + out ReadOnlySpan startTime, + out ReadOnlySpan end, + out ReadOnlySpan endTime) { standardName = null; standardOffset = null; @@ -1240,7 +1336,7 @@ namespace System standardOffset = TZif_ParsePosixOffset(posixFormat, ref index); daylightSavingsName = TZif_ParsePosixName(posixFormat, ref index); - if (!string.IsNullOrEmpty(daylightSavingsName)) + if (!daylightSavingsName.IsEmpty) { daylightSavingsOffset = TZif_ParsePosixOffset(posixFormat, ref index); @@ -1257,10 +1353,10 @@ namespace System } } - return !string.IsNullOrEmpty(standardName) && !string.IsNullOrEmpty(standardOffset); + return !standardName.IsEmpty && !standardOffset.IsEmpty; } - private static string TZif_ParsePosixName(string posixFormat, ref int index) + private static ReadOnlySpan TZif_ParsePosixName(ReadOnlySpan posixFormat, ref int index) { bool isBracketEnclosed = index < posixFormat.Length && posixFormat[index] == '<'; if (isBracketEnclosed) @@ -1268,7 +1364,7 @@ namespace System // move past the opening bracket index++; - string result = TZif_ParsePosixString(posixFormat, ref index, c => c == '>'); + ReadOnlySpan result = TZif_ParsePosixString(posixFormat, ref index, c => c == '>'); // move past the closing bracket if (index < posixFormat.Length && posixFormat[index] == '>') @@ -1287,10 +1383,10 @@ namespace System } } - private static string TZif_ParsePosixOffset(string posixFormat, ref int index) => + private static ReadOnlySpan TZif_ParsePosixOffset(ReadOnlySpan posixFormat, ref int index) => TZif_ParsePosixString(posixFormat, ref index, c => !char.IsDigit(c) && c != '+' && c != '-' && c != ':'); - private static void TZif_ParsePosixDateTime(string posixFormat, ref int index, out string date, out string time) + private static void TZif_ParsePosixDateTime(ReadOnlySpan posixFormat, ref int index, out ReadOnlySpan date, out ReadOnlySpan time) { time = null; @@ -1302,13 +1398,13 @@ namespace System } } - private static string TZif_ParsePosixDate(string posixFormat, ref int index) => + private static ReadOnlySpan TZif_ParsePosixDate(ReadOnlySpan posixFormat, ref int index) => TZif_ParsePosixString(posixFormat, ref index, c => c == '/' || c == ','); - private static string TZif_ParsePosixTime(string posixFormat, ref int index) => + private static ReadOnlySpan TZif_ParsePosixTime(ReadOnlySpan posixFormat, ref int index) => TZif_ParsePosixString(posixFormat, ref index, c => c == ','); - private static string TZif_ParsePosixString(string posixFormat, ref int index, Func breakCondition) + private static ReadOnlySpan TZif_ParsePosixString(ReadOnlySpan posixFormat, ref int index, Func breakCondition) { int startIndex = index; for (; index < posixFormat.Length; index++) @@ -1320,7 +1416,7 @@ namespace System } } - return posixFormat.Substring(startIndex, index - startIndex); + return posixFormat.Slice(startIndex, index - startIndex); } // Returns the Substring from zoneAbbreviations starting at index and ending at '\0' diff --git a/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs b/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs index 5950c9565a..443b8d45d3 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs @@ -422,7 +422,7 @@ namespace System if (!supportsDst) { - transitionTime = default(TransitionTime); + transitionTime = default; return false; } @@ -676,7 +676,7 @@ namespace System return true; } - private unsafe static bool TryGetTimeZoneEntryFromRegistry(RegistryKey key, string name, out REG_TZI_FORMAT dtzi) + private static unsafe bool TryGetTimeZoneEntryFromRegistry(RegistryKey key, string name, out REG_TZI_FORMAT dtzi) { byte[] regValue = key.GetValue(name, null, RegistryValueOptions.None) as byte[]; if (regValue == null || regValue.Length != sizeof(REG_TZI_FORMAT)) diff --git a/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.cs b/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.cs index 6e27376b68..e95321df26 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneInfo.cs @@ -1917,12 +1917,6 @@ namespace System return result; } - /// - /// Helper function that validates the TimeSpan is within +/- 14.0 hours - /// - internal static bool UtcOffsetOutOfRange(TimeSpan offset) => - offset.TotalHours < -14.0 || offset.TotalHours > 14.0; - /// /// Helper function that performs all of the validation checks for the /// factory methods and deserialization callback. @@ -1972,11 +1966,7 @@ namespace System throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesNoNulls); } - // FUTURE: check to see if this rule supports Daylight Saving Time - // adjustmentRulesSupportDst = adjustmentRulesSupportDst || current.SupportsDaylightSavingTime; - // FUTURE: test baseUtcOffset + current.StandardDelta - - if (UtcOffsetOutOfRange(baseUtcOffset + current.DaylightDelta)) + if (!IsValidAdjustmentRuleOffest(baseUtcOffset, current)) { throw new InvalidTimeZoneException(SR.ArgumentOutOfRange_UtcOffsetAndDaylightDelta); } @@ -1989,5 +1979,82 @@ namespace System } } } + + private static readonly TimeSpan MaxOffset = TimeSpan.FromHours(14.0); + private static readonly TimeSpan MinOffset = -MaxOffset; + + /// + /// Helper function that validates the TimeSpan is within +/- 14.0 hours + /// + internal static bool UtcOffsetOutOfRange(TimeSpan offset) => + offset < MinOffset || offset > MaxOffset; + + private static TimeSpan GetUtcOffset(TimeSpan baseUtcOffset, AdjustmentRule adjustmentRule) + { + return baseUtcOffset + + adjustmentRule.BaseUtcOffsetDelta + + (adjustmentRule.HasDaylightSaving ? adjustmentRule.DaylightDelta : TimeSpan.Zero); + } + + /// + /// Helper function that performs adjustment rule validation + /// + private static bool IsValidAdjustmentRuleOffest(TimeSpan baseUtcOffset, AdjustmentRule adjustmentRule) + { + TimeSpan utcOffset = GetUtcOffset(baseUtcOffset, adjustmentRule); + return !UtcOffsetOutOfRange(utcOffset); + } + + /// + /// Normalize adjustment rule offset so that it is within valid range + /// This method should not be called at all but is here in case something changes in the future + /// or if really old time zones are present on the OS (no combination is known at the moment) + /// + private static void NormalizeAdjustmentRuleOffset(TimeSpan baseUtcOffset, ref AdjustmentRule adjustmentRule) + { + // Certain time zones such as: + // Time Zone start date end date offset + // ----------------------------------------------------- + // America/Yakutat 0001-01-01 1867-10-18 14:41:00 + // America/Yakutat 1867-10-18 1900-08-20 14:41:00 + // America/Sitka 0001-01-01 1867-10-18 14:58:00 + // America/Sitka 1867-10-18 1900-08-20 14:58:00 + // Asia/Manila 0001-01-01 1844-12-31 -15:56:00 + // Pacific/Guam 0001-01-01 1845-01-01 -14:21:00 + // Pacific/Saipan 0001-01-01 1845-01-01 -14:21:00 + // + // have larger offset than currently supported by framework. + // If for whatever reason we find that time zone exceeding max + // offset of 14h this function will truncate it to the max valid offset. + // Updating max offset may cause problems with interacting with SQL server + // which uses SQL DATETIMEOFFSET field type which was originally designed to be + // bit-for-bit compatible with DateTimeOffset. + + TimeSpan utcOffset = GetUtcOffset(baseUtcOffset, adjustmentRule); + + // utc base offset delta increment + TimeSpan adjustment = TimeSpan.Zero; + + if (utcOffset > MaxOffset) + { + adjustment = MaxOffset - utcOffset; + } + else if (utcOffset < MinOffset) + { + adjustment = MinOffset - utcOffset; + } + + if (adjustment != TimeSpan.Zero) + { + adjustmentRule = AdjustmentRule.CreateAdjustmentRule( + adjustmentRule.DateStart, + adjustmentRule.DateEnd, + adjustmentRule.DaylightDelta, + adjustmentRule.DaylightTransitionStart, + adjustmentRule.DaylightTransitionEnd, + adjustmentRule.BaseUtcOffsetDelta + adjustment, + adjustmentRule.NoDaylightTransitions); + } + } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneNotFoundException.cs b/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneNotFoundException.cs index f83c6443c3..3dc1bb1d4c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneNotFoundException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/TimeZoneNotFoundException.cs @@ -14,12 +14,12 @@ namespace System { } - public TimeZoneNotFoundException(String message) + public TimeZoneNotFoundException(string message) : base(message) { } - public TimeZoneNotFoundException(String message, Exception innerException) + public TimeZoneNotFoundException(string message, Exception innerException) : base(message, innerException) { } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/TimeoutException.cs b/external/corert/src/System.Private.CoreLib/shared/System/TimeoutException.cs index ddaa47747d..2480f4bc28 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/TimeoutException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/TimeoutException.cs @@ -25,13 +25,13 @@ namespace System HResult = HResults.COR_E_TIMEOUT; } - public TimeoutException(String message) + public TimeoutException(string message) : base(message) { HResult = HResults.COR_E_TIMEOUT; } - public TimeoutException(String message, Exception innerException) + public TimeoutException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_TIMEOUT; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Tuple.cs b/external/corert/src/System.Private.CoreLib/shared/System/Tuple.cs index d0c8462330..8529e01f92 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Tuple.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Tuple.cs @@ -4,9 +4,7 @@ using System.Collections; using System.Collections.Generic; -#if MONO -using System.Diagnostics.Private; -#endif +using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; @@ -119,12 +117,12 @@ namespace System m_Item1 = item1; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -138,12 +136,12 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -159,15 +157,15 @@ namespace System public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return comparer.GetHashCode(m_Item1); } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } @@ -224,12 +222,12 @@ namespace System m_Item2 = item2; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -243,12 +241,12 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -270,15 +268,15 @@ namespace System public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2)); } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } @@ -344,12 +342,12 @@ namespace System m_Item3 = item3; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -363,12 +361,12 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -394,15 +392,15 @@ namespace System public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3)); } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } @@ -475,12 +473,12 @@ namespace System m_Item4 = item4; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -494,12 +492,12 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -529,15 +527,15 @@ namespace System public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4)); } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } @@ -617,12 +615,12 @@ namespace System m_Item5 = item5; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -636,12 +634,12 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -675,15 +673,15 @@ namespace System public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5)); } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } @@ -770,12 +768,12 @@ namespace System m_Item6 = item6; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -789,12 +787,12 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -832,15 +830,15 @@ namespace System public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6)); } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } @@ -934,12 +932,12 @@ namespace System m_Item7 = item7; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -953,12 +951,12 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -1000,15 +998,15 @@ namespace System public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7)); } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } @@ -1114,12 +1112,12 @@ namespace System m_Rest = rest; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -1133,12 +1131,12 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7) && comparer.Equals(m_Rest, objTuple.m_Rest); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -1184,10 +1182,10 @@ namespace System public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple ITupleInternal t = (ITupleInternal)m_Rest; @@ -1216,7 +1214,7 @@ namespace System return -1; } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Type.Helpers.cs b/external/corert/src/System.Private.CoreLib/shared/System/Type.Helpers.cs index db8df231e4..3de7d827e2 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Type.Helpers.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Type.Helpers.cs @@ -473,54 +473,31 @@ namespace System // This method will filter based upon the name. A partial wildcard // at the end of the string is supported. // filterCriteria -- This is the string name - private static bool FilterNameImpl(MemberInfo m, object filterCriteria) + private static bool FilterNameImpl(MemberInfo m, object filterCriteria, StringComparison comparison) { // Check that the criteria object is a String object - if (filterCriteria == null || !(filterCriteria is string)) + if (!(filterCriteria is string filterCriteriaString)) + { throw new InvalidFilterCriteriaException(SR.InvalidFilterCriteriaException_CritString); + } - // At the moment this fails if its done on a single line.... - string str = ((string)filterCriteria); - str = str.Trim(); + ReadOnlySpan str = filterCriteriaString.AsSpan().Trim(); + ReadOnlySpan name = m.Name; - string name = m.Name; // Get the nested class name only, as opposed to the mangled one if (m.MemberType == MemberTypes.NestedType) - name = name.Substring(name.LastIndexOf('+') + 1); + { + name = name.Slice(name.LastIndexOf('+') + 1); + } + // Check to see if this is a prefix or exact match requirement if (str.Length > 0 && str[str.Length - 1] == '*') { - str = str.Substring(0, str.Length - 1); - return (name.StartsWith(str, StringComparison.Ordinal)); + str = str.Slice(0, str.Length - 1); + return name.StartsWith(str, comparison); } - return (name.Equals(str)); - } - - // FilterIgnoreCase - // This delegate will do a name search but does it with the - // ignore case specified. - private static bool FilterNameIgnoreCaseImpl(MemberInfo m, object filterCriteria) - { - // Check that the criteria object is a String object - if (filterCriteria == null || !(filterCriteria is string)) - throw new InvalidFilterCriteriaException(SR.InvalidFilterCriteriaException_CritString); - - string str = (string)filterCriteria; - str = str.Trim(); - - string name = m.Name; - // Get the nested class name only, as opposed to the mangled one - if (m.MemberType == MemberTypes.NestedType) - name = name.Substring(name.LastIndexOf('+') + 1); - // Check to see if this is a prefix or exact match requirement - if (str.Length > 0 && str[str.Length - 1] == '*') - { - str = str.Substring(0, str.Length - 1); - return (string.Compare(name, 0, str, 0, str.Length, StringComparison.OrdinalIgnoreCase) == 0); - } - - return (string.Compare(str, name, StringComparison.OrdinalIgnoreCase) == 0); + return name.Equals(str, comparison); } } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Type.cs b/external/corert/src/System.Private.CoreLib/shared/System/Type.cs index a0d219ddd4..c78d98833a 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Type.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Type.cs @@ -346,10 +346,12 @@ namespace System public virtual Type MakeGenericType(params Type[] typeArguments) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } public virtual Type MakePointerType() { throw new NotSupportedException(); } + public static Type MakeGenericSignatureType(Type genericTypeDefinition, params Type[] typeArguments) => new SignatureConstructedGenericType(genericTypeDefinition, typeArguments); + public static Type MakeGenericMethodParameter(int position) { if (position < 0) - throw new ArgumentException(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(position)); + throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(position)); return new SignatureGenericMethodParameterType(position); } @@ -387,8 +389,8 @@ namespace System public static readonly object Missing = System.Reflection.Missing.Value; public static readonly MemberFilter FilterAttribute = FilterAttributeImpl; - public static readonly MemberFilter FilterName = FilterNameImpl; - public static readonly MemberFilter FilterNameIgnoreCase = FilterNameIgnoreCaseImpl; + public static readonly MemberFilter FilterName = (m, c) => FilterNameImpl(m, c, StringComparison.Ordinal); + public static readonly MemberFilter FilterNameIgnoreCase = (m, c) => FilterNameImpl(m, c, StringComparison.OrdinalIgnoreCase); private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/TypeInitializationException.cs b/external/corert/src/System.Private.CoreLib/shared/System/TypeInitializationException.cs index 4bf2906217..2ef822ab2c 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/TypeInitializationException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/TypeInitializationException.cs @@ -23,7 +23,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class TypeInitializationException : SystemException { - private String _typeName; + private string _typeName; // This exception is not creatable without specifying the // inner exception. @@ -34,19 +34,19 @@ namespace System } - public TypeInitializationException(String fullTypeName, Exception innerException) + public TypeInitializationException(string fullTypeName, Exception innerException) : this(fullTypeName, SR.Format(SR.TypeInitialization_Type, fullTypeName), innerException) { } // This is called from within the runtime. I believe this is necessary // for Interop only, though it's not particularly useful. - internal TypeInitializationException(String message) : base(message) + internal TypeInitializationException(string message) : base(message) { HResult = HResults.COR_E_TYPEINITIALIZATION; } - internal TypeInitializationException(String fullTypeName, String message, Exception innerException) + internal TypeInitializationException(string fullTypeName, string message, Exception innerException) : base(message, innerException) { _typeName = fullTypeName; @@ -65,13 +65,13 @@ namespace System info.AddValue("TypeName", TypeName, typeof(string)); } - public String TypeName + public string TypeName { get { if (_typeName == null) { - return String.Empty; + return string.Empty; } return _typeName; } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/UInt16.cs b/external/corert/src/System.Private.CoreLib/shared/System/UInt16.cs index 3047d18198..f9ef1f6a62 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/UInt16.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/UInt16.cs @@ -13,9 +13,9 @@ namespace System [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct UInt16 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct UInt16 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private ushort m_value; // Do not rename (binary serialization) + private readonly ushort m_value; // Do not rename (binary serialization) public const ushort MaxValue = (ushort)0xFFFF; public const ushort MinValue = 0; @@ -27,35 +27,35 @@ namespace System // null is considered to be less than any instance. // If object is not of type UInt16, this method throws an ArgumentException. // - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) { return 1; } - if (value is UInt16) + if (value is ushort) { - return ((int)m_value - (int)(((UInt16)value).m_value)); + return ((int)m_value - (int)(((ushort)value).m_value)); } throw new ArgumentException(SR.Arg_MustBeUInt16); } - public int CompareTo(UInt16 value) + public int CompareTo(ushort value) { return ((int)m_value - (int)value); } - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is UInt16)) + if (!(obj is ushort)) { return false; } - return m_value == ((UInt16)obj).m_value; + return m_value == ((ushort)obj).m_value; } [NonVersionable] - public bool Equals(UInt16 obj) + public bool Equals(ushort obj) { return m_value == obj; } @@ -67,23 +67,23 @@ namespace System } // Converts the current value to a String in base-10 with no extra padding. - public override String ToString() + public override string ToString() { return Number.FormatUInt32(m_value, null, null); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatUInt32(m_value, null, provider); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatUInt32(m_value, format, null); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatUInt32(m_value, format, provider); } @@ -94,14 +94,14 @@ namespace System } [CLSCompliant(false)] - public static ushort Parse(String s) + public static ushort Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] - public static ushort Parse(String s, NumberStyles style) + public static ushort Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -110,14 +110,14 @@ namespace System [CLSCompliant(false)] - public static ushort Parse(String s, IFormatProvider provider) + public static ushort Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] - public static ushort Parse(String s, NumberStyles style, IFormatProvider provider) + public static ushort Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -148,7 +148,7 @@ namespace System } [CLSCompliant(false)] - public static bool TryParse(String s, out UInt16 result) + public static bool TryParse(string s, out ushort result) { if (s == null) { @@ -166,7 +166,7 @@ namespace System } [CLSCompliant(false)] - public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt16 result) + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out ushort result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -186,10 +186,10 @@ namespace System return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } - private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out UInt16 result) + private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out ushort result) { result = 0; - UInt32 i; + uint i; if (!Number.TryParseUInt32(s, style, info, out i)) { return false; @@ -198,7 +198,7 @@ namespace System { return false; } - result = (UInt16)i; + result = (ushort)i; return true; } @@ -271,7 +271,7 @@ namespace System return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -281,7 +281,7 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt16", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/UInt32.cs b/external/corert/src/System.Private.CoreLib/shared/System/UInt32.cs index 1e33dcf17b..5ed193e956 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/UInt32.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/UInt32.cs @@ -13,9 +13,9 @@ namespace System [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct UInt32 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct UInt32 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private uint m_value; // Do not rename (binary serialization) + private readonly uint m_value; // Do not rename (binary serialization) public const uint MaxValue = (uint)0xffffffff; public const uint MinValue = 0U; @@ -27,13 +27,13 @@ namespace System // null is considered to be less than any instance. // If object is not of type UInt32, this method throws an ArgumentException. // - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) { return 1; } - if (value is UInt32) + if (value is uint) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. @@ -45,7 +45,7 @@ namespace System throw new ArgumentException(SR.Arg_MustBeUInt32); } - public int CompareTo(UInt32 value) + public int CompareTo(uint value) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. @@ -54,17 +54,17 @@ namespace System return 0; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is UInt32)) + if (!(obj is uint)) { return false; } - return m_value == ((UInt32)obj).m_value; + return m_value == ((uint)obj).m_value; } [NonVersionable] - public bool Equals(UInt32 obj) + public bool Equals(uint obj) { return m_value == obj; } @@ -76,22 +76,22 @@ namespace System } // The base 10 representation of the number with no extra padding. - public override String ToString() + public override string ToString() { return Number.FormatUInt32(m_value, null, null); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatUInt32(m_value, null, provider); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatUInt32(m_value, format, null); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatUInt32(m_value, format, provider); } @@ -102,14 +102,14 @@ namespace System } [CLSCompliant(false)] - public static uint Parse(String s) + public static uint Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] - public static uint Parse(String s, NumberStyles style) + public static uint Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -118,14 +118,14 @@ namespace System [CLSCompliant(false)] - public static uint Parse(String s, IFormatProvider provider) + public static uint Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] - public static uint Parse(String s, NumberStyles style, IFormatProvider provider) + public static uint Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -140,7 +140,7 @@ namespace System } [CLSCompliant(false)] - public static bool TryParse(String s, out UInt32 result) + public static bool TryParse(string s, out uint result) { if (s == null) { @@ -158,7 +158,7 @@ namespace System } [CLSCompliant(false)] - public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt32 result) + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out uint result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -247,7 +247,7 @@ namespace System return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -257,7 +257,7 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt32", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/UInt64.cs b/external/corert/src/System.Private.CoreLib/shared/System/UInt64.cs index d30fbe1e42..6abd76da21 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/UInt64.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/UInt64.cs @@ -13,9 +13,9 @@ namespace System [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct UInt64 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct UInt64 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private ulong m_value; // Do not rename (binary serialization) + private readonly ulong m_value; // Do not rename (binary serialization) public const ulong MaxValue = (ulong)0xffffffffffffffffL; public const ulong MinValue = 0x0; @@ -26,13 +26,13 @@ namespace System // null is considered to be less than any instance. // If object is not of type UInt64, this method throws an ArgumentException. // - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) { return 1; } - if (value is UInt64) + if (value is ulong) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. @@ -44,7 +44,7 @@ namespace System throw new ArgumentException(SR.Arg_MustBeUInt64); } - public int CompareTo(UInt64 value) + public int CompareTo(ulong value) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. @@ -53,17 +53,17 @@ namespace System return 0; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is UInt64)) + if (!(obj is ulong)) { return false; } - return m_value == ((UInt64)obj).m_value; + return m_value == ((ulong)obj).m_value; } [NonVersionable] - public bool Equals(UInt64 obj) + public bool Equals(ulong obj) { return m_value == obj; } @@ -74,22 +74,22 @@ namespace System return ((int)m_value) ^ (int)(m_value >> 32); } - public override String ToString() + public override string ToString() { return Number.FormatUInt64(m_value, null, null); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatUInt64(m_value, null, provider); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatUInt64(m_value, format, null); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatUInt64(m_value, format, provider); } @@ -100,14 +100,14 @@ namespace System } [CLSCompliant(false)] - public static ulong Parse(String s) + public static ulong Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] - public static ulong Parse(String s, NumberStyles style) + public static ulong Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -122,7 +122,7 @@ namespace System } [CLSCompliant(false)] - public static ulong Parse(String s, NumberStyles style, IFormatProvider provider) + public static ulong Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -137,7 +137,7 @@ namespace System } [CLSCompliant(false)] - public static Boolean TryParse(String s, out UInt64 result) + public static bool TryParse(string s, out ulong result) { if (s == null) { @@ -155,7 +155,7 @@ namespace System } [CLSCompliant(false)] - public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt64 result) + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out ulong result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -244,7 +244,7 @@ namespace System return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -254,7 +254,7 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt64", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/UIntPtr.cs b/external/corert/src/System.Private.CoreLib/shared/System/UIntPtr.cs index 23750e95fa..c57dd86a76 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/UIntPtr.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/UIntPtr.cs @@ -18,9 +18,9 @@ namespace System [Serializable] [CLSCompliant(false)] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct UIntPtr : IEquatable, ISerializable + public readonly struct UIntPtr : IEquatable, ISerializable { - unsafe private void* _value; // Do not rename (binary serialization) + private readonly unsafe void* _value; // Do not rename (binary serialization) [Intrinsic] public static readonly UIntPtr Zero; @@ -68,7 +68,7 @@ namespace System info.AddValue("value", ToUInt64()); } - public unsafe override bool Equals(Object obj) + public unsafe override bool Equals(object obj) { if (obj is UIntPtr) { @@ -77,9 +77,9 @@ namespace System return false; } - unsafe bool IEquatable.Equals(UIntPtr value) + unsafe bool IEquatable.Equals(UIntPtr other) { - return _value == value._value; + return _value == other._value; } public unsafe override int GetHashCode() @@ -208,6 +208,9 @@ namespace System [Intrinsic] [NonVersionable] +#if PROJECTN + [System.Runtime.CompilerServices.DependencyReductionRootAttribute] +#endif public unsafe void* ToPointer() { return _value; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/UnauthorizedAccessException.cs b/external/corert/src/System.Private.CoreLib/shared/System/UnauthorizedAccessException.cs index a28f6dd73c..e384dfeb31 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/UnauthorizedAccessException.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/UnauthorizedAccessException.cs @@ -29,13 +29,13 @@ namespace System HResult = HResults.COR_E_UNAUTHORIZEDACCESS; } - public UnauthorizedAccessException(String message) + public UnauthorizedAccessException(string message) : base(message) { HResult = HResults.COR_E_UNAUTHORIZEDACCESS; } - public UnauthorizedAccessException(String message, Exception inner) + public UnauthorizedAccessException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_UNAUTHORIZEDACCESS; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs b/external/corert/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs index 5cde572161..c214afdc71 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs @@ -6,16 +6,16 @@ namespace System { public class UnhandledExceptionEventArgs : EventArgs { - private Object _exception; + private object _exception; private bool _isTerminating; - public UnhandledExceptionEventArgs(Object exception, bool isTerminating) + public UnhandledExceptionEventArgs(object exception, bool isTerminating) { _exception = exception; _isTerminating = isTerminating; } - public Object ExceptionObject + public object ExceptionObject { get { return _exception; } } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventHandler.cs b/external/corert/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventHandler.cs index 14e31c7bbd..58f1eb5145 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventHandler.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventHandler.cs @@ -4,5 +4,5 @@ namespace System { - public delegate void UnhandledExceptionEventHandler(Object sender, UnhandledExceptionEventArgs e); + public delegate void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e); } diff --git a/external/corert/src/System.Private.CoreLib/shared/System/UnitySerializationHolder.cs b/external/corert/src/System.Private.CoreLib/shared/System/UnitySerializationHolder.cs index 2f30356709..53323c32bc 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/UnitySerializationHolder.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/UnitySerializationHolder.cs @@ -11,12 +11,8 @@ namespace System /// This only exists for compatibility with .NET Framework. /// [Serializable] -#if CORERT - public -#else - internal -#endif - sealed class UnitySerializationHolder : ISerializable, IObjectReference + // Needs to be public to support binary serialization compatibility + public sealed class UnitySerializationHolder : ISerializable, IObjectReference { internal const int NullUnity = 0x0002; private readonly int _unityType; diff --git a/external/corert/src/System.Private.CoreLib/shared/System/ValueTuple.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/shared/System/ValueTuple.cs.REMOVED.git-id index 0fb79fb5ba..28b10d4202 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/ValueTuple.cs.REMOVED.git-id +++ b/external/corert/src/System.Private.CoreLib/shared/System/ValueTuple.cs.REMOVED.git-id @@ -1 +1 @@ -ddbf22ed6553f66401bd92a5e86ebb7e377acc16 \ No newline at end of file +b486573ff5ac2ba3e12be4f6a7c3bce3b8535000 \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/shared/System/Version.cs b/external/corert/src/System.Private.CoreLib/shared/System/Version.cs index 9e4cefcd6f..444ee48858 100644 --- a/external/corert/src/System.Private.CoreLib/shared/System/Version.cs +++ b/external/corert/src/System.Private.CoreLib/shared/System/Version.cs @@ -73,7 +73,7 @@ namespace System _Minor = minor; } - public Version(String version) + public Version(string version) { Version v = Version.Parse(version); _Major = v.Major; @@ -134,7 +134,7 @@ namespace System get { return (short)(_Revision & 0xFFFF); } } - public int CompareTo(Object version) + public int CompareTo(object version) { if (version == null) { @@ -154,7 +154,7 @@ namespace System { return object.ReferenceEquals(value, this) ? 0 : - object.ReferenceEquals(value, null) ? 1 : + value is null ? 1 : _Major != value._Major ? (_Major > value._Major ? 1 : -1) : _Minor != value._Minor ? (_Minor > value._Minor ? 1 : -1) : _Build != value._Build ? (_Build > value._Build ? 1 : -1) : @@ -162,7 +162,7 @@ namespace System 0; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { return Equals(obj as Version); } @@ -170,7 +170,7 @@ namespace System public bool Equals(Version obj) { return object.ReferenceEquals(obj, this) || - (!object.ReferenceEquals(obj, null) && + (!(obj is null) && _Major == obj._Major && _Minor == obj._Minor && _Build == obj._Build && @@ -333,13 +333,15 @@ namespace System // Find the ends of the optional minor and build portions. // We musn't have any separators after build. int buildEnd = -1; - int minorEnd = input.IndexOf('.', majorEnd + 1); + int minorEnd = input.Slice(majorEnd + 1).IndexOf('.'); if (minorEnd != -1) { - buildEnd = input.IndexOf('.', minorEnd + 1); + minorEnd += (majorEnd + 1); + buildEnd = input.Slice(minorEnd + 1).IndexOf('.'); if (buildEnd != -1) { - if (input.IndexOf('.', buildEnd + 1) != -1) + buildEnd += (minorEnd + 1); + if (input.Slice(buildEnd + 1).Contains('.')) { if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input)); return null; @@ -347,10 +349,10 @@ namespace System } } - int major, minor, build, revision; + int minor, build, revision; // Parse the major version - if (!TryParseComponent(input.Slice(0, majorEnd), nameof(input), throwOnFailure, out major)) + if (!TryParseComponent(input.Slice(0, majorEnd), nameof(input), throwOnFailure, out int major)) { return null; } @@ -405,9 +407,9 @@ namespace System public static bool operator ==(Version v1, Version v2) { - if (Object.ReferenceEquals(v1, null)) + if (v1 is null) { - return Object.ReferenceEquals(v2, null); + return v2 is null; } return v1.Equals(v2); @@ -420,14 +422,14 @@ namespace System public static bool operator <(Version v1, Version v2) { - if ((Object)v1 == null) + if ((object)v1 == null) throw new ArgumentNullException(nameof(v1)); return (v1.CompareTo(v2) < 0); } public static bool operator <=(Version v1, Version v2) { - if ((Object)v1 == null) + if ((object)v1 == null) throw new ArgumentNullException(nameof(v1)); return (v1.CompareTo(v2) <= 0); } diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/DeveloperExperience/DeveloperExperience.cs b/external/corert/src/System.Private.CoreLib/src/Internal/DeveloperExperience/DeveloperExperience.cs index 791f0ed353..c507307c61 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/DeveloperExperience/DeveloperExperience.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/DeveloperExperience/DeveloperExperience.cs @@ -16,28 +16,49 @@ namespace Internal.DeveloperExperience [System.Runtime.CompilerServices.ReflectionBlocked] public class DeveloperExperience { - public virtual void WriteLine(String s) + /// + /// Check the AppCompat switch 'Diagnostics.DisableMetadataStackTraceResolution'. + /// Some customers use DIA-based tooling to translate stack traces in the raw format + /// (module)+RVA - for them, stack trace and reflection metadata-based resolution + /// constitutes technically a regression because these two resolution methods today cannot + /// provide file name and line number information; PDB-based tooling can easily do that + /// based on the RVA information. + /// + /// Note: a related switch 'Diagnostics.DisableDiaStackTraceResolution' controls whether + /// runtime may try to use DIA for PDB-based stack frame resolution. + /// + private static bool IsMetadataStackTraceResolutionDisabled() + { + bool disableMetadata = false; + AppContext.TryGetSwitch("Diagnostics.DisableMetadataStackTraceResolution", out disableMetadata); + return disableMetadata; + } + + public virtual void WriteLine(string s) { Debug.WriteLine(s); return; } - public virtual String CreateStackTraceString(IntPtr ip, bool includeFileInfo) + public virtual string CreateStackTraceString(IntPtr ip, bool includeFileInfo) { - StackTraceMetadataCallbacks stackTraceCallbacks = RuntimeAugments.StackTraceCallbacksIfAvailable; - if (stackTraceCallbacks != null) + if (!IsMetadataStackTraceResolutionDisabled()) { - IntPtr methodStart = RuntimeImports.RhFindMethodStartAddress(ip); - if (methodStart != IntPtr.Zero) + StackTraceMetadataCallbacks stackTraceCallbacks = RuntimeAugments.StackTraceCallbacksIfAvailable; + if (stackTraceCallbacks != null) { - string methodName = stackTraceCallbacks.TryGetMethodNameFromStartAddress(methodStart); - if (methodName != null) + IntPtr methodStart = RuntimeImports.RhFindMethodStartAddress(ip); + if (methodStart != IntPtr.Zero) { - if (ip != methodStart) + string methodName = stackTraceCallbacks.TryGetMethodNameFromStartAddress(methodStart); + if (methodName != null) { - methodName += " + 0x" + (ip.ToInt64() - methodStart.ToInt64()).ToString("x"); + if (ip != methodStart) + { + methodName += " + 0x" + (ip.ToInt64() - methodStart.ToInt64()).ToString("x"); + } + return methodName; } - return methodName; } } } @@ -53,7 +74,7 @@ namespace Internal.DeveloperExperience } StringBuilder sb = new StringBuilder(); - String fileNameWithoutExtension = GetFileNameWithoutExtension(moduleFullFileName); + string fileNameWithoutExtension = GetFileNameWithoutExtension(moduleFullFileName); int rva = RuntimeAugments.ConvertIpToRva(ip); sb.Append(fileNameWithoutExtension); sb.Append("!+0x"); @@ -86,7 +107,7 @@ namespace Internal.DeveloperExperience } } - public virtual bool OnContractFailure(String stackTrace, ContractFailureKind contractFailureKind, String displayMessage, String userMessage, String conditionText, Exception innerException) + public virtual bool OnContractFailure(string stackTrace, ContractFailureKind contractFailureKind, string displayMessage, string userMessage, string conditionText, Exception innerException) { Debug.WriteLine("Assertion failed: " + (displayMessage == null ? "" : displayMessage)); if (Debugger.IsAttached) @@ -110,7 +131,7 @@ namespace Internal.DeveloperExperience } } - private static String GetFileNameWithoutExtension(String path) + private static string GetFileNameWithoutExtension(string path) { path = GetFileName(path); int i; @@ -120,7 +141,7 @@ namespace Internal.DeveloperExperience return path.Substring(0, i); } - private static String GetFileName(String path) + private static string GetFileName(string path) { int length = path.Length; for (int i = length; --i >= 0;) diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/ComparerHelpers.cs b/external/corert/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/ComparerHelpers.cs index bcbd541dd0..f882239170 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/ComparerHelpers.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/ComparerHelpers.cs @@ -175,7 +175,7 @@ namespace System.Collections.Generic } // Equals method for the comparer itself. - public sealed override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); + public sealed override bool Equals(object obj) => obj != null && GetType() == obj.GetType(); public sealed override int GetHashCode() => GetType().GetHashCode(); } @@ -201,7 +201,7 @@ namespace System.Collections.Generic } // Equals method for the comparer itself. - public sealed override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); + public sealed override bool Equals(object obj) => obj != null && GetType() == obj.GetType(); public sealed override int GetHashCode() => GetType().GetHashCode(); } @@ -216,7 +216,7 @@ namespace System.Collections.Generic } // Equals method for the comparer itself. - public sealed override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); + public sealed override bool Equals(object obj) => obj != null && GetType() == obj.GetType(); public sealed override int GetHashCode() => GetType().GetHashCode(); } diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/EqualityComparerHelpers.cs b/external/corert/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/EqualityComparerHelpers.cs index 73ed2b25df..b9c735ca1e 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/EqualityComparerHelpers.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/EqualityComparerHelpers.cs @@ -195,10 +195,15 @@ namespace Internal.IntrinsicSupport #endif } + private static bool StructOnlyNormalEquals(T left, T right) + { + return left.Equals(right); + } + [Intrinsic] internal static bool StructOnlyEquals(T left, T right) { - return left.Equals(right); + return EqualityComparer.Default.Equals(left, right); } } } @@ -239,7 +244,7 @@ namespace System.Collections.Generic } // Equals method for the comparer itself. - public sealed override bool Equals(Object obj) => obj is GenericEqualityComparer; + public sealed override bool Equals(object obj) => obj is GenericEqualityComparer; public sealed override int GetHashCode() => typeof(GenericEqualityComparer).GetHashCode(); } @@ -270,7 +275,7 @@ namespace System.Collections.Generic // Equals method for the comparer itself. - public sealed override bool Equals(Object obj) => obj is NullableEqualityComparer; + public sealed override bool Equals(object obj) => obj is NullableEqualityComparer; public sealed override int GetHashCode() => typeof(NullableEqualityComparer).GetHashCode(); } @@ -303,7 +308,7 @@ namespace System.Collections.Generic } // Equals method for the comparer itself. - public override bool Equals(Object obj) => obj is EnumEqualityComparer; + public override bool Equals(object obj) => obj is EnumEqualityComparer; public override int GetHashCode() => typeof(EnumEqualityComparer).GetHashCode(); } @@ -335,7 +340,7 @@ namespace System.Collections.Generic } // Equals method for the comparer itself. - public sealed override bool Equals(Object obj) + public sealed override bool Equals(object obj) { if(obj == null) { diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/Reflection/ExplicitScopeAttribute.cs b/external/corert/src/System.Private.CoreLib/src/Internal/Reflection/ExplicitScopeAttribute.cs index fc309169b6..ef0aa65975 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/Reflection/ExplicitScopeAttribute.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/Reflection/ExplicitScopeAttribute.cs @@ -21,7 +21,7 @@ namespace Internal.Reflection [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, Inherited = false)] public sealed class ExplicitScopeAttribute : Attribute { - public ExplicitScopeAttribute(String assemblyIdentity) + public ExplicitScopeAttribute(string assemblyIdentity) { } } diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeInstantiator.cs b/external/corert/src/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeInstantiator.cs index 260166e554..c19686db27 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeInstantiator.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeInstantiator.cs @@ -48,7 +48,7 @@ namespace Internal.Reflection.Extensions.NonPortable { Type parameterType = parameters[i].ParameterType; if (!(parameterType.Equals(constructorArguments[i].ArgumentType) || - parameterType.Equals(typeof(Object)))) + parameterType.Equals(typeof(object)))) break; } if (i == parameters.Length) @@ -65,7 +65,7 @@ namespace Internal.Reflection.Extensions.NonPortable // Found the right constructor. Instantiate the Attribute. // int arity = matchingParameters.Length; - Object[] invokeArguments = new Object[arity]; + object[] invokeArguments = new object[arity]; for (int i = 0; i < arity; i++) { invokeArguments[i] = constructorArguments[i].Convert(); @@ -77,9 +77,9 @@ namespace Internal.Reflection.Extensions.NonPortable // foreach (CustomAttributeNamedArgument namedArgument in cad.NamedArguments) { - Object argumentValue = namedArgument.TypedValue.Convert(); + object argumentValue = namedArgument.TypedValue.Convert(); Type walk = attributeType; - String name = namedArgument.MemberName; + string name = namedArgument.MemberName; if (namedArgument.IsField) { // Field @@ -122,13 +122,13 @@ namespace Internal.Reflection.Extensions.NonPortable // // Convert the argument value reported by Reflection into an actual object. // - private static Object Convert(this CustomAttributeTypedArgument typedArgument) + private static object Convert(this CustomAttributeTypedArgument typedArgument) { Type argumentType = typedArgument.ArgumentType; if (!argumentType.IsArray) { bool isEnum = argumentType.IsEnum; - Object argumentValue = typedArgument.Value; + object argumentValue = typedArgument.Value; if (isEnum) argumentValue = Enum.ToObject(argumentType, argumentValue); return argumentValue; @@ -142,7 +142,7 @@ namespace Internal.Reflection.Extensions.NonPortable Array array = Array.CreateInstance(elementType, typedElements.Count); for (int i = 0; i < typedElements.Count; i++) { - Object elementValue = typedElements[i].Convert(); + object elementValue = typedElements[i].Convert(); array.SetValue(elementValue, i); } return array; diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/EnvironmentAugments.Unix.cs b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/EnvironmentAugments.Unix.cs index 6d28d393b2..76ead8cb79 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/EnvironmentAugments.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/EnvironmentAugments.Unix.cs @@ -27,10 +27,55 @@ namespace Internal.Runtime.Augments public static IEnumerable> EnumerateEnvironmentVariables() { - if ("".Length != 0) - throw new NotImplementedException(); // Need to return something better than an empty environment block. + IntPtr block = Interop.Sys.GetEnviron(); + if (block == IntPtr.Zero) + yield break; - return Array.Empty>(); + // Per man page, environment variables come back as an array of pointers to strings + // Parse each pointer of strings individually + while (ParseEntry(block, out string key, out string value)) + { + if (key != null && value != null) + yield return new KeyValuePair(key, value); + + // Increment to next environment variable entry + block += IntPtr.Size; + } + + // Use a local, unsafe function since we cannot use `yield return` inside of an `unsafe` block + unsafe bool ParseEntry(IntPtr current, out string key, out string value) + { + // Setup + key = null; + value = null; + + // Point to current entry + byte* entry = *(byte**)current; + + // Per man page, "The last pointer in this array has the value NULL" + // Therefore, if entry is null then we're at the end and can bail + if (entry == null) + return false; + + // Parse each byte of the entry until we hit either the separator '=' or '\0'. + // This finds the split point for creating key/value strings below. + // On some old OS, the environment block can be corrupted. + // Some will not have '=', so we need to check for '\0'. + byte* splitpoint = entry; + while (*splitpoint != '=' && *splitpoint != '\0') + splitpoint++; + + // Skip over entries starting with '=' and entries with no value (just a null-terminating char '\0') + if (splitpoint == entry || *splitpoint == '\0') + return true; + + // The key is the bytes from start (0) until our splitpoint + key = new string((sbyte*)entry, 0, checked((int)(splitpoint - entry))); + // The value is the rest of the bytes starting after the splitpoint + value = new string((sbyte*)(splitpoint + 1)); + + return true; + } } private static void ExitRaw() diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/ReflectionExecutionDomainCallbacks.cs b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/ReflectionExecutionDomainCallbacks.cs index c37c0d064d..bf19ab6083 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/ReflectionExecutionDomainCallbacks.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/ReflectionExecutionDomainCallbacks.cs @@ -47,7 +47,7 @@ namespace Internal.Runtime.Augments // Flotsam and jetsam. public abstract Exception CreateMissingMetadataException(Type typeWithMissingMetadata); - public abstract String GetBetterDiagnosticInfoIfAvailable(RuntimeTypeHandle runtimeTypeHandle); + public abstract string GetBetterDiagnosticInfoIfAvailable(RuntimeTypeHandle runtimeTypeHandle); public abstract MethodBase GetMethodBaseFromStartAddressIfAvailable(IntPtr methodStartAddress); public abstract int ValueTypeGetHashCodeUsingReflection(object valueType); public abstract bool ValueTypeEqualsUsingReflection(object left, object right); diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeAugments.cs b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeAugments.cs index 0213e88210..23c22a9656 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeAugments.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeAugments.cs @@ -87,11 +87,11 @@ namespace Internal.Runtime.Augments // // In these cases, this helper returns "null" and ConstructorInfo.Invoke() must deal with these specially. // - public static Object NewObject(RuntimeTypeHandle typeHandle) + public static object NewObject(RuntimeTypeHandle typeHandle) { EETypePtr eeType = typeHandle.ToEETypePtr(); if (eeType.IsNullable - || eeType == EETypePtr.EETypePtrOf() + || eeType == EETypePtr.EETypePtrOf() ) return null; return RuntimeImports.RhNewObject(eeType); @@ -102,7 +102,7 @@ namespace Internal.Runtime.Augments // Unlike the NewObject API, this is the raw version that does not special case any EEType, and should be used with // caution for very specific scenarios. // - public static Object RawNewObject(RuntimeTypeHandle typeHandle) + public static object RawNewObject(RuntimeTypeHandle typeHandle) { return RuntimeImports.RhNewObject(typeHandle.ToEETypePtr()); } @@ -192,7 +192,7 @@ namespace Internal.Runtime.Augments // // Helper to create a delegate on a runtime-supplied type. // - public static Delegate CreateDelegate(RuntimeTypeHandle typeHandleForDelegate, IntPtr ldftnResult, Object thisObject, bool isStatic, bool isOpen) + public static Delegate CreateDelegate(RuntimeTypeHandle typeHandleForDelegate, IntPtr ldftnResult, object thisObject, bool isStatic, bool isOpen) { return Delegate.CreateDelegate(typeHandleForDelegate.ToEETypePtr(), ldftnResult, thisObject, isStatic: isStatic, isOpen: isOpen); } @@ -248,7 +248,7 @@ namespace Internal.Runtime.Augments return new IntPtr(RuntimeImports.RhGetThreadStaticFieldAddress(typeHandle.ToEETypePtr(), threadStaticsBlockOffset, fieldOffset)); } - public static unsafe void StoreValueTypeField(IntPtr address, Object fieldValue, RuntimeTypeHandle fieldType) + public static unsafe void StoreValueTypeField(IntPtr address, object fieldValue, RuntimeTypeHandle fieldType) { RuntimeImports.RhUnbox(fieldValue, *(void**)&address, fieldType.ToEETypePtr()); } @@ -258,7 +258,7 @@ namespace Internal.Runtime.Augments return ref obj.GetRawData(); } - public static unsafe Object LoadValueTypeField(IntPtr address, RuntimeTypeHandle fieldType) + public static unsafe object LoadValueTypeField(IntPtr address, RuntimeTypeHandle fieldType) { return RuntimeImports.RhBox(fieldType.ToEETypePtr(), *(void**)&address); } @@ -268,12 +268,12 @@ namespace Internal.Runtime.Augments return Pointer.Box(*(void**)address, Type.GetTypeFromHandle(fieldType)); } - public static unsafe void StoreValueTypeField(ref byte address, Object fieldValue, RuntimeTypeHandle fieldType) + public static unsafe void StoreValueTypeField(ref byte address, object fieldValue, RuntimeTypeHandle fieldType) { RuntimeImports.RhUnbox(fieldValue, ref address, fieldType.ToEETypePtr()); } - public static unsafe void StoreValueTypeField(Object obj, int fieldOffset, Object fieldValue, RuntimeTypeHandle fieldType) + public static unsafe void StoreValueTypeField(object obj, int fieldOffset, object fieldValue, RuntimeTypeHandle fieldType) { fixed (IntPtr* pObj = &obj.m_pEEType) { @@ -283,7 +283,7 @@ namespace Internal.Runtime.Augments } } - public static unsafe Object LoadValueTypeField(Object obj, int fieldOffset, RuntimeTypeHandle fieldType) + public static unsafe object LoadValueTypeField(object obj, int fieldOffset, RuntimeTypeHandle fieldType) { fixed (IntPtr* pObj = &obj.m_pEEType) { @@ -293,7 +293,7 @@ namespace Internal.Runtime.Augments } } - public static unsafe Object LoadPointerTypeField(Object obj, int fieldOffset, RuntimeTypeHandle fieldType) + public static unsafe object LoadPointerTypeField(object obj, int fieldOffset, RuntimeTypeHandle fieldType) { fixed (IntPtr* pObj = &obj.m_pEEType) { @@ -303,17 +303,17 @@ namespace Internal.Runtime.Augments } } - public static unsafe void StoreReferenceTypeField(IntPtr address, Object fieldValue) + public static unsafe void StoreReferenceTypeField(IntPtr address, object fieldValue) { - Volatile.Write(ref Unsafe.As(ref *(IntPtr*)address), fieldValue); + Volatile.Write(ref Unsafe.As(ref *(IntPtr*)address), fieldValue); } - public static unsafe Object LoadReferenceTypeField(IntPtr address) + public static unsafe object LoadReferenceTypeField(IntPtr address) { - return Volatile.Read(ref Unsafe.As(ref *(IntPtr*)address)); + return Volatile.Read(ref Unsafe.As(ref *(IntPtr*)address)); } - public static unsafe void StoreReferenceTypeField(Object obj, int fieldOffset, Object fieldValue) + public static unsafe void StoreReferenceTypeField(object obj, int fieldOffset, object fieldValue) { fixed (IntPtr* pObj = &obj.m_pEEType) { @@ -323,7 +323,7 @@ namespace Internal.Runtime.Augments } } - public static unsafe Object LoadReferenceTypeField(Object obj, int fieldOffset) + public static unsafe object LoadReferenceTypeField(object obj, int fieldOffset) { fixed (IntPtr* pObj = &obj.m_pEEType) { @@ -473,7 +473,7 @@ namespace Internal.Runtime.Augments // Note that this is not versionable as it is exposed as a const (and needs to be a const so we can used as a custom attribute argument - which // is the other reason this string is not versionable.) // - public const String HiddenScopeAssemblyName = "HiddenScope, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; + public const string HiddenScopeAssemblyName = "HiddenScope, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; // // This implements the "IsAssignableFrom()" api for runtime-created types. By policy, we let the underlying runtime decide assignability. @@ -716,7 +716,7 @@ namespace Internal.Runtime.Augments return true; } - public static Object CheckArgument(Object srcObject, RuntimeTypeHandle dstType, BinderBundle binderBundle) + public static object CheckArgument(object srcObject, RuntimeTypeHandle dstType, BinderBundle binderBundle) { return InvokeUtils.CheckArgument(srcObject, dstType, binderBundle); } @@ -728,7 +728,7 @@ namespace Internal.Runtime.Augments return InvokeUtils.CheckArgument(srcObject, dstType.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.SetFieldDirect, binderBundle: null); } - public static bool IsAssignable(Object srcObject, RuntimeTypeHandle dstType) + public static bool IsAssignable(object srcObject, RuntimeTypeHandle dstType) { EETypePtr srcEEType = srcObject.EETypePtr; return RuntimeImports.AreTypesAssignable(srcEEType, dstType.ToEETypePtr()); @@ -751,9 +751,9 @@ namespace Internal.Runtime.Augments // // Useful helper for finding .pdb's. (This design is admittedly tied to the single-module design of Project N.) // - public static String TryGetFullPathToMainApplication() + public static string TryGetFullPathToMainApplication() { - Func delegateToAnythingInsideMergedApp = TryGetFullPathToMainApplication; + Func delegateToAnythingInsideMergedApp = TryGetFullPathToMainApplication; IntPtr ipToAnywhereInsideMergedApp = delegateToAnythingInsideMergedApp.GetFunctionPointer(out RuntimeTypeHandle _, out bool _, out bool _); IntPtr moduleBase = RuntimeImports.RhGetOSModuleFromPointer(ipToAnywhereInsideMergedApp); return TryGetFullPathToApplicationModule(moduleBase); @@ -763,7 +763,7 @@ namespace Internal.Runtime.Augments /// Locate the file path for a given native application module. /// /// Module base address - public static unsafe String TryGetFullPathToApplicationModule(IntPtr moduleBase) + public static unsafe string TryGetFullPathToApplicationModule(IntPtr moduleBase) { #if PLATFORM_UNIX byte* pModuleNameUtf8; @@ -772,7 +772,7 @@ namespace Internal.Runtime.Augments #else // PLATFORM_UNIX char* pModuleName; int numChars = RuntimeImports.RhGetModuleFileName(moduleBase, out pModuleName); - String modulePath = new String(pModuleName, 0, numChars); + string modulePath = new string(pModuleName, 0, numChars); #endif // PLATFORM_UNIX return modulePath; } @@ -1111,7 +1111,7 @@ namespace Internal.Runtime.Augments return RuntimeImports.RhBoxAny((void*)pData, new EETypePtr(pEEType)); } - public static IntPtr RhHandleAlloc(Object value, GCHandleType type) + public static IntPtr RhHandleAlloc(object value, GCHandleType type) { return RuntimeImports.RhHandleAlloc(value, type); } diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.Unix.cs b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.Unix.cs index 7b9d380e76..bc3a042eb3 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.Unix.cs @@ -144,6 +144,14 @@ namespace Internal.Runtime.Augments return IntPtr.Zero; } + private void InitializeComOnNewThread() + { + } + + internal static void InitializeCom() + { + } + public void Interrupt() => WaitSubsystem.Interrupt(this); internal static void UninterruptibleSleep0() => WaitSubsystem.UninterruptibleSleep0(); private static void SleepInternal(int millisecondsTimeout) => WaitSubsystem.Sleep(millisecondsTimeout); @@ -159,5 +167,17 @@ namespace Internal.Runtime.Augments { throw new PlatformNotSupportedException(); } + + private static int ComputeCurrentProcessorId() + { + int processorId = Interop.Sys.SchedGetCpu(); + + // sched_getcpu doesn't exist on all platforms. On those it doesn't exist on, the shim + // returns -1. As a fallback in that case and to spread the threads across the buckets + // by default, we use the current managed thread ID as a proxy. + if (processorId < 0) processorId = Environment.CurrentManagedThreadId; + + return processorId; + } } } diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.Windows.cs b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.Windows.cs index 6d0e937dcb..e9fe5485b7 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.Windows.cs @@ -21,8 +21,13 @@ namespace Internal.Runtime.Augments [ThreadStatic] private static ApartmentType t_apartmentType; + [ThreadStatic] + private static bool t_comInitializedByUs; + private SafeWaitHandle _osHandle; + private ApartmentState _initialAppartmentState = ApartmentState.Unknown; + /// /// Used by 's multi-wait functions /// @@ -99,7 +104,7 @@ namespace Internal.Runtime.Augments // Throw an ApplicationException for compatibility with CoreCLR. First save the error code. int errorCode = Marshal.GetLastWin32Error(); var ex = new ApplicationException(); - ex.SetErrorCode(errorCode); + ex.HResult = errorCode; throw ex; } @@ -283,10 +288,103 @@ namespace Internal.Runtime.Augments return 0; } - public ApartmentState GetApartmentState() { throw null; } - public bool TrySetApartmentState(ApartmentState state) { throw null; } - public void DisableComObjectEagerCleanup() { throw null; } - public void Interrupt() { throw null; } + public ApartmentState GetApartmentState() + { + if (this != CurrentThread) + { + if (HasStarted()) + throw new ThreadStateException(); + return _initialAppartmentState; + } + + switch (GetCurrentApartmentType()) + { + case ApartmentType.STA: + return ApartmentState.STA; + case ApartmentType.MTA: + return ApartmentState.MTA; + default: + return ApartmentState.Unknown; + } + } + + public bool TrySetApartmentState(ApartmentState state) + { + if (this != CurrentThread) + { + using (LockHolder.Hold(_lock)) + { + if (HasStarted()) + throw new ThreadStateException(); + _initialAppartmentState = state; + return true; + } + } + + if (state != ApartmentState.Unknown) + { + InitializeCom(state); + } + else + { + UninitializeCom(); + } + + // Clear the cache and check whether new state matches the desired state + t_apartmentType = ApartmentType.Unknown; + return state == GetApartmentState(); + } + + private void InitializeComOnNewThread() + { + InitializeCom(_initialAppartmentState); + } + + internal static void InitializeCom(ApartmentState state = ApartmentState.MTA) + { + if (t_comInitializedByUs) + return; + +#if ENABLE_WINRT + int hr = Interop.WinRT.RoInitialize( + (state == ApartmentState.STA) ? Interop.WinRT.RO_INIT_SINGLETHREADED + : Interop.WinRT.RO_INIT_MULTITHREADED); +#else + int hr = Interop.Ole32.CoInitializeEx(IntPtr.Zero, + (state == ApartmentState.STA) ? Interop.Ole32.COINIT_APARTMENTTHREADED + : Interop.Ole32.COINIT_MULTITHREADED); +#endif + // RPC_E_CHANGED_MODE indicates this thread has been already initialized with a different + // concurrency model. We stay away and let whoever else initialized the COM to be in control. + if (hr == HResults.RPC_E_CHANGED_MODE) + return; + if (hr < 0) + throw new OutOfMemoryException(); + + t_comInitializedByUs = true; + + // If the thread has already been CoInitialized to the proper mode, then + // we don't want to leave an outstanding CoInit so we CoUninit. + if (hr > 0) + UninitializeCom(); + } + + private static void UninitializeCom() + { + if (!t_comInitializedByUs) + return; + +#if ENABLE_WINRT + Interop.WinRT.RoUninitialize(); +#else + Interop.Ole32.CoUninitialize(); +#endif + t_comInitializedByUs = false; + } + + // TODO: https://github.com/dotnet/corefx/issues/20766 + public void DisableComObjectEagerCleanup() { } + public void Interrupt() { throw new PlatformNotSupportedException(); } internal static void UninterruptibleSleep0() { @@ -324,40 +422,40 @@ namespace Internal.Runtime.Augments if (currentThreadType != ApartmentType.Unknown) return currentThreadType; - Interop._APTTYPE aptType; - Interop._APTTYPEQUALIFIER aptTypeQualifier; - int result = Interop.mincore.CoGetApartmentType(out aptType, out aptTypeQualifier); + Interop.APTTYPE aptType; + Interop.APTTYPEQUALIFIER aptTypeQualifier; + int result = Interop.Ole32.CoGetApartmentType(out aptType, out aptTypeQualifier); ApartmentType type = ApartmentType.Unknown; - switch ((Interop.Constants)result) + switch (result) { - case Interop.Constants.CoENotInitialized: + case HResults.CO_E_NOTINITIALIZED: type = ApartmentType.None; break; - case Interop.Constants.SOk: + case HResults.S_OK: switch (aptType) { - case Interop._APTTYPE.APTTYPE_STA: - case Interop._APTTYPE.APTTYPE_MAINSTA: + case Interop.APTTYPE.APTTYPE_STA: + case Interop.APTTYPE.APTTYPE_MAINSTA: type = ApartmentType.STA; break; - case Interop._APTTYPE.APTTYPE_MTA: + case Interop.APTTYPE.APTTYPE_MTA: type = ApartmentType.MTA; break; - case Interop._APTTYPE.APTTYPE_NA: + case Interop.APTTYPE.APTTYPE_NA: switch (aptTypeQualifier) { - case Interop._APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_MTA: - case Interop._APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_IMPLICIT_MTA: + case Interop.APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_MTA: + case Interop.APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_IMPLICIT_MTA: type = ApartmentType.MTA; break; - case Interop._APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_STA: - case Interop._APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_MAINSTA: + case Interop.APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_STA: + case Interop.APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_MAINSTA: type = ApartmentType.STA; break; @@ -386,5 +484,7 @@ namespace Internal.Runtime.Augments STA, MTA } + + private static int ComputeCurrentProcessorId() => (int)Interop.mincore.GetCurrentProcessorNumber(); } } diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.cs b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.cs index b21d9ced8b..b3e9a14fef 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.cs @@ -7,6 +7,7 @@ using System; using System.Diagnostics; using System.Globalization; using System.Runtime; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; @@ -79,6 +80,14 @@ namespace Internal.Runtime.Augments } } + internal static ulong CurrentOSThreadId + { + get + { + return RuntimeImports.RhCurrentOSThreadId(); + } + } + // Slow path executed once per thread private static RuntimeThread InitializeExistingThread(bool threadPoolThread) { @@ -103,7 +112,7 @@ namespace Internal.Runtime.Augments if (threadPoolThread) { - RoInitialize(); + InitializeCom(); } return currentThread; @@ -141,16 +150,6 @@ namespace Internal.Runtime.Augments } } - /// - /// Ensures the Windows Runtime is initialized on the current thread. - /// - internal static void RoInitialize() - { -#if ENABLE_WINRT - Interop.WinRT.RoInitialize(); -#endif - } - /// /// Returns true if the underlying OS thread has been created and started execution of managed code. /// @@ -370,6 +369,7 @@ namespace Internal.Runtime.Augments return JoinInternal(millisecondsTimeout); } + [MethodImpl(MethodImplOptions.NoInlining)] // Slow path method. Make sure that the caller frame does not pay for PInvoke overhead. public static void Sleep(int millisecondsTimeout) => SleepInternal(VerifyTimeoutMilliseconds(millisecondsTimeout)); /// @@ -381,6 +381,8 @@ namespace Internal.Runtime.Augments internal static readonly int OptimalMaxSpinWaitsPerSpinIteration = 64; public static void SpinWait(int iterations) => RuntimeImports.RhSpinWait(iterations); + + [MethodImpl(MethodImplOptions.NoInlining)] // Slow path method. Make sure that the caller frame does not pay for PInvoke overhead. public static bool Yield() => RuntimeImports.RhYield(); public void Start() => StartInternal(null); @@ -455,7 +457,7 @@ namespace Internal.Runtime.Augments { t_currentThread = thread; System.Threading.ManagedThreadId.SetForCurrentThread(thread._managedThreadId); - RoInitialize(); + thread.InitializeComOnNewThread(); } catch (OutOfMemoryException) { @@ -491,5 +493,42 @@ namespace Internal.Runtime.Augments thread.SetThreadStateBit(ThreadState.Stopped); } } + + // The upper bits of t_currentProcessorIdCache are the currentProcessorId. The lower bits of + // the t_currentProcessorIdCache are counting down to get it periodically refreshed. + // TODO: Consider flushing the currentProcessorIdCache on Wait operations or similar + // actions that are likely to result in changing the executing core + [ThreadStatic] + private static int t_currentProcessorIdCache; + + private const int ProcessorIdCacheShift = 16; + private const int ProcessorIdCacheCountDownMask = (1 << ProcessorIdCacheShift) - 1; + private const int ProcessorIdRefreshRate = 5000; + + private static int RefreshCurrentProcessorId() + { + int currentProcessorId = ComputeCurrentProcessorId(); + + // Add offset to make it clear that it is not guaranteed to be 0-based processor number + currentProcessorId += 100; + + Debug.Assert(ProcessorIdRefreshRate <= ProcessorIdCacheCountDownMask); + + // Mask with int.MaxValue to ensure the execution Id is not negative + t_currentProcessorIdCache = ((currentProcessorId << ProcessorIdCacheShift) & int.MaxValue) + ProcessorIdRefreshRate; + + return currentProcessorId; + } + + // Cached processor id used as a hint for which per-core stack to access. It is periodically + // refreshed to trail the actual thread core affinity. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int GetCurrentProcessorId() + { + int currentProcessorIdCache = t_currentProcessorIdCache--; + if ((currentProcessorIdCache & ProcessorIdCacheCountDownMask) == 0) + return RefreshCurrentProcessorId(); + return (currentProcessorIdCache >> ProcessorIdCacheShift); + } } } diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/InteropHelpers.cs b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/InteropHelpers.cs index ad79c2510b..dc598bbb76 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/InteropHelpers.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/InteropHelpers.cs @@ -3,10 +3,11 @@ // See the LICENSE file in the project root for more information. using System; -using System.Text; -using System.Runtime.InteropServices; using System.Diagnostics; -using Interlocked = System.Threading.Interlocked; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; namespace Internal.Runtime.CompilerHelpers { @@ -15,7 +16,7 @@ namespace Internal.Runtime.CompilerHelpers /// internal static class InteropHelpers { - internal static unsafe byte* StringToAnsiString(String str, bool bestFit, bool throwOnUnmappableChar) + internal static unsafe byte* StringToAnsiString(string str, bool bestFit, bool throwOnUnmappableChar) { return PInvokeMarshal.StringToAnsiString(str, bestFit, throwOnUnmappableChar); } @@ -37,7 +38,7 @@ namespace Internal.Runtime.CompilerHelpers return PInvokeMarshal.ByValAnsiStringToString(buffer, length); } - internal static unsafe void StringToUnicodeFixedArray(String str, UInt16* buffer, int length) + internal static unsafe void StringToUnicodeFixedArray(string str, ushort* buffer, int length) { if (buffer == null) return; @@ -58,16 +59,16 @@ namespace Internal.Runtime.CompilerHelpers } } - internal static unsafe string UnicodeToStringFixedArray(UInt16* buffer, int length) + internal static unsafe string UnicodeToStringFixedArray(ushort* buffer, int length) { if (buffer == null) - return String.Empty; + return string.Empty; - string result = String.Empty; + string result = string.Empty; if (length > 0) { - result = new String(' ', length); + result = new string(' ', length); fixed (char* pTemp = result) { @@ -78,7 +79,7 @@ namespace Internal.Runtime.CompilerHelpers return result; } - internal static unsafe char* StringToUnicodeBuffer(String str) + internal static unsafe char* StringToUnicodeBuffer(string str) { if (str == null) return null; @@ -98,7 +99,7 @@ namespace Internal.Runtime.CompilerHelpers public static unsafe string UnicodeBufferToString(char* buffer) { - return new String(buffer); + return new string(buffer); } public static unsafe byte* AllocMemoryForAnsiStringBuilder(StringBuilder sb) @@ -208,6 +209,7 @@ namespace Internal.Runtime.CompilerHelpers return ResolvePInvokeSlow(pCell); } + [MethodImpl(MethodImplOptions.NoInlining)] internal static unsafe IntPtr ResolvePInvokeSlow(MethodFixupCell* pCell) { ModuleFixupCell* pModuleCell = pCell->Module; @@ -304,8 +306,8 @@ namespace Internal.Runtime.CompilerHelpers { byte* methodName = (byte*)pCell->MethodName; -#if !PLATFORM_UNIX - pCell->Target = Interop.mincore.GetProcAddress(hModule, methodName); +#if PLATFORM_WINDOWS + pCell->Target = GetProcAddress(hModule, methodName, pCell->CharSetMangling); #else pCell->Target = Interop.Sys.GetProcAddress(hModule, methodName); #endif @@ -316,6 +318,44 @@ namespace Internal.Runtime.CompilerHelpers } } +#if PLATFORM_WINDOWS + private static unsafe IntPtr GetProcAddress(IntPtr hModule, byte* methodName, CharSet charSetMangling) + { + // First look for the unmangled name. If it is unicode function, we are going + // to need to check for the 'W' API because it takes precedence over the + // unmangled one (on NT some APIs have unmangled ANSI exports). + + var exactMatch = Interop.mincore.GetProcAddress(hModule, methodName); + + if ((charSetMangling == CharSet.Ansi && exactMatch != IntPtr.Zero) || charSetMangling == 0) + { + return exactMatch; + } + + int nameLength = strlen(methodName); + + // We need to add an extra byte for the suffix, and an extra byte for the null terminator + byte* probedMethodName = stackalloc byte[nameLength + 2]; + + for (int i = 0; i < nameLength; i++) + { + probedMethodName[i] = methodName[i]; + } + + probedMethodName[nameLength + 1] = 0; + + probedMethodName[nameLength] = (charSetMangling == CharSet.Ansi) ? (byte)'A' : (byte)'W'; + + IntPtr probedMethod = Interop.mincore.GetProcAddress(hModule, probedMethodName); + if (probedMethod != IntPtr.Zero) + { + return probedMethod; + } + + return exactMatch; + } +#endif + internal static unsafe int strlen(byte* pString) { byte* p = pString; @@ -379,6 +419,7 @@ namespace Internal.Runtime.CompilerHelpers public IntPtr Target; public IntPtr MethodName; public ModuleFixupCell* Module; + public CharSet CharSetMangling; } } } diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/MathHelpers.cs b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/MathHelpers.cs index c31521d806..6947cc9f30 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/MathHelpers.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/MathHelpers.cs @@ -24,64 +24,64 @@ namespace Internal.Runtime.CompilerHelpers // Helper to multiply two 32-bit uints [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static UInt64 Mul32x32To64(UInt32 a, UInt32 b) + private static ulong Mul32x32To64(uint a, uint b) { - return a * (UInt64)b; + return a * (ulong)b; } // Helper to get high 32-bit of 64-bit int [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static UInt32 Hi32Bits(Int64 a) + private static uint Hi32Bits(long a) { - return (UInt32)(a >> 32); + return (uint)(a >> 32); } // Helper to get high 32-bit of 64-bit int [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static UInt32 Hi32Bits(UInt64 a) + private static uint Hi32Bits(ulong a) { - return (UInt32)(a >> 32); + return (uint)(a >> 32); } [RuntimeExport("LMulOvf")] - public static Int64 LMulOvf(Int64 i, Int64 j) + public static long LMulOvf(long i, long j) { - Int64 ret; + long ret; // Remember the sign of the result - Int32 sign = (Int32)(Hi32Bits(i) ^ Hi32Bits(j)); + int sign = (int)(Hi32Bits(i) ^ Hi32Bits(j)); // Convert to unsigned multiplication if (i < 0) i = -i; if (j < 0) j = -j; // Get the upper 32 bits of the numbers - UInt32 val1High = Hi32Bits(i); - UInt32 val2High = Hi32Bits(j); + uint val1High = Hi32Bits(i); + uint val2High = Hi32Bits(j); - UInt64 valMid; + ulong valMid; if (val1High == 0) { // Compute the 'middle' bits of the long multiplication - valMid = Mul32x32To64(val2High, (UInt32)i); + valMid = Mul32x32To64(val2High, (uint)i); } else { if (val2High != 0) goto ThrowExcep; // Compute the 'middle' bits of the long multiplication - valMid = Mul32x32To64(val1High, (UInt32)j); + valMid = Mul32x32To64(val1High, (uint)j); } // See if any bits after bit 32 are set if (Hi32Bits(valMid) != 0) goto ThrowExcep; - ret = (Int64)(Mul32x32To64((UInt32)i, (UInt32)j) + (valMid << 32)); + ret = (long)(Mul32x32To64((uint)i, (uint)j) + (valMid << 32)); // check for overflow - if (Hi32Bits(ret) < (UInt32)valMid) + if (Hi32Bits(ret) < (uint)valMid) goto ThrowExcep; if (sign >= 0) @@ -104,39 +104,39 @@ namespace Internal.Runtime.CompilerHelpers } [RuntimeExport("ULMulOvf")] - public static UInt64 ULMulOvf(UInt64 i, UInt64 j) + public static ulong ULMulOvf(ulong i, ulong j) { - UInt64 ret; + ulong ret; // Get the upper 32 bits of the numbers - UInt32 val1High = Hi32Bits(i); - UInt32 val2High = Hi32Bits(j); + uint val1High = Hi32Bits(i); + uint val2High = Hi32Bits(j); - UInt64 valMid; + ulong valMid; if (val1High == 0) { if (val2High == 0) - return Mul32x32To64((UInt32)i, (UInt32)j); + return Mul32x32To64((uint)i, (uint)j); // Compute the 'middle' bits of the long multiplication - valMid = Mul32x32To64(val2High, (UInt32)i); + valMid = Mul32x32To64(val2High, (uint)i); } else { if (val2High != 0) goto ThrowExcep; // Compute the 'middle' bits of the long multiplication - valMid = Mul32x32To64(val1High, (UInt32)j); + valMid = Mul32x32To64(val1High, (uint)j); } // See if any bits after bit 32 are set if (Hi32Bits(valMid) != 0) goto ThrowExcep; - ret = Mul32x32To64((UInt32)i, (UInt32)j) + (valMid << 32); + ret = Mul32x32To64((uint)i, (uint)j) + (valMid << 32); // check for overflow - if (Hi32Bits(ret) < (UInt32)valMid) + if (Hi32Bits(ret) < (uint)valMid) goto ThrowExcep; return ret; @@ -212,7 +212,7 @@ namespace Internal.Runtime.CompilerHelpers // Note that this expression also works properly for val = NaN case // We need to compare with the very next double to two63. 0x402 is epsilon to get us there. if (val > -two63 - 0x402 && val < two63) - return ((Int64)val); + return ((long)val); return ThrowIntOvf(); } @@ -222,13 +222,13 @@ namespace Internal.Runtime.CompilerHelpers [RuntimeImport(RuntimeLibrary, "RhpIDiv")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern Int32 RhpIDiv(Int32 i, Int32 j); + private static extern int RhpIDiv(int i, int j); - public static int IDiv(Int32 i, Int32 j) + public static int IDiv(int i, int j) { if (j == 0) return ThrowIntDivByZero(); - else if (j == -1 && i == Int32.MinValue) + else if (j == -1 && i == int.MinValue) return ThrowIntArithExc(); else return RhpIDiv(i, j); @@ -236,9 +236,9 @@ namespace Internal.Runtime.CompilerHelpers [RuntimeImport(RuntimeLibrary, "RhpUDiv")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern UInt32 RhpUDiv(UInt32 i, UInt32 j); + private static extern uint RhpUDiv(uint i, uint j); - public static long UDiv(UInt32 i, UInt32 j) + public static long UDiv(uint i, uint j) { if (j == 0) return ThrowUIntDivByZero(); @@ -248,9 +248,9 @@ namespace Internal.Runtime.CompilerHelpers [RuntimeImport(RuntimeLibrary, "RhpULDiv")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern UInt64 RhpULDiv(UInt64 i, UInt64 j); + private static extern ulong RhpULDiv(ulong i, ulong j); - public static ulong ULDiv(UInt64 i, UInt64 j) + public static ulong ULDiv(ulong i, ulong j) { if (j == 0) return ThrowULngDivByZero(); @@ -260,13 +260,13 @@ namespace Internal.Runtime.CompilerHelpers [RuntimeImport(RuntimeLibrary, "RhpLDiv")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern Int64 RhpLDiv(Int64 i, Int64 j); + private static extern long RhpLDiv(long i, long j); - public static long LDiv(Int64 i, Int64 j) + public static long LDiv(long i, long j) { if (j == 0) return ThrowLngDivByZero(); - else if (j == -1 && i == Int64.MinValue) + else if (j == -1 && i == long.MinValue) return ThrowLngArithExc(); else return RhpLDiv(i, j); @@ -274,9 +274,9 @@ namespace Internal.Runtime.CompilerHelpers [RuntimeImport(RuntimeLibrary, "RhpIMod")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern Int32 RhpIMod(Int32 i, Int32 j); + private static extern int RhpIMod(int i, int j); - public static int IMod(Int32 i, Int32 j) + public static int IMod(int i, int j) { if (j == 0) return ThrowIntDivByZero(); @@ -286,9 +286,9 @@ namespace Internal.Runtime.CompilerHelpers [RuntimeImport(RuntimeLibrary, "RhpUMod")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern UInt32 RhpUMod(UInt32 i, UInt32 j); + private static extern uint RhpUMod(uint i, uint j); - public static long UMod(UInt32 i, UInt32 j) + public static long UMod(uint i, uint j) { if (j == 0) return ThrowUIntDivByZero(); @@ -298,9 +298,9 @@ namespace Internal.Runtime.CompilerHelpers [RuntimeImport(RuntimeLibrary, "RhpULMod")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern UInt64 RhpULMod(UInt64 i, UInt64 j); + private static extern ulong RhpULMod(ulong i, ulong j); - public static ulong ULMod(UInt64 i, UInt64 j) + public static ulong ULMod(ulong i, ulong j) { if (j == 0) return ThrowULngDivByZero(); @@ -310,9 +310,9 @@ namespace Internal.Runtime.CompilerHelpers [RuntimeImport(RuntimeLibrary, "RhpLMod")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern Int64 RhpLMod(Int64 i, Int64 j); + private static extern long RhpLMod(long i, long j); - public static long LMod(Int64 i, Int64 j) + public static long LMod(long i, long j) { if (j == 0) return ThrowLngDivByZero(); diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/SynchronizedMethodHelpers.cs b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/SynchronizedMethodHelpers.cs index 30694aeadb..018c8005c3 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/SynchronizedMethodHelpers.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/SynchronizedMethodHelpers.cs @@ -54,7 +54,7 @@ namespace Internal.Runtime.CompilerHelpers lockTaken = false; } - private static Object GetStaticLockObject(IntPtr pEEType) + private static object GetStaticLockObject(IntPtr pEEType) { return Internal.Reflection.Core.NonPortable.RuntimeTypeUnifier.GetRuntimeTypeForEEType(new System.EETypePtr(pEEType)); } diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/RelocatedTypeAttribute.cs b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/RelocatedTypeAttribute.cs index a848f5a94a..74363b72b9 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/RelocatedTypeAttribute.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/RelocatedTypeAttribute.cs @@ -19,7 +19,7 @@ namespace Internal.Runtime.CompilerServices /// /// Simple name of the CoreFX assembly the type was relocated from. /// For example, System.Collections (with no version or public key token) - public RelocatedTypeAttribute(String originalAssemblySimpleName) + public RelocatedTypeAttribute(string originalAssemblySimpleName) { } } diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/ThreadStatics.cs b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/ThreadStatics.cs index db6977ee52..be6537858b 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/ThreadStatics.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/Runtime/ThreadStatics.cs @@ -4,6 +4,7 @@ using System; using System.Runtime; +using System.Runtime.CompilerServices; using Internal.Runtime.CompilerHelpers; namespace Internal.Runtime @@ -18,21 +19,29 @@ namespace Internal.Runtime /// This method is called from a ReadyToRun helper to get base address of thread /// static storage for the given type. /// - internal static unsafe object GetThreadStaticBaseForType(TypeManagerSlot* pModuleData, Int32 typeTlsIndex) + internal static unsafe object GetThreadStaticBaseForType(TypeManagerSlot* pModuleData, int typeTlsIndex) { // Get the array that holds thread static memory blocks for each type in the given module - Int32 moduleIndex = pModuleData->ModuleIndex; - object[] storage = (object[])RuntimeImports.RhGetThreadStaticStorageForModule(moduleIndex); + object[] storage = RuntimeImports.RhGetThreadStaticStorageForModule(pModuleData->ModuleIndex); // Check whether thread static storage has already been allocated for this module and type. - if ((storage != null) && (typeTlsIndex < storage.Length) && (storage[typeTlsIndex] != null)) + if ((storage != null) && ((uint)typeTlsIndex < (uint)storage.Length) && (storage[typeTlsIndex] != null)) { return storage[typeTlsIndex]; } + return GetThreadStaticBaseForTypeSlow(pModuleData, typeTlsIndex); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + internal static unsafe object GetThreadStaticBaseForTypeSlow(TypeManagerSlot* pModuleData, int typeTlsIndex) + { + // Get the array that holds thread static memory blocks for each type in the given module + object[] storage = RuntimeImports.RhGetThreadStaticStorageForModule(pModuleData->ModuleIndex); + // This the first access to the thread statics of the type corresponding to typeTlsIndex. // Make sure there is enough storage allocated to hold it. - storage = EnsureThreadStaticStorage(moduleIndex, storage, requiredSize: typeTlsIndex + 1); + storage = EnsureThreadStaticStorage(pModuleData->ModuleIndex, storage, requiredSize: typeTlsIndex + 1); // Allocate an object that will represent a memory block for all thread static fields of the type object threadStaticBase = AllocateThreadStaticStorageForType(pModuleData->TypeManager, typeTlsIndex); @@ -45,7 +54,7 @@ namespace Internal.Runtime /// if it is required, this method extends thread static storage of the given module /// to the specified size and then registers the memory with the runtime. /// - private static object[] EnsureThreadStaticStorage(Int32 moduleIndex, object[] existingStorage, Int32 requiredSize) + private static object[] EnsureThreadStaticStorage(int moduleIndex, object[] existingStorage, int requiredSize) { if ((existingStorage != null) && (requiredSize < existingStorage.Length)) { @@ -73,9 +82,9 @@ namespace Internal.Runtime /// This method allocates an object that represents a memory block for all thread static fields of the type /// that corresponds to the specified TLS index. /// - private static unsafe object AllocateThreadStaticStorageForType(TypeManagerHandle typeManager, Int32 typeTlsIndex) + private static unsafe object AllocateThreadStaticStorageForType(TypeManagerHandle typeManager, int typeTlsIndex) { - Int32 length; + int length; IntPtr* threadStaticRegion; // Get a pointer to the beginning of the module's Thread Static section. Then get a pointer diff --git a/external/corert/src/System.Private.CoreLib/src/Internal/Threading/Tasks/AsyncCausalitySupport.cs b/external/corert/src/System.Private.CoreLib/src/Internal/Threading/Tasks/AsyncCausalitySupport.cs index f9cd9d037d..ef427a3ca6 100644 --- a/external/corert/src/System.Private.CoreLib/src/Internal/Threading/Tasks/AsyncCausalitySupport.cs +++ b/external/corert/src/System.Private.CoreLib/src/Internal/Threading/Tasks/AsyncCausalitySupport.cs @@ -42,7 +42,7 @@ namespace Internal.Threading.Tasks } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void TraceOperationCreation(Task task, String operationName) + public static void TraceOperationCreation(Task task, string operationName) { DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, task, operationName, 0); } diff --git a/external/corert/src/System.Private.CoreLib/src/Interop/Interop.WinRT.cs b/external/corert/src/System.Private.CoreLib/src/Interop/Interop.WinRT.cs index 741ce4f21f..0823dcffc1 100644 --- a/external/corert/src/System.Private.CoreLib/src/Interop/Interop.WinRT.cs +++ b/external/corert/src/System.Private.CoreLib/src/Interop/Interop.WinRT.cs @@ -11,26 +11,13 @@ internal partial class Interop { private const string CORE_WINRT = "api-ms-win-core-winrt-l1-1-0.dll"; - private const int RPC_E_CHANGED_MODE = unchecked((int)0x80010106); - - private enum RO_INIT_TYPE : uint - { - RO_INIT_MULTITHREADED = 1 - } - - internal static void RoInitialize() - { - int hr = RoInitialize((uint)RO_INIT_TYPE.RO_INIT_MULTITHREADED); - - // RPC_E_CHANGED_MODE indicates this thread has been already initialized with a different - // concurrency model. That is fine; we just need to skip the RoUninitialize call on shutdown. - if ((hr < 0) && (hr != RPC_E_CHANGED_MODE)) - { - throw new OutOfMemoryException(); - } - } + internal const uint RO_INIT_SINGLETHREADED = 0; + internal const uint RO_INIT_MULTITHREADED = 1; [DllImport(CORE_WINRT, ExactSpelling = true)] - private static extern int RoInitialize(uint initType); + internal static extern int RoInitialize(uint initType); + + [DllImport(CORE_WINRT, ExactSpelling = true)] + internal static extern int RoUninitialize(); } } diff --git a/external/corert/src/System.Private.CoreLib/src/Interop/Interop.manual.cs b/external/corert/src/System.Private.CoreLib/src/Interop/Interop.manual.cs index c1785e5d3b..b54b155224 100644 --- a/external/corert/src/System.Private.CoreLib/src/Interop/Interop.manual.cs +++ b/external/corert/src/System.Private.CoreLib/src/Interop/Interop.manual.cs @@ -10,51 +10,18 @@ internal partial class Interop internal enum Constants : uint { WaitObject0 = 0x0u, - SOk = 0x0u, FailFastGenerateExceptionAddress = 0x1u, ExceptionNonContinuable = 0x1u, - CreateMutexInitialOwner = 0x1u, - CreateEventManualReset = 0x1u, - MutexModifyState = 0x1u, - CreateEventInitialSet = 0x2u, - SemaphoreModifyState = 0x2u, - EventModifyState = 0x2u, DuplicateSameAccess = 0x2u, - FileTypeChar = 0x2u, CreateSuspended = 0x4u, WaitAbandoned0 = 0x80u, WaitTimeout = 0x102u, StackSizeParamIsAReservation = 0x10000u, - Synchronize = 0x100000u, - MaximumAllowed = 0x02000000u, - EFail = 0x80004005u, - CoENotInitialized = 0x800401F0u, WaitFailed = 0xFFFFFFFFu, } - // MCG doesn't currently support constants that are not uint. internal static IntPtr InvalidHandleValue => new IntPtr(-1); - internal enum _APTTYPE : uint - { - APTTYPE_STA = 0x0u, - APTTYPE_MTA = 0x1u, - APTTYPE_NA = 0x2u, - APTTYPE_MAINSTA = 0x3u, - APTTYPE_CURRENT = 0xFFFFFFFFu, - } - - internal enum _APTTYPEQUALIFIER : uint - { - APTTYPEQUALIFIER_NONE = 0x0u, - APTTYPEQUALIFIER_IMPLICIT_MTA = 0x1u, - APTTYPEQUALIFIER_NA_ON_MTA = 0x2u, - APTTYPEQUALIFIER_NA_ON_STA = 0x3u, - APTTYPEQUALIFIER_NA_ON_IMPLICIT_MTA = 0x4u, - APTTYPEQUALIFIER_NA_ON_MAINSTA = 0x5u, - APTTYPEQUALIFIER_APPLICATION_STA = 0x6u, - } - #pragma warning disable 649 internal unsafe struct _EXCEPTION_RECORD { @@ -73,9 +40,6 @@ internal partial class Interop internal partial class mincore { - [DllImport("api-ms-win-core-com-l1-1-0.dll")] - internal extern static int CoGetApartmentType(out _APTTYPE pAptType, out _APTTYPEQUALIFIER pAptQualifier); - [DllImport("api-ms-win-core-debug-l1-1-0.dll", EntryPoint = "IsDebuggerPresent", CharSet = CharSet.Unicode)] internal extern static bool IsDebuggerPresent(); diff --git a/external/corert/src/System.Private.CoreLib/src/MembersMustExist.AnalyzerData b/external/corert/src/System.Private.CoreLib/src/MembersMustExist.AnalyzerData index 840e4bba11..c2c9ba98f3 100644 --- a/external/corert/src/System.Private.CoreLib/src/MembersMustExist.AnalyzerData +++ b/external/corert/src/System.Private.CoreLib/src/MembersMustExist.AnalyzerData @@ -215,8 +215,7 @@ public string System.IntPtr.ToString(string format) private static System.Text.StringBuilder System.Text.StringBuilderCache.t_cachedInstance private int string._stringLength private char string._firstChar -private void* System.IntPtr._value -private static volatile System.Collections.Generic.ArraySortHelper System.Collections.Generic.ArraySortHelper.s_defaultArraySortHelper +private readonly void* System.IntPtr._value private static volatile System.Globalization.CultureInfo System.Globalization.CultureInfo.s_DefaultThreadCurrentCulture private static volatile System.Globalization.CultureInfo System.Globalization.CultureInfo.s_DefaultThreadCurrentUICulture private static readonly System.Globalization.CultureInfo System.Globalization.CultureInfo.s_InvariantCultureInfo diff --git a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/Registry.cs b/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/Registry.cs deleted file mode 100644 index 4afd135aca..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/Registry.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - - -using System; - -namespace Microsoft.Win32 -{ - /** - * Registry encapsulation. Contains members representing all top level system - * keys. - * - * @security(checkClassLinking=on) - */ - //This class contains only static members and does not need to be serializable. - internal static class Registry - { - /** - * Current User Key. - * - * This key should be used as the root for all user specific settings. - */ - public static readonly RegistryKey CurrentUser = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_USER); - - /** - * Local Machine Key. - * - * This key should be used as the root for all machine specific settings. - */ - public static readonly RegistryKey LocalMachine = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE); - } -} - diff --git a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryKey.Windows.cs b/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryKey.Windows.cs index 6b0cc89629..b9221327e1 100644 --- a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryKey.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryKey.Windows.cs @@ -4,6 +4,7 @@ using Microsoft.Win32.SafeHandles; using System; +using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; @@ -75,14 +76,14 @@ namespace Microsoft.Win32 // the dispose below and usage elsewhere (other threads). This is By Design. // This is less of an issue when OS > NT5 (i.e Vista & higher), we can close the perfkey // (to release & refresh PERFLIB resources) and the OS will rebuild PERFLIB as necessary. - Interop.mincore.RegCloseKey(HKEY_PERFORMANCE_DATA); + Interop.Advapi32.RegCloseKey(HKEY_PERFORMANCE_DATA); } private void FlushCore() { if (_hkey != null && IsDirty()) { - Interop.mincore.RegFlushKey(_hkey); + Interop.Advapi32.RegFlushKey(_hkey); } } @@ -93,7 +94,7 @@ namespace Microsoft.Win32 // By default, the new key will be writable. SafeRegistryHandle result = null; - int ret = Interop.mincore.RegCreateKeyEx(_hkey, + int ret = Interop.Advapi32.RegCreateKeyEx(_hkey, subkey, 0, null, @@ -185,7 +186,7 @@ namespace Microsoft.Win32 private RegistryKey InternalOpenSubKeyCore(string name, RegistryRights rights, bool throwOnPermissionFailure) { SafeRegistryHandle result = null; - int ret = Interop.mincore.RegOpenKeyEx(_hkey, name, 0, ((int)rights | (int)_regView), out result); + int ret = Interop.Advapi32.RegOpenKeyEx(_hkey, name, 0, ((int)rights | (int)_regView), out result); if (ret == 0 && !result.IsInvalid) { RegistryKey key = new RegistryKey(result, IsWritable((int)rights), false, _remoteKey, false, _regView); @@ -242,7 +243,7 @@ namespace Microsoft.Win32 // open the base key so that RegistryKey.Handle will return a valid handle SafeRegistryHandle result; - ret = Interop.mincore.RegOpenKeyEx(baseKey, + ret = Interop.Advapi32.RegOpenKeyEx(baseKey, null, 0, (int)GetRegistryKeyRights(IsWritable()) | (int)_regView, @@ -264,7 +265,7 @@ namespace Microsoft.Win32 { int subkeys = 0; int junk = 0; - int ret = Interop.mincore.RegQueryInfoKey(_hkey, + int ret = Interop.Advapi32.RegQueryInfoKey(_hkey, null, null, IntPtr.Zero, @@ -285,43 +286,52 @@ namespace Microsoft.Win32 return subkeys; } - private unsafe string[] InternalGetSubKeyNamesCore(int subkeys) + private string[] InternalGetSubKeyNamesCore(int subkeys) { - string[] names = new string[subkeys]; - char[] name = new char[MaxKeyLength + 1]; + var names = new List(subkeys); + char[] name = ArrayPool.Shared.Rent(MaxKeyLength + 1); - int namelen; - - fixed (char* namePtr = &name[0]) + try { - for (int i = 0; i < subkeys; i++) - { - namelen = name.Length; // Don't remove this. The API's doesn't work if this is not properly initialized. - int ret = Interop.mincore.RegEnumKeyEx(_hkey, - i, - namePtr, - ref namelen, - null, - null, - null, - null); - if (ret != 0) - { - Win32Error(ret, null); - } + int result; + int nameLength = name.Length; - names[i] = new string(namePtr); + while ((result = Interop.Advapi32.RegEnumKeyEx( + _hkey, + names.Count, + name, + ref nameLength, + null, + null, + null, + null)) != Interop.Errors.ERROR_NO_MORE_ITEMS) + { + switch (result) + { + case Interop.Errors.ERROR_SUCCESS: + names.Add(new string(name, 0, nameLength)); + nameLength = name.Length; + break; + default: + // Throw the error + Win32Error(result, null); + break; + } } } + finally + { + ArrayPool.Shared.Return(name); + } - return names; + return names.ToArray(); } private int InternalValueCountCore() { int values = 0; int junk = 0; - int ret = Interop.mincore.RegQueryInfoKey(_hkey, + int ret = Interop.Advapi32.RegQueryInfoKey(_hkey, null, null, IntPtr.Zero, @@ -345,37 +355,79 @@ namespace Microsoft.Win32 /// All value names. private unsafe string[] GetValueNamesCore(int values) { - string[] names = new string[values]; - char[] name = new char[MaxValueLength + 1]; - int namelen; + var names = new List(values); - fixed (char* namePtr = &name[0]) + // Names in the registry aren't usually very long, although they can go to as large + // as 16383 characters (MaxValueLength). + // + // Every call to RegEnumValue will allocate another buffer to get the data from + // NtEnumerateValueKey before copying it back out to our passed in buffer. This can + // add up quickly- we'll try to keep the memory pressure low and grow the buffer + // only if needed. + + char[] name = ArrayPool.Shared.Rent(100); + + try { - for (int i = 0; i < values; i++) + int result; + int nameLength = name.Length; + + while ((result = Interop.Advapi32.RegEnumValue( + _hkey, + names.Count, + name, + ref nameLength, + IntPtr.Zero, + null, + null, + null)) != Interop.Errors.ERROR_NO_MORE_ITEMS) { - namelen = name.Length; - - int ret = Interop.mincore.RegEnumValue(_hkey, - i, - namePtr, - ref namelen, - IntPtr.Zero, - null, - null, - null); - - if (ret != 0) + switch (result) { - // ignore ERROR_MORE_DATA if we're querying HKEY_PERFORMANCE_DATA - if (!(IsPerfDataKey() && ret == Interop.Errors.ERROR_MORE_DATA)) - Win32Error(ret, null); + // The size is only ever reported back correctly in the case + // of ERROR_SUCCESS. It will almost always be changed, however. + case Interop.Errors.ERROR_SUCCESS: + names.Add(new string(name, 0, nameLength)); + break; + case Interop.Errors.ERROR_MORE_DATA: + if (IsPerfDataKey()) + { + // Enumerating the values for Perf keys always returns + // ERROR_MORE_DATA, but has a valid name. Buffer does need + // to be big enough however. 8 characters is the largest + // known name. The size isn't returned, but the string is + // null terminated. + fixed (char* c = &name[0]) + { + names.Add(new string(c)); + } + } + else + { + char[] oldName = name; + int oldLength = oldName.Length; + name = null; + ArrayPool.Shared.Return(oldName); + name = ArrayPool.Shared.Rent(checked(oldLength * 2)); + } + break; + default: + // Throw the error + Win32Error(result, null); + break; } - names[i] = new string(namePtr); + // Always set the name length back to the buffer size + nameLength = name.Length; } } + finally + { + if (name != null) + ArrayPool.Shared.Return(name); + } - return names; + return names.ToArray(); } private object InternalGetValueCore(string name, object defaultValue, bool doNotExpand) @@ -384,7 +436,7 @@ namespace Microsoft.Win32 int type = 0; int datasize = 0; - int ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize); + int ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize); if (ret != 0) { @@ -395,17 +447,17 @@ namespace Microsoft.Win32 int r; byte[] blob = new byte[size]; - while (Interop.Errors.ERROR_MORE_DATA == (r = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, blob, ref sizeInput))) + while (Interop.Errors.ERROR_MORE_DATA == (r = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref sizeInput))) { - if (size == Int32.MaxValue) + if (size == int.MaxValue) { - // ERROR_MORE_DATA was returned however we cannot increase the buffer size beyond Int32.MaxValue + // ERROR_MORE_DATA was returned however we cannot increase the buffer size beyond int.MaxValue Win32Error(r, name); } - else if (size > (Int32.MaxValue / 2)) + else if (size > (int.MaxValue / 2)) { // at this point in the loop "size * 2" would cause an overflow - size = Int32.MaxValue; + size = int.MaxValue; } else { @@ -441,47 +493,47 @@ namespace Microsoft.Win32 switch (type) { - case Interop.mincore.RegistryValues.REG_NONE: - case Interop.mincore.RegistryValues.REG_DWORD_BIG_ENDIAN: - case Interop.mincore.RegistryValues.REG_BINARY: + case Interop.Advapi32.RegistryValues.REG_NONE: + case Interop.Advapi32.RegistryValues.REG_DWORD_BIG_ENDIAN: + case Interop.Advapi32.RegistryValues.REG_BINARY: { byte[] blob = new byte[datasize]; - ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); + ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); data = blob; } break; - case Interop.mincore.RegistryValues.REG_QWORD: + case Interop.Advapi32.RegistryValues.REG_QWORD: { // also REG_QWORD_LITTLE_ENDIAN if (datasize > 8) { // prevent an AV in the edge case that datasize is larger than sizeof(long) - goto case Interop.mincore.RegistryValues.REG_BINARY; + goto case Interop.Advapi32.RegistryValues.REG_BINARY; } long blob = 0; Debug.Assert(datasize == 8, "datasize==8"); // Here, datasize must be 8 when calling this - ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); + ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); data = blob; } break; - case Interop.mincore.RegistryValues.REG_DWORD: + case Interop.Advapi32.RegistryValues.REG_DWORD: { // also REG_DWORD_LITTLE_ENDIAN if (datasize > 4) { // prevent an AV in the edge case that datasize is larger than sizeof(int) - goto case Interop.mincore.RegistryValues.REG_QWORD; + goto case Interop.Advapi32.RegistryValues.REG_QWORD; } int blob = 0; Debug.Assert(datasize == 4, "datasize==4"); // Here, datasize must be four when calling this - ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); + ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); data = blob; } break; - case Interop.mincore.RegistryValues.REG_SZ: + case Interop.Advapi32.RegistryValues.REG_SZ: { if (datasize % 2 == 1) { @@ -497,7 +549,7 @@ namespace Microsoft.Win32 } char[] blob = new char[datasize / 2]; - ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); + ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); if (blob.Length > 0 && blob[blob.Length - 1] == (char)0) { data = new string(blob, 0, blob.Length - 1); @@ -511,7 +563,7 @@ namespace Microsoft.Win32 } break; - case Interop.mincore.RegistryValues.REG_EXPAND_SZ: + case Interop.Advapi32.RegistryValues.REG_EXPAND_SZ: { if (datasize % 2 == 1) { @@ -527,7 +579,7 @@ namespace Microsoft.Win32 } char[] blob = new char[datasize / 2]; - ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); + ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); if (blob.Length > 0 && blob[blob.Length - 1] == (char)0) { @@ -546,7 +598,7 @@ namespace Microsoft.Win32 } } break; - case Interop.mincore.RegistryValues.REG_MULTI_SZ: + case Interop.Advapi32.RegistryValues.REG_MULTI_SZ: { if (datasize % 2 == 1) { @@ -562,7 +614,7 @@ namespace Microsoft.Win32 } char[] blob = new char[datasize / 2]; - ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); + ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); // make sure the string is null terminated before processing the data if (blob.Length > 0 && blob[blob.Length - 1] != (char)0) @@ -622,7 +674,7 @@ namespace Microsoft.Win32 data = strings; } break; - case Interop.mincore.RegistryValues.REG_LINK: + case Interop.Advapi32.RegistryValues.REG_LINK: default: break; } @@ -634,14 +686,14 @@ namespace Microsoft.Win32 { int type = 0; int datasize = 0; - int ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize); + int ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize); if (ret != 0) { Win32Error(ret, null); } return - type == Interop.mincore.RegistryValues.REG_NONE ? RegistryValueKind.None : + type == Interop.Advapi32.RegistryValues.REG_NONE ? RegistryValueKind.None : !Enum.IsDefined(typeof(RegistryValueKind), type) ? RegistryValueKind.Unknown : (RegistryValueKind)type; } @@ -719,8 +771,8 @@ namespace Microsoft.Win32 private static bool IsWritable(int rights) { - return (rights & (Interop.mincore.RegistryOperations.KEY_SET_VALUE | - Interop.mincore.RegistryOperations.KEY_CREATE_SUB_KEY | + return (rights & (Interop.Advapi32.RegistryOperations.KEY_SET_VALUE | + Interop.Advapi32.RegistryOperations.KEY_CREATE_SUB_KEY | (int)RegistryRights.Delete | (int)RegistryRights.TakeOwnership | (int)RegistryRights.ChangePermissions)) != 0; diff --git a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryKey.cs b/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryKey.cs index 1fd407afa2..ecf8376eda 100644 --- a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryKey.cs +++ b/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryKey.cs @@ -167,6 +167,11 @@ namespace Microsoft.Win32 DeleteValueCore(name, throwOnMissingValue); } + public static RegistryKey OpenBaseKey(RegistryHive hKey) + { + return OpenBaseKey(hKey, RegistryView.Default); + } + public static RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view) { ValidateKeyView(view); @@ -530,7 +535,7 @@ namespace Microsoft.Win32 // the dispose below and usage elsewhere (other threads). This is By Design. // This is less of an issue when OS > NT5 (i.e Vista & higher), we can close the perfkey // (to release & refresh PERFLIB resources) and the OS will rebuild PERFLIB as necessary. - Interop.mincore.RegCloseKey(RegistryKey.HKEY_PERFORMANCE_DATA); + Interop.Advapi32.RegCloseKey(RegistryKey.HKEY_PERFORMANCE_DATA); } } } @@ -552,5 +557,9 @@ namespace Microsoft.Win32 key._keyName = s_hkeyNames[index]; return key; } + + // This dummy method is added to have the same implemenatation of Registry class. + // Its not being used anywhere. + public void SetValue(string name, object value, RegistryValueKind valueKind) { } } } diff --git a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.Unix.cs b/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.Unix.cs new file mode 100644 index 0000000000..35e464b673 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.Unix.cs @@ -0,0 +1,17 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Threading; + +namespace Microsoft.Win32.SafeHandles +{ + public sealed partial class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid + { + protected override bool ReleaseHandle() + { + WaitSubsystem.DeleteHandle(handle); + return true; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs b/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs deleted file mode 100644 index 7527395fe2..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** -** A wrapper for Win32 events (mutexes, auto reset events, and -** manual reset events). Used by WaitHandle. -** -** -===========================================================*/ - -using System; -using System.Security; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; -using System.Runtime.Versioning; -using Microsoft.Win32; -using System.Threading; - -namespace Microsoft.Win32.SafeHandles -{ - public sealed class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid - { - // Called by P/Invoke marshaler - private SafeWaitHandle() : base(true) - { - } - - public SafeWaitHandle(IntPtr existingHandle, bool ownsHandle) : base(ownsHandle) - { - SetHandle(existingHandle); - } - - protected override bool ReleaseHandle() - { -#if PLATFORM_UNIX - WaitSubsystem.DeleteHandle(handle); -#else - Interop.Kernel32.CloseHandle(handle); -#endif - return true; - } - } -} diff --git a/external/corert/src/System.Private.CoreLib/src/Resources/Strings.resx.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/src/Resources/Strings.resx.REMOVED.git-id index 0fb663f8d8..ebce8f5d4e 100644 --- a/external/corert/src/System.Private.CoreLib/src/Resources/Strings.resx.REMOVED.git-id +++ b/external/corert/src/System.Private.CoreLib/src/Resources/Strings.resx.REMOVED.git-id @@ -1 +1 @@ -2eedd405ce53c21b93239ee9ad64d45bc60796c6 \ No newline at end of file +8c132237e4c63e874b0657983009aae57d87c15c \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj b/external/corert/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj index 9f041c4627..5efa4931c2 100644 --- a/external/corert/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj +++ b/external/corert/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj @@ -26,7 +26,7 @@ true true true - EETYPE_TYPE_MANAGER;ES_BUILD_PN;ES_SESSION_INFO;$(DefineConstants) + netcoreapp;EETYPE_TYPE_MANAGER;ES_BUILD_PN;ES_SESSION_INFO;$(DefineConstants) FEATURE_SYNCTABLE;$(DefineConstants) @@ -148,8 +148,8 @@ - + @@ -162,20 +162,31 @@ - + + + + + + + + + + + + + + + + + - - - - - @@ -183,16 +194,14 @@ + - - + - - @@ -201,11 +210,9 @@ - - + - @@ -213,7 +220,6 @@ - @@ -223,19 +229,13 @@ - - - - - - + - @@ -246,14 +246,12 @@ - - @@ -262,7 +260,6 @@ - @@ -270,9 +267,6 @@ - - - @@ -289,39 +283,27 @@ - - - - - - - - - - - - @@ -334,8 +316,6 @@ - - @@ -365,51 +345,9 @@ - - - - - - - - - - - Interop\Windows\advapi32\Interop.RegDeleteValue.cs - - - Interop\Windows\advapi32\Interop.RegSetValueEx.cs - - - Interop\Windows\mincore\Interop.RegistryOptions.cs - - - Interop\Windows\mincore\Interop.RegCloseKey.cs - - - Interop\Windows\mincore\Interop.RegCreateKeyEx.cs - - - Interop\Windows\mincore\Interop.RegEnumKeyEx.cs - - - Interop\Windows\mincore\Interop.RegEnumValue.cs - - - Interop\Windows\mincore\Interop.RegFlushKey.cs - - - Interop\Windows\mincore\Interop.RegOpenKeyEx.cs - - - Interop\Windows\mincore\Interop.RegQueryInfoKey.cs - - - Interop\Windows\mincore\Interop.RegQueryValueEx.cs - Interop\Windows\mincore\Interop.ExitProcess.cs @@ -429,9 +367,6 @@ Interop\Windows\kernel32\Interop.Memory.cs - - Interop\Windows\kernel32\Interop.MultiByteToWideChar.cs - Interop\Windows\kernel32\Interop.CompletionPort.cs @@ -474,6 +409,15 @@ Interop\Windows\ole32\Interop.CoTaskMemAllocFree.cs + + Interop\Windows\ole32\Interop.CoInitializeEx.cs + + + Interop\Windows\ole32\Interop.CoUninitialize.cs + + + Interop\Windows\ole32\Interop.CoGetApartmentType.cs + Interop\Windows\mincore\Interop.CommandLine.cs @@ -503,11 +447,8 @@ Interop\Windows\mincore\Interop.DynamicLoad.cs - - - @@ -530,16 +471,12 @@ Interop\Windows\mincore\Interop.GetSystemDirectory.cs - - Interop\Windows\mincore\Interop.CoCreateGuid.cs - Interop\Windows\mincore\Interop.QueryUnbiasedInterruptTime.cs - @@ -568,10 +505,10 @@ - + @@ -595,9 +532,6 @@ Interop\Unix\System.Private.CoreLib.Native\Interop.GetSystemTimeAsTicks.cs - - Interop\Unix\System.Private.CoreLib.Native\Interop.CreateGuid.cs - Interop\Unix\System.Private.CoreLib.Native\Interop.Exit.cs @@ -637,6 +571,9 @@ Interop\Unix\System.Private.CoreLib.Native\Interop.ErrNo.cs + + Interop\Unix\System.Private.CoreLib.Native\Interop.GetEnviron.cs + diff --git a/external/corert/src/System.Private.CoreLib/src/System/Activator.cs b/external/corert/src/System.Private.CoreLib/src/System/Activator.cs index 8ecfa24b8e..b098adfd52 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Activator.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Activator.cs @@ -11,6 +11,7 @@ using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; +using System.Runtime.Remoting; using System.Runtime; using Internal.Reflection.Augments; @@ -147,6 +148,50 @@ namespace System } private const BindingFlags ConstructorDefault = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance; + + public static ObjectHandle CreateInstance(string assemblyName, string typeName) + { + throw new PlatformNotSupportedException(); // https://github.com/dotnet/corefx/issues/30845 + } + + public static ObjectHandle CreateInstance(string assemblyName, + string typeName, + bool ignoreCase, + BindingFlags bindingAttr, + Binder binder, + object[] args, + CultureInfo culture, + object[] activationAttributes) + { + throw new PlatformNotSupportedException(); // https://github.com/dotnet/corefx/issues/30845 + } + + public static ObjectHandle CreateInstance(string assemblyName, string typeName, object[] activationAttributes) + { + throw new PlatformNotSupportedException(); // https://github.com/dotnet/corefx/issues/30845 + } + + public static ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName) + { + throw new PlatformNotSupportedException(); + } + + public static ObjectHandle CreateInstanceFrom(string assemblyFile, + string typeName, + bool ignoreCase, + BindingFlags bindingAttr, + Binder binder, + object[] args, + CultureInfo culture, + object[] activationAttributes) + { + throw new PlatformNotSupportedException(); + } + + public static ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, object[] activationAttributes) + { + throw new PlatformNotSupportedException(); + } } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/AppContext.cs b/external/corert/src/System.Private.CoreLib/src/System/AppContext.cs index 6b316a4487..0858f357ac 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/AppContext.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/AppContext.cs @@ -25,7 +25,7 @@ namespace System UnknownValue = 0x8 // Has no default and could not find an override } private static readonly Dictionary s_switchMap = new Dictionary(); - private static Dictionary s_localStore = new Dictionary(); + private static Dictionary s_localStore = new Dictionary(); private static string s_defaultBaseDirectory; // AppDomain lives in CoreFX, but some of this class's events need to pass in AppDomains, so people registering those // events need to first pass in an AppDomain that we stash here to pass back in the events. diff --git a/external/corert/src/System.Private.CoreLib/src/System/AppContextDefaultValues.cs b/external/corert/src/System.Private.CoreLib/src/System/AppContextDefaultValues.cs index a0093c94a3..3dd5d55f57 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/AppContextDefaultValues.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/AppContextDefaultValues.cs @@ -32,14 +32,14 @@ namespace System // - The identifier and version is required, profile is optional // - Only three components are allowed. // - The version string must be in the System.Version format; an optional "v" or "V" prefix is allowed - private static bool TryParseFrameworkName(String frameworkName, out String identifier, out int version, out String profile) + private static bool TryParseFrameworkName(string frameworkName, out string identifier, out int version, out string profile) { // For parsing a target Framework moniker, from the FrameworkName class const char c_componentSeparator = ','; const char c_keyValueSeparator = '='; const char c_versionValuePrefix = 'v'; - const String c_versionKey = "Version"; - const String c_profileKey = "Profile"; + const string c_versionKey = "Version"; + const string c_profileKey = "Profile"; identifier = profile = string.Empty; version = 0; @@ -49,7 +49,7 @@ namespace System return false; } - String[] components = frameworkName.Split(c_componentSeparator); + string[] components = frameworkName.Split(c_componentSeparator); version = 0; // Identifer and Version are required, Profile is optional. @@ -113,7 +113,7 @@ namespace System // else if (key.Equals(c_profileKey, StringComparison.OrdinalIgnoreCase)) { - if (!String.IsNullOrEmpty(value)) + if (!string.IsNullOrEmpty(value)) { profile = value; } diff --git a/external/corert/src/System.Private.CoreLib/src/System/AppContextSwitches.cs b/external/corert/src/System.Private.CoreLib/src/System/AppContextSwitches.cs new file mode 100644 index 0000000000..f838871e8d --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/AppContextSwitches.cs @@ -0,0 +1,60 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.CompilerServices; + +namespace System +{ + internal static class AppContextSwitches + { + private static int _enforceJapaneseEraYearRanges; + public static bool EnforceJapaneseEraYearRanges + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return GetCachedSwitchValue("Switch.System.Globalization.EnforceJapaneseEraYearRanges", ref _enforceJapaneseEraYearRanges); + } + } + + // + // Implementation details + // + + private static bool DisableCaching { get; set; } + + static AppContextSwitches() + { + bool isEnabled; + if (AppContext.TryGetSwitch(@"TestSwitch.LocalAppContext.DisableCaching", out isEnabled)) + { + DisableCaching = isEnabled; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool GetCachedSwitchValue(string switchName, ref int switchValue) + { + if (switchValue < 0) return false; + if (switchValue > 0) return true; + + return GetCachedSwitchValueInternal(switchName, ref switchValue); + } + + private static bool GetCachedSwitchValueInternal(string switchName, ref int switchValue) + { + bool isSwitchEnabled; + AppContext.TryGetSwitch(switchName, out isSwitchEnabled); + + if (DisableCaching) + { + return isSwitchEnabled; + } + + switchValue = isSwitchEnabled ? 1 /*true*/ : -1 /*false*/; + return isSwitchEnabled; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Array.CoreRT.cs b/external/corert/src/System.Private.CoreLib/src/System/Array.CoreRT.cs index 80c4d2bbf0..f4c57285af 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Array.CoreRT.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Array.CoreRT.cs @@ -445,7 +445,7 @@ namespace System ref object refDestinationArray = ref Unsafe.As(ref destinationArray.GetRawArrayData()); for (int i = 0; i < length; i++) { - Object boxedValue = RuntimeImports.RhBox(sourceElementEEType, pElement); + object boxedValue = RuntimeImports.RhBox(sourceElementEEType, pElement); Unsafe.Add(ref refDestinationArray, destinationIndex + i) = boxedValue; pElement += sourceElementSize; } @@ -474,7 +474,7 @@ namespace System for (int i = 0; i < length; i++) { - Object boxedValue = Unsafe.Add(ref refSourceArray, sourceIndex + i); + object boxedValue = Unsafe.Add(ref refSourceArray, sourceIndex + i); if (boxedValue == null) { if (!isNullable) @@ -918,7 +918,7 @@ namespace System if (length > MaxArrayLength) maxArrayDimensionLengthOverflow = true; totalLength = totalLength * (ulong)length; - if (totalLength > Int32.MaxValue) + if (totalLength > int.MaxValue) throw new OutOfMemoryException(); // "Array dimensions exceeded supported range." } @@ -938,14 +938,14 @@ namespace System } // Wraps an IComparer inside an IComparer. - private sealed class ComparerAsComparerT : IComparer + private sealed class ComparerAsComparerT : IComparer { public ComparerAsComparerT(IComparer comparer) { _comparer = (comparer == null) ? Comparer.Default : comparer; } - public int Compare(Object x, Object y) + public int Compare(object x, object y) { return _comparer.Compare(x, y); } @@ -999,7 +999,7 @@ namespace System return Length - 1; } - public unsafe Object GetValue(int index) + public unsafe object GetValue(int index) { if (!IsSzArray) { @@ -1018,7 +1018,7 @@ namespace System return GetValueWithFlattenedIndex_NoErrorCheck(index); } - public unsafe Object GetValue(int index1, int index2) + public unsafe object GetValue(int index1, int index2) { if (Rank != 2) throw new ArgumentException(SR.Arg_Need2DArray); @@ -1029,7 +1029,7 @@ namespace System return GetValue(pIndices, 2); } - public unsafe Object GetValue(int index1, int index2, int index3) + public unsafe object GetValue(int index1, int index2, int index3) { if (Rank != 3) throw new ArgumentException(SR.Arg_Need3DArray); @@ -1041,7 +1041,7 @@ namespace System return GetValue(pIndices, 3); } - public unsafe Object GetValue(params int[] indices) + public unsafe object GetValue(params int[] indices) { if (indices == null) throw new ArgumentNullException(nameof(indices)); @@ -1059,7 +1059,7 @@ namespace System return GetValue(pIndices, length); } - private unsafe Object GetValue(int* pIndices, int rank) + private unsafe object GetValue(int* pIndices, int rank) { Debug.Assert(Rank == rank); Debug.Assert(!IsSzArray); @@ -1085,7 +1085,7 @@ namespace System return GetValueWithFlattenedIndex_NoErrorCheck(flattenedIndex); } - private Object GetValueWithFlattenedIndex_NoErrorCheck(int flattenedIndex) + private object GetValueWithFlattenedIndex_NoErrorCheck(int flattenedIndex) { ref byte element = ref Unsafe.AddByteOffset(ref GetRawArrayData(), (nuint)flattenedIndex * ElementSize); @@ -1101,7 +1101,7 @@ namespace System } } - public unsafe void SetValue(Object value, int index) + public unsafe void SetValue(object value, int index) { if (!IsSzArray) { @@ -1146,7 +1146,7 @@ namespace System } } - public unsafe void SetValue(Object value, int index1, int index2) + public unsafe void SetValue(object value, int index1, int index2) { if (Rank != 2) throw new ArgumentException(SR.Arg_Need2DArray); @@ -1157,7 +1157,7 @@ namespace System SetValue(value, pIndices, 2); } - public unsafe void SetValue(Object value, int index1, int index2, int index3) + public unsafe void SetValue(object value, int index1, int index2, int index3) { if (Rank != 3) throw new ArgumentException(SR.Arg_Need3DArray); @@ -1169,7 +1169,7 @@ namespace System SetValue(value, pIndices, 3); } - public unsafe void SetValue(Object value, params int[] indices) + public unsafe void SetValue(object value, params int[] indices) { if (indices == null) throw new ArgumentNullException(nameof(indices)); @@ -1193,7 +1193,7 @@ namespace System } } - private unsafe void SetValue(Object value, int* pIndices, int rank) + private unsafe void SetValue(object value, int* pIndices, int rank) { Debug.Assert(Rank == rank); Debug.Assert(!IsSzArray); @@ -1241,7 +1241,7 @@ namespace System { throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); } - Unsafe.As(ref element) = value; + Unsafe.As(ref element) = value; } } @@ -1255,7 +1255,7 @@ namespace System private sealed partial class ArrayEnumerator : IEnumerator, ICloneable { - public Object Current + public object Current { get { @@ -1332,9 +1332,9 @@ namespace System static void SortImpl(Array keys, Array items, int index, int length, IComparer comparer) { - IComparer comparerT = new ComparerAsComparerT(comparer); - Object[] objKeys = keys as Object[]; - Object[] objItems = items as Object[]; + IComparer comparerT = new ComparerAsComparerT(comparer); + object[] objKeys = keys as object[]; + object[] objItems = items as object[]; // Unfortunately, on Project N, we don't have the ability to specialize ArraySortHelper<> on demand // for value types. Rather than incur a boxing cost on every compare and every swap (and maintain a separate introsort algorithm @@ -1343,12 +1343,12 @@ namespace System // Check if either of the arrays need to be copied. if (objKeys == null) { - objKeys = new Object[index + length]; + objKeys = new object[index + length]; Array.CopyImplValueTypeArrayToReferenceArray(keys, index, objKeys, index, length, reliable: false); } if (objItems == null && items != null) { - objItems = new Object[index + length]; + objItems = new object[index + length]; Array.CopyImplValueTypeArrayToReferenceArray(items, index, objItems, index, length, reliable: false); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Array.cs b/external/corert/src/System.Private.CoreLib/src/System/Array.cs index 12412a28f1..d30a072d89 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Array.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Array.cs @@ -80,7 +80,7 @@ namespace System bool IList.IsReadOnly { get { return false; } } - Object IList.this[int index] + object IList.this[int index] { get { @@ -93,12 +93,12 @@ namespace System } } - int IList.Add(Object value) + int IList.Add(object value) { throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } - bool IList.Contains(Object value) + bool IList.Contains(object value) { return Array.IndexOf(this, value) >= 0; } @@ -108,17 +108,17 @@ namespace System Array.Clear(this, GetLowerBound(0), this.Length); } - int IList.IndexOf(Object value) + int IList.IndexOf(object value) { return Array.IndexOf(this, value); } - void IList.Insert(int index, Object value) + void IList.Insert(int index, object value) { throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } - void IList.Remove(Object value) + void IList.Remove(object value) { throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } @@ -146,12 +146,12 @@ namespace System // Make a new array which is a deep copy of the original array. // - public Object Clone() + public object Clone() { return MemberwiseClone(); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) { @@ -180,14 +180,14 @@ namespace System return c; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) { return false; } - if (Object.ReferenceEquals(this, other)) + if (object.ReferenceEquals(this, other)) { return true; } @@ -249,7 +249,7 @@ namespace System // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - public static int BinarySearch(Array array, Object value) + public static int BinarySearch(Array array, object value) { if (array == null) throw new ArgumentNullException(nameof(array)); @@ -274,7 +274,7 @@ namespace System public static void Copy(Array sourceArray, Array destinationArray, long length) { - if (length > Int32.MaxValue || length < Int32.MinValue) + if (length > int.MaxValue || length < int.MinValue) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_HugeArrayNotSupported); Array.Copy(sourceArray, destinationArray, (int)length); @@ -282,11 +282,11 @@ namespace System public static void Copy(Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length) { - if (sourceIndex > Int32.MaxValue || sourceIndex < Int32.MinValue) + if (sourceIndex > int.MaxValue || sourceIndex < int.MinValue) throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_HugeArrayNotSupported); - if (destinationIndex > Int32.MaxValue || destinationIndex < Int32.MinValue) + if (destinationIndex > int.MaxValue || destinationIndex < int.MinValue) throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_HugeArrayNotSupported); - if (length > Int32.MaxValue || length < Int32.MinValue) + if (length > int.MaxValue || length < int.MinValue) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_HugeArrayNotSupported); Array.Copy(sourceArray, (int)sourceIndex, destinationArray, (int)destinationIndex, (int)length); @@ -294,7 +294,7 @@ namespace System public void CopyTo(Array array, long index) { - if (index > Int32.MaxValue || index < Int32.MinValue) + if (index > int.MaxValue || index < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_HugeArrayNotSupported); this.CopyTo(array, (int)index); @@ -336,37 +336,37 @@ namespace System return GetLength(dimension); } - public Object GetValue(long index) + public object GetValue(long index) { - if (index > Int32.MaxValue || index < Int32.MinValue) + if (index > int.MaxValue || index < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_HugeArrayNotSupported); return this.GetValue((int)index); } - public Object GetValue(long index1, long index2) + public object GetValue(long index1, long index2) { - if (index1 > Int32.MaxValue || index1 < Int32.MinValue) + if (index1 > int.MaxValue || index1 < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index1), SR.ArgumentOutOfRange_HugeArrayNotSupported); - if (index2 > Int32.MaxValue || index2 < Int32.MinValue) + if (index2 > int.MaxValue || index2 < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index2), SR.ArgumentOutOfRange_HugeArrayNotSupported); return this.GetValue((int)index1, (int)index2); } - public Object GetValue(long index1, long index2, long index3) + public object GetValue(long index1, long index2, long index3) { - if (index1 > Int32.MaxValue || index1 < Int32.MinValue) + if (index1 > int.MaxValue || index1 < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index1), SR.ArgumentOutOfRange_HugeArrayNotSupported); - if (index2 > Int32.MaxValue || index2 < Int32.MinValue) + if (index2 > int.MaxValue || index2 < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index2), SR.ArgumentOutOfRange_HugeArrayNotSupported); - if (index3 > Int32.MaxValue || index3 < Int32.MinValue) + if (index3 > int.MaxValue || index3 < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index3), SR.ArgumentOutOfRange_HugeArrayNotSupported); return this.GetValue((int)index1, (int)index2, (int)index3); } - public Object GetValue(params long[] indices) + public object GetValue(params long[] indices) { if (indices == null) throw new ArgumentNullException(nameof(indices)); @@ -378,7 +378,7 @@ namespace System for (int i = 0; i < indices.Length; ++i) { long index = indices[i]; - if (index > Int32.MaxValue || index < Int32.MinValue) + if (index > int.MaxValue || index < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_HugeArrayNotSupported); intIndices[i] = (int)index; } @@ -398,7 +398,7 @@ namespace System // Returns an object appropriate for synchronizing access to this // Array. - public Object SyncRoot { get { return this; } } + public object SyncRoot { get { return this; } } // Searches a section of an array for a given element using a binary search // algorithm. Elements of the array are compared to the search value using @@ -413,7 +413,7 @@ namespace System // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - public static int BinarySearch(Array array, int index, int length, Object value) + public static int BinarySearch(Array array, int index, int length, object value) { return BinarySearch(array, index, length, value, null); } @@ -432,7 +432,7 @@ namespace System // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - public static int BinarySearch(Array array, Object value, IComparer comparer) + public static int BinarySearch(Array array, object value, IComparer comparer) { if (array == null) throw new ArgumentNullException(nameof(array)); @@ -454,7 +454,7 @@ namespace System // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - public static int BinarySearch(Array array, int index, int length, Object value, IComparer comparer) + public static int BinarySearch(Array array, int index, int length, object value, IComparer comparer) { if (array == null) throw new ArgumentNullException(nameof(array)); @@ -470,7 +470,7 @@ namespace System int lo = index; int hi = index + length - 1; - Object[] objArray = array as Object[]; + object[] objArray = array as object[]; if (objArray != null) { while (lo <= hi) @@ -561,14 +561,14 @@ namespace System if (array.Length - index < length) throw new ArgumentException(SR.Argument_InvalidOffLen); - return ArraySortHelper.BinarySearch(array, index, length, value, comparer); + return ArraySortHelper.Default.BinarySearch(array, index, length, value, comparer); } // Returns the index of the first occurrence of a given value in an array. // The array is searched forwards, and the elements of the array are // compared to the given value using the Object.Equals method. // - public static int IndexOf(Array array, Object value) + public static int IndexOf(Array array, object value) { if (array == null) { @@ -584,7 +584,7 @@ namespace System // elements of the array are compared to the given value using the // Object.Equals method. // - public static int IndexOf(Array array, Object value, int startIndex) + public static int IndexOf(Array array, object value, int startIndex) { if (array == null) { @@ -601,7 +601,7 @@ namespace System // elements of the array are compared to the given value using the // Object.Equals method. // - public static int IndexOf(Array array, Object value, int startIndex, int count) + public static int IndexOf(Array array, object value, int startIndex, int count) { if (array == null) throw new ArgumentNullException(nameof(array)); @@ -613,7 +613,7 @@ namespace System if (count < 0 || count > array.Length - startIndex + lb) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); - Object[] objArray = array as Object[]; + object[] objArray = array as object[]; int endIndex = startIndex + count; if (objArray != null) { @@ -628,7 +628,7 @@ namespace System { for (int i = startIndex; i < endIndex; i++) { - Object obj = objArray[i]; + object obj = objArray[i]; if (obj != null && obj.Equals(value)) return i; } } @@ -637,7 +637,7 @@ namespace System { for (int i = startIndex; i < endIndex; i++) { - Object obj = array.GetValue(i); + object obj = array.GetValue(i); if (obj == null) { if (value == null) return i; @@ -696,7 +696,7 @@ namespace System return IndexOfImpl(array, value, startIndex, count); } - public static int LastIndexOf(Array array, Object value) + public static int LastIndexOf(Array array, object value) { if (array == null) throw new ArgumentNullException(nameof(array)); @@ -709,7 +709,7 @@ namespace System // startIndex and ending at index 0. The elements of the array are // compared to the given value using the Object.Equals method. // - public static int LastIndexOf(Array array, Object value, int startIndex) + public static int LastIndexOf(Array array, object value, int startIndex) { if (array == null) throw new ArgumentNullException(nameof(array)); @@ -723,7 +723,7 @@ namespace System // the array are compared to the given value using the Object.Equals // method. // - public static int LastIndexOf(Array array, Object value, int startIndex, int count) + public static int LastIndexOf(Array array, object value, int startIndex, int count) { if (array == null) throw new ArgumentNullException(nameof(array)); @@ -742,7 +742,7 @@ namespace System if (array.Rank != 1) throw new RankException(SR.Rank_MultiDimNotSupported); - Object[] objArray = array as Object[]; + object[] objArray = array as object[]; int endIndex = startIndex - count + 1; if (objArray != null) { @@ -757,7 +757,7 @@ namespace System { for (int i = startIndex; i >= endIndex; i--) { - Object obj = objArray[i]; + object obj = objArray[i]; if (obj != null && obj.Equals(value)) return i; } } @@ -766,7 +766,7 @@ namespace System { for (int i = startIndex; i >= endIndex; i--) { - Object obj = array.GetValue(i); + object obj = array.GetValue(i); if (obj == null) { if (value == null) return i; @@ -873,7 +873,7 @@ namespace System if (array.Rank != 1) throw new RankException(SR.Rank_MultiDimNotSupported); - Object[] objArray = array as Object[]; + object[] objArray = array as object[]; if (objArray != null) { Array.Reverse(objArray, index, length); @@ -884,7 +884,7 @@ namespace System int j = index + length - 1; while (i < j) { - Object temp = array.GetValue(i); + object temp = array.GetValue(i); array.SetValue(array.GetValue(j), i); array.SetValue(temp, j); i++; @@ -910,6 +910,10 @@ namespace System if (array.Length - index < length) throw new ArgumentException(SR.Argument_InvalidOffLen); + if (length <= 1) + return; + +#if __MonoCS__ ref T p = ref Unsafe.As(ref array.GetRawSzArrayData()); int i = index; int j = index + length - 1; @@ -921,6 +925,18 @@ namespace System i++; j--; } +#else + ref T first = ref Unsafe.Add(ref Unsafe.As(ref array.GetRawSzArrayData()), index); + ref T last = ref Unsafe.Add(ref Unsafe.Add(ref first, length), -1); + do + { + T temp = first; + first = last; + last = temp; + first = ref Unsafe.Add(ref first, 1); + last = ref Unsafe.Add(ref last, -1); + } while (Unsafe.IsAddressLessThan(ref first, ref last)); +#endif } public void SetValue(object value, long index) @@ -1094,7 +1110,7 @@ namespace System throw new ArgumentException(SR.Argument_InvalidOffLen); if (length > 1) - ArraySortHelper.Sort(array, index, length, comparer); + ArraySortHelper.Default.Sort(array, index, length, comparer); } public static void Sort(T[] array, Comparison comparison) diff --git a/external/corert/src/System.Private.CoreLib/src/System/Attribute.cs b/external/corert/src/System.Private.CoreLib/src/System/Attribute.cs index 5f20722e2b..8c48f16e30 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Attribute.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Attribute.cs @@ -20,7 +20,7 @@ namespace System // // This implementation implements the .NET Core behavior. // - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (obj == null) return false; @@ -28,14 +28,14 @@ namespace System if (this.GetType() != obj.GetType()) return false; - Object[] thisFieldValues = this.ReadFields(); - Object[] thatfieldValues = ((Attribute)obj).ReadFields(); + object[] thisFieldValues = this.ReadFields(); + object[] thatfieldValues = ((Attribute)obj).ReadFields(); for (int i = 0; i < thisFieldValues.Length; i++) { // Visibility check and consistency check are not necessary. - Object thisResult = thisFieldValues[i]; - Object thatResult = thatfieldValues[i]; + object thisResult = thisFieldValues[i]; + object thatResult = thatfieldValues[i]; if (!AreFieldValuesEqual(thisResult, thatResult)) { @@ -47,7 +47,7 @@ namespace System } // Compares values of custom-attribute fields. - private static bool AreFieldValuesEqual(Object thisValue, Object thatValue) + private static bool AreFieldValuesEqual(object thisValue, object thatValue) { if (thisValue == null && thatValue == null) return true; @@ -97,12 +97,12 @@ namespace System public override int GetHashCode() { - Object vThis = null; + object vThis = null; - Object[] fieldValues = this.ReadFields(); + object[] fieldValues = this.ReadFields(); for (int i = 0; i < fieldValues.Length; i++) { - Object fieldValue = fieldValues[i]; + object fieldValue = fieldValues[i]; // The hashcode of an array ignores the contents of the array, so it can produce // different hashcodes for arrays with the same contents. @@ -150,7 +150,7 @@ namespace System // offset inside a caller-supplied array. Attribute.ReadFields() calls _ILT_GetNumFields() to figure out how large an array is needed. // [CLSCompliant(false)] - protected virtual void _ILT_ReadFields(Object[] destination, int offset) + protected virtual void _ILT_ReadFields(object[] destination, int offset) { } @@ -158,10 +158,10 @@ namespace System // ProjectN: Unlike the desktop, low level code such as Attributes cannot go running off to Reflection to fetch the FieldInfo's. // Instead, we use the ILTransform to generate a method that returns the relevant field values, which we then compare as the desktop does. // - private Object[] ReadFields() + private object[] ReadFields() { int numFields = _ILT_GetNumFields(); - Object[] fieldValues = new Object[numFields]; + object[] fieldValues = new object[numFields]; _ILT_ReadFields(fieldValues, 0); return fieldValues; } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Buffer.cs b/external/corert/src/System.Private.CoreLib/src/System/Buffer.cs index b8c840e421..35ce0d5a28 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Buffer.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Buffer.cs @@ -98,80 +98,6 @@ namespace System } } - // This is ported from the optimized CRT assembly in memchr.asm. The JIT generates - // pretty good code here and this ends up being within a couple % of the CRT asm. - // It is however cross platform as the CRT hasn't ported their fast version to 64-bit - // platforms. - // - internal static unsafe int IndexOfByte(byte* src, byte value, int index, int count) - { - byte* pByte = src + index; - - // Align up the pointer to sizeof(int). - while (((int)pByte & 3) != 0) - { - if (count == 0) - return -1; - else if (*pByte == value) - return (int)(pByte - src); - - count--; - pByte++; - } - - // Fill comparer with value byte for comparisons - // - // comparer = 0/0/value/value - uint comparer = (((uint)value << 8) + (uint)value); - // comparer = value/value/value/value - comparer = (comparer << 16) + comparer; - - // Run through buffer until we hit a 4-byte section which contains - // the byte we're looking for or until we exhaust the buffer. - while (count > 3) - { - // Test the buffer for presence of value. comparer contains the byte - // replicated 4 times. - uint t1 = *(uint*)pByte; - t1 = t1 ^ comparer; - uint t2 = 0x7efefeff + t1; - t1 = t1 ^ 0xffffffff; - t1 = t1 ^ t2; - t1 = t1 & 0x81010100; - - // if t1 is zero then these 4-bytes don't contain a match - if (t1 != 0) - { - // We've found a match for value, figure out which position it's in. - int foundIndex = (int)(pByte - src); - if (pByte[0] == value) - return foundIndex; - else if (pByte[1] == value) - return foundIndex + 1; - else if (pByte[2] == value) - return foundIndex + 2; - else if (pByte[3] == value) - return foundIndex + 3; - } - - count -= 4; - pByte += 4; - } - - // Catch any bytes that might be left at the tail of the buffer - while (count > 0) - { - if (*pByte == value) - return (int)(pByte - src); - - count--; - pByte++; - } - - // If we don't have a match return -1; - return -1; - } - internal static unsafe void ZeroMemory(byte* src, long len) { while (len-- > 0) diff --git a/external/corert/src/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.CoreRT.cs b/external/corert/src/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.CoreRT.cs new file mode 100644 index 0000000000..d80eefb7a5 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.CoreRT.cs @@ -0,0 +1,37 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Diagnostics; +using System.Runtime.Versioning; + +namespace System.Collections.Generic +{ + internal partial class ArraySortHelper + { + private static readonly ArraySortHelper s_defaultArraySortHelper = new ArraySortHelper(); + + public static ArraySortHelper Default + { + get + { + return s_defaultArraySortHelper; + } + } + } + + internal partial class ArraySortHelper + { + private static readonly ArraySortHelper s_defaultArraySortHelper = new ArraySortHelper(); + + public static ArraySortHelper Default + { + get + { + return s_defaultArraySortHelper; + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.cs b/external/corert/src/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.cs deleted file mode 100644 index dcb7d01acd..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.cs +++ /dev/null @@ -1,603 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; - -namespace System.Collections.Generic -{ - #region ArraySortHelper for single arrays - - internal static class IntrospectiveSortUtilities - { - // This is the threshold where Introspective sort switches to Insertion sort. - // Empirically, 16 seems to speed up most cases without slowing down others, at least for integers. - // Large value types may benefit from a smaller number. - internal const int IntrosortSizeThreshold = 16; - - internal static int FloorLog2PlusOne(int n) - { - int result = 0; - while (n >= 1) - { - result++; - n = n / 2; - } - return result; - } - - internal static void ThrowOrIgnoreBadComparer(Object comparer) - { - // This is hit when an invarant of QuickSort is violated due to a bad IComparer implementation (for - // example, imagine an IComparer that returns 0 when items are equal but -1 all other times). - throw new ArgumentException(SR.Format(SR.Arg_BogusIComparer, comparer)); - } - } - - internal class ArraySortHelper - { - #region ArraySortHelper public Members - - public static void Sort(T[] keys, int index, int length, IComparer comparer) - { - Debug.Assert(keys != null, "Check the arguments in the caller!"); - Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); - - // Add a try block here to detect IComparers (or their - // underlying IComparables, etc) that are bogus. - try - { - if (comparer == null) - { - comparer = Comparer.Default; - } - - IntrospectiveSort(keys, index, length, comparer.Compare); - } - catch (IndexOutOfRangeException) - { - IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); - } - catch (Exception e) - { - throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); - } - } - - public static int BinarySearch(T[] array, int index, int length, T value, IComparer comparer) - { - try - { - if (comparer == null) - { - comparer = Comparer.Default; - } - - return InternalBinarySearch(array, index, length, value, comparer); - } - catch (Exception e) - { - throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); - } - } - - #endregion - - internal static void Sort(T[] keys, int index, int length, Comparison comparer) - { - Debug.Assert(keys != null, "Check the arguments in the caller!"); - Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); - Debug.Assert(comparer != null, "Check the arguments in the caller!"); - - // Add a try block here to detect bogus comparisons - try - { - IntrospectiveSort(keys, index, length, comparer); - } - catch (IndexOutOfRangeException) - { - IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); - } - catch (Exception e) - { - throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); - } - } - - internal static int InternalBinarySearch(T[] array, int index, int length, T value, IComparer comparer) - { - Debug.Assert(array != null, "Check the arguments in the caller!"); - Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); - - int lo = index; - int hi = index + length - 1; - while (lo <= hi) - { - int i = lo + ((hi - lo) >> 1); - int order = comparer.Compare(array[i], value); - - if (order == 0) return i; - if (order < 0) - { - lo = i + 1; - } - else - { - hi = i - 1; - } - } - - return ~lo; - } - - private static void SwapIfGreater(T[] keys, Comparison comparer, int a, int b) - { - if (a != b) - { - if (comparer(keys[a], keys[b]) > 0) - { - T key = keys[a]; - keys[a] = keys[b]; - keys[b] = key; - } - } - } - - private static void Swap(T[] a, int i, int j) - { - if (i != j) - { - T t = a[i]; - a[i] = a[j]; - a[j] = t; - } - } - - internal static void IntrospectiveSort(T[] keys, int left, int length, Comparison comparer) - { - Debug.Assert(keys != null); - Debug.Assert(comparer != null); - Debug.Assert(left >= 0); - Debug.Assert(length >= 0); - Debug.Assert(length <= keys.Length); - Debug.Assert(length + left <= keys.Length); - - if (length < 2) - return; - - IntroSort(keys, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(keys.Length), comparer); - } - - private static void IntroSort(T[] keys, int lo, int hi, int depthLimit, Comparison comparer) - { - Debug.Assert(keys != null); - Debug.Assert(comparer != null); - Debug.Assert(lo >= 0); - Debug.Assert(hi < keys.Length); - - while (hi > lo) - { - int partitionSize = hi - lo + 1; - if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold) - { - if (partitionSize == 1) - { - return; - } - if (partitionSize == 2) - { - SwapIfGreater(keys, comparer, lo, hi); - return; - } - if (partitionSize == 3) - { - SwapIfGreater(keys, comparer, lo, hi - 1); - SwapIfGreater(keys, comparer, lo, hi); - SwapIfGreater(keys, comparer, hi - 1, hi); - return; - } - - InsertionSort(keys, lo, hi, comparer); - return; - } - - if (depthLimit == 0) - { - Heapsort(keys, lo, hi, comparer); - return; - } - depthLimit--; - - int p = PickPivotAndPartition(keys, lo, hi, comparer); - // Note we've already partitioned around the pivot and do not have to move the pivot again. - IntroSort(keys, p + 1, hi, depthLimit, comparer); - hi = p - 1; - } - } - - private static int PickPivotAndPartition(T[] keys, int lo, int hi, Comparison comparer) - { - Debug.Assert(keys != null); - Debug.Assert(comparer != null); - Debug.Assert(lo >= 0); - Debug.Assert(hi > lo); - Debug.Assert(hi < keys.Length); - - // Compute median-of-three. But also partition them, since we've done the comparison. - int middle = lo + ((hi - lo) / 2); - - // Sort lo, mid and hi appropriately, then pick mid as the pivot. - SwapIfGreater(keys, comparer, lo, middle); // swap the low with the mid point - SwapIfGreater(keys, comparer, lo, hi); // swap the low with the high - SwapIfGreater(keys, comparer, middle, hi); // swap the middle with the high - - T pivot = keys[middle]; - Swap(keys, middle, hi - 1); - int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. - - while (left < right) - { - while (comparer(keys[++left], pivot) < 0) ; - while (comparer(pivot, keys[--right]) < 0) ; - - if (left >= right) - break; - - Swap(keys, left, right); - } - - // Put pivot in the right location. - Swap(keys, left, (hi - 1)); - return left; - } - - private static void Heapsort(T[] keys, int lo, int hi, Comparison comparer) - { - Debug.Assert(keys != null); - Debug.Assert(comparer != null); - Debug.Assert(lo >= 0); - Debug.Assert(hi > lo); - Debug.Assert(hi < keys.Length); - - int n = hi - lo + 1; - for (int i = n / 2; i >= 1; i = i - 1) - { - DownHeap(keys, i, n, lo, comparer); - } - for (int i = n; i > 1; i = i - 1) - { - Swap(keys, lo, lo + i - 1); - DownHeap(keys, 1, i - 1, lo, comparer); - } - } - - private static void DownHeap(T[] keys, int i, int n, int lo, Comparison comparer) - { - Debug.Assert(keys != null); - Debug.Assert(comparer != null); - Debug.Assert(lo >= 0); - Debug.Assert(lo < keys.Length); - - T d = keys[lo + i - 1]; - int child; - while (i <= n / 2) - { - child = 2 * i; - if (child < n && comparer(keys[lo + child - 1], keys[lo + child]) < 0) - { - child++; - } - if (!(comparer(d, keys[lo + child - 1]) < 0)) - break; - keys[lo + i - 1] = keys[lo + child - 1]; - i = child; - } - keys[lo + i - 1] = d; - } - - private static void InsertionSort(T[] keys, int lo, int hi, Comparison comparer) - { - Debug.Assert(keys != null); - Debug.Assert(lo >= 0); - Debug.Assert(hi >= lo); - Debug.Assert(hi <= keys.Length); - - int i, j; - T t; - for (i = lo; i < hi; i++) - { - j = i; - t = keys[i + 1]; - while (j >= lo && comparer(t, keys[j]) < 0) - { - keys[j + 1] = keys[j]; - j--; - } - keys[j + 1] = t; - } - } - } - - - #endregion - - #region ArraySortHelper for paired key and value arrays - - internal class ArraySortHelper - { - // WARNING: We allow diagnostic tools to directly inspect this member (s_defaultArraySortHelper). - // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. - // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. - // Get in touch with the diagnostics team if you have questions. - private static volatile ArraySortHelper s_defaultArraySortHelper; - - public static ArraySortHelper Default - { - get - { - ArraySortHelper sorter = s_defaultArraySortHelper; - if (sorter == null) - sorter = CreateArraySortHelper(); - - return sorter; - } - } - - private static ArraySortHelper CreateArraySortHelper() - { - s_defaultArraySortHelper = new ArraySortHelper(); - return s_defaultArraySortHelper; - } - - public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer comparer) - { - Debug.Assert(keys != null, "Check the arguments in the caller!"); // Precondition on interface method - Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); - - // Add a try block here to detect IComparers (or their - // underlying IComparables, etc) that are bogus. - try - { - if (comparer == null || comparer == Comparer.Default) - { - comparer = Comparer.Default; - } - - IntrospectiveSort(keys, values, index, length, comparer); - } - catch (IndexOutOfRangeException) - { - IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); - } - catch (Exception e) - { - throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); - } - } - - private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, IComparer comparer, int a, int b) - { - Debug.Assert(keys != null); - Debug.Assert(comparer != null); - Debug.Assert(0 <= a && a < keys.Length); - Debug.Assert(0 <= b && b < keys.Length); - Debug.Assert(values == null || (0 <= a && a < values.Length)); - Debug.Assert(values == null || (0 <= b && b < values.Length)); - - if (a != b) - { - if (comparer.Compare(keys[a], keys[b]) > 0) - { - TKey key = keys[a]; - keys[a] = keys[b]; - keys[b] = key; - if (values != null) - { - TValue value = values[a]; - values[a] = values[b]; - values[b] = value; - } - } - } - } - - private static void Swap(TKey[] keys, TValue[] values, int i, int j) - { - if (i != j) - { - TKey k = keys[i]; - keys[i] = keys[j]; - keys[j] = k; - if (values != null) - { - TValue v = values[i]; - values[i] = values[j]; - values[j] = v; - } - } - } - - internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length, IComparer comparer) - { - Debug.Assert(keys != null); - Debug.Assert(values != null); - Debug.Assert(comparer != null); - Debug.Assert(left >= 0); - Debug.Assert(length >= 0); - Debug.Assert(length <= keys.Length); - Debug.Assert(length + left <= keys.Length); - Debug.Assert(length + left <= values.Length); - - if (length < 2) - return; - - IntroSort(keys, values, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(keys.Length), comparer); - } - - private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit, IComparer comparer) - { - Debug.Assert(keys != null); - Debug.Assert(values != null); - Debug.Assert(comparer != null); - Debug.Assert(lo >= 0); - Debug.Assert(hi < keys.Length); - - while (hi > lo) - { - int partitionSize = hi - lo + 1; - if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold) - { - if (partitionSize == 1) - { - return; - } - if (partitionSize == 2) - { - SwapIfGreaterWithItems(keys, values, comparer, lo, hi); - return; - } - if (partitionSize == 3) - { - SwapIfGreaterWithItems(keys, values, comparer, lo, hi - 1); - SwapIfGreaterWithItems(keys, values, comparer, lo, hi); - SwapIfGreaterWithItems(keys, values, comparer, hi - 1, hi); - return; - } - - InsertionSort(keys, values, lo, hi, comparer); - return; - } - - if (depthLimit == 0) - { - Heapsort(keys, values, lo, hi, comparer); - return; - } - depthLimit--; - - int p = PickPivotAndPartition(keys, values, lo, hi, comparer); - // Note we've already partitioned around the pivot and do not have to move the pivot again. - IntroSort(keys, values, p + 1, hi, depthLimit, comparer); - hi = p - 1; - } - } - - private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi, IComparer comparer) - { - Debug.Assert(keys != null); - Debug.Assert(values != null); - Debug.Assert(comparer != null); - Debug.Assert(lo >= 0); - Debug.Assert(hi > lo); - Debug.Assert(hi < keys.Length); - - // Compute median-of-three. But also partition them, since we've done the comparison. - int middle = lo + ((hi - lo) / 2); - - // Sort lo, mid and hi appropriately, then pick mid as the pivot. - SwapIfGreaterWithItems(keys, values, comparer, lo, middle); // swap the low with the mid point - SwapIfGreaterWithItems(keys, values, comparer, lo, hi); // swap the low with the high - SwapIfGreaterWithItems(keys, values, comparer, middle, hi); // swap the middle with the high - - TKey pivot = keys[middle]; - Swap(keys, values, middle, hi - 1); - int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. - - while (left < right) - { - while (comparer.Compare(keys[++left], pivot) < 0) ; - while (comparer.Compare(pivot, keys[--right]) < 0) ; - - if (left >= right) - break; - - Swap(keys, values, left, right); - } - - // Put pivot in the right location. - Swap(keys, values, left, (hi - 1)); - return left; - } - - private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi, IComparer comparer) - { - Debug.Assert(keys != null); - Debug.Assert(values != null); - Debug.Assert(comparer != null); - Debug.Assert(lo >= 0); - Debug.Assert(hi > lo); - Debug.Assert(hi < keys.Length); - - int n = hi - lo + 1; - for (int i = n / 2; i >= 1; i = i - 1) - { - DownHeap(keys, values, i, n, lo, comparer); - } - for (int i = n; i > 1; i = i - 1) - { - Swap(keys, values, lo, lo + i - 1); - DownHeap(keys, values, 1, i - 1, lo, comparer); - } - } - - private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo, IComparer comparer) - { - Debug.Assert(keys != null); - Debug.Assert(comparer != null); - Debug.Assert(lo >= 0); - Debug.Assert(lo < keys.Length); - - TKey d = keys[lo + i - 1]; - TValue dValue = (values != null) ? values[lo + i - 1] : default(TValue); - int child; - while (i <= n / 2) - { - child = 2 * i; - if (child < n && comparer.Compare(keys[lo + child - 1], keys[lo + child]) < 0) - { - child++; - } - if (!(comparer.Compare(d, keys[lo + child - 1]) < 0)) - break; - keys[lo + i - 1] = keys[lo + child - 1]; - if (values != null) - values[lo + i - 1] = values[lo + child - 1]; - i = child; - } - keys[lo + i - 1] = d; - if (values != null) - values[lo + i - 1] = dValue; - } - - private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi, IComparer comparer) - { - Debug.Assert(keys != null); - Debug.Assert(values != null); - Debug.Assert(comparer != null); - Debug.Assert(lo >= 0); - Debug.Assert(hi >= lo); - Debug.Assert(hi <= keys.Length); - - int i, j; - TKey t; - TValue tValue; - for (i = lo; i < hi; i++) - { - j = i; - t = keys[i + 1]; - tValue = (values != null) ? values[i + 1] : default(TValue); - while (j >= lo && comparer.Compare(t, keys[j]) < 0) - { - keys[j + 1] = keys[j]; - if (values != null) - values[j + 1] = values[j]; - j--; - } - keys[j + 1] = t; - if (values != null) - values[j + 1] = tValue; - } - } - } - #endregion -} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Collections/Generic/CompatibilityEqualityComparers.cs b/external/corert/src/System.Private.CoreLib/src/System/Collections/Generic/CompatibilityEqualityComparers.cs index 33aef24b9c..c22edd601b 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Collections/Generic/CompatibilityEqualityComparers.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Collections/Generic/CompatibilityEqualityComparers.cs @@ -24,7 +24,7 @@ namespace System.Collections.Generic } // Equals method for the comparer itself. - public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); + public override bool Equals(object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Collections/Generic/EqualOnlyComparer.cs b/external/corert/src/System.Private.CoreLib/src/System/Collections/Generic/EqualOnlyComparer.cs index 8916147f7e..cd52c6c3ee 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Collections/Generic/EqualOnlyComparer.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Collections/Generic/EqualOnlyComparer.cs @@ -9,42 +9,42 @@ namespace System.Collections.Generic { internal static class EqualOnlyComparerHelper { - public static bool Equals(SByte x, SByte y) + public static bool Equals(sbyte x, sbyte y) { return x == y; } - public static bool Equals(Byte x, Byte y) + public static bool Equals(byte x, byte y) { return x == y; } - public static bool Equals(Int16 x, Int16 y) + public static bool Equals(short x, short y) { return x == y; } - public static bool Equals(UInt16 x, UInt16 y) + public static bool Equals(ushort x, ushort y) { return x == y; } - public static bool Equals(Int32 x, Int32 y) + public static bool Equals(int x, int y) { return x == y; } - public static bool Equals(UInt32 x, UInt32 y) + public static bool Equals(uint x, uint y) { return x == y; } - public static bool Equals(Int64 x, Int64 y) + public static bool Equals(long x, long y) { return x == y; } - public static bool Equals(UInt64 x, UInt64 y) + public static bool Equals(ulong x, ulong y) { return x == y; } @@ -59,22 +59,22 @@ namespace System.Collections.Generic return x == y; } - public static bool Equals(Single x, Single y) + public static bool Equals(float x, float y) { return x == y; } - public static bool Equals(Double x, Double y) + public static bool Equals(double x, double y) { return x == y; } - public static bool Equals(Decimal x, Decimal y) + public static bool Equals(decimal x, decimal y) { return x == y; } - public static bool Equals(String x, String y) + public static bool Equals(string x, string y) { return x == y; } @@ -95,33 +95,33 @@ namespace System.Collections.Generic { // Specialized Comparers if (typeof(T) == typeof(System.SByte)) - return EqualOnlyComparerHelper.Equals(((System.SByte)(Object)(x)), ((System.SByte)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.SByte)(object)(x)), ((System.SByte)(object)(y))); else if (typeof(T) == typeof(System.Byte)) - return EqualOnlyComparerHelper.Equals(((System.Byte)(Object)(x)), ((System.Byte)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.Byte)(object)(x)), ((System.Byte)(object)(y))); else if (typeof(T) == typeof(System.Int16)) - return EqualOnlyComparerHelper.Equals(((System.Int16)(Object)(x)), ((System.Int16)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.Int16)(object)(x)), ((System.Int16)(object)(y))); else if (typeof(T) == typeof(System.UInt16)) - return EqualOnlyComparerHelper.Equals(((System.UInt16)(Object)(x)), ((System.UInt16)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.UInt16)(object)(x)), ((System.UInt16)(object)(y))); else if (typeof(T) == typeof(System.Int32)) - return EqualOnlyComparerHelper.Equals(((System.Int32)(Object)(x)), ((System.Int32)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.Int32)(object)(x)), ((System.Int32)(object)(y))); else if (typeof(T) == typeof(System.UInt32)) - return EqualOnlyComparerHelper.Equals(((System.UInt32)(Object)(x)), ((System.UInt32)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.UInt32)(object)(x)), ((System.UInt32)(object)(y))); else if (typeof(T) == typeof(System.Int64)) - return EqualOnlyComparerHelper.Equals(((System.Int64)(Object)(x)), ((System.Int64)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.Int64)(object)(x)), ((System.Int64)(object)(y))); else if (typeof(T) == typeof(System.UInt64)) - return EqualOnlyComparerHelper.Equals(((System.UInt64)(Object)(x)), ((System.UInt64)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.UInt64)(object)(x)), ((System.UInt64)(object)(y))); else if (typeof(T) == typeof(System.IntPtr)) - return EqualOnlyComparerHelper.Equals(((System.IntPtr)(Object)(x)), ((System.IntPtr)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.IntPtr)(object)(x)), ((System.IntPtr)(object)(y))); else if (typeof(T) == typeof(System.UIntPtr)) - return EqualOnlyComparerHelper.Equals(((System.UIntPtr)(Object)(x)), ((System.UIntPtr)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.UIntPtr)(object)(x)), ((System.UIntPtr)(object)(y))); else if (typeof(T) == typeof(System.Single)) - return EqualOnlyComparerHelper.Equals(((System.Single)(Object)(x)), ((System.Single)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.Single)(object)(x)), ((System.Single)(object)(y))); else if (typeof(T) == typeof(System.Double)) - return EqualOnlyComparerHelper.Equals(((System.Double)(Object)(x)), ((System.Double)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.Double)(object)(x)), ((System.Double)(object)(y))); else if (typeof(T) == typeof(System.Decimal)) - return EqualOnlyComparerHelper.Equals(((System.Decimal)(Object)(x)), ((System.Decimal)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.Decimal)(object)(x)), ((System.Decimal)(object)(y))); else if (typeof(T) == typeof(System.String)) - return EqualOnlyComparerHelper.Equals(((System.String)(Object)(x)), ((System.String)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.String)(object)(x)), ((System.String)(object)(y))); // Default Comparer diff --git a/external/corert/src/System.Private.CoreLib/src/System/CurrentSystemTimeZone.Cache.cs b/external/corert/src/System.Private.CoreLib/src/System/CurrentSystemTimeZone.Cache.cs deleted file mode 100644 index efa66ece9e..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/CurrentSystemTimeZone.Cache.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Globalization; -using System.Collections.Concurrent; - -namespace System -{ - internal partial class CurrentSystemTimeZone - { - private DaylightTime GetCachedDaylightChanges(int year) => _daylightChangesUnifier.GetOrAdd(year); - - private sealed class DaylightChangesUnifier : ConcurrentUnifier - { - protected sealed override DaylightTime Factory(int key) => CurrentSystemTimeZone.CreateDaylightChanges(key); - } - - private readonly DaylightChangesUnifier _daylightChangesUnifier = new DaylightChangesUnifier(); - } -} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Decimal.DecCalc.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/src/System/Decimal.DecCalc.cs.REMOVED.git-id deleted file mode 100644 index 5de76f9948..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/Decimal.DecCalc.cs.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -05afe6b7e296d261b03eff87b6fb61e1db537d32 \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/src/System/DefaultBinder.CanConvert.cs b/external/corert/src/System.Private.CoreLib/src/System/DefaultBinder.CanConvert.cs index 593deba6fb..d0e4886a57 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/DefaultBinder.CanConvert.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/DefaultBinder.CanConvert.cs @@ -16,7 +16,7 @@ namespace System } // CanChangePrimitiveObjectToType - private static bool CanChangePrimitiveObjectToType(Object source, Type type) + private static bool CanChangePrimitiveObjectToType(object source, Type type) { return CanPrimitiveWiden(source.GetType(), type); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Delegate.DefaultParameters.cs b/external/corert/src/System.Private.CoreLib/src/System/Delegate.DefaultParameters.cs index 1820f68f1a..8460fb8fad 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Delegate.DefaultParameters.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Delegate.DefaultParameters.cs @@ -52,7 +52,7 @@ namespace System // Special encoding for MinInt is 0x0001 (which would normally mean -0). if (curVal == 0x0001) { - return Int64.MinValue; + return long.MinValue; } // High bit is used to indicate an extended value @@ -248,7 +248,7 @@ namespace System decimalBits[1] = dataParser.GetInt(); decimalBits[2] = dataParser.GetInt(); decimalBits[3] = dataParser.GetInt(); - defaultValue = new Decimal(decimalBits); + defaultValue = new decimal(decimalBits); return true; case DefaultParamTypeDateTime: defaultValue = new DateTime(dataParser.GetLong()); diff --git a/external/corert/src/System.Private.CoreLib/src/System/Delegate.cs b/external/corert/src/System.Private.CoreLib/src/System/Delegate.cs index e4746b1abd..d44045b6fc 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Delegate.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Delegate.cs @@ -31,7 +31,7 @@ namespace System } // V1 API: Create closed instance delegates. Method name matching is case sensitive. - protected Delegate(Object target, String method) + protected Delegate(object target, string method) { // This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an // overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal @@ -41,7 +41,7 @@ namespace System } // V1 API: Create open static delegates. Method name matching is case insensitive. - protected Delegate(Type target, String method) + protected Delegate(Type target, string method) { // This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an // overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal @@ -373,7 +373,22 @@ namespace System else { IntPtr invokeThunk = this.GetThunk(DelegateInvokeThunk); - object result = System.InvokeUtils.CallDynamicInvokeMethod(this.m_firstParameter, this.m_functionPointer, this, invokeThunk, IntPtr.Zero, this, args, binderBundle: null, wrapInTargetInvocationException: true); +#if PROJECTN + object result = InvokeUtils.CallDynamicInvokeMethod(this.m_firstParameter, this.m_functionPointer, this, invokeThunk, IntPtr.Zero, this, args, binderBundle: null, wrapInTargetInvocationException: true); +#else + IntPtr genericDictionary = IntPtr.Zero; + if (FunctionPointerOps.IsGenericMethodPointer(invokeThunk)) + { + unsafe + { + GenericMethodDescriptor* descriptor = FunctionPointerOps.ConvertToGenericDescriptor(invokeThunk); + genericDictionary = descriptor->InstantiationArgument; + invokeThunk = descriptor->MethodFunctionPointer; + } + } + + object result = InvokeUtils.CallDynamicInvokeMethod(this.m_firstParameter, this.m_functionPointer, null, invokeThunk, genericDictionary, this, args, binderBundle: null, wrapInTargetInvocationException: true, invokeMethodHelperIsThisCall: false); +#endif DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); return result; } @@ -479,8 +494,8 @@ namespace System MulticastDelegate d = (MulticastDelegate)o; MulticastDelegate dd = (MulticastDelegate)a[index]; - if (Object.ReferenceEquals(dd.m_firstParameter, d.m_firstParameter) && - Object.ReferenceEquals(dd.m_helperObject, d.m_helperObject) && + if (object.ReferenceEquals(dd.m_firstParameter, d.m_firstParameter) && + object.ReferenceEquals(dd.m_helperObject, d.m_helperObject) && dd.m_extraFunctionPointerOrData == d.m_extraFunctionPointerOrData && dd.m_functionPointer == d.m_functionPointer) { @@ -495,7 +510,7 @@ namespace System // to form a new delegate. protected virtual Delegate CombineImpl(Delegate d) { - if ((Object)d == null) // cast to object for a more efficient test + if ((object)d == null) // cast to object for a more efficient test return this; // Verify that the types are the same... @@ -724,7 +739,7 @@ namespace System return RuntimeAugments.Callbacks.GetDelegateMethod(this); } - public override bool Equals(Object obj) + public override bool Equals(object obj) { // It is expected that all real uses of the Equals method will hit the MulticastDelegate.Equals logic instead of this // therefore, instead of duplicating the desktop behavior where direct calls to this Equals function do not behave @@ -734,21 +749,21 @@ namespace System public static bool operator ==(Delegate d1, Delegate d2) { - if ((Object)d1 == null) - return (Object)d2 == null; + if ((object)d1 == null) + return (object)d2 == null; return d1.Equals(d2); } public static bool operator !=(Delegate d1, Delegate d2) { - if ((Object)d1 == null) - return (Object)d2 != null; + if ((object)d1 == null) + return (object)d2 != null; return !d1.Equals(d2); } - public Object Target + public object Target { get { @@ -767,7 +782,7 @@ namespace System return m_helperObject; // Other non-closed thunks can be identified as the m_firstParameter field points at this. - if (Object.ReferenceEquals(m_firstParameter, this)) + if (object.ReferenceEquals(m_firstParameter, this)) { return null; } @@ -853,7 +868,7 @@ namespace System // Note that delegates constructed the normal way do not come through here. The IL transformer generates the equivalent of // this code customized for each delegate type. // - internal static Delegate CreateDelegate(EETypePtr delegateEEType, IntPtr ldftnResult, Object thisObject, bool isStatic, bool isOpen) + internal static Delegate CreateDelegate(EETypePtr delegateEEType, IntPtr ldftnResult, object thisObject, bool isStatic, bool isOpen) { Delegate del = (Delegate)(RuntimeImports.RhNewObject(delegateEEType)); diff --git a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Contracts/Contracts.cs b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Contracts/Contracts.cs index 4ff7706e9b..dbc814dedf 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Contracts/Contracts.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Contracts/Contracts.cs @@ -161,14 +161,14 @@ namespace System.Diagnostics.Contracts [SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Thank you very much, but we like the names we've defined for the accessors")] public sealed class ContractPublicPropertyNameAttribute : Attribute { - private String _publicName; + private string _publicName; - public ContractPublicPropertyNameAttribute(String name) + public ContractPublicPropertyNameAttribute(string name) { _publicName = name; } - public String Name + public string Name { get { return _publicName; } } @@ -200,31 +200,31 @@ namespace System.Diagnostics.Contracts [Conditional("CONTRACTS_FULL")] public sealed class ContractOptionAttribute : Attribute { - private String _category; - private String _setting; + private string _category; + private string _setting; private bool _enabled; - private String _value; + private string _value; - public ContractOptionAttribute(String category, String setting, bool enabled) + public ContractOptionAttribute(string category, string setting, bool enabled) { _category = category; _setting = setting; _enabled = enabled; } - public ContractOptionAttribute(String category, String setting, String value) + public ContractOptionAttribute(string category, string setting, string value) { _category = category; _setting = setting; _value = value; } - public String Category + public string Category { get { return _category; } } - public String Setting + public string Setting { get { return _setting; } } @@ -234,7 +234,7 @@ namespace System.Diagnostics.Contracts get { return _enabled; } } - public String Value + public string Value { get { return _value; } } @@ -293,7 +293,7 @@ namespace System.Diagnostics.Contracts #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - public static void Assume(bool condition, String userMessage) + public static void Assume(bool condition, string userMessage) { if (!condition) { @@ -332,7 +332,7 @@ namespace System.Diagnostics.Contracts #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - public static void Assert(bool condition, String userMessage) + public static void Assert(bool condition, string userMessage) { if (!condition) ReportFailure(ContractFailureKind.Assert, userMessage, null, null); @@ -376,7 +376,7 @@ namespace System.Diagnostics.Contracts #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - public static void Requires(bool condition, String userMessage) + public static void Requires(bool condition, string userMessage) { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } @@ -418,7 +418,7 @@ namespace System.Diagnostics.Contracts #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - public static void Requires(bool condition, String userMessage) where TException : Exception + public static void Requires(bool condition, string userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } @@ -461,7 +461,7 @@ namespace System.Diagnostics.Contracts #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - public static void Ensures(bool condition, String userMessage) + public static void Ensures(bool condition, string userMessage) { AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures"); } @@ -504,7 +504,7 @@ namespace System.Diagnostics.Contracts #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - public static void EnsuresOnThrow(bool condition, String userMessage) where TException : Exception + public static void EnsuresOnThrow(bool condition, string userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow"); } @@ -598,7 +598,7 @@ namespace System.Diagnostics.Contracts #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - public static void Invariant(bool condition, String userMessage) + public static void Invariant(bool condition, string userMessage) { AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant"); } @@ -733,7 +733,7 @@ namespace System.Diagnostics.Contracts /// The runtime value is 2^64 - 1 or 2^32 - 1. /// [SuppressMessage("Microsoft.Performance", "CA1802", Justification = "FxCop is confused")] - static readonly ulong MaxWritableExtent = (UIntPtr.Size == 4) ? UInt32.MaxValue : UInt64.MaxValue; + static readonly ulong MaxWritableExtent = (UIntPtr.Size == 4) ? uint.MaxValue : ulong.MaxValue; /// /// Allows specifying a writable extent for a UIntPtr, similar to SAL's writable extent. @@ -851,13 +851,13 @@ namespace System.Diagnostics.Contracts /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// - static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException); + static partial void ReportFailure(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException); /// /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// - static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind); + static partial void AssertMustUseRewriter(ContractFailureKind kind, string contractKind); #endregion } @@ -936,9 +936,9 @@ namespace System.Runtime.CompilerServices #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) + public static string RaiseContractFailedEvent(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException) { - String resultFailureMessage = "Contract failed"; // default in case implementation does not assign anything. + string resultFailureMessage = "Contract failed"; // default in case implementation does not assign anything. RaiseContractFailedEventImplementation(failureKind, userMessage, conditionText, innerException, ref resultFailureMessage); return resultFailureMessage; } @@ -951,7 +951,7 @@ namespace System.Runtime.CompilerServices #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif - public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) + public static void TriggerFailure(ContractFailureKind kind, string displayMessage, string userMessage, string conditionText, Exception innerException) { TriggerFailureImplementation(kind, displayMessage, userMessage, conditionText, innerException); } @@ -971,12 +971,12 @@ namespace System.Runtime.CompilerServices /// Should really be out (or the return value), but partial methods are not flexible enough. /// On exit: null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message - static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage); + static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException, ref string resultFailureMessage); /// /// Implements the default failure behavior of the platform. Under the BCL, it triggers an Assert box. /// - static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException); + static partial void TriggerFailureImplementation(ContractFailureKind kind, string displayMessage, string userMessage, string conditionText, Exception innerException); #endregion Implementation Stubs } } // namespace System.Runtime.CompilerServices diff --git a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Contracts/ContractsBCL.cs b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Contracts/ContractsBCL.cs index 56626bb8f9..38b080bcb5 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Contracts/ContractsBCL.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Contracts/ContractsBCL.cs @@ -36,7 +36,7 @@ namespace System.Diagnostics.Contracts /// #if FEATURE_UNTRUSTED_CALLERS #endif - static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind) + static partial void AssertMustUseRewriter(ContractFailureKind kind, string contractKind) { //TODO: Implement CodeContract failure mechanics including enabling CCIRewrite @@ -65,7 +65,7 @@ namespace System.Diagnostics.Contracts //if (probablyNotRewritten == null) // probablyNotRewritten = thisAssembly; //String simpleName = probablyNotRewritten.GetName().Name; - String simpleName = "System.Private.CoreLib"; + string simpleName = "System.Private.CoreLib"; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null); t_assertingMustUseRewriter = false; @@ -85,14 +85,14 @@ namespace System.Diagnostics.Contracts #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) + static partial void ReportFailure(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); Contract.EndContractBlock(); // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message - String displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); + string displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); if (displayMessage == null) return; @@ -139,8 +139,8 @@ namespace System.Diagnostics.Contracts public sealed class ContractFailedEventArgs : EventArgs { private ContractFailureKind _failureKind; - private String _message; - private String _condition; + private string _message; + private string _condition; private Exception _originalException; private bool _handled; private bool _unwind; @@ -150,7 +150,7 @@ namespace System.Diagnostics.Contracts #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException) + public ContractFailedEventArgs(ContractFailureKind failureKind, string message, string condition, Exception originalException) { Contract.Requires(originalException == null || failureKind == ContractFailureKind.PostconditionOnException); _failureKind = failureKind; @@ -159,8 +159,8 @@ namespace System.Diagnostics.Contracts _originalException = originalException; } - public String Message { get { return _message; } } - public String Condition { get { return _condition; } } + public string Message { get { return _message; } } + public string Condition { get { return _condition; } } public ContractFailureKind FailureKind { get { return _failureKind; } } public Exception OriginalException { get { return _originalException; } } @@ -257,7 +257,7 @@ namespace System.Runtime.CompilerServices #if !FEATURE_CORECLR private static volatile EventHandler s_contractFailedEvent; - private static readonly Object s_lockObject = new Object(); + private static readonly object s_lockObject = new object(); #endif // !FEATURE_CORECLR internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542); @@ -321,14 +321,14 @@ namespace System.Runtime.CompilerServices [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS #endif - static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage) + static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException, ref string resultFailureMessage) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); Contract.EndContractBlock(); string returnValue; - String displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup... + string displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup... #if !FEATURE_CORECLR ContractFailedEventArgs eventArgs = null; // In case of OOM. #endif // !FEATURE_CORECLR @@ -392,7 +392,7 @@ namespace System.Runtime.CompilerServices [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_UNTRUSTED_CALLERS && !FEATURE_CORECLR #endif - static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) + static partial void TriggerFailureImplementation(ContractFailureKind kind, string displayMessage, string userMessage, string conditionText, Exception innerException) { // If we're here, our intent is to pop up a dialog box (if we can). For developers // interacting live with a debugger, this is a good experience. For Silverlight @@ -414,7 +414,7 @@ namespace System.Runtime.CompilerServices //TODO: Implement CodeContract failure mechanics including enabling CCIRewrite - String stackTrace = null; //@todo: Any reasonable way to get a stack trace here? + string stackTrace = null; //@todo: Any reasonable way to get a stack trace here? bool userSelectedIgnore = DeveloperExperience.Default.OnContractFailure(stackTrace, kind, displayMessage, userMessage, conditionText, innerException); if (userSelectedIgnore) return; @@ -431,9 +431,9 @@ namespace System.Runtime.CompilerServices // If we got here, the user selected Ignore. Continue. } - private static String GetFailureMessage(ContractFailureKind failureKind, String conditionText) + private static string GetFailureMessage(ContractFailureKind failureKind, string conditionText) { - bool hasConditionText = !String.IsNullOrEmpty(conditionText); + bool hasConditionText = !string.IsNullOrEmpty(conditionText); switch (failureKind) { case ContractFailureKind.Assert: @@ -463,7 +463,7 @@ namespace System.Runtime.CompilerServices #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - private static String GetDisplayMessage(ContractFailureKind failureKind, String userMessage, String conditionText) + private static string GetDisplayMessage(ContractFailureKind failureKind, string userMessage, string conditionText) { // Well-formatted English messages will take one of four forms. A sentence ending in // either a period or a colon, the condition string, then the message tacked @@ -471,9 +471,9 @@ namespace System.Runtime.CompilerServices // Note that both the conditionText and userMessage may be null. Also, // on Silverlight we may not be able to look up a friendly string for the // error message. Let's leverage Silverlight's default error message there. - String failureMessage = GetFailureMessage(failureKind, conditionText); + string failureMessage = GetFailureMessage(failureKind, conditionText); // Now add in the user message, if present. - if (!String.IsNullOrEmpty(userMessage)) + if (!string.IsNullOrEmpty(userMessage)) { return failureMessage + " " + userMessage; } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Debug.Windows.cs b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Debug.Windows.cs index 9493cadef8..9cd935feb0 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Debug.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Debug.Windows.cs @@ -22,7 +22,7 @@ namespace System.Diagnostics } } - private static readonly object s_ForLock = new Object(); + private static readonly object s_ForLock = new object(); private static void WriteCore(string message) { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs index 10298ebd5c..4c47bd66b4 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs @@ -49,14 +49,14 @@ namespace System.Diagnostics /// desired events are actually reported to the debugger. /// Constant representing the default category /// - public static readonly String DefaultCategory = null; + public static readonly string DefaultCategory = null; /// /// Posts a message for the attached debugger. If there is no /// debugger attached, has no effect. The debugger may or may not /// report the message depending on its settings. /// - public static void Log(int level, String category, String message) + public static void Log(int level, string category, string message) { if (IsLogging()) { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/StackFrame.CoreRT.cs b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/StackFrame.CoreRT.cs index cc8ac5a3d6..31a0da58d9 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/StackFrame.CoreRT.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/StackFrame.CoreRT.cs @@ -129,15 +129,15 @@ namespace System.Diagnostics /// internal void AppendToStackTrace(StringBuilder builder) { - if (_ipAddress == StackTraceHelper.SpecialIP.EdiSeparator) - { - builder.AppendLine(SR.StackTrace_EndStackTraceFromPreviousThrow); - } - else + if (_ipAddress != StackTraceHelper.SpecialIP.EdiSeparator) { builder.Append(SR.StackTrace_AtWord); builder.AppendLine(DeveloperExperience.Default.CreateStackTraceString(_ipAddress, _needFileInfo)); } + if (GetIsLastFrameFromForeignExceptionStackTrace()) + { + builder.AppendLine(SR.StackTrace_EndStackTraceFromPreviousThrow); + } } } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs index 4d5a2155ca..2aed3264ab 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs @@ -148,14 +148,35 @@ namespace System.Diagnostics private void InitializeForIpAddressArray(IntPtr[] ipAddresses, int skipFrames, int endFrameIndex, bool needFileInfo) { int frameCount = (skipFrames < endFrameIndex ? endFrameIndex - skipFrames : 0); - if (frameCount > 0) + + // Calculate true frame count upfront - we need to skip EdiSeparators which get + // collapsed onto boolean flags on the preceding stack frame + int outputFrameCount = 0; + for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { - _stackFrames = new StackFrame[frameCount]; + if (ipAddresses[frameIndex + skipFrames] != StackTraceHelper.SpecialIP.EdiSeparator) + { + outputFrameCount++; + } + } + + if (outputFrameCount > 0) + { + _stackFrames = new StackFrame[outputFrameCount]; + int outputFrameIndex = 0; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { IntPtr ipAddress = ipAddresses[frameIndex + skipFrames]; - _stackFrames[frameIndex] = new StackFrame(ipAddress, needFileInfo); + if (ipAddress != StackTraceHelper.SpecialIP.EdiSeparator) + { + _stackFrames[outputFrameIndex++] = new StackFrame(ipAddress, needFileInfo); + } + else if (outputFrameIndex > 0) + { + _stackFrames[outputFrameIndex - 1].SetIsLastFrameFromForeignExceptionStackTrace(true); + } } + Debug.Assert(outputFrameIndex == outputFrameCount); } } @@ -201,7 +222,7 @@ namespace System.Diagnostics /// /// Builds a readable representation of the stack trace /// - public override String ToString() + public override string ToString() { return ToString(TraceFormat.Normal); // default behavior in RT did not have trailing newline } @@ -214,7 +235,7 @@ namespace System.Diagnostics TrailingNewLine, // include a trailing new line character } - internal String ToString(TraceFormat traceFormat) + internal string ToString(TraceFormat traceFormat) { if (_stackFrames == null) { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource_CoreRT.cs b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource_CoreRT.cs index fc7e17d2a6..72ce7c99fa 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource_CoreRT.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource_CoreRT.cs @@ -178,6 +178,9 @@ namespace System.Diagnostics.Tracing this.Tags = tags; this.EnabledForAnyListener = enabledForAnyListener; this.EnabledForETW = enabledForETW; +#if FEATURE_PERFTRACING + this.EnabledForEventPipe = false; +#endif this.TriggersActivityTracking = 0; this.Name = name; this.Message = message; @@ -338,10 +341,10 @@ namespace System.Diagnostics.Tracing if (fmt != null) return string.Format(fmt, args); - string sargs = String.Empty; + string sargs = string.Empty; foreach(var arg in args) { - if (sargs != String.Empty) + if (sargs != string.Empty) sargs += ", "; sargs += arg.ToString(); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/UnsafeNativeMethods.cs b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/UnsafeNativeMethods.cs index 3d2e41eba6..c070027e7d 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/UnsafeNativeMethods.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/UnsafeNativeMethods.cs @@ -235,7 +235,7 @@ namespace Microsoft.Win32 [System.Security.SecuritySafeCritical] // Gets an error message for a Win32 error code. - internal static String GetMessage(int errorCode) + internal static string GetMessage(int errorCode) { #if FEATURE_MANAGED_ETW return Interop.Kernel32.GetMessage(errorCode); diff --git a/external/corert/src/System.Private.CoreLib/src/System/EETypePtr.cs b/external/corert/src/System.Private.CoreLib/src/System/EETypePtr.cs index fa5abb6b09..d4778aeb16 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/EETypePtr.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/EETypePtr.cs @@ -41,7 +41,7 @@ namespace System return _value; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (obj is EETypePtr) { @@ -396,6 +396,7 @@ namespace System } [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static EETypePtr EETypePtrOf() { // Compilers are required to provide a low level implementation of this method. diff --git a/external/corert/src/System.Private.CoreLib/src/System/Enum.cs b/external/corert/src/System.Private.CoreLib/src/System/Enum.cs index 06da1b1174..578c8f9950 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Enum.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Enum.cs @@ -19,7 +19,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible { - public int CompareTo(Object target) + public int CompareTo(object target) { if (target == null) return 1; @@ -77,7 +77,7 @@ namespace System } } - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (obj == null) return false; @@ -137,7 +137,7 @@ namespace System } } - public static String Format(Type enumType, Object value, String format) + public static string Format(Type enumType, object value, string format) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); @@ -170,7 +170,7 @@ namespace System return Format(enumInfo, value, format); } - private static String Format(EnumInfo enumInfo, Object value, String format) + private static string Format(EnumInfo enumInfo, object value, string format) { ulong rawValue; if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue)) @@ -213,20 +213,20 @@ namespace System // // Helper for Enum.Format(,,"d") // - private static String DoFormatD(ulong rawValue, RuntimeImports.RhCorElementType corElementType) + private static string DoFormatD(ulong rawValue, RuntimeImports.RhCorElementType corElementType) { switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { - SByte result = (SByte)rawValue; + sbyte result = (sbyte)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { - Byte result = (Byte)rawValue; + byte result = (byte)rawValue; return result.ToString(); } @@ -240,49 +240,49 @@ namespace System case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { - Int16 result = (Int16)rawValue; + short result = (short)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { - UInt16 result = (UInt16)rawValue; + ushort result = (ushort)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { - Char result = (Char)rawValue; + char result = (char)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { - UInt32 result = (UInt32)rawValue; + uint result = (uint)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { - Int32 result = (Int32)rawValue; + int result = (int)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { - UInt64 result = (UInt64)rawValue; + ulong result = (ulong)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { - Int64 result = (Int64)rawValue; + long result = (long)rawValue; return result.ToString(); } @@ -297,20 +297,20 @@ namespace System // // Helper for Enum.Format(,,"x") // - private static String DoFormatX(ulong rawValue, RuntimeImports.RhCorElementType corElementType) + private static string DoFormatX(ulong rawValue, RuntimeImports.RhCorElementType corElementType) { switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { - Byte result = (byte)(sbyte)rawValue; + byte result = (byte)(sbyte)rawValue; return result.ToString("X2", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { - Byte result = (byte)rawValue; + byte result = (byte)rawValue; return result.ToString("X2", null); } @@ -318,56 +318,56 @@ namespace System case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: { // direct cast from bool to byte is not allowed - Byte result = (byte)rawValue; + byte result = (byte)rawValue; return result.ToString("X2", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { - UInt16 result = (UInt16)(Int16)rawValue; + ushort result = (ushort)(short)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { - UInt16 result = (UInt16)rawValue; + ushort result = (ushort)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { - UInt16 result = (UInt16)(Char)rawValue; + ushort result = (ushort)(char)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { - UInt32 result = (UInt32)rawValue; + uint result = (uint)rawValue; return result.ToString("X8", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { - UInt32 result = (UInt32)(int)rawValue; + uint result = (uint)(int)rawValue; return result.ToString("X8", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { - UInt64 result = (UInt64)rawValue; + ulong result = (ulong)rawValue; return result.ToString("X16", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { - UInt64 result = (UInt64)(Int64)rawValue; + ulong result = (ulong)(long)rawValue; return result.ToString("X16", null); } @@ -381,13 +381,13 @@ namespace System // // Helper for Enum.Format(,,"g") // - private static String DoFormatG(EnumInfo enumInfo, ulong rawValue) + private static string DoFormatG(EnumInfo enumInfo, ulong rawValue) { Debug.Assert(enumInfo != null); if (!enumInfo.HasFlagsAttribute) // Not marked with Flags attribute { // Try to see if its one of the enum values, then we return a String back else the value - String name = GetNameIfAny(enumInfo, rawValue); + string name = GetNameIfAny(enumInfo, rawValue); if (name == null) return DoFormatD(rawValue, enumInfo.UnderlyingType.TypeHandle.ToEETypePtr().CorElementType); else @@ -402,12 +402,12 @@ namespace System // // Helper for Enum.Format(,,"f") // - private static String DoFormatF(EnumInfo enumInfo, ulong rawValue) + private static string DoFormatF(EnumInfo enumInfo, ulong rawValue) { Debug.Assert(enumInfo != null); // These values are sorted by value. Don't change this - KeyValuePair[] namesAndValues = enumInfo.NamesAndValues; + KeyValuePair[] namesAndValues = enumInfo.NamesAndValues; int index = namesAndValues.Length - 1; StringBuilder retval = new StringBuilder(); @@ -451,7 +451,7 @@ namespace System return retval.ToString(); // Built a list of matching names. Return it. } - internal Object GetValue() + internal object GetValue() { ref byte pValue = ref this.GetRawData(); @@ -483,7 +483,7 @@ namespace System } } - public static String GetName(Type enumType, Object value) + public static string GetName(Type enumType, object value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); @@ -502,11 +502,11 @@ namespace System throw new ArgumentException(SR.Arg_MustBeEnum); EnumInfo enumInfo = GetEnumInfo(enumType); - String nameOrNull = GetNameIfAny(enumInfo, rawValue); + string nameOrNull = GetNameIfAny(enumInfo, rawValue); return nameOrNull; } - public static String[] GetNames(Type enumType) + public static string[] GetNames(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); @@ -517,8 +517,8 @@ namespace System if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum); - KeyValuePair[] namesAndValues = GetEnumInfo(enumType).NamesAndValues; - String[] names = new String[namesAndValues.Length]; + KeyValuePair[] namesAndValues = GetEnumInfo(enumType).NamesAndValues; + string[] names = new string[namesAndValues.Length]; for (int i = 0; i < namesAndValues.Length; i++) names[i] = namesAndValues[i].Key; return names; @@ -551,13 +551,24 @@ namespace System Array values = GetEnumInfo(enumType).Values; int count = values.Length; +#if PROJECTN Array result = Array.CreateInstance(enumType, count); +#else + // Without universal shared generics, chances are slim that we'll have the appropriate + // array type available. Offer an escape hatch that avoids a MissingMetadataException + // at the cost of a small appcompat risk. + Array result; + if (AppContext.TryGetSwitch("Switch.System.Enum.RelaxedGetValues", out bool isRelaxed) && isRelaxed) + result = Array.CreateInstance(Enum.GetUnderlyingType(enumType), count); + else + result = Array.CreateInstance(enumType, count); +#endif Array.CopyImplValueTypeArrayNoInnerGcRefs(values, 0, result, 0, count); return result; } [Intrinsic] - public Boolean HasFlag(Enum flag) + public bool HasFlag(Enum flag) { if (flag == null) throw new ArgumentNullException(nameof(flag)); @@ -584,7 +595,7 @@ namespace System } } - public static bool IsDefined(Type enumType, Object value) + public static bool IsDefined(Type enumType, object value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); @@ -601,7 +612,7 @@ namespace System throw new ArgumentException(SR.Arg_MustBeEnum); EnumInfo enumInfo = GetEnumInfo(enumType); - foreach (KeyValuePair kv in enumInfo.NamesAndValues) + foreach (KeyValuePair kv in enumInfo.NamesAndValues) { if (value.Equals(kv.Key)) return true; @@ -641,33 +652,33 @@ namespace System throw new ArgumentException(SR.Arg_MustBeEnum); enumInfo = GetEnumInfo(enumType); } - String nameOrNull = GetNameIfAny(enumInfo, rawValue); + string nameOrNull = GetNameIfAny(enumInfo, rawValue); return nameOrNull != null; } } - public static Object Parse(Type enumType, String value) + public static object Parse(Type enumType, string value) { return Parse(enumType, value, ignoreCase: false); } - public static Object Parse(Type enumType, String value, bool ignoreCase) + public static object Parse(Type enumType, string value, bool ignoreCase) { - Object result; + object result; Exception exception; if (!TryParseEnum(enumType, value, ignoreCase, out result, out exception)) throw exception; return result; } - public static TEnum Parse(String value) where TEnum : struct + public static TEnum Parse(string value) where TEnum : struct { return Parse(value, ignoreCase: false); } - public static TEnum Parse(String value, bool ignoreCase) where TEnum : struct + public static TEnum Parse(string value, bool ignoreCase) where TEnum : struct { - Object result; + object result; Exception exception; if (!TryParseEnum(typeof(TEnum), value, ignoreCase, out result, out exception)) throw exception; @@ -728,7 +739,7 @@ namespace System return RuntimeImports.RhBox(enumEEType, pValue); } - public static Object ToObject(Type enumType, Object value) + public static object ToObject(Type enumType, object value) { if (value == null) throw new ArgumentNullException(nameof(value)); @@ -774,22 +785,22 @@ namespace System } } - public static bool TryParse(Type enumType, String value, bool ignoreCase, out Object result) + public static bool TryParse(Type enumType, string value, bool ignoreCase, out object result) { Exception exception; return TryParseEnum(enumType, value, ignoreCase, out result, out exception); } - public static bool TryParse(Type enumType, String value, out Object result) + public static bool TryParse(Type enumType, string value, out object result) { Exception exception; return TryParseEnum(enumType, value, false, out result, out exception); } - public static bool TryParse(String value, bool ignoreCase, out TEnum result) where TEnum : struct + public static bool TryParse(string value, bool ignoreCase, out TEnum result) where TEnum : struct { Exception exception; - Object tempResult; + object tempResult; if (!TryParseEnum(typeof(TEnum), value, ignoreCase, out tempResult, out exception)) { result = default(TEnum); @@ -799,12 +810,12 @@ namespace System return true; } - public static bool TryParse(String value, out TEnum result) where TEnum : struct + public static bool TryParse(string value, out TEnum result) where TEnum : struct { return TryParse(value, false, out result); } - public override String ToString() + public override string ToString() { try { @@ -816,7 +827,7 @@ namespace System } } - public String ToString(String format) + public string ToString(string format) { if (format == null || format.Length == 0) format = "G"; @@ -834,13 +845,13 @@ namespace System } [Obsolete("The provider argument is not used. Please use ToString().")] - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return ToString(format); } [Obsolete("The provider argument is not used. Please use ToString().")] - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return ToString(); } @@ -857,7 +868,7 @@ namespace System // // Checks if value.GetType() matches enumType exactly. // - private static bool ValueTypeMatchesEnumType(Type enumType, Object value) + private static bool ValueTypeMatchesEnumType(Type enumType, object value) { EETypePtr enumEEType; if (!enumType.TryGetEEType(out enumEEType)) @@ -885,7 +896,7 @@ namespace System // // The return value is "bool" if "value" is not an enum or an "integer type" as defined by the BCL Enum apis. // - private static bool TryGetUnboxedValueOfEnumOrInteger(Object value, out ulong result) + private static bool TryGetUnboxedValueOfEnumOrInteger(object value, out ulong result) { EETypePtr eeType = value.EETypePtr; // For now, this check is required to flush out pointers. @@ -949,10 +960,10 @@ namespace System // // Look up a name for rawValue if a matching one exists. Returns null if no matching name exists. // - private static String GetNameIfAny(EnumInfo enumInfo, ulong rawValue) + private static string GetNameIfAny(EnumInfo enumInfo, ulong rawValue) { - KeyValuePair[] namesAndValues = enumInfo.NamesAndValues; - KeyValuePair searchKey = new KeyValuePair(null, rawValue); + KeyValuePair[] namesAndValues = enumInfo.NamesAndValues; + KeyValuePair searchKey = new KeyValuePair(null, rawValue); int index = Array.BinarySearch>(namesAndValues, searchKey, s_nameAndValueComparer); if (index < 0) return null; @@ -962,7 +973,7 @@ namespace System // // Common funnel for Enum.Parse methods. // - private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, out Object result, out Exception exception) + private static bool TryParseEnum(Type enumType, string value, bool ignoreCase, out object result, out Exception exception) { exception = null; result = null; @@ -1021,7 +1032,7 @@ namespace System StringComparison comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - KeyValuePair[] actualNamesAndValues = enumInfo.NamesAndValues; + KeyValuePair[] actualNamesAndValues = enumInfo.NamesAndValues; int valueIndex = firstNonWhitespaceIndex; while (valueIndex <= value.Length) // '=' is to handle invalid case of an ending comma { @@ -1040,11 +1051,11 @@ namespace System // Try to match this substring against each enum name bool foundMatch = false; - foreach (KeyValuePair kv in actualNamesAndValues) + foreach (KeyValuePair kv in actualNamesAndValues) { - String actualName = kv.Key; + string actualName = kv.Key; if (actualName.Length == valueSubstringLength && - String.Compare(actualName, 0, value, valueIndex, valueSubstringLength, comparison) == 0) + string.Compare(actualName, 0, value, valueIndex, valueSubstringLength, comparison) == 0) { v |= kv.Value; foundMatch = true; @@ -1067,7 +1078,7 @@ namespace System return true; } - private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int valueOffset, out Object result) + private static bool TryParseAsInteger(EETypePtr enumEEType, string value, int valueOffset, out object result) { Debug.Assert(value != null, "Expected non-null value"); Debug.Assert(value.Length > 0, "Expected non-empty value"); @@ -1076,7 +1087,7 @@ namespace System result = null; char firstNonWhitespaceChar = value[valueOffset]; - if (!(Char.IsDigit(firstNonWhitespaceChar) || firstNonWhitespaceChar == '+' || firstNonWhitespaceChar == '-')) + if (!(char.IsDigit(firstNonWhitespaceChar) || firstNonWhitespaceChar == '+' || firstNonWhitespaceChar == '-')) return false; RuntimeImports.RhCorElementType corElementType = enumEEType.CorElementType; @@ -1087,8 +1098,8 @@ namespace System { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: { - Boolean v; - if (!Boolean.TryParse(value, out v)) + bool v; + if (!bool.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1096,8 +1107,8 @@ namespace System case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { - Char v; - if (!Char.TryParse(value, out v)) + char v; + if (!char.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1105,8 +1116,8 @@ namespace System case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { - SByte v; - if (!SByte.TryParse(value, out v)) + sbyte v; + if (!sbyte.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1114,8 +1125,8 @@ namespace System case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { - Byte v; - if (!Byte.TryParse(value, out v)) + byte v; + if (!byte.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1123,8 +1134,8 @@ namespace System case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { - Int16 v; - if (!Int16.TryParse(value, out v)) + short v; + if (!short.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1132,8 +1143,8 @@ namespace System case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { - UInt16 v; - if (!UInt16.TryParse(value, out v)) + ushort v; + if (!ushort.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1141,8 +1152,8 @@ namespace System case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { - Int32 v; - if (!Int32.TryParse(value, out v)) + int v; + if (!int.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1150,8 +1161,8 @@ namespace System case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { - UInt32 v; - if (!UInt32.TryParse(value, out v)) + uint v; + if (!uint.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1159,8 +1170,8 @@ namespace System case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { - Int64 v; - if (!Int64.TryParse(value, out v)) + long v; + if (!long.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1168,8 +1179,8 @@ namespace System case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { - UInt64 v; - if (!UInt64.TryParse(value, out v)) + ulong v; + if (!ulong.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1181,7 +1192,7 @@ namespace System } } - private static bool StillLooksLikeInteger(String value, int index) + private static bool StillLooksLikeInteger(string value, int index) { if (index != value.Length && (value[index] == '-' || value[index] == '+')) { @@ -1243,9 +1254,9 @@ namespace System // // Sort comparer for NamesAndValues // - private class NamesAndValueComparer : IComparer> + private class NamesAndValueComparer : IComparer> { - public int Compare(KeyValuePair kv1, KeyValuePair kv2) + public int Compare(KeyValuePair kv1, KeyValuePair kv2) { ulong x = kv1.Value; ulong y = kv2.Value; @@ -1260,11 +1271,11 @@ namespace System private static NamesAndValueComparer s_nameAndValueComparer = new NamesAndValueComparer(); - private String LastResortToString + private string LastResortToString { get { - return String.Format("{0}", GetValue()); + return string.Format("{0}", GetValue()); } } @@ -1361,17 +1372,17 @@ namespace System return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { - throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Enum", "DateTime")); + throw new InvalidCastException(string.Format(SR.InvalidCast_FromTo, "Enum", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Environment.Unix.cs b/external/corert/src/System.Private.CoreLib/src/System/Environment.Unix.cs index c45d54bd8f..af2e5517a1 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Environment.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Environment.Unix.cs @@ -20,18 +20,6 @@ namespace System } } - private static int ComputeExecutionId() - { - int executionId = Interop.Sys.SchedGetCpu(); - - // sched_getcpu doesn't exist on all platforms. On those it doesn't exist on, the shim - // returns -1. As a fallback in that case and to spread the threads across the buckets - // by default, we use the current managed thread ID as a proxy. - if (executionId < 0) executionId = Environment.CurrentManagedThreadId; - - return executionId; - } - #if DEBUG [Obsolete("ExpandEnvironmentVariables() only called on Windows so not implemented on Unix.")] public static string ExpandEnvironmentVariables(string name) diff --git a/external/corert/src/System.Private.CoreLib/src/System/Environment.Windows.cs b/external/corert/src/System.Private.CoreLib/src/System/Environment.Windows.cs index f5fca35ab4..71c9e06a47 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Environment.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Environment.Windows.cs @@ -12,8 +12,6 @@ namespace System internal static long TickCount64 => (long)Interop.mincore.GetTickCount64(); - private static int ComputeExecutionId() => (int)Interop.mincore.GetCurrentProcessorNumber(); - public static string ExpandEnvironmentVariables(string name) { if (name == null) diff --git a/external/corert/src/System.Private.CoreLib/src/System/Environment.cs b/external/corert/src/System.Private.CoreLib/src/System/Environment.cs index c1d4ac171b..015c68bf9f 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Environment.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Environment.cs @@ -50,17 +50,17 @@ namespace System //// another managed helper method, unless you consult with some CLR Watson experts. - public static void FailFast(String message) + public static void FailFast(string message) { RuntimeExceptionHelpers.FailFast(message); } - public static void FailFast(String message, Exception exception) + public static void FailFast(string message, Exception exception) { RuntimeExceptionHelpers.FailFast(message, exception); } - internal static void FailFast(String message, Exception exception, String errorSource) + internal static void FailFast(string message, Exception exception, string errorSource) { // TODO: errorSource originates from CoreCLR (See: https://github.com/dotnet/coreclr/pull/15895) // For now, we ignore errorSource on CoreRT but we should distinguish the way FailFast prints exception message using errorSource @@ -82,43 +82,6 @@ namespace System } } - // The upper bits of t_executionIdCache are the executionId. The lower bits of - // the t_executionIdCache are counting down to get it periodically refreshed. - // TODO: Consider flushing the executionIdCache on Wait operations or similar - // actions that are likely to result in changing the executing core - [ThreadStatic] - private static int t_executionIdCache; - - private const int ExecutionIdCacheShift = 16; - private const int ExecutionIdCacheCountDownMask = (1 << ExecutionIdCacheShift) - 1; - private const int ExecutionIdRefreshRate = 5000; - - private static int RefreshExecutionId() - { - int executionId = ComputeExecutionId(); - - Debug.Assert(ExecutionIdRefreshRate <= ExecutionIdCacheCountDownMask); - - // Mask with Int32.MaxValue to ensure the execution Id is not negative - t_executionIdCache = ((executionId << ExecutionIdCacheShift) & Int32.MaxValue) + ExecutionIdRefreshRate; - - return executionId; - } - - // Cached processor number used as a hint for which per-core stack to access. It is periodically - // refreshed to trail the actual thread core affinity. - internal static int CurrentExecutionId - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - int executionIdCache = t_executionIdCache--; - if ((executionIdCache & ExecutionIdCacheCountDownMask) == 0) - return RefreshExecutionId(); - return (executionIdCache >> ExecutionIdCacheShift); - } - } - public static bool HasShutdownStarted { get @@ -135,7 +98,7 @@ namespace System **Arguments: None. **Exceptions: None. ==============================================================================*/ - public static String NewLine + public static string NewLine { get { @@ -147,7 +110,7 @@ namespace System } } - public static String StackTrace + public static string StackTrace { // Disable inlining to have predictable stack frame that EnvironmentAugments can skip [MethodImpl(MethodImplOptions.NoInlining)] diff --git a/external/corert/src/System.Private.CoreLib/src/System/Exception.cs b/external/corert/src/System.Private.CoreLib/src/System/Exception.cs index 6e4aba99c0..0e3dbf7bd6 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Exception.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Exception.cs @@ -29,7 +29,7 @@ namespace System Init(); } - public Exception(String message) + public Exception(string message) { Init(); _message = message; @@ -40,7 +40,7 @@ namespace System // Note: the stack trace is not started until the exception // is thrown // - public Exception(String message, Exception innerException) + public Exception(string message, Exception innerException) { Init(); _message = message; @@ -63,13 +63,13 @@ namespace System _source = info.GetString("Source"); // Do not rename (binary serialization) } - public virtual String Message + public virtual string Message { get { if (_message == null) { - String className = GetClassName(); + string className = GetClassName(); return SR.Format(SR.Exception_WasThrown, className); } else @@ -176,14 +176,6 @@ namespace System } } - /// - /// Allow System.Private.Interop to set HRESULT of an exception - /// - internal void SetErrorCode(int hr) - { - HResult = hr; - } - /// /// Allow System.Private.Interop to set message of an exception /// @@ -240,18 +232,18 @@ namespace System _message = Message; // Set the Message information correctly before serialization } - info.AddValue("ClassName", GetClassName(), typeof(String)); // Do not rename (binary serialization) - info.AddValue("Message", _message, typeof(String)); // Do not rename (binary serialization) + info.AddValue("ClassName", GetClassName(), typeof(string)); // Do not rename (binary serialization) + info.AddValue("Message", _message, typeof(string)); // Do not rename (binary serialization) info.AddValue("Data", _data, typeof(IDictionary)); // Do not rename (binary serialization) info.AddValue("InnerException", _innerException, typeof(Exception)); // Do not rename (binary serialization) - info.AddValue("HelpURL", _helpURL, typeof(String)); // Do not rename (binary serialization) - info.AddValue("StackTraceString", StackTrace, typeof(String)); // Do not rename (binary serialization) - info.AddValue("RemoteStackTraceString", null, typeof(String)); // Do not rename (binary serialization) - info.AddValue("RemoteStackIndex", 0, typeof(Int32)); // Do not rename (binary serialization) - info.AddValue("ExceptionMethod", null, typeof(String)); // Do not rename (binary serialization) + info.AddValue("HelpURL", _helpURL, typeof(string)); // Do not rename (binary serialization) + info.AddValue("StackTraceString", StackTrace, typeof(string)); // Do not rename (binary serialization) + info.AddValue("RemoteStackTraceString", null, typeof(string)); // Do not rename (binary serialization) + info.AddValue("RemoteStackIndex", 0, typeof(int)); // Do not rename (binary serialization) + info.AddValue("ExceptionMethod", null, typeof(string)); // Do not rename (binary serialization) info.AddValue("HResult", HResult); // Do not rename (binary serialization) - info.AddValue("Source", _source, typeof(String)); // Do not rename (binary serialization) - info.AddValue("WatsonBuckets", null, typeof(String)); // Do not rename (binary serialization) + info.AddValue("Source", _source, typeof(string)); // Do not rename (binary serialization) + info.AddValue("WatsonBuckets", null, typeof(string)); // Do not rename (binary serialization) } private string GetStackTrace(bool needFileInfo) @@ -259,7 +251,7 @@ namespace System return this.StackTrace; } - public virtual String HelpLink + public virtual string HelpLink { get { @@ -272,7 +264,7 @@ namespace System } } - public virtual String Source + public virtual string Source { get { @@ -288,15 +280,15 @@ namespace System } } - public override String ToString() + public override string ToString() { return ToString(true, true); } - private String ToString(bool needFileLineInfo, bool needMessage) + private string ToString(bool needFileLineInfo, bool needMessage) { - String message = (needMessage ? Message : null); - String s; + string message = (needMessage ? Message : null); + string s; if (message == null || message.Length <= 0) { @@ -326,26 +318,26 @@ namespace System // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. - internal String _message; + internal string _message; private IDictionary _data; private Exception _innerException; - private String _helpURL; - private String _source; // Mainly used by VB. + private string _helpURL; + private string _source; // Mainly used by VB. private int _HResult; // HResult // To maintain compatibility across runtimes, if this object was deserialized, it will store its stack trace as a string - private String _stackTrace; + private string _stackTrace; public int HResult { get { return _HResult; } - protected set { _HResult = value; } + set { _HResult = value; } } // Returns the stack trace as a string. If no stack trace is // available, null is returned. - public virtual String StackTrace + public virtual string StackTrace { get { @@ -524,7 +516,7 @@ namespace System // for a small duration but that sounds reasonable considering // such scenarios are going to be extremely rare, where timing // matches precisely. - private static Object s_EDILock = new Object(); + private static object s_EDILock = new object(); /// /// This is the binary format for serialized exceptions that get saved into a special buffer that is @@ -536,8 +528,8 @@ namespace System private struct SERIALIZED_EXCEPTION_HEADER { internal IntPtr ExceptionEEType; - internal Int32 HResult; - internal Int32 StackTraceElementCount; + internal int HResult; + internal int StackTraceElementCount; // IntPtr * N : StackTrace elements } internal const int CurrentSerializationSignature = 0x31305845; // 'EX01' diff --git a/external/corert/src/System.Private.CoreLib/src/System/GC.cs b/external/corert/src/System.Private.CoreLib/src/System/GC.cs index 68d1bc9a34..1fc2846a65 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/GC.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/GC.cs @@ -61,7 +61,7 @@ namespace System public static class GC { - public static int GetGeneration(Object obj) + public static int GetGeneration(object obj) { if (obj == null) { @@ -84,7 +84,7 @@ namespace System { // note - this throws an NRE if given a null weak reference. This isn't // documented, but it's the behavior of Desktop and CoreCLR. - Object handleRef = RuntimeImports.RhHandleGet(wo.m_handle); + object handleRef = RuntimeImports.RhHandleGet(wo.m_handle); if (handleRef == null) { throw new ArgumentNullException(nameof(wo)); @@ -170,14 +170,14 @@ namespace System { throw new ArgumentOutOfRangeException( nameof(maxGenerationThreshold), - String.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); + string.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); } if (largeObjectHeapThreshold < 1 || largeObjectHeapThreshold > 99) { throw new ArgumentOutOfRangeException( nameof(largeObjectHeapThreshold), - String.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); + string.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); } // This is not documented on MSDN, but CoreCLR throws when the GC's @@ -394,7 +394,7 @@ namespace System RuntimeImports.RhWaitForPendingFinalizers(RuntimeThread.ReentrantWaitsEnabled); } - public static void SuppressFinalize(Object obj) + public static void SuppressFinalize(object obj) { if (obj == null) { @@ -404,7 +404,7 @@ namespace System RuntimeImports.RhSuppressFinalize(obj); } - public static void ReRegisterForFinalize(Object obj) + public static void ReRegisterForFinalize(object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); @@ -414,7 +414,7 @@ namespace System [Intrinsic] [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations - public static void KeepAlive(Object obj) + public static void KeepAlive(object obj) { } @@ -516,7 +516,7 @@ namespace System } #if !BIT64 - if (bytesAllocated > Int32.MaxValue) + if (bytesAllocated > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); @@ -585,7 +585,7 @@ namespace System } #if !BIT64 - if (bytesAllocated > Int32.MaxValue) + if (bytesAllocated > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); @@ -631,5 +631,20 @@ namespace System { return RuntimeImports.RhGetAllocatedBytesForCurrentThread(); } + + internal static void GetMemoryInfo(out uint highMemLoadThreshold, + out ulong totalPhysicalMem, + out uint lastRecordedMemLoad, + // The next two are size_t + out UIntPtr lastRecordedHeapSize, + out UIntPtr lastRecordedFragmentation) + { + // TODO: https://github.com/dotnet/corert/issues/5680 + highMemLoadThreshold = default; + totalPhysicalMem = default; + lastRecordedMemLoad = default; + lastRecordedHeapSize = default; + lastRecordedFragmentation = default; + } } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.Windows.cs b/external/corert/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.Windows.cs index df13759f74..151bb0d633 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.Windows.cs @@ -78,7 +78,7 @@ namespace System.Globalization index++; } - CultureInfo temp = GetCultureByName(new String(languages, 0, index), true); + CultureInfo temp = GetCultureByName(new string(languages, 0, index), true); temp._isReadOnly = true; return temp; } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs b/external/corert/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs index 08be455f97..19ccb9fef7 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs @@ -155,12 +155,12 @@ namespace System.Globalization //////////////////////////////////////////////////////////////////////// - public CultureInfo(String name) + public CultureInfo(string name) : this(name, true) { } - public CultureInfo(String name, bool useUserOverride) + public CultureInfo(string name, bool useUserOverride) { if (name == null) { @@ -176,7 +176,11 @@ namespace System.Globalization nameof(name), name, SR.Argument_CultureNotSupported); _name = _cultureData.CultureName; +#if MONO + _isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo)); +#else _isInherited = !this.EETypePtr.FastEquals(EETypePtr.EETypePtrOf()); +#endif } private CultureInfo(CultureData cultureData, bool isReadOnly = false) @@ -238,7 +242,7 @@ namespace System.Globalization // Note that we really cannot use an LCID version of this override as the cached // name we create for it has to include both names, and the logic for this is in // the GetCultureInfo override *only*. - internal CultureInfo(String cultureName, String textAndCompareCultureName) + internal CultureInfo(string cultureName, string textAndCompareCultureName) { if (cultureName == null) { @@ -261,7 +265,7 @@ namespace System.Globalization // // TODO: It would appear that this is only ever called with userOveride = true // and this method only has one caller. Can we fold it into the caller? - private static CultureInfo GetCultureByName(String name, bool userOverride) + private static CultureInfo GetCultureByName(string name, bool userOverride) { CultureInfo ci = null; // Try to get our culture @@ -289,7 +293,7 @@ namespace System.Globalization // if we can't find a bigger name. That doesn't help with things like "zh" though, so // the approach is of questionable value // - public static CultureInfo CreateSpecificCulture(String name) + public static CultureInfo CreateSpecificCulture(string name) { CultureInfo culture; @@ -339,7 +343,7 @@ namespace System.Globalization return (new CultureInfo(culture._cultureData.SSPECIFICCULTURE)); } - internal static bool VerifyCultureName(String cultureName, bool throwException) + internal static bool VerifyCultureName(string cultureName, bool throwException) { // This function is used by ResourceManager.GetResourceFileName(). // ResourceManager searches for resource using CultureInfo.Name, @@ -349,7 +353,7 @@ namespace System.Globalization { char c = cultureName[i]; // TODO: Names can only be RFC4646 names (ie: a-zA-Z0-9) while this allows any unicode letter/digit - if (Char.IsLetterOrDigit(c) || c == '-' || c == '_') + if (char.IsLetterOrDigit(c) || c == '-' || c == '_') { continue; } @@ -567,7 +571,7 @@ namespace System.Globalization CultureInfo culture = null; string parentName = _cultureData.SPARENT; - if (String.IsNullOrEmpty(parentName)) + if (string.IsNullOrEmpty(parentName)) { culture = InvariantCulture; } @@ -624,7 +628,7 @@ namespace System.Globalization // "en-US" This version does NOT include sort information in the name. // //////////////////////////////////////////////////////////////////////// - public virtual String Name + public virtual string Name { get { @@ -634,7 +638,7 @@ namespace System.Globalization _nonSortName = _cultureData.SNAME; if (_nonSortName == null) { - _nonSortName = String.Empty; + _nonSortName = string.Empty; } } return _nonSortName; @@ -642,7 +646,7 @@ namespace System.Globalization } // This one has the sort information (ie: de-DE_phoneb) - internal String SortName + internal string SortName { get { @@ -681,7 +685,7 @@ namespace System.Globalization // US English, "Ingles (Estados Unidos)" will be returned. // //////////////////////////////////////////////////////////////////////// - public virtual String DisplayName + public virtual string DisplayName { get { @@ -700,7 +704,7 @@ namespace System.Globalization // (United States)" will be returned. // //////////////////////////////////////////////////////////////////////// - public virtual String NativeName + public virtual string NativeName { get { @@ -717,7 +721,7 @@ namespace System.Globalization // (United States)" will be returned. // //////////////////////////////////////////////////////////////////////// - public virtual String EnglishName + public virtual string EnglishName { get { @@ -726,7 +730,7 @@ namespace System.Globalization } // ie: en - public virtual String TwoLetterISOLanguageName + public virtual string TwoLetterISOLanguageName { get { @@ -735,7 +739,7 @@ namespace System.Globalization } // ie: eng - public virtual String ThreeLetterISOLanguageName + public virtual string ThreeLetterISOLanguageName { get { @@ -751,7 +755,7 @@ namespace System.Globalization // The ISO names are much preferred // //////////////////////////////////////////////////////////////////////// - public virtual String ThreeLetterWindowsLanguageName + public virtual string ThreeLetterWindowsLanguageName { get { @@ -838,9 +842,9 @@ namespace System.Globalization //////////////////////////////////////////////////////////////////////// - public override bool Equals(Object value) + public override bool Equals(object value) { - if (Object.ReferenceEquals(this, value)) + if (object.ReferenceEquals(this, value)) return true; CultureInfo that = value as CultureInfo; @@ -883,13 +887,13 @@ namespace System.Globalization //////////////////////////////////////////////////////////////////////// - public override String ToString() + public override string ToString() { return _name; } - public virtual Object GetFormat(Type formatType) + public virtual object GetFormat(Type formatType) { if (formatType == typeof(NumberFormatInfo)) return (NumberFormat); @@ -1127,7 +1131,7 @@ namespace System.Globalization return (temp); } - public virtual Object Clone() + public virtual object Clone() { CultureInfo ci = (CultureInfo)MemberwiseClone(); ci._isReadOnly = false; diff --git a/external/corert/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Unix.cs b/external/corert/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Unix.cs index f292d54dce..eaa126b015 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Unix.cs @@ -13,12 +13,17 @@ namespace System.Globalization bool invariantEnabled = false; if (!invariantEnabled) { + // WASM TODO: There's no WASM build of LibICU. We may be able to cross-compile it ourselves. +#if WASM + return true; +#else if (Interop.Globalization.LoadICU() == 0) { string message = "Couldn't find a valid ICU package installed on the system. " + "Set the configuration flag System.Globalization.Invariant to true if you want to run with no globalization support."; Environment.FailFast(message); } +#endif // !WASM } return invariantEnabled; } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Guid.Unix.cs b/external/corert/src/System.Private.CoreLib/src/System/Guid.Unix.cs deleted file mode 100644 index 326362d042..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/Guid.Unix.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; -using System.Runtime.InteropServices; - -namespace System -{ - partial struct Guid - { - // This will create a new guid. Since we've now decided that constructors should 0-init, - // we need a method that allows users to create a guid. - public static Guid NewGuid() - { - // CoCreateGuid should never return Guid.Empty, since it attempts to maintain some - // uniqueness guarantees. It should also never return a known GUID, but it's unclear - // how extensively it checks for known values. - - Interop.Sys.CreateGuid(out Guid g); - return g; - } - } -} diff --git a/external/corert/src/System.Private.CoreLib/src/System/IO/Stream.CoreRT.cs b/external/corert/src/System.Private.CoreLib/src/System/IO/Stream.CoreRT.cs new file mode 100644 index 0000000000..091b0fcefc --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/IO/Stream.CoreRT.cs @@ -0,0 +1,13 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.IO +{ + public abstract partial class Stream + { + private bool HasOverriddenBeginEndRead() => true; + + private bool HasOverriddenBeginEndWrite() => true; + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/IO/Stream.cs b/external/corert/src/System.Private.CoreLib/src/System/IO/Stream.cs deleted file mode 100644 index c307ec91e1..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/IO/Stream.cs +++ /dev/null @@ -1,808 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Buffers; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Threading; -using System.Threading.Tasks; - -namespace System.IO -{ - public abstract class Stream : MarshalByRefObject, IDisposable - { - public static readonly Stream Null = new NullStream(); - - //We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K). - // The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant - // improvement in Copy performance. - private const int DefaultCopyBufferSize = 81920; - - // To implement Async IO operations on streams that don't support async IO - - private SemaphoreSlim _asyncActiveSemaphore; - - internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() - { - // Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's - // WaitHandle, we don't need to worry about Disposing it. - return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); - } - - public abstract bool CanRead - { - get; - } - - // If CanSeek is false, Position, Seek, Length, and SetLength should throw. - public abstract bool CanSeek - { - get; - } - - public virtual bool CanTimeout - { - get - { - return false; - } - } - - public abstract bool CanWrite - { - get; - } - - public abstract long Length - { - get; - } - - public abstract long Position - { - get; - set; - } - - public virtual int ReadTimeout - { - get - { - throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); - } - set - { - throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); - } - } - - public virtual int WriteTimeout - { - get - { - throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); - } - set - { - throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); - } - } - - public Task CopyToAsync(Stream destination) - { - int bufferSize = GetCopyBufferSize(); - - return CopyToAsync(destination, bufferSize); - } - - public Task CopyToAsync(Stream destination, int bufferSize) - { - return CopyToAsync(destination, bufferSize, CancellationToken.None); - } - - public Task CopyToAsync(Stream destination, CancellationToken cancellationToken) - { - int bufferSize = GetCopyBufferSize(); - - return CopyToAsync(destination, bufferSize, cancellationToken); - } - - public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) - { - StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); - - return CopyToAsyncInternal(destination, bufferSize, cancellationToken); - } - - private async Task CopyToAsyncInternal(Stream destination, int bufferSize, CancellationToken cancellationToken) - { - Debug.Assert(destination != null); - Debug.Assert(bufferSize > 0); - Debug.Assert(CanRead); - Debug.Assert(destination.CanWrite); - - byte[] buffer = new byte[bufferSize]; - while (true) - { - int bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); - if (bytesRead == 0) break; - await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); - } - } - - // Reads the bytes from the current stream and writes the bytes to - // the destination stream until all bytes are read, starting at - // the current position. - public void CopyTo(Stream destination) - { - int bufferSize = GetCopyBufferSize(); - - CopyTo(destination, bufferSize); - } - - public virtual void CopyTo(Stream destination, int bufferSize) - { - StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); - - byte[] buffer = new byte[bufferSize]; - int read; - while ((read = Read(buffer, 0, buffer.Length)) != 0) - { - destination.Write(buffer, 0, read); - } - } - - private int GetCopyBufferSize() - { - int bufferSize = DefaultCopyBufferSize; - - if (CanSeek) - { - long length = Length; - long position = Position; - if (length <= position) // Handles negative overflows - { - // There are no bytes left in the stream to copy. - // However, because CopyTo{Async} is virtual, we need to - // ensure that any override is still invoked to provide its - // own validation, so we use the smallest legal buffer size here. - bufferSize = 1; - } - else - { - long remaining = length - position; - if (remaining > 0) - { - // In the case of a positive overflow, stick to the default size - bufferSize = (int)Math.Min(bufferSize, remaining); - } - } - } - - return bufferSize; - } - - public virtual void Close() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - public void Dispose() - { - Close(); - } - - protected virtual void Dispose(bool disposing) - { - // Note: Never change this to call other virtual methods on Stream - // like Write, since the state on subclasses has already been - // torn down. This is the last code to run on cleanup for a stream. - } - - public abstract void Flush(); - - public Task FlushAsync() - { - return FlushAsync(CancellationToken.None); - } - - public virtual Task FlushAsync(CancellationToken cancellationToken) - { - if (cancellationToken.IsCancellationRequested) - { - return Task.FromCanceled(cancellationToken); - } - - return Task.Factory.StartNew(state => ((Stream)state).Flush(), this, - cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); - } - - [Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")] - protected virtual WaitHandle CreateWaitHandle() - { - return new ManualResetEvent(initialState: false); - } - - public Task ReadAsync(Byte[] buffer, int offset, int count) - { - return ReadAsync(buffer, offset, count, CancellationToken.None); - } - - public virtual Task ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - return cancellationToken.IsCancellationRequested ? - Task.FromCanceled(cancellationToken) : - Task.Factory.FromAsync( - (localBuffer, localOffset, localCount, callback, state) => ((Stream)state).BeginRead(localBuffer, localOffset, localCount, callback, state), - iar => ((Stream)iar.AsyncState).EndRead(iar), - buffer, offset, count, this); - } - - public virtual ValueTask ReadAsync(Memory destination, CancellationToken cancellationToken = default(CancellationToken)) - { - if (MemoryMarshal.TryGetArray(destination, out ArraySegment array)) - { - return new ValueTask(ReadAsync(array.Array, array.Offset, array.Count, cancellationToken)); - } - else - { - byte[] buffer = ArrayPool.Shared.Rent(destination.Length); - return FinishReadAsync(ReadAsync(buffer, 0, destination.Length, cancellationToken), buffer, destination); - - async ValueTask FinishReadAsync(Task readTask, byte[] localBuffer, Memory localDestination) - { - try - { - int result = await readTask.ConfigureAwait(false); - new Span(localBuffer, 0, result).CopyTo(localDestination.Span); - return result; - } - finally - { - ArrayPool.Shared.Return(localBuffer); - } - } - } - } - - public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) - { - if (!CanRead) - { - throw new NotSupportedException(SR.NotSupported_UnreadableStream); - } - - return TaskToApm.Begin(ReadAsyncInternal(buffer, offset, count), callback, state); - } - - public virtual int EndRead(IAsyncResult asyncResult) => - TaskToApm.End(asyncResult); - - private Task ReadAsyncInternal(Byte[] buffer, int offset, int count) - { - // To avoid a race with a stream's position pointer & generating race - // conditions with internal buffer indexes in our own streams that - // don't natively support async IO operations when there are multiple - // async requests outstanding, we will serialize the requests. - return EnsureAsyncActiveSemaphoreInitialized().WaitAsync().ContinueWith((completedWait, s) => - { - Debug.Assert(completedWait.Status == TaskStatus.RanToCompletion); - var state = (Tuple)s; - try - { - return state.Item1.Read(state.Item2, state.Item3, state.Item4); // this.Read(buffer, offset, count); - } - finally - { - state.Item1._asyncActiveSemaphore.Release(); - } - }, Tuple.Create(this, buffer, offset, count), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); - } - - public Task WriteAsync(Byte[] buffer, int offset, int count) - { - return WriteAsync(buffer, offset, count, CancellationToken.None); - } - - public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - return cancellationToken.IsCancellationRequested ? - Task.FromCanceled(cancellationToken) : - Task.Factory.FromAsync( - (localBuffer, localOffset, localCount, callback, state) => ((Stream)state).BeginWrite(localBuffer, localOffset, localCount, callback, state), - iar => ((Stream)iar.AsyncState).EndWrite(iar), - buffer, offset, count, this); - } - - public virtual ValueTask WriteAsync(ReadOnlyMemory source, CancellationToken cancellationToken = default(CancellationToken)) - { - if (MemoryMarshal.TryGetArray(source, out ArraySegment array)) - { - return new ValueTask(WriteAsync(array.Array, array.Offset, array.Count, cancellationToken)); - } - else - { - byte[] buffer = ArrayPool.Shared.Rent(source.Length); - source.Span.CopyTo(buffer); - return new ValueTask(FinishWriteAsync(WriteAsync(buffer, 0, source.Length, cancellationToken), buffer)); - - async Task FinishWriteAsync(Task writeTask, byte[] localBuffer) - { - try - { - await writeTask.ConfigureAwait(false); - } - finally - { - ArrayPool.Shared.Return(localBuffer); - } - } - } - } - - public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) - { - if (!CanWrite) - { - throw new NotSupportedException(SR.NotSupported_UnwritableStream); - } - - return TaskToApm.Begin(WriteAsyncInternal(buffer, offset, count), callback, state); - } - - public virtual void EndWrite(IAsyncResult asyncResult) => - TaskToApm.End(asyncResult); - - private Task WriteAsyncInternal(Byte[] buffer, int offset, int count) - { - // To avoid a race with a stream's position pointer & generating race - // conditions with internal buffer indexes in our own streams that - // don't natively support async IO operations when there are multiple - // async requests outstanding, we will serialize the requests. - return EnsureAsyncActiveSemaphoreInitialized().WaitAsync().ContinueWith((completedWait, s) => - { - Debug.Assert(completedWait.Status == TaskStatus.RanToCompletion); - var state = (Tuple)s; - try - { - state.Item1.Write(state.Item2, state.Item3, state.Item4); // this.Write(buffer, offset, count); - } - finally - { - state.Item1._asyncActiveSemaphore.Release(); - } - }, Tuple.Create(this, buffer, offset, count), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); - } - - public abstract long Seek(long offset, SeekOrigin origin); - - public abstract void SetLength(long value); - - public abstract int Read(byte[] buffer, int offset, int count); - - public virtual int Read(Span destination) - { - ArrayPool pool = ArrayPool.Shared; - byte[] buffer = pool.Rent(destination.Length); - try - { - int numRead = Read(buffer, 0, destination.Length); - if ((uint)numRead > destination.Length) - { - throw new IOException(SR.IO_StreamTooLong); - } - new Span(buffer, 0, numRead).CopyTo(destination); - return numRead; - } - finally { pool.Return(buffer); } - } - - // Reads one byte from the stream by calling Read(byte[], int, int). - // Will return an unsigned byte cast to an int or -1 on end of stream. - // This implementation does not perform well because it allocates a new - // byte[] each time you call it, and should be overridden by any - // subclass that maintains an internal buffer. Then, it can help perf - // significantly for people who are reading one byte at a time. - public virtual int ReadByte() - { - byte[] oneByteArray = new byte[1]; - int r = Read(oneByteArray, 0, 1); - if (r == 0) - { - return -1; - } - return oneByteArray[0]; - } - - public abstract void Write(byte[] buffer, int offset, int count); - - public virtual void Write(ReadOnlySpan source) - { - ArrayPool pool = ArrayPool.Shared; - byte[] buffer = pool.Rent(source.Length); - try - { - source.CopyTo(buffer); - Write(buffer, 0, source.Length); - } - finally { pool.Return(buffer); } - } - - // Writes one byte from the stream by calling Write(byte[], int, int). - // This implementation does not perform well because it allocates a new - // byte[] each time you call it, and should be overridden by any - // subclass that maintains an internal buffer. Then, it can help perf - // significantly for people who are writing one byte at a time. - public virtual void WriteByte(byte value) - { - byte[] oneByteArray = new byte[1]; - oneByteArray[0] = value; - Write(oneByteArray, 0, 1); - } - - public static Stream Synchronized(Stream stream) - { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - - if (stream is SyncStream) - return stream; - - return new SyncStream(stream); - } - - [Obsolete("Do not call or override this method.")] - protected virtual void ObjectInvariant() - { - } - - private sealed class NullStream : Stream - { - internal NullStream() { } - - public override bool CanRead => true; - - public override bool CanWrite => true; - - public override bool CanSeek => true; - - public override long Length => 0; - - public override long Position - { - get { return 0; } - set { } - } - - public override void CopyTo(Stream destination, int bufferSize) - { - StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); - - // After we validate arguments this is a nop. - } - - public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) - { - // Validate arguments for compat, since previously this - // method was inherited from Stream, which did check its arguments. - StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); - - return cancellationToken.IsCancellationRequested ? - Task.FromCanceled(cancellationToken) : - Task.CompletedTask; - } - - protected override void Dispose(bool disposing) - { - // Do nothing - we don't want NullStream singleton (static) to be closable - } - - public override void Flush() - { - } - -#pragma warning disable 1998 // async method with no await - public override async Task FlushAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - } -#pragma warning restore 1998 - - public override int Read(byte[] buffer, int offset, int count) - { - return 0; - } - - public override int Read(Span destination) - { - return 0; - } - -#pragma warning disable 1998 // async method with no await - public override async Task ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - return 0; - } - - public override async ValueTask ReadAsync(Memory destination, CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - return 0; - } -#pragma warning restore 1998 - - public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => - TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state); - - public override int EndRead(IAsyncResult asyncResult) => - TaskToApm.End(asyncResult); - - public override int ReadByte() - { - return -1; - } - - public override void Write(byte[] buffer, int offset, int count) - { - } - - public override void Write(ReadOnlySpan source) - { - } - -#pragma warning disable 1998 // async method with no await - public override async Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - } - - public override async ValueTask WriteAsync(ReadOnlyMemory source, CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - } -#pragma warning restore 1998 - - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => - TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state); - - public override void EndWrite(IAsyncResult asyncResult) => - TaskToApm.End(asyncResult); - - public override void WriteByte(byte value) - { - } - - public override long Seek(long offset, SeekOrigin origin) - { - return 0; - } - - public override void SetLength(long length) - { - } - } - - // SyncStream is a wrapper around a stream that takes - // a lock for every operation making it thread safe. - private sealed class SyncStream : Stream, IDisposable - { - private Stream _stream; - - internal SyncStream(Stream stream) - { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - - _stream = stream; - } - - public override bool CanRead => _stream.CanRead; - - public override bool CanWrite => _stream.CanWrite; - - public override bool CanSeek => _stream.CanSeek; - - public override bool CanTimeout => _stream.CanTimeout; - - public override long Length - { - get - { - lock (_stream) - { - return _stream.Length; - } - } - } - - public override long Position - { - get - { - lock (_stream) - { - return _stream.Position; - } - } - set - { - lock (_stream) - { - _stream.Position = value; - } - } - } - - public override int ReadTimeout - { - get - { - return _stream.ReadTimeout; - } - set - { - _stream.ReadTimeout = value; - } - } - - public override int WriteTimeout - { - get - { - return _stream.WriteTimeout; - } - set - { - _stream.WriteTimeout = value; - } - } - - // In the off chance that some wrapped stream has different - // semantics for Close vs. Dispose, let's preserve that. - public override void Close() - { - lock (_stream) - { - try - { - _stream.Close(); - } - finally - { - base.Dispose(true); - } - } - } - - protected override void Dispose(bool disposing) - { - lock (_stream) - { - try - { - // Explicitly pick up a potentially methodimpl'ed Dispose - if (disposing) - ((IDisposable)_stream).Dispose(); - } - finally - { - base.Dispose(disposing); - } - } - } - - public override void Flush() - { - lock (_stream) - _stream.Flush(); - } - - public override int Read(byte[] bytes, int offset, int count) - { - lock (_stream) - return _stream.Read(bytes, offset, count); - } - - public override int Read(Span destination) - { - lock (_stream) - return _stream.Read(destination); - } - - public override int ReadByte() - { - lock (_stream) - return _stream.ReadByte(); - } - - public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) - { - throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251 - //bool overridesBeginRead = _stream.HasOverriddenBeginEndRead(); - - //lock (_stream) - //{ - // // If the Stream does have its own BeginRead implementation, then we must use that override. - // // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic - // // which ensures only one asynchronous operation does so with an asynchronous wait rather - // // than a synchronous wait. A synchronous wait will result in a deadlock condition, because - // // the EndXx method for the outstanding async operation won't be able to acquire the lock on - // // _stream due to this call blocked while holding the lock. - // return overridesBeginRead ? - // _stream.BeginRead(buffer, offset, count, callback, state) : - // _stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true); - //} - } - - public override int EndRead(IAsyncResult asyncResult) - { - if (asyncResult == null) - throw new ArgumentNullException(nameof(asyncResult)); - - lock (_stream) - return _stream.EndRead(asyncResult); - } - - public override long Seek(long offset, SeekOrigin origin) - { - lock (_stream) - return _stream.Seek(offset, origin); - } - - public override void SetLength(long length) - { - lock (_stream) - _stream.SetLength(length); - } - - public override void Write(byte[] bytes, int offset, int count) - { - lock (_stream) - _stream.Write(bytes, offset, count); - } - - public override void Write(ReadOnlySpan source) - { - lock (_stream) - _stream.Write(source); - } - - public override void WriteByte(byte b) - { - lock (_stream) - _stream.WriteByte(b); - } - - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) - { - throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251 - //bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite(); - - //lock (_stream) - //{ - // // If the Stream does have its own BeginWrite implementation, then we must use that override. - // // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic - // // which ensures only one asynchronous operation does so with an asynchronous wait rather - // // than a synchronous wait. A synchronous wait will result in a deadlock condition, because - // // the EndXx method for the outstanding async operation won't be able to acquire the lock on - // // _stream due to this call blocked while holding the lock. - // return overridesBeginWrite ? - // _stream.BeginWrite(buffer, offset, count, callback, state) : - // _stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true); - //} - } - - public override void EndWrite(IAsyncResult asyncResult) - { - if (asyncResult == null) - throw new ArgumentNullException(nameof(asyncResult)); - - lock (_stream) - _stream.EndWrite(asyncResult); - } - } - } -} diff --git a/external/corert/src/System.Private.CoreLib/src/System/InvokeUtils.cs b/external/corert/src/System.Private.CoreLib/src/System/InvokeUtils.cs index 69435aee9a..0a66ea6c27 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/InvokeUtils.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/InvokeUtils.cs @@ -12,6 +12,8 @@ using Internal.Reflection.Core.NonPortable; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; +using Interlocked = System.Threading.Interlocked; + namespace System { [System.Runtime.CompilerServices.ReflectionBlocked] @@ -39,7 +41,7 @@ namespace System // This method is targeted by the Delegate ILTransformer. // // - public static Object CheckArgument(Object srcObject, RuntimeTypeHandle dstType, BinderBundle binderBundle) + public static object CheckArgument(object srcObject, RuntimeTypeHandle dstType, BinderBundle binderBundle) { EETypePtr dstEEType = dstType.ToEETypePtr(); return CheckArgument(srcObject, dstEEType, CheckArgumentSemantics.DynamicInvoke, binderBundle, getExactTypeForCustomBinder: null); @@ -53,12 +55,16 @@ namespace System SetFieldDirect, // Throws ArgumentException - other than that, like DynamicInvoke except that enums and integers cannot be intermingled, and null cannot substitute for default(valuetype). } - internal static Object CheckArgument(Object srcObject, EETypePtr dstEEType, CheckArgumentSemantics semantics, BinderBundle binderBundle, Func getExactTypeForCustomBinder = null) + internal static object CheckArgument(object srcObject, EETypePtr dstEEType, CheckArgumentSemantics semantics, BinderBundle binderBundle, Func getExactTypeForCustomBinder = null) { if (srcObject == null) { // null -> default(T) - if (dstEEType.IsValueType && !dstEEType.IsNullable) + if (dstEEType.IsPointer) + { + return default(IntPtr); + } + else if (dstEEType.IsValueType && !dstEEType.IsNullable) { if (semantics == CheckArgumentSemantics.SetFieldDirect) throw CreateChangeTypeException(CommonRuntimeTypes.Object.TypeHandle.ToEETypePtr(), dstEEType, semantics); @@ -412,9 +418,9 @@ namespace System s_curIndex = 0; s_targetMethodOrDelegate = targetMethodOrDelegate; + object result; try { - object result = null; if (invokeMethodHelperIsThisCall) { Debug.Assert(methodToCallIsThisCall == true); @@ -434,8 +440,6 @@ namespace System DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } } - - return result; } catch (Exception e) when (wrapInTargetInvocationException && argSetupState.fComplete) { @@ -464,6 +468,11 @@ namespace System } } } + + if (result == NullByRefValueSentinel) + throw new NullReferenceException(SR.NullReference_InvokeNullRefReturned); + + return result; } finally { @@ -730,6 +739,15 @@ namespace System return finalObjectToReturn; } + internal static object DynamicInvokeUnmanagedPointerReturn(out DynamicInvokeParamLookupType paramLookupType, object boxedPointerType, int index, RuntimeTypeHandle type, DynamicInvokeParamType paramType) + { + object finalObjectToReturn = boxedPointerType; + + Debug.Assert(finalObjectToReturn is IntPtr); + paramLookupType = DynamicInvokeParamLookupType.ValuetypeObjectReturned; + return finalObjectToReturn; + } + public static object DynamicInvokeParamHelperCore(RuntimeTypeHandle type, out DynamicInvokeParamLookupType paramLookupType, out int index, DynamicInvokeParamType paramType) { index = s_curIndex++; @@ -790,17 +808,22 @@ namespace System incomingParam = InvokeUtils.CheckArgument(incomingParam, type.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke, s_binderBundle, s_getExactTypeForCustomBinder); if (s_binderBundle == null) { - System.Diagnostics.Debug.Assert(s_parameters[index] == null || Object.ReferenceEquals(incomingParam, s_parameters[index])); + System.Diagnostics.Debug.Assert(s_parameters[index] == null || object.ReferenceEquals(incomingParam, s_parameters[index])); } return DynamicInvokeBoxedValuetypeReturn(out paramLookupType, incomingParam, index, type, paramType); } + else if (type.ToEETypePtr().IsPointer) + { + incomingParam = InvokeUtils.CheckArgument(incomingParam, type.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke, s_binderBundle, s_getExactTypeForCustomBinder); + return DynamicInvokeUnmanagedPointerReturn(out paramLookupType, incomingParam, index, type, paramType); + } else { incomingParam = InvokeUtils.CheckArgument(incomingParam, widenAndCompareType.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke, s_binderBundle, s_getExactTypeForCustomBinder); paramLookupType = DynamicInvokeParamLookupType.IndexIntoObjectArrayReturned; if (s_binderBundle == null) { - System.Diagnostics.Debug.Assert(Object.ReferenceEquals(incomingParam, s_parameters[index])); + System.Diagnostics.Debug.Assert(object.ReferenceEquals(incomingParam, s_parameters[index])); return s_parameters; } else @@ -833,6 +856,19 @@ namespace System } } } + + private static volatile object _nullByRefValueSentinel; + public static object NullByRefValueSentinel + { + get + { + if (_nullByRefValueSentinel == null) + { + Interlocked.CompareExchange(ref _nullByRefValueSentinel, new object(), null); + } + return _nullByRefValueSentinel; + } + } } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/MissingMemberException.CoreRT.cs b/external/corert/src/System.Private.CoreLib/src/System/MissingMemberException.CoreRT.cs new file mode 100644 index 0000000000..f79f086b82 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/MissingMemberException.CoreRT.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.Serialization; + +namespace System +{ + public partial class MissingMemberException : MemberAccessException + { + internal static string FormatSignature(byte[] signature) + { + // This is not the correct implementation, however, it's probably not worth the time to port given that + // (1) it's for a diagnostic + // (2) Signature is non-null when this exception is created from the native runtime. Which we don't do in .Net Native. + // (3) Only other time the signature is non-null is if this exception object is deserialized from a persisted blob from an older runtime. + return string.Empty; + } + } +} \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/src/System/MulticastDelegate.cs b/external/corert/src/System.Private.CoreLib/src/System/MulticastDelegate.cs index a3a23e67a0..6ab8764215 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/MulticastDelegate.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/MulticastDelegate.cs @@ -18,7 +18,7 @@ namespace System internal MulticastDelegate() { } // V1 API: Create closed instance delegates. Method name matching is case sensitive. - protected MulticastDelegate(Object target, String method) + protected MulticastDelegate(object target, string method) { // This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an // overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal @@ -28,7 +28,7 @@ namespace System } // V1 API: Create open static delegates. Method name matching is case insensitive. - protected MulticastDelegate(Type target, String method) + protected MulticastDelegate(Type target, string method) { // This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an // overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal @@ -54,7 +54,7 @@ namespace System return true; } - public override sealed bool Equals(Object obj) + public override sealed bool Equals(object obj) { if (obj == null) return false; @@ -79,7 +79,7 @@ namespace System } else { - if (!Object.ReferenceEquals(m_helperObject, d.m_helperObject) || + if (!object.ReferenceEquals(m_helperObject, d.m_helperObject) || (!FunctionPointerOps.Compare(m_extraFunctionPointerOrData, d.m_extraFunctionPointerOrData)) || (!FunctionPointerOps.Compare(m_functionPointer, d.m_functionPointer))) { @@ -88,12 +88,12 @@ namespace System // Those delegate kinds with thunks put themselves into the m_firstParamter, so we can't // blindly compare the m_firstParameter fields for equality. - if (Object.ReferenceEquals(m_firstParameter, this)) + if (object.ReferenceEquals(m_firstParameter, this)) { - return Object.ReferenceEquals(d.m_firstParameter, d); + return object.ReferenceEquals(d.m_firstParameter, d); } - return Object.ReferenceEquals(m_firstParameter, d.m_firstParameter); + return object.ReferenceEquals(m_firstParameter, d.m_firstParameter); } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Number.CoreRT.cs b/external/corert/src/System.Private.CoreLib/src/System/Number.CoreRT.cs index 1c7fdadce1..7cfc5899d8 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Number.CoreRT.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Number.CoreRT.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Globalization; -using System.Text; namespace System { @@ -283,112 +282,6 @@ namespace System { private const int _CVTBUFSIZE = 349; - public static bool IsPositiveInfinity(string s, IFormatProvider provider) - { - NumberFormatInfo nfi = provider == null ? NumberFormatInfo.CurrentInfo : NumberFormatInfo.GetInstance(provider); - return s.Equals(nfi.PositiveInfinitySymbol); - } - - public static bool IsNegativeInfinity(string s, IFormatProvider provider) - { - NumberFormatInfo nfi = provider == null ? NumberFormatInfo.CurrentInfo : NumberFormatInfo.GetInstance(provider); - return s.Equals(nfi.NegativeInfinitySymbol); - } - - public static bool IsNaNSymbol(string s, IFormatProvider provider) - { - NumberFormatInfo nfi = provider == null ? NumberFormatInfo.CurrentInfo : NumberFormatInfo.GetInstance(provider); - return s.Equals(nfi.NaNSymbol); - } - - #region Decimal Number Formatting Helpers - private static unsafe bool NumberBufferToDecimal(ref Number.NumberBuffer number, ref Decimal value) - { - Decimal d = new Decimal(); - - char* p = number.digits; - int e = number.scale; - if (*p == 0) - { - // To avoid risking an app-compat issue with pre 4.5 (where some app was illegally using Reflection to examine the internal scale bits), we'll only force - // the scale to 0 if the scale was previously positive (previously, such cases were unparsable to a bug.) - if (e > 0) - { - e = 0; - } - } - else - { - if (e > DecimalPrecision) - return false; - - while (((e > 0) || ((*p != 0) && (e > -28))) && - ((d.High < 0x19999999) || ((d.High == 0x19999999) && - ((d.Mid < 0x99999999) || ((d.Mid == 0x99999999) && - ((d.Low < 0x99999999) || ((d.Low == 0x99999999) && - (*p <= '5')))))))) - { - Decimal.DecMul10(ref d); - if (*p != 0) - Decimal.DecAddInt32(ref d, (uint)(*p++ - '0')); - e--; - } - - if (*p++ >= '5') - { - bool round = true; - if ((*(p - 1) == '5') && ((*(p - 2) % 2) == 0)) - { - // Check if previous digit is even, only if the when we are unsure whether hows to do - // Banker's rounding. For digits > 5 we will be roundinp up anyway. - int count = 20; // Look at the next 20 digits to check to round - while ((*p == '0') && (count != 0)) - { - p++; - count--; - } - if ((*p == '\0') || (count == 0)) - round = false;// Do nothing - } - - if (round) - { - Decimal.DecAddInt32(ref d, 1); - if ((d.High | d.Mid | d.Low) == 0) - { - d.High = 0x19999999; - d.Mid = 0x99999999; - d.Low = 0x9999999A; - e++; - } - } - } - } - - if (e > 0) - return false; - - if (e <= -DecimalPrecision) - { - // Parsing a large scale zero can give you more precision than fits in the decimal. - // This should only happen for actual zeros or very small numbers that round to zero. - d.High = 0; - d.Low = 0; - d.Mid = 0; - d.Scale = DecimalPrecision - 1; - } - else - { - d.Scale = -e; - } - d.IsNegative = number.sign; - - value = d; - return true; - } - - #endregion - /*=========================================================== Portable NumberToDouble implementation -------------------------------------- diff --git a/external/corert/src/System.Private.CoreLib/src/System/Number.Unix.cs b/external/corert/src/System.Private.CoreLib/src/System/Number.Unix.cs index ae82d2e66e..39e2dfcb1b 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Number.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Number.Unix.cs @@ -30,15 +30,10 @@ namespace System char* dst = number.digits; number.scale = 0; - number.sign = false; + number.sign = double.IsNegative(value); *dst = '\0'; - if (value < 0.0) - { - number.sign = true; - } - - if (BitConverter.DoubleToInt64Bits (value) == 0) + if (value == 0.0) { for (int j = 0; j < precision; j++) { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Object.cs b/external/corert/src/System.Private.CoreLib/src/System/Object.cs index 17a2f99cf8..ffe36ea883 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Object.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Object.cs @@ -80,7 +80,7 @@ namespace System return RuntimeTypeUnifier.GetRuntimeTypeForEEType(EETypePtr); } - public virtual String ToString() + public virtual string ToString() { return GetType().ToString(); } @@ -90,7 +90,7 @@ namespace System // For Value Types, the toolchain (will) generate a ValueType.Equals override method, // and will not be using this routine. - public virtual bool Equals(Object obj) + public virtual bool Equals(object obj) { if (this == obj) return true; @@ -102,7 +102,7 @@ namespace System return false; } - public static bool Equals(Object objA, Object objB) + public static bool Equals(object objA, object objB) { if (objA == objB) { @@ -116,7 +116,7 @@ namespace System } //[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - public static bool ReferenceEquals(Object objA, Object objB) + public static bool ReferenceEquals(object objA, object objB) { return objA == objB; } diff --git a/external/corert/src/System.Private.CoreLib/src/System/PrimitivesRuntimeContracts.cs b/external/corert/src/System.Private.CoreLib/src/System/PrimitivesRuntimeContracts.cs deleted file mode 100644 index b0ca615fe4..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/PrimitivesRuntimeContracts.cs +++ /dev/null @@ -1,409 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - - -// This file contains the basic primitive type definitions (int etc) -// These types are well known to the compiler and the runtime and are basic interchange types that do not change - -// CONTRACT with Runtime -// Each of the data types has a data contract with the runtime. See the contract in the type definition -// - -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; - -namespace System -{ - // CONTRACT with Runtime - // Place holder type for type hierarchy, Compiler/Runtime requires this class - public abstract class ValueType - { - } - - // CONTRACT with Runtime, Compiler/Runtime requires this class - // Place holder type for type hierarchy - public abstract class Enum : ValueType - { - } - - /*============================================================ - ** - ** Class: Boolean - ** - ** - ** Purpose: The boolean class serves as a wrapper for the primitive - ** type boolean. - ** - ** - ===========================================================*/ - - // CONTRACT with Runtime - // The Boolean type is one of the primitives understood by the compilers and runtime - // Data Contract: Single field of type bool - - public struct Boolean - { - private bool m_value; - } - - - /*============================================================ - ** - ** Class: Char - ** - ** - ** Purpose: This is the value class representing a Unicode character - ** - ** - ===========================================================*/ - - - - // CONTRACT with Runtime - // The Char type is one of the primitives understood by the compilers and runtime - // Data Contract: Single field of type char - // This type is LayoutKind Sequential - - [StructLayout(LayoutKind.Sequential)] - public struct Char - { - private char m_value; - } - - - /*============================================================ - ** - ** Class: SByte - ** - ** - ** Purpose: A representation of a 8 bit 2's complement integer. - ** - ** - ===========================================================*/ - - // CONTRACT with Runtime - // The SByte type is one of the primitives understood by the compilers and runtime - // Data Contract: Single field of type sbyte - // This type is LayoutKind Sequential - - [StructLayout(LayoutKind.Sequential)] - public struct SByte - { - private sbyte m_value; - } - - - /*============================================================ - ** - ** Class: Byte - ** - ** - ** Purpose: A representation of a 8 bit integer (byte) - ** - ** - ===========================================================*/ - - - // CONTRACT with Runtime - // The Byte type is one of the primitives understood by the compilers and runtime - // Data Contract: Single field of type bool - // This type is LayoutKind Sequential - - [StructLayout(LayoutKind.Sequential)] - public struct Byte - { - private byte m_value; - } - - - /*============================================================ - ** - ** Class: Int16 - ** - ** - ** Purpose: A representation of a 16 bit 2's complement integer. - ** - ** - ===========================================================*/ - - - // CONTRACT with Runtime - // The Int16 type is one of the primitives understood by the compilers and runtime - // Data Contract: Single field of type short - // This type is LayoutKind Sequential - - [StructLayout(LayoutKind.Sequential)] - public struct Int16 - { - private short m_value; - } - - /*============================================================ - ** - ** Class: UInt16 - ** - ** - ** Purpose: A representation of a short (unsigned 16-bit) integer. - ** - ** - ===========================================================*/ - - // CONTRACT with Runtime - // The Uint16 type is one of the primitives understood by the compilers and runtime - // Data Contract: Single field of type ushort - // This type is LayoutKind Sequential - - [StructLayout(LayoutKind.Sequential)] - public struct UInt16 - { - private ushort m_value; - } - - /*============================================================ - ** - ** Class: Int32 - ** - ** - ** Purpose: A representation of a 32 bit 2's complement integer. - ** - ** - ===========================================================*/ - - // CONTRACT with Runtime - // The Int32 type is one of the primitives understood by the compilers and runtime - // Data Contract: Single field of type int - // This type is LayoutKind Sequential - - [StructLayout(LayoutKind.Sequential)] - public struct Int32 - { - private int m_value; - } - - - /*============================================================ - ** - ** Class: UInt32 - ** - ** - ** Purpose: A representation of a 32 bit unsigned integer. - ** - ** - ===========================================================*/ - - // CONTRACT with Runtime - // The Uint32 type is one of the primitives understood by the compilers and runtime - // Data Contract: Single field of type uint - // This type is LayoutKind Sequential - - [StructLayout(LayoutKind.Sequential)] - public struct UInt32 - { - private uint m_value; - } - - - /*============================================================ - ** - ** Class: Int64 - ** - ** - ** Purpose: A representation of a 64 bit 2's complement integer. - ** - ** - ===========================================================*/ - - // CONTRACT with Runtime - // The Int64 type is one of the primitives understood by the compilers and runtime - // Data Contract: Single field of type long - // This type is LayoutKind Sequential - - [StructLayout(LayoutKind.Sequential)] - public struct Int64 - { - private long m_value; - } - - - /*============================================================ - ** - ** Class: UInt64 - ** - ** - ** Purpose: A representation of a 64 bit unsigned integer. - ** - ** - ===========================================================*/ - - // CONTRACT with Runtime - // The UInt64 type is one of the primitives understood by the compilers and runtime - // Data Contract: Single field of type ulong - // This type is LayoutKind Sequential - - [StructLayout(LayoutKind.Sequential)] - public struct UInt64 - { - private ulong m_value; - } - - - /*============================================================ - ** - ** Class: Single - ** - ** - ** Purpose: A wrapper class for the primitive type float. - ** - ** - ===========================================================*/ - - // CONTRACT with Runtime - // The Single type is one of the primitives understood by the compilers and runtime - // Data Contract: Single field of type float - // This type is LayoutKind Sequential - - [StructLayout(LayoutKind.Sequential)] - public struct Single - { - private float m_value; - } - - - /*============================================================ - ** - ** Class: Double - ** - ** - ** Purpose: A representation of an IEEE double precision - ** floating point number. - ** - ** - ===========================================================*/ - - // CONTRACT with Runtime - // The Double type is one of the primitives understood by the compilers and runtime - // Data Contract: Single field of type double - // This type is LayoutKind Sequential - - [StructLayout(LayoutKind.Sequential)] - public struct Double - { - private double m_value; - } - - - - /*============================================================ - ** - ** Class: IntPtr - ** - ** - ** Purpose: Platform independent integer - ** - ** - ===========================================================*/ - - // CONTRACT with Runtime - // The IntPtr type is one of the primitives understood by the compilers and runtime - // Data Contract: Single field of type void * - - // This type implements == without overriding GetHashCode, disable compiler warning -#pragma warning disable 0659, 0661 - public struct IntPtr - { - unsafe private void* m_value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior - - public static readonly IntPtr Zero; - - public unsafe IntPtr(void* value) - { - m_value = value; - } - - public unsafe IntPtr(long value) - { -#if BIT64 - m_value = (void*)value; -#else - m_value = (void*)checked((int)value); -#endif - } - - public unsafe override bool Equals(Object obj) - { - if (obj is IntPtr) - { - return (m_value == ((IntPtr)obj).m_value); - } - return false; - } - - public unsafe bool Equals(IntPtr obj) - { - return (m_value == obj.m_value); - } - - public static unsafe explicit operator IntPtr(void* value) - { - return new IntPtr(value); - } - - public static unsafe explicit operator long (IntPtr value) - { -#if BIT64 - return (long)value.m_value; -#else - return (long)(int)value.m_value; -#endif - } - - public static unsafe bool operator ==(IntPtr value1, IntPtr value2) - { - return value1.m_value == value2.m_value; - } - - public static unsafe bool operator !=(IntPtr value1, IntPtr value2) - { - return value1.m_value != value2.m_value; - } - - public unsafe void* ToPointer() - { - return m_value; - } - } -#pragma warning restore 0659, 0661 - - - /*============================================================ - ** - ** Class: UIntPtr - ** - ** - ** Purpose: Platform independent integer - ** - ** - ===========================================================*/ - - // CONTRACT with Runtime - // The UIntPtr type is one of the primitives understood by the compilers and runtime - // Data Contract: Single field of type void * - - public struct UIntPtr - { - // Disable compile warning about unused m_value field -#pragma warning disable 0169 - unsafe private void* m_value; -#pragma warning restore 0169 - - public static readonly UIntPtr Zero; - } - - // Decimal class is not supported in RH. Only here to keep compiler happy - [TypeNeededIn(TypeNeededInOptions.SOURCE)] - internal struct Decimal - { - } -} - diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs index 3dadda396b..34b2fbcc37 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs @@ -6,16 +6,27 @@ using System.Globalization; using System.Runtime.Serialization; using System.Configuration.Assemblies; -using Internal.Reflection.Augments; - namespace System.Reflection { public sealed class AssemblyName : ICloneable, IDeserializationCallback, ISerializable { + private string _name; + private byte[] _publicKey; + private byte[] _publicKeyToken; + private CultureInfo _cultureInfo; + private string _codeBase; + private Version _version; + + private StrongNameKeyPair _strongNameKeyPair; + private AssemblyHashAlgorithm _hashAlgorithm; + + private AssemblyVersionCompatibility _versionCompatibility; + private AssemblyNameFlags _flags; + public AssemblyName() { - HashAlgorithm = AssemblyHashAlgorithm.None; - VersionCompatibility = AssemblyVersionCompatibility.SameMachine; + _hashAlgorithm = AssemblyHashAlgorithm.None; + _versionCompatibility = AssemblyVersionCompatibility.SameMachine; _flags = AssemblyNameFlags.None; } @@ -28,19 +39,55 @@ namespace System.Reflection runtimeAssemblyName.CopyToAssemblyName(this); } - public object Clone() + // Set and get the name of the assembly. If this is a weak Name + // then it optionally contains a site. For strong assembly names, + // the name partitions up the strong name's namespace + public string Name { - AssemblyName n = new AssemblyName(); - n.Name = Name; - n._publicKey = (byte[])_publicKey?.Clone(); - n._publicKeyToken = (byte[])_publicKeyToken?.Clone(); - n.CultureInfo = CultureInfo; - n.Version = (Version)Version?.Clone(); - n._flags = _flags; - n.CodeBase = CodeBase; - n.HashAlgorithm = HashAlgorithm; - n.VersionCompatibility = VersionCompatibility; - return n; + get { return _name; } + set { _name = value; } + } + + public Version Version + { + get { return _version; } + set { _version = value; } + } + + // Locales, internally the LCID is used for the match. + public CultureInfo CultureInfo + { + get { return _cultureInfo; } + set { _cultureInfo = value; } + } + + public string CultureName + { + get + { + return (_cultureInfo == null) ? null : _cultureInfo.Name; + } + set + { + _cultureInfo = (value == null) ? null : new CultureInfo(value); + } + } + + public string CodeBase + { + get { return _codeBase; } + set { _codeBase = value; } + } + + public string EscapedCodeBase + { + get + { + if (_codeBase == null) + return null; + else + return EscapeCodeBase(_codeBase); + } } public ProcessorArchitecture ProcessorArchitecture @@ -83,72 +130,36 @@ namespace System.Reflection } } - public string CultureName + // Make a copy of this assembly name. + public object Clone() { - get - { - return CultureInfo?.Name; - } - set - { - CultureInfo = (value == null) ? null : new CultureInfo(value); - } + AssemblyName name = new AssemblyName(); + name._name = _name; + name._publicKey = (byte[])_publicKey?.Clone(); + name._publicKeyToken = (byte[])_publicKeyToken?.Clone(); + name._cultureInfo = _cultureInfo; + name._version = (Version)_version?.Clone(); + name._flags = _flags; + name._codeBase = _codeBase; + name._hashAlgorithm = _hashAlgorithm; + name._versionCompatibility = _versionCompatibility; + return name; } - public CultureInfo CultureInfo { get; set; } - - public AssemblyNameFlags Flags + public static AssemblyName GetAssemblyName(string assemblyFile) { - get { return (AssemblyNameFlags)((uint)_flags & 0xFFFFF10F); } - set - { - _flags &= unchecked((AssemblyNameFlags)0x00000EF0); - _flags |= (value & unchecked((AssemblyNameFlags)0xFFFFF10F)); - } - } - - public string FullName - { - get - { - if (this.Name == null) - return string.Empty; - // Do not call GetPublicKeyToken() here - that latches the result into AssemblyName which isn't a side effect we want. - byte[] pkt = _publicKeyToken ?? AssemblyNameHelpers.ComputePublicKeyToken(_publicKey); - return AssemblyNameFormatter.ComputeDisplayName(Name, Version, CultureName, pkt, Flags, ContentType); - } - } - - public string Name { get; set; } - public Version Version { get; set; } - public string CodeBase { get; set; } - public AssemblyHashAlgorithm HashAlgorithm { get; set; } - public AssemblyVersionCompatibility VersionCompatibility { get; set; } - public StrongNameKeyPair KeyPair { get; set; } - - public string EscapedCodeBase - { - get - { - if (CodeBase == null) - return null; - else - return EscapeCodeBase(CodeBase); - } + throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported_AssemblyName_GetAssemblyName); } + // The public key that is used to verify an assemblies + // inclusion into the namespace. If the public key associated + // with the namespace cannot verify the assembly the assembly + // will fail to load. public byte[] GetPublicKey() { return _publicKey; } - public byte[] GetPublicKeyToken() - { - if (_publicKeyToken == null) - _publicKeyToken = AssemblyNameHelpers.ComputePublicKeyToken(_publicKey); - return _publicKeyToken; - } - public void SetPublicKey(byte[] publicKey) { _publicKey = publicKey; @@ -159,11 +170,67 @@ namespace System.Reflection _flags |= AssemblyNameFlags.PublicKey; } + // The compressed version of the public key formed from a truncated hash. + // Will throw a SecurityException if _PublicKey is invalid + public byte[] GetPublicKeyToken() + { + if (_publicKeyToken == null) + _publicKeyToken = AssemblyNameHelpers.ComputePublicKeyToken(_publicKey); + return _publicKeyToken; + } + public void SetPublicKeyToken(byte[] publicKeyToken) { _publicKeyToken = publicKeyToken; } + // Flags modifying the name. So far the only flag is PublicKey, which + // indicates that a full public key and not the compressed version is + // present. + // Processor Architecture flags are set only through ProcessorArchitecture + // property and can't be set or retrieved directly + // Content Type flags are set only through ContentType property and can't be + // set or retrieved directly + public AssemblyNameFlags Flags + { + get { return (AssemblyNameFlags)((uint)_flags & 0xFFFFF10F); } + set + { + _flags &= unchecked((AssemblyNameFlags)0x00000EF0); + _flags |= (value & unchecked((AssemblyNameFlags)0xFFFFF10F)); + } + } + + public AssemblyHashAlgorithm HashAlgorithm + { + get { return _hashAlgorithm; } + set { _hashAlgorithm = value; } + } + + public AssemblyVersionCompatibility VersionCompatibility + { + get { return _versionCompatibility; } + set { _versionCompatibility = value; } + } + + public StrongNameKeyPair KeyPair + { + get { return _strongNameKeyPair; } + set { _strongNameKeyPair = value; } + } + + public string FullName + { + get + { + if (this.Name == null) + return string.Empty; + // Do not call GetPublicKeyToken() here - that latches the result into AssemblyName which isn't a side effect we want. + byte[] pkt = _publicKeyToken ?? AssemblyNameHelpers.ComputePublicKeyToken(_publicKey); + return AssemblyNameFormatter.ComputeDisplayName(Name, Version, CultureName, pkt, Flags, ContentType); + } + } + public override string ToString() { string s = FullName; @@ -183,11 +250,6 @@ namespace System.Reflection throw new PlatformNotSupportedException(); } - public static AssemblyName GetAssemblyName(string assemblyFile) - { - throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported_AssemblyName_GetAssemblyName); - } - /// /// Compares the simple names disregarding Version, Culture and PKT. While this clearly does not /// match the intent of this api, this api has been broken this way since its debut and we cannot @@ -210,10 +272,6 @@ namespace System.Reflection } internal static string EscapeCodeBase(string codebase) { throw new PlatformNotSupportedException(); } - - private AssemblyNameFlags _flags; - private byte[] _publicKey; - private byte[] _publicKeyToken; } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameLexer.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameLexer.cs index 4838e5d5d6..9b45714930 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameLexer.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameLexer.cs @@ -16,7 +16,7 @@ namespace System.Reflection // internal struct AssemblyNameLexer { - internal AssemblyNameLexer(String s) + internal AssemblyNameLexer(string s) { // Convert string to char[] with NUL terminator. (An actual NUL terminator in the input string will be treated // as an actual end of string: this is compatible with desktop behavior.) @@ -32,7 +32,7 @@ namespace System.Reflection // internal Token GetNext() { - String ignore; + string ignore; return GetNext(out ignore); } @@ -40,10 +40,10 @@ namespace System.Reflection // Return the next token in assembly name. If the result is DisplayNameToken.String, // sets "tokenString" to the tokenized string. // - internal Token GetNext(out String tokenString) + internal Token GetNext(out string tokenString) { tokenString = null; - while (Char.IsWhiteSpace(_chars[_index])) + while (char.IsWhiteSpace(_chars[_index])) _index++; char c = _chars[_index++]; @@ -87,7 +87,7 @@ namespace System.Reflection { c = _chars[_index++]; bool matched = false; - foreach (KeyValuePair kv in AssemblyNameFormatter.EscapeSequences) + foreach (KeyValuePair kv in AssemblyNameFormatter.EscapeSequences) { if (c == kv.Key) { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameParser.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameParser.cs index f963e0323c..8ace065fc7 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameParser.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameParser.cs @@ -18,7 +18,7 @@ namespace System.Reflection [System.Runtime.CompilerServices.ReflectionBlocked] public static class AssemblyNameParser { - public static void Parse(AssemblyName blank, String s) + public static void Parse(AssemblyName blank, string s) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -26,7 +26,7 @@ namespace System.Reflection runtimeAssemblyName.CopyToAssemblyName(blank); } - public static RuntimeAssemblyName Parse(String s) + public static RuntimeAssemblyName Parse(string s) { Debug.Assert(s != null); @@ -39,26 +39,26 @@ namespace System.Reflection AssemblyNameLexer lexer = new AssemblyNameLexer(s); // Name must come first. - String name; + string name; AssemblyNameLexer.Token token = lexer.GetNext(out name); if (token != AssemblyNameLexer.Token.String) throw new FileLoadException(SR.InvalidAssemblyName); - if (name == String.Empty || name.IndexOfAny(s_illegalCharactersInSimpleName) != -1) + if (name == string.Empty || name.IndexOfAny(s_illegalCharactersInSimpleName) != -1) throw new FileLoadException(SR.InvalidAssemblyName); Version version = null; - String cultureName = null; + string cultureName = null; byte[] pkt = null; AssemblyNameFlags flags = 0; - LowLevelList alreadySeen = new LowLevelList(); + LowLevelList alreadySeen = new LowLevelList(); token = lexer.GetNext(); while (token != AssemblyNameLexer.Token.End) { if (token != AssemblyNameLexer.Token.Comma) throw new FileLoadException(SR.InvalidAssemblyName); - String attributeName; + string attributeName; token = lexer.GetNext(out attributeName); if (token != AssemblyNameLexer.Token.String) @@ -73,12 +73,12 @@ namespace System.Reflection if (token != AssemblyNameLexer.Token.Equals) throw new FileLoadException(SR.InvalidAssemblyName); - String attributeValue; + string attributeValue; token = lexer.GetNext(out attributeValue); if (token != AssemblyNameLexer.Token.String) throw new FileLoadException(SR.InvalidAssemblyName); - if (attributeName == String.Empty) + if (attributeName == string.Empty) throw new FileLoadException(SR.InvalidAssemblyName); for (int i = 0; i < alreadySeen.Count; i++) @@ -134,9 +134,9 @@ namespace System.Reflection return new RuntimeAssemblyName(name, version, cultureName, flags, pkt); } - private static Version ParseVersion(String attributeValue) + private static Version ParseVersion(string attributeValue) { - String[] parts = attributeValue.Split('.'); + string[] parts = attributeValue.Split('.'); if (parts.Length > 4) throw new FileLoadException(SR.InvalidAssemblyName); ushort[] versionNumbers = new ushort[4]; @@ -149,7 +149,7 @@ namespace System.Reflection // Desktop compat: TryParse is a little more forgiving than Fusion. for (int j = 0; j < parts[i].Length; j++) { - if (!Char.IsDigit(parts[i][j])) + if (!char.IsDigit(parts[i][j])) throw new FileLoadException(SR.InvalidAssemblyName); } if (!(ushort.TryParse(parts[i], out versionNumbers[i]))) @@ -168,7 +168,7 @@ namespace System.Reflection return new Version(versionNumbers[0], versionNumbers[1], versionNumbers[2], versionNumbers[3]); } - private static String ParseCulture(String attributeValue) + private static string ParseCulture(string attributeValue) { if (attributeValue.Equals("Neutral", StringComparison.OrdinalIgnoreCase)) { @@ -181,9 +181,9 @@ namespace System.Reflection } } - private static byte[] ParsePKT(String attributeValue) + private static byte[] ParsePKT(string attributeValue) { - if (attributeValue.Equals("null", StringComparison.OrdinalIgnoreCase) || attributeValue == String.Empty) + if (attributeValue.Equals("null", StringComparison.OrdinalIgnoreCase) || attributeValue == string.Empty) return Array.Empty(); if (attributeValue.Length != 8 * 2) @@ -200,7 +200,7 @@ namespace System.Reflection return pkt; } - private static ProcessorArchitecture ParseProcessorArchitecture(String attributeValue) + private static ProcessorArchitecture ParseProcessorArchitecture(string attributeValue) { if (attributeValue.Equals("msil", StringComparison.OrdinalIgnoreCase)) return ProcessorArchitecture.MSIL; diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs index bdf6d56c25..71b85feae4 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs @@ -12,7 +12,7 @@ namespace System.Reflection { protected CustomAttributeData() { } - public Type AttributeType + public virtual Type AttributeType { get { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeNamedArgument.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeNamedArgument.cs index 8139d50cb6..d3aaca10b3 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeNamedArgument.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeNamedArgument.cs @@ -39,6 +39,13 @@ namespace System.Reflection _lazyMemberInfo = memberInfo; _attributeType = memberInfo.DeclaringType; +#if MONO + // Mono runtime "create_cattr_named_arg" method passes value wrapped into CustomAttributeTypedArgument object + // but CoreFX expects just value. + if (value is CustomAttributeTypedArgument typedArument) + TypedValue = typedArument; + else +#endif TypedValue = new CustomAttributeTypedArgument(type, value); IsField = field != null; MemberName = memberInfo.Name; diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.cs index 3ca0a5ca94..5af435962f 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.cs @@ -27,6 +27,18 @@ namespace System.Reflection Value = (value == null) ? null : CanonicalizeValue(value); ArgumentType = argumentType; +#if MONO + if (value is Array a) { + Type etype = a.GetType().GetElementType(); + CustomAttributeTypedArgument[] new_value = new CustomAttributeTypedArgument[a.GetLength(0)]; + for (int i = 0; i < new_value.Length; ++i) { + var val = a.GetValue (i); + var elemType = etype == typeof (System.Object) && val != null ? val.GetType () : etype; + new_value[i] = new CustomAttributeTypedArgument (elemType, val); + } + Value = new System.Collections.ObjectModel.ReadOnlyCollection (new_value); + } +#endif } public Type ArgumentType { get; } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs new file mode 100644 index 0000000000..e812e7ec2c --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs @@ -0,0 +1,96 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.IO; + +namespace System.Reflection.Emit +{ + public sealed class AssemblyBuilder : Assembly + { + internal AssemblyBuilder() + { + // Prevent generating a default constructor + } + + public override string FullName + { + get + { + return default; + } + } + + public override bool IsDynamic + { + get + { + return default; + } + } + + public override Module ManifestModule + { + get + { + return default; + } + } + + public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + return default; + } + + public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, IEnumerable assemblyAttributes) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + return default; + } + + public ModuleBuilder DefineDynamicModule(string name) + { + return default; + } + + public override bool Equals(object obj) + { + return default; + } + + public ModuleBuilder GetDynamicModule(string name) + { + return default; + } + + public override int GetHashCode() + { + return default; + } + + public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) + { + return default; + } + + public override string[] GetManifestResourceNames() + { + return default; + } + + public override Stream GetManifestResourceStream(string name) + { + return default; + } + + public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + { + } + + public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + { + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.cs new file mode 100644 index 0000000000..d0f02d7f5e --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.cs @@ -0,0 +1,150 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Globalization; + +namespace System.Reflection.Emit +{ + public sealed class ConstructorBuilder : ConstructorInfo + { + internal ConstructorBuilder() + { + // Prevent generating a default constructor + } + + public override MethodAttributes Attributes + { + get + { + return default; + } + } + + public override CallingConventions CallingConvention + { + get + { + return default; + } + } + + public override Type DeclaringType + { + get + { + return default; + } + } + + public bool InitLocals + { + get + { + return default; + } + set + { + } + } + + public override RuntimeMethodHandle MethodHandle + { + get + { + return default; + } + } + + public override Module Module + { + get + { + return default; + } + } + + public override string Name + { + get + { + return default; + } + } + + public override Type ReflectedType + { + get + { + return default; + } + } + + public ParameterBuilder DefineParameter(int iSequence, ParameterAttributes attributes, string strParamName) + { + return default; + } + + public override object[] GetCustomAttributes(bool inherit) + { + return default; + } + + public override object[] GetCustomAttributes(Type attributeType, bool inherit) + { + return default; + } + + public ILGenerator GetILGenerator() + { + return default; + } + + public ILGenerator GetILGenerator(int streamSize) + { + return default; + } + + public override MethodImplAttributes GetMethodImplementationFlags() + { + return default; + } + + public override ParameterInfo[] GetParameters() + { + return default; + } + + public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + { + return default; + } + + public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + { + return default; + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + return default; + } + + public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + { + } + + public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + { + } + + public void SetImplementationFlags(MethodImplAttributes attributes) + { + } + + public override string ToString() + { + return default; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.cs new file mode 100644 index 0000000000..27060a966c --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.cs @@ -0,0 +1,29 @@ +// Licensed to the.NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection.Emit +{ + public class CustomAttributeBuilder + { + public CustomAttributeBuilder(ConstructorInfo con, object[] constructorArgs) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + } + + public CustomAttributeBuilder(ConstructorInfo con, object[] constructorArgs, FieldInfo[] namedFields, object[] fieldValues) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + } + + public CustomAttributeBuilder(ConstructorInfo con, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + } + + public CustomAttributeBuilder(ConstructorInfo con, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs new file mode 100644 index 0000000000..0f5b41c19b --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs @@ -0,0 +1,194 @@ +// Licensed to the.NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Globalization; + +namespace System.Reflection.Emit +{ + public sealed class DynamicMethod : MethodInfo + { + public DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + } + + public DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + } + + public DynamicMethod(string name, Type returnType, Type[] parameterTypes) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + } + + public DynamicMethod(string name, Type returnType, Type[] parameterTypes, bool restrictedSkipVisibility) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + } + + public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Module m) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + } + + public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + } + + public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + } + + public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + } + + public override MethodAttributes Attributes + { + get + { + return default; + } + } + + public override CallingConventions CallingConvention + { + get + { + return default; + } + } + + public override Type DeclaringType + { + get + { + return default; + } + } + + public bool InitLocals + { + get + { + return default; + } + set + { + } + } + + public override RuntimeMethodHandle MethodHandle + { + get + { + return default; + } + } + + public override string Name + { + get + { + return default; + } + } + + public override Type ReflectedType + { + get + { + return default; + } + } + + public override ParameterInfo ReturnParameter + { + get + { + return default; + } + } + + public override Type ReturnType + { + get + { + return default; + } + } + + public override ICustomAttributeProvider ReturnTypeCustomAttributes + { + get + { + return default; + } + } + + public sealed override Delegate CreateDelegate(Type delegateType) + { + return default; + } + + public sealed override Delegate CreateDelegate(Type delegateType, object target) + { + return default; + } + + public override MethodInfo GetBaseDefinition() + { + return default; + } + + public override object[] GetCustomAttributes(bool inherit) + { + return default; + } + + public override object[] GetCustomAttributes(Type attributeType, bool inherit) + { + return default; + } + + public ILGenerator GetILGenerator() + { + return default; + } + + public ILGenerator GetILGenerator(int streamSize) + { + return default; + } + + public override MethodImplAttributes GetMethodImplementationFlags() + { + return default; + } + + public override ParameterInfo[] GetParameters() + { + return default; + } + + public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + { + return default; + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + return default; + } + + public override string ToString() + { + return default; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/EnumBuilder.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/EnumBuilder.cs new file mode 100644 index 0000000000..b9e2f89222 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/EnumBuilder.cs @@ -0,0 +1,361 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection.Emit +{ + public sealed partial class EnumBuilder : TypeInfo + { + internal EnumBuilder() + { + // Prevent generating a default constructor + } + + public override Assembly Assembly + { + get + { + return default; + } + } + + public override string AssemblyQualifiedName + { + get + { + return default; + } + } + + public override Type BaseType + { + get + { + return default; + } + } + + public override Type DeclaringType + { + get + { + return default; + } + } + + public override string FullName + { + get + { + return default; + } + } + + public override Guid GUID + { + get + { + return default; + } + } + + public override bool IsConstructedGenericType + { + get + { + return default; + } + } + + public override Module Module + { + get + { + return default; + } + } + + public override string Name + { + get + { + return default; + } + } + + public override string Namespace + { + get + { + return default; + } + } + + public override Type ReflectedType + { + get + { + return default; + } + } + + public override RuntimeTypeHandle TypeHandle + { + get + { + return default; + } + } + + public FieldBuilder UnderlyingField + { + get + { + return default; + } + } + + public override Type UnderlyingSystemType + { + get + { + return default; + } + } + + public TypeInfo CreateTypeInfo() + { + return default; + } + + public FieldBuilder DefineLiteral(string literalName, object literalValue) + { + return default; + } + + protected override TypeAttributes GetAttributeFlagsImpl() + { + return default; + } + + protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + { + return default; + } + + public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) + { + return default; + } + + public override object[] GetCustomAttributes(bool inherit) + { + return default; + } + + public override object[] GetCustomAttributes(Type attributeType, bool inherit) + { + return default; + } + + public override Type GetElementType() + { + return default; + } + + public override Type GetEnumUnderlyingType() + { + return default; + } + + public override EventInfo GetEvent(string name, BindingFlags bindingAttr) + { + return default; + } + + public override EventInfo[] GetEvents() + { + return default; + } + + public override EventInfo[] GetEvents(BindingFlags bindingAttr) + { + return default; + } + + public override FieldInfo GetField(string name, BindingFlags bindingAttr) + { + return default; + } + + public override FieldInfo[] GetFields(BindingFlags bindingAttr) + { + return default; + } + + public override Type GetInterface(string name, bool ignoreCase) + { + return default; + } + + public override InterfaceMapping GetInterfaceMap(Type interfaceType) + { + return default; + } + + public override Type[] GetInterfaces() + { + return default; + } + + public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) + { + return default; + } + + public override MemberInfo[] GetMembers(BindingFlags bindingAttr) + { + return default; + } + + protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, System.Type[] types, ParameterModifier[] modifiers) + { + return default; + } + + public override MethodInfo[] GetMethods(BindingFlags bindingAttr) + { + return default; + } + + public override Type GetNestedType(string name, BindingFlags bindingAttr) + { + return default; + } + + public override Type[] GetNestedTypes(BindingFlags bindingAttr) + { + return default; + } + + public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) + { + return default; + } + + protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) + { + return default; + } + + protected override bool HasElementTypeImpl() + { + return default; + } + + public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters) + { + return default; + } + + protected override bool IsArrayImpl() + { + return default; + } + + public override bool IsAssignableFrom(TypeInfo typeInfo) + { + return default; + } + + protected override bool IsByRefImpl() + { + return default; + } + + public override bool IsByRefLike + { + get + { + return default; + } + } + + protected override bool IsCOMObjectImpl() + { + return default; + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + return default; + } + + protected override bool IsPointerImpl() + { + return default; + } + + protected override bool IsPrimitiveImpl() + { + return default; + } + + public override bool IsTypeDefinition + { + get + { + return default; + } + } + + public override bool IsSZArray + { + get + { + return default; + } + } + + public override bool IsVariableBoundArray + { + get + { + return default; + } + } + + protected override bool IsValueTypeImpl() + { + return default; + } + + public override Type MakeArrayType() + { + return default; + } + + public override Type MakeArrayType(int rank) + { + return default; + } + + public override Type MakeByRefType() + { + return default; + } + + public override Type MakePointerType() + { + return default; + } + + public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + { + } + + public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + { + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.cs new file mode 100644 index 0000000000..80f4b2c5b1 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.cs @@ -0,0 +1,38 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection.Emit +{ + public sealed class EventBuilder + { + internal EventBuilder() + { + // Prevent generating a default constructor + } + + public void AddOtherMethod(MethodBuilder mdBuilder) + { + } + + public void SetAddOnMethod(MethodBuilder mdBuilder) + { + } + + public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + { + } + + public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + { + } + + public void SetRaiseMethod(MethodBuilder mdBuilder) + { + } + + public void SetRemoveOnMethod(MethodBuilder mdBuilder) + { + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.cs new file mode 100644 index 0000000000..ff0765e5c9 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.cs @@ -0,0 +1,105 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Globalization; + +namespace System.Reflection.Emit +{ + + public sealed class FieldBuilder : FieldInfo + { + internal FieldBuilder() + { + // Prevent generating a default constructor + } + + public override FieldAttributes Attributes + { + get + { + return default; + } + } + + public override Type DeclaringType + { + get + { + return default; + } + } + + public override RuntimeFieldHandle FieldHandle + { + get + { + return default; + } + } + + public override Type FieldType + { + get + { + return default; + } + } + + public override string Name + { + get + { + return default; + } + } + + public override Type ReflectedType + { + get + { + return default; + } + } + + public override object[] GetCustomAttributes(bool inherit) + { + return default; + } + + public override object[] GetCustomAttributes(Type attributeType, bool inherit) + { + return default; + } + + public override object GetValue(object obj) + { + return default; + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + return default; + } + + public void SetConstant(object defaultValue) + { + } + + public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + { + } + + public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + { + } + + public void SetOffset(int iOffset) + { + } + + public override void SetValue(object obj, object val, BindingFlags invokeAttr, Binder binder, CultureInfo culture) + { + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs new file mode 100644 index 0000000000..f374fea336 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs @@ -0,0 +1,446 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection.Emit +{ + public sealed partial class GenericTypeParameterBuilder : TypeInfo + { + internal GenericTypeParameterBuilder() + { + // Prevent generating a default constructor + } + + public override Assembly Assembly + { + get + { + return default; + } + } + + public override string AssemblyQualifiedName + { + get + { + return default; + } + } + + public override Type BaseType + { + get + { + return default; + } + } + + public override bool ContainsGenericParameters + { + get + { + return default; + } + } + + public override MethodBase DeclaringMethod + { + get + { + return default; + } + } + + public override Type DeclaringType + { + get + { + return default; + } + } + + public override string FullName + { + get + { + return default; + } + } + + public override GenericParameterAttributes GenericParameterAttributes + { + get + { + return default; + } + } + + public override int GenericParameterPosition + { + get + { + return default; + } + } + + public override Guid GUID + { + get + { + return default; + } + } + + public override bool IsConstructedGenericType + { + get + { + return default; + } + } + + public override bool IsGenericParameter + { + get + { + return default; + } + } + + public override bool IsGenericType + { + get + { + return default; + } + } + + public override bool IsGenericTypeDefinition + { + get + { + return default; + } + } + + public override Module Module + { + get + { + return default; + } + } + + public override string Name + { + get + { + return default; + } + } + + public override string Namespace + { + get + { + return default; + } + } + + public override Type ReflectedType + { + get + { + return default; + } + } + + public override RuntimeTypeHandle TypeHandle + { + get + { + return default; + } + } + + public override Type UnderlyingSystemType + { + get + { + return default; + } + } + + public override bool Equals(object o) + { + return default; + } + + protected override TypeAttributes GetAttributeFlagsImpl() + { + return default; + } + + protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + { + return default; + } + + public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) + { + return default; + } + + public override object[] GetCustomAttributes(bool inherit) + { + return default; + } + + public override object[] GetCustomAttributes(Type attributeType, bool inherit) + { + return default; + } + + public override Type GetElementType() + { + return default; + } + + public override EventInfo GetEvent(string name, BindingFlags bindingAttr) + { + return default; + } + + public override EventInfo[] GetEvents() + { + return default; + } + + public override EventInfo[] GetEvents(BindingFlags bindingAttr) + { + return default; + } + + public override FieldInfo GetField(string name, BindingFlags bindingAttr) + { + return default; + } + + public override FieldInfo[] GetFields(BindingFlags bindingAttr) + { + return default; + } + + public override Type[] GetGenericArguments() + { + return default; + } + + public override Type GetGenericTypeDefinition() + { + return default; + } + + public override int GetHashCode() + { + return default; + } + + public override Type GetInterface(string name, bool ignoreCase) + { + return default; + } + + public override InterfaceMapping GetInterfaceMap(Type interfaceType) + { + return default; + } + + public override Type[] GetInterfaces() + { + return default; + } + + public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) + { + return default; + } + + public override MemberInfo[] GetMembers(BindingFlags bindingAttr) + { + return default; + } + + protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + { + return default; + } + + public override MethodInfo[] GetMethods(BindingFlags bindingAttr) + { + return default; + } + + public override Type GetNestedType(string name, BindingFlags bindingAttr) + { + return default; + } + + public override Type[] GetNestedTypes(BindingFlags bindingAttr) + { + return default; + } + + public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) + { + return default; + } + + protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) + { + return default; + } + + protected override bool HasElementTypeImpl() + { + return default; + } + + public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, Globalization.CultureInfo culture, string[] namedParameters) + { + return default; + } + + protected override bool IsArrayImpl() + { + return default; + } + + public override bool IsAssignableFrom(TypeInfo typeInfo) + { + return default; + } + + public override bool IsAssignableFrom(Type c) + { + return default; + } + + protected override bool IsByRefImpl() + { + return default; + } + + public override bool IsByRefLike + { + get + { + return default; + } + } + + protected override bool IsCOMObjectImpl() + { + return default; + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + return default; + } + + protected override bool IsPointerImpl() + { + return default; + } + + protected override bool IsPrimitiveImpl() + { + return default; + } + + public override bool IsSubclassOf(Type c) + { + return default; + } + + public override bool IsTypeDefinition + { + get + { + return default; + } + } + + public override bool IsSZArray + { + get + { + return default; + } + } + + public override bool IsVariableBoundArray + { + get + { + return default; + } + } + + protected override bool IsValueTypeImpl() + { + return default; + } + + public override Type MakeArrayType() + { + return default; + } + + public override Type MakeArrayType(int rank) + { + return default; + } + + public override Type MakeByRefType() + { + return default; + } + + public override Type MakeGenericType(params Type[] typeArguments) + { + return default; + } + + public override Type MakePointerType() + { + return default; + } + + public void SetBaseTypeConstraint(Type baseTypeConstraint) + { + } + + public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + { + } + + public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + { + } + + public void SetGenericParameterAttributes(GenericParameterAttributes genericParameterAttributes) + { + } + + public void SetInterfaceConstraints(params Type[] interfaceConstraints) + { + } + + public override string ToString() + { + return default; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs new file mode 100644 index 0000000000..bb52d48d0a --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs @@ -0,0 +1,177 @@ +// Licensed to the.NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.InteropServices; + +namespace System.Reflection.Emit +{ + public partial class ILGenerator + { + internal ILGenerator() + { + // Prevent generating a default constructor + } + + public virtual int ILOffset + { + get + { + return default; + } + } + + public virtual void BeginCatchBlock(Type exceptionType) + { + } + + public virtual void BeginExceptFilterBlock() + { + } + + public virtual Label BeginExceptionBlock() + { + return default; + } + + public virtual void BeginFaultBlock() + { + } + + public virtual void BeginFinallyBlock() + { + } + + public virtual void BeginScope() + { + } + + public virtual LocalBuilder DeclareLocal(Type localType) + { + return default; + } + + public virtual LocalBuilder DeclareLocal(Type localType, bool pinned) + { + return default; + } + + public virtual Label DefineLabel() + { + return default; + } + + public virtual void Emit(OpCode opcode) + { + } + + public virtual void Emit(OpCode opcode, byte arg) + { + } + + public virtual void Emit(OpCode opcode, double arg) + { + } + + public virtual void Emit(OpCode opcode, short arg) + { + } + + public virtual void Emit(OpCode opcode, int arg) + { + } + + public virtual void Emit(OpCode opcode, long arg) + { + } + + public virtual void Emit(OpCode opcode, ConstructorInfo con) + { + } + + public virtual void Emit(OpCode opcode, Label label) + { + } + + public virtual void Emit(OpCode opcode, Label[] labels) + { + } + + public virtual void Emit(OpCode opcode, LocalBuilder local) + { + } + + public virtual void Emit(OpCode opcode, SignatureHelper signature) + { + } + + public virtual void Emit(OpCode opcode, FieldInfo field) + { + } + + public virtual void Emit(OpCode opcode, MethodInfo meth) + { + } + + [CLSCompliantAttribute(false)] + public void Emit(OpCode opcode, sbyte arg) + { + } + + public virtual void Emit(OpCode opcode, float arg) + { + } + + public virtual void Emit(OpCode opcode, string str) + { + } + + public virtual void Emit(OpCode opcode, Type cls) + { + } + + public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) + { + } + + public virtual void EmitCalli(OpCode opcode, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) + { + } + + public virtual void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes) + { + } + + public virtual void EmitWriteLine(LocalBuilder localBuilder) + { + } + + public virtual void EmitWriteLine(FieldInfo fld) + { + } + + public virtual void EmitWriteLine(string value) + { + } + + public virtual void EndExceptionBlock() + { + } + + public virtual void EndScope() + { + } + + public virtual void MarkLabel(Label loc) + { + } + + public virtual void ThrowException(Type excType) + { + } + + public virtual void UsingNamespace(string usingNamespace) + { + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/LocalBuilder.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/LocalBuilder.cs new file mode 100644 index 0000000000..a0cbfbde06 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/LocalBuilder.cs @@ -0,0 +1,38 @@ +// Licensed to the.NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection.Emit +{ + public sealed class LocalBuilder : LocalVariableInfo + { + internal LocalBuilder() + { + // Prevent generating a default constructor + } + + public override bool IsPinned + { + get + { + return default; + } + } + + public override int LocalIndex + { + get + { + return default; + } + } + + public override Type LocalType + { + get + { + return default; + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.cs new file mode 100644 index 0000000000..c1d528682d --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.cs @@ -0,0 +1,246 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection.Emit +{ + public sealed class MethodBuilder : MethodInfo + { + internal MethodBuilder() + { + // Prevent generating a default constructor + } + + public override MethodAttributes Attributes + { + get + { + return default; + } + } + + public override CallingConventions CallingConvention + { + get + { + return default; + } + } + + public override bool ContainsGenericParameters + { + get + { + return default; + } + } + + public override Type DeclaringType + { + get + { + return default; + } + } + + public bool InitLocals + { + get + { + return default; + } + set + { + } + } + + public override bool IsGenericMethod + { + get + { + return default; + } + } + + public override bool IsGenericMethodDefinition + { + get + { + return default; + } + } + + public override bool IsConstructedGenericMethod + { + get + { + return default; + } + } + + public override RuntimeMethodHandle MethodHandle + { + get + { + return default; + } + } + + public override Module Module + { + get + { + return default; + } + } + + public override string Name + { + get + { + return default; + } + } + + public override Type ReflectedType + { + get + { + return default; + } + } + + public override ParameterInfo ReturnParameter + { + get + { + return default; + } + } + + public override Type ReturnType + { + get + { + return default; + } + } + + public override ICustomAttributeProvider ReturnTypeCustomAttributes + { + get + { + return default; + } + } + + public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) + { + return default; + } + + public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string strParamName) + { + return default; + } + + public override bool Equals(object obj) + { + return default; + } + + public override MethodInfo GetBaseDefinition() + { + return default; + } + + public override object[] GetCustomAttributes(bool inherit) + { + return default; + } + + public override object[] GetCustomAttributes(Type attributeType, bool inherit) + { + return default; + } + + public override Type[] GetGenericArguments() + { + return default; + } + + public override MethodInfo GetGenericMethodDefinition() + { + return default; + } + + public override int GetHashCode() + { + return default; + } + + public ILGenerator GetILGenerator() + { + return default; + } + + public ILGenerator GetILGenerator(int size) + { + return default; + } + + public override MethodImplAttributes GetMethodImplementationFlags() + { + return default; + } + + public override ParameterInfo[] GetParameters() + { + return default; + } + + public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, Globalization.CultureInfo culture) + { + return default; + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + return default; + } + + public override MethodInfo MakeGenericMethod(params Type[] typeArguments) + { + return default; + } + + public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + { + } + + public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + { + } + + public void SetImplementationFlags(MethodImplAttributes attributes) + { + } + + public void SetParameters(params Type[] parameterTypes) + { + } + + public void SetReturnType(Type returnType) + { + } + + public void SetSignature(Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) + { + } + + public override string ToString() + { + return default; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs new file mode 100644 index 0000000000..2e98335b3d --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs @@ -0,0 +1,142 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.InteropServices; + +namespace System.Reflection.Emit +{ + public class ModuleBuilder : Module + { + internal ModuleBuilder() + { + // Prevent generating a default constructor + } + + public override Assembly Assembly + { + get + { + return default; + } + } + + public override string FullyQualifiedName + { + get + { + return default; + } + } + + public override string Name + { + get + { + return default; + } + } + + public void CreateGlobalFunctions() + { + } + + public EnumBuilder DefineEnum(string name, TypeAttributes visibility, Type underlyingType) + { + return default; + } + + public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) + { + return default; + } + + public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) + { + return default; + } + + public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) + { + return default; + } + + public FieldBuilder DefineInitializedData(string name, byte[] data, FieldAttributes attributes) + { + return default; + } + + public MethodBuilder DefinePInvokeMethod(string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) + { + return default; + } + + public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) + { + return default; + } + + public TypeBuilder DefineType(string name) + { + return default; + } + + public TypeBuilder DefineType(string name, TypeAttributes attr) + { + return default; + } + + public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent) + { + return default; + } + + public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, int typesize) + { + return default; + } + + public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, PackingSize packsize) + { + return default; + } + + public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize) + { + return default; + } + + public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, Type[] interfaces) + { + return default; + } + + public FieldBuilder DefineUninitializedData(string name, int size, FieldAttributes attributes) + { + return default; + } + + public override bool Equals(object obj) + { + return default; + } + + public MethodInfo GetArrayMethod(Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) + { + return default; + } + + public override int GetHashCode() + { + return default; + } + + public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + { + } + + public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + { + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs new file mode 100644 index 0000000000..a633da26b8 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs @@ -0,0 +1,74 @@ +// Licensed to the.NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection.Emit +{ + public partial class ParameterBuilder + { + internal ParameterBuilder() + { + // Prevent generating a default constructor + } + + public virtual int Attributes + { + get + { + return default; + } + } + + public bool IsIn + { + get + { + return default; + } + } + + public bool IsOptional + { + get + { + return default; + } + } + + public bool IsOut + { + get + { + return default; + } + } + + public virtual string Name + { + get + { + return default; + } + } + + public virtual int Position + { + get + { + return default; + } + } + + public virtual void SetConstant(object defaultValue) + { + } + + public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + { + } + + public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + { + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.cs new file mode 100644 index 0000000000..2262252681 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.cs @@ -0,0 +1,155 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection.Emit +{ + public sealed class PropertyBuilder : PropertyInfo + { + internal PropertyBuilder() + { + // Prevent generating a default constructor + } + + public override PropertyAttributes Attributes + { + get + { + return default; + } + } + + public override bool CanRead + { + get + { + return default; + } + } + + public override bool CanWrite + { + get + { + return default; + } + } + + public override Type DeclaringType + { + get + { + return default; + } + } + + public override Module Module + { + get + { + return default; + } + } + + public override string Name + { + get + { + return default; + } + } + + public override Type PropertyType + { + get + { + return default; + } + } + + public override Type ReflectedType + { + get + { + return default; + } + } + + public void AddOtherMethod(MethodBuilder mdBuilder) + { + } + + public override MethodInfo[] GetAccessors(bool nonPublic) + { + return default; + } + + public override object[] GetCustomAttributes(bool inherit) + { + return default; + } + + public override object[] GetCustomAttributes(Type attributeType, bool inherit) + { + return default; + } + + public override MethodInfo GetGetMethod(bool nonPublic) + { + return default; + } + + public override ParameterInfo[] GetIndexParameters() + { + return default; + } + + public override MethodInfo GetSetMethod(bool nonPublic) + { + return default; + } + + public override object GetValue(object obj, object[] index) + { + return default; + } + + public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, Globalization.CultureInfo culture) + { + return default; + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + return default; + } + + public void SetConstant(object defaultValue) + { + } + + public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + { + } + + public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + { + } + + public void SetGetMethod(MethodBuilder mdBuilder) + { + } + + public void SetSetMethod(MethodBuilder mdBuilder) + { + } + + public override void SetValue(object obj, object value, object[] index) + { + } + + public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, Globalization.CultureInfo culture) + { + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ReflectionEmitThrower.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ReflectionEmitThrower.cs new file mode 100644 index 0000000000..6eb7c38cdb --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/ReflectionEmitThrower.cs @@ -0,0 +1,14 @@ +// Licensed to the.NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection.Emit +{ + internal static class ReflectionEmitThrower + { + public static void ThrowPlatformNotSupportedException() + { + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionEmit); + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs new file mode 100644 index 0000000000..c1da03ffb6 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs @@ -0,0 +1,108 @@ +// Licensed to the.NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection.Emit +{ + public sealed class SignatureHelper + { + internal SignatureHelper() + { + // Prevent generating a default constructor + } + + public void AddArgument(Type clsArgument) + { + } + + public void AddArgument(Type argument, bool pinned) + { + } + + public void AddArgument(Type argument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) + { + } + + public void AddArguments(Type[] arguments, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers) + { + } + + public void AddSentinel() + { + } + + public override bool Equals(object obj) + { + return default; + } + + public static SignatureHelper GetFieldSigHelper(Module mod) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + return default; + } + + public override int GetHashCode() + { + return default; + } + + public static SignatureHelper GetLocalVarSigHelper() + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + return default; + } + + public static SignatureHelper GetLocalVarSigHelper(Module mod) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + return default; + } + + public static SignatureHelper GetMethodSigHelper(CallingConventions callingConvention, Type returnType) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + return default; + } + + public static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + return default; + } + + public static SignatureHelper GetMethodSigHelper(Module mod, Type returnType, Type[] parameterTypes) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + return default; + } + + public static SignatureHelper GetPropertySigHelper(Module mod, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + return default; + } + + public static SignatureHelper GetPropertySigHelper(Module mod, Type returnType, Type[] parameterTypes) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + return default; + } + + public static SignatureHelper GetPropertySigHelper(Module mod, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + return default; + } + + public byte[] GetSignature() + { + return default; + } + + public override string ToString() + { + return default; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs new file mode 100644 index 0000000000..d4f5c977d2 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs @@ -0,0 +1,642 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.InteropServices; + +namespace System.Reflection.Emit +{ + public sealed partial class TypeBuilder : TypeInfo + { + internal TypeBuilder() + { + // Prevent generating a default constructor + } + + public const int UnspecifiedTypeSize = 0; + + public override Assembly Assembly + { + get + { + return default; + } + } + + public override string AssemblyQualifiedName + { + get + { + return default; + } + } + + public override Type BaseType + { + get + { + return default; + } + } + + public override MethodBase DeclaringMethod + { + get + { + return default; + } + } + + public override Type DeclaringType + { + get + { + return default; + } + } + + public override string FullName + { + get + { + return default; + } + } + + public override GenericParameterAttributes GenericParameterAttributes + { + get + { + return default; + } + } + + public override int GenericParameterPosition + { + get + { + return default; + } + } + + public override Guid GUID + { + get + { + return default; + } + } + + public override bool IsByRefLike + { + get + { + return default; + } + } + + public override bool IsConstructedGenericType + { + get + { + return default; + } + } + + public override bool IsGenericParameter + { + get + { + return default; + } + } + + public override bool IsGenericType + { + get + { + return default; + } + } + + public override bool IsGenericTypeDefinition + { + get + { + return default; + } + } + + public override bool IsSecurityCritical + { + get + { + return default; + } + } + + public override bool IsSecuritySafeCritical + { + get + { + return default; + } + } + + public override bool IsSecurityTransparent + { + get + { + return default; + } + } + + public override Module Module + { + get + { + return default; + } + } + + public override string Name + { + get + { + return default; + } + } + + public override string Namespace + { + get + { + return default; + } + } + + public PackingSize PackingSize + { + get + { + return default; + } + } + + public override Type ReflectedType + { + get + { + return default; + } + } + + public int Size + { + get + { + return default; + } + } + + public override RuntimeTypeHandle TypeHandle + { + get + { + return default; + } + } + + public override Type UnderlyingSystemType + { + get + { + return default; + } + } + + public void AddInterfaceImplementation(Type interfaceType) { } + public Type CreateType() + { + return default; + } + + public TypeInfo CreateTypeInfo() + { + return default; + } + + public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes) + { + return default; + } + + public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers) + { + return default; + } + + public ConstructorBuilder DefineDefaultConstructor(MethodAttributes attributes) + { + return default; + } + + public EventBuilder DefineEvent(string name, EventAttributes attributes, Type eventtype) + { + return default; + } + + public FieldBuilder DefineField(string fieldName, Type type, FieldAttributes attributes) + { + return default; + } + + public FieldBuilder DefineField(string fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes) + { + return default; + } + + public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) + { + return default; + } + + public FieldBuilder DefineInitializedData(string name, byte[] data, FieldAttributes attributes) + { + return default; + } + + public MethodBuilder DefineMethod(string name, MethodAttributes attributes) + { + return default; + } + + public MethodBuilder DefineMethod(string name, MethodAttributes attributes, CallingConventions callingConvention) + { + return default; + } + + public MethodBuilder DefineMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) + { + return default; + } + + public MethodBuilder DefineMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) + { + return default; + } + + public MethodBuilder DefineMethod(string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) + { + return default; + } + + public void DefineMethodOverride(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) + { + } + + public TypeBuilder DefineNestedType(string name) + { + return default; + } + + public TypeBuilder DefineNestedType(string name, TypeAttributes attr) + { + return default; + } + + public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent) + { + return default; + } + + public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent, int typeSize) + { + return default; + } + + public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent, PackingSize packSize) + { + return default; + } + + public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent, PackingSize packSize, int typeSize) + { + return default; + } + + public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent, Type[] interfaces) + { + return default; + } + + public MethodBuilder DefinePInvokeMethod(string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) + { + return default; + } + + public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) + { + return default; + } + + public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, CallingConvention nativeCallConv, CharSet nativeCharSet) + { + return default; + } + + public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) + { + return default; + } + + public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) + { + return default; + } + + public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes) + { + return default; + } + + public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) + { + return default; + } + + public ConstructorBuilder DefineTypeInitializer() + { + return default; + } + + public FieldBuilder DefineUninitializedData(string name, int size, FieldAttributes attributes) + { + return default; + } + + protected override TypeAttributes GetAttributeFlagsImpl() + { + return default; + } + + public static ConstructorInfo GetConstructor(Type type, ConstructorInfo constructor) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + return default; + } + + protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + { + return default; + } + + public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) + { + return default; + } + + public override object[] GetCustomAttributes(bool inherit) + { + return default; + } + + public override object[] GetCustomAttributes(Type attributeType, bool inherit) + { + return default; + } + + public override Type GetElementType() + { + return default; + } + + public override EventInfo GetEvent(string name, BindingFlags bindingAttr) + { + return default; + } + + public override EventInfo[] GetEvents() + { + return default; + } + + public override EventInfo[] GetEvents(BindingFlags bindingAttr) + { + return default; + } + + public override FieldInfo GetField(string name, BindingFlags bindingAttr) + { + return default; + } + + public static FieldInfo GetField(Type type, FieldInfo field) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + return default; + } + + public override FieldInfo[] GetFields(BindingFlags bindingAttr) + { + return default; + } + + public override Type[] GetGenericArguments() + { + return default; + } + + public override Type GetGenericTypeDefinition() + { + return default; + } + + public override Type GetInterface(string name, bool ignoreCase) + { + return default; + } + + public override InterfaceMapping GetInterfaceMap(Type interfaceType) + { + return default; + } + + public override Type[] GetInterfaces() + { + return default; + } + + public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) + { + return default; + } + + public override MemberInfo[] GetMembers(BindingFlags bindingAttr) + { + return default; + } + + public static MethodInfo GetMethod(Type type, MethodInfo method) + { + ReflectionEmitThrower.ThrowPlatformNotSupportedException(); + return default; + } + + protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + { + return default; + } + + public override MethodInfo[] GetMethods(BindingFlags bindingAttr) + { + return default; + } + + public override Type GetNestedType(string name, BindingFlags bindingAttr) + { + return default; + } + + public override Type[] GetNestedTypes(BindingFlags bindingAttr) + { + return default; + } + + public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) + { + return default; + } + + protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) + { + return default; + } + + protected override bool HasElementTypeImpl() + { + return default; + } + + public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, Globalization.CultureInfo culture, string[] namedParameters) + { + return default; + } + + protected override bool IsArrayImpl() + { + return default; + } + + public override bool IsAssignableFrom(TypeInfo typeInfo) + { + return default; + } + + public override bool IsAssignableFrom(Type c) + { + return default; + } + + protected override bool IsByRefImpl() + { + return default; + } + + protected override bool IsCOMObjectImpl() + { + return default; + } + + public bool IsCreated() + { + return default; + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + return default; + } + + protected override bool IsPointerImpl() + { + return default; + } + + protected override bool IsPrimitiveImpl() + { + return default; + } + + public override bool IsSubclassOf(Type c) + { + return default; + } + + public override bool IsTypeDefinition + { + get + { + return default; + } + } + + public override bool IsSZArray + { + get + { + return default; + } + } + + public override bool IsVariableBoundArray + { + get + { + return default; + } + } + + public override Type MakeArrayType() + { + return default; + } + + public override Type MakeArrayType(int rank) + { + return default; + } + + public override Type MakeByRefType() + { + return default; + } + + public override Type MakeGenericType(params Type[] typeArguments) + { + return default; + } + + public override Type MakePointerType() + { + return default; + } + + public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + { + } + + public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + { + } + + public void SetParent(Type parent) + { + } + + public override string ToString() + { + return default; + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/LocalVariableInfo.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/LocalVariableInfo.cs deleted file mode 100644 index 31e58caeb7..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/Reflection/LocalVariableInfo.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; - -namespace System.Reflection -{ - public class LocalVariableInfo - { - protected LocalVariableInfo() - { - } - - public virtual bool IsPinned - { - get - { - return false; - } - } - - public virtual int LocalIndex - { - get - { - return 0; - } - } - - public virtual Type LocalType - { - get - { - // Don't laugh - this is really how the desktop behaves if you don't override. - Debug.Fail("type must be set!"); - return null; - } - } - - public override string ToString() - { - // Don't laugh - this is really how the desktop behaves if you don't override, including the NullReference when - // it calls ToString() on LocalType's null return. - string toString = LocalType.ToString() + " (" + LocalIndex + ")"; - - if (IsPinned) - toString += " (pinned)"; - - return toString; - } - } -} - diff --git a/external/corert/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssemblyName.cs b/external/corert/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssemblyName.cs index 0e8d7a33ff..4faa7e2580 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssemblyName.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssemblyName.cs @@ -17,7 +17,7 @@ namespace System.Reflection // public sealed class RuntimeAssemblyName : IEquatable { - public RuntimeAssemblyName(String name, Version version, String cultureName, AssemblyNameFlags flags, byte[] publicKeyOrToken) + public RuntimeAssemblyName(string name, Version version, string cultureName, AssemblyNameFlags flags, byte[] publicKeyOrToken) { Debug.Assert(name != null); this.Name = name; @@ -36,13 +36,13 @@ namespace System.Reflection } // Simple name. - public String Name { get; } + public string Name { get; } // Optional version. public Version Version { get; } // Optional culture name. - public String CultureName { get; } + public string CultureName { get; } // Optional flags (this is actually an OR of the classic flags and the ContentType.) public AssemblyNameFlags Flags { get; } @@ -69,7 +69,7 @@ namespace System.Reflection if (!this.Version.Equals(other.Version)) return false; } - if (!String.Equals(this.CultureName, other.CultureName)) + if (!string.Equals(this.CultureName, other.CultureName)) return false; if (this.Flags != other.Flags) return false; @@ -101,7 +101,7 @@ namespace System.Reflection return true; } - public sealed override bool Equals(Object obj) + public sealed override bool Equals(object obj) { RuntimeAssemblyName other = obj as RuntimeAssemblyName; if (other == null) @@ -157,7 +157,7 @@ namespace System.Reflection return; } - public String FullName + public string FullName { get { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Resources/FileBasedResourceGroveler.cs b/external/corert/src/System.Private.CoreLib/src/System/Resources/FileBasedResourceGroveler.cs index 174a41975f..92b6da3975 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Resources/FileBasedResourceGroveler.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Resources/FileBasedResourceGroveler.cs @@ -34,16 +34,16 @@ namespace System.Resources // Consider modifying IResourceGroveler interface (hence this method signature) when we figure out // serialization compat story for moving ResourceManager members to either file-based or // manifest-based classes. Want to continue tightening the design to get rid of unused params. - public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary localResourceSets, bool tryParents, bool createIfNotExists) + public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary localResourceSets, bool tryParents, bool createIfNotExists) { Debug.Assert(culture != null, "culture shouldn't be null; check caller"); - String fileName = null; + string fileName = null; ResourceSet rs = null; // Don't use Assembly manifest, but grovel on disk for a file. // Create new ResourceSet, if a file exists on disk for it. - String tempFileName = _mediator.GetResourceFileName(culture); + string tempFileName = _mediator.GetResourceFileName(culture); fileName = FindResourceFile(culture, tempFileName); if (fileName == null) { @@ -73,7 +73,7 @@ namespace System.Resources // diretory or the module dir wasn't provided, look in the current // directory. - private String FindResourceFile(CultureInfo culture, String fileName) + private string FindResourceFile(CultureInfo culture, string fileName) { Debug.Assert(culture != null, "culture shouldn't be null; check caller"); Debug.Assert(fileName != null, "fileName shouldn't be null; check caller"); @@ -82,7 +82,7 @@ namespace System.Resources // qualified name, append path to that. if (_mediator.ModuleDir != null) { - String path = Path.Combine(_mediator.ModuleDir, fileName); + string path = Path.Combine(_mediator.ModuleDir, fileName); if (File.Exists(path)) { return path; @@ -92,27 +92,22 @@ namespace System.Resources // look in . if (File.Exists(fileName)) return fileName; - + return null; // give up. } - // Constructs a new ResourceSet for a given file name. The logic in - // here avoids a ReflectionPermission check for our RuntimeResourceSet - // for perf and working set reasons. - private ResourceSet CreateResourceSet(String file) + // Constructs a new ResourceSet for a given file name. + private ResourceSet CreateResourceSet(string file) { Debug.Assert(file != null, "file shouldn't be null; check caller"); if (_mediator.UserResourceSet == null) { - // Explicitly avoid CreateInstance if possible, because it - // requires ReflectionPermission to call private & protected - // constructors. return new RuntimeResourceSet(file); } else { - Object[] args = new Object[1]; + object[] args = new object[1]; args[0] = file; try { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Resources/IResourceGroveler.cs b/external/corert/src/System.Private.CoreLib/src/System/Resources/IResourceGroveler.cs index 1b909a2702..4dc5c5d874 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Resources/IResourceGroveler.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Resources/IResourceGroveler.cs @@ -2,10 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Generic; -using System.Globalization; - /*============================================================ ** ** @@ -17,11 +13,15 @@ using System.Globalization; ** ===========================================================*/ +using System; +using System.Collections.Generic; +using System.Globalization; + namespace System.Resources { internal interface IResourceGroveler { - ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary localResourceSets, bool tryParents, + ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary localResourceSets, bool tryParents, bool createIfNotExists); } } \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.cs b/external/corert/src/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.cs index fc22413519..449fa4e5b7 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.cs @@ -52,7 +52,7 @@ namespace System.Resources _mediator = mediator; } - public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary localResourceSets, bool tryParents, bool createIfNotExists) + public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary localResourceSets, bool tryParents, bool createIfNotExists) { Debug.Assert(culture != null, "culture shouldn't be null; check caller"); Debug.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller"); @@ -94,7 +94,7 @@ namespace System.Resources // get resource file name we'll search for. Note, be careful if you're moving this statement // around because lookForCulture may be modified from originally requested culture above. - String fileName = _mediator.GetResourceFileName(lookForCulture); + string fileName = _mediator.GetResourceFileName(lookForCulture); // 3. If we identified an assembly to search; look in manifest resource stream for resource file if (satellite != null) @@ -179,7 +179,7 @@ namespace System.Resources // Note we could go into infinite loops if mscorlib's // NeutralResourcesLanguageAttribute is mangled. If this assert // fires, please fix the build process for the BCL directory. - if (a == typeof(Object).GetTypeInfo().Assembly) + if (a == typeof(object).GetTypeInfo().Assembly) { Debug.Fail(a.GetName().Name + "'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e); return CultureInfo.InvariantCulture; @@ -207,12 +207,12 @@ namespace System.Resources // not disposing because we want to leave stream open BinaryReader br = new BinaryReader(store); - // Look for our magic number as a little endian Int32. + // Look for our magic number as a little endian int. int bytes = br.ReadInt32(); if (bytes == ResourceManager.MagicNumber) { int resMgrHeaderVersion = br.ReadInt32(); - String readerTypeName = null, resSetTypeName = null; + string readerTypeName = null, resSetTypeName = null; if (resMgrHeaderVersion == ResourceManager.HeaderVersionNumber) { br.ReadInt32(); // We don't want the number of bytes to skip. @@ -256,11 +256,11 @@ namespace System.Resources { // we do not want to use partial binding here. Type readerType = Type.GetType(readerTypeName, true); - Object[] args = new Object[1]; + object[] args = new object[1]; args[0] = store; IResourceReader reader = (IResourceReader)Activator.CreateInstance(readerType, args); - Object[] resourceSetArgs = new Object[1]; + object[] resourceSetArgs = new object[1]; resourceSetArgs[0] = reader; Type resSetType; if (_mediator.UserResourceSet == null) @@ -294,7 +294,7 @@ namespace System.Resources } else { - Object[] args = new Object[2]; + object[] args = new object[2]; args[0] = store; args[1] = assembly; try @@ -308,7 +308,7 @@ namespace System.Resources } catch (MissingMethodException) { } - args = new Object[1]; + args = new object[1]; args[0] = store; rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); return rs; @@ -320,7 +320,7 @@ namespace System.Resources } } - private Stream GetManifestResourceStream(Assembly satellite, String fileName) + private Stream GetManifestResourceStream(Assembly satellite, string fileName) { Debug.Assert(satellite != null, "satellite shouldn't be null; check caller"); Debug.Assert(fileName != null, "fileName shouldn't be null; check caller"); @@ -338,7 +338,7 @@ namespace System.Resources // case-insensitive lookup rules. Yes, this is slow. The metadata // dev lead refuses to make all assembly manifest resource lookups case-insensitive, // even optionally case-insensitive. - private Stream CaseInsensitiveManifestResourceStreamLookup(Assembly satellite, String name) + private Stream CaseInsensitiveManifestResourceStreamLookup(Assembly satellite, string name) { Debug.Assert(satellite != null, "satellite shouldn't be null; check caller"); Debug.Assert(name != null, "name shouldn't be null; check caller"); @@ -346,7 +346,7 @@ namespace System.Resources StringBuilder sb = new StringBuilder(); if (_mediator.LocationInfo != null) { - String nameSpace = _mediator.LocationInfo.Namespace; + string nameSpace = _mediator.LocationInfo.Namespace; if (nameSpace != null) { sb.Append(nameSpace); @@ -356,11 +356,11 @@ namespace System.Resources } sb.Append(name); - String givenName = sb.ToString(); - String canonicalName = null; - foreach (String existingName in satellite.GetManifestResourceNames()) + string givenName = sb.ToString(); + string canonicalName = null; + foreach (string existingName in satellite.GetManifestResourceNames()) { - if (String.Equals(existingName, givenName, StringComparison.InvariantCultureIgnoreCase)) + if (string.Equals(existingName, givenName, StringComparison.InvariantCultureIgnoreCase)) { if (canonicalName == null) { @@ -391,7 +391,7 @@ namespace System.Resources } Assembly satellite = null; - String satAssemblyName = GetSatelliteAssemblyName(); + string satAssemblyName = GetSatelliteAssemblyName(); // Look up the satellite assembly, but don't let problems // like a partially signed satellite assembly stop us from @@ -421,8 +421,11 @@ namespace System.Resources // Perf optimization - Don't use Reflection for most cases with // our .resources files. This makes our code run faster and we can avoid - // creating a ResourceReader via Reflection. - private bool CanUseDefaultResourceClasses(String readerTypeName, String resSetTypeName) + // creating a ResourceReader via Reflection. This would incur + // a security check (since the link-time check on the constructor that + // takes a String is turned into a full demand with a stack walk) + // and causes partially trusted localized apps to fail. + private bool CanUseDefaultResourceClasses(string readerTypeName, string resSetTypeName) { Debug.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller"); Debug.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller"); @@ -450,16 +453,16 @@ namespace System.Resources return true; } - private String GetSatelliteAssemblyName() + private string GetSatelliteAssemblyName() { - String satAssemblyName = _mediator.MainAssembly.GetName().Name; + string satAssemblyName = _mediator.MainAssembly.GetName().Name; satAssemblyName += ".resources"; return satAssemblyName; } private void HandleSatelliteMissing() { - String satAssemName = _mediator.MainAssembly.GetName().Name + ".resources.dll"; + string satAssemName = _mediator.MainAssembly.GetName().Name + ".resources.dll"; if (_mediator.SatelliteContractVersion != null) { satAssemName += ", Version=" + _mediator.SatelliteContractVersion.ToString(); @@ -477,7 +480,7 @@ namespace System.Resources } satAssemName += ", PublicKeyToken=" + publicKeyTok; - String missingCultureName = _mediator.NeutralResourcesCulture.Name; + string missingCultureName = _mediator.NeutralResourcesCulture.Name; if (missingCultureName.Length == 0) { missingCultureName = ""; @@ -485,10 +488,10 @@ namespace System.Resources throw new MissingSatelliteAssemblyException(SR.Format(SR.MissingSatelliteAssembly_Culture_Name, _mediator.NeutralResourcesCulture, satAssemName), missingCultureName); } - private void HandleResourceStreamMissing(String fileName) + private void HandleResourceStreamMissing(string fileName) { // Keep people from bothering me about resources problems - if (_mediator.MainAssembly == typeof(Object).GetTypeInfo().Assembly && _mediator.BaseName.Equals(System.CoreLib.Name)) + if (_mediator.MainAssembly == typeof(object).GetTypeInfo().Assembly && _mediator.BaseName.Equals(System.CoreLib.Name)) { // This would break CultureInfo & all our exceptions. Debug.Fail("Couldn't get " + System.CoreLib.Name + ResourceManager.ResFileExtension + " from " + System.CoreLib.Name + "'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug."); @@ -499,7 +502,7 @@ namespace System.Resources } // We really don't think this should happen - we always // expect the neutral locale's resources to be present. - String resName = String.Empty; + string resName = string.Empty; if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null) resName = _mediator.LocationInfo.Namespace + '.'; resName += fileName; diff --git a/external/corert/src/System.Private.CoreLib/src/System/Resources/ResourceManager.cs b/external/corert/src/System.Private.CoreLib/src/System/Resources/ResourceManager.cs index cabbff6a75..e219dc7d17 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Resources/ResourceManager.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Resources/ResourceManager.cs @@ -32,7 +32,7 @@ namespace System public static string FixupCoreLibName(string strToFixup) { - if (!String.IsNullOrEmpty(strToFixup)) + if (!string.IsNullOrEmpty(strToFixup)) { strToFixup = strToFixup.Replace("mscorlib", System.CoreLib.Name); } @@ -45,7 +45,7 @@ namespace System.Resources { internal static class ExtensionMethods { - public static Assembly InternalGetSatelliteAssembly(this Assembly mainAssembly, String name, + public static Assembly InternalGetSatelliteAssembly(this Assembly mainAssembly, string name, CultureInfo culture, Version version, bool throwOnFileNotFound) @@ -83,7 +83,7 @@ namespace System.Resources { public virtual bool Initialize(string reswFilename, out PRIExceptionInfo exceptionInfo) { exceptionInfo = null; return false; } - public virtual String GetString(String stringName, String startingCulture, String neutralResourcesCulture) { return null; } + public virtual string GetString(string stringName, string startingCulture, string neutralResourcesCulture) { return null; } public virtual CultureInfo GlobalResourceContextBestFitCultureInfo { @@ -187,16 +187,16 @@ namespace System.Resources { internal class CultureNameResourceSetPair { - public String lastCultureName; + public string lastCultureName; public ResourceSet lastResourceSet; } - protected String BaseNameField; + protected string BaseNameField; // don't serialize the cache of ResourceSets [NonSerialized] - private Dictionary _resourceSets; - private String moduleDir; // For assembly-ignorant directory location + private Dictionary _resourceSets; + private string moduleDir; // For assembly-ignorant directory location protected Assembly MainAssembly; // Need the assembly manifest sometimes. private Type _locationInfo; // For Assembly or type-based directory layout private Type _userResourceSet; // Which ResourceSet instance to create @@ -255,10 +255,10 @@ namespace System.Resources // These Strings are used to avoid using Reflection in CreateResourceSet. // The first set are used by ResourceWriter. The second are used by // InternalResGen. - internal static readonly String ResReaderTypeName = typeof(ResourceReader).FullName; - internal static readonly String ResSetTypeName = typeof(RuntimeResourceSet).FullName; - internal static readonly String MscorlibName = typeof(ResourceReader).GetTypeInfo().Assembly.FullName; - internal const String ResFileExtension = ".resources"; + internal static readonly string ResReaderTypeName = typeof(ResourceReader).FullName; + internal static readonly string ResSetTypeName = typeof(RuntimeResourceSet).FullName; + internal static readonly string MscorlibName = typeof(ResourceReader).GetTypeInfo().Assembly.FullName; + internal const string ResFileExtension = ".resources"; internal const int ResFileExtensionLength = 10; // My private debugging aid. Set to 5 or 6 for verbose output. Set to 3 @@ -298,7 +298,7 @@ namespace System.Resources // // Note: System.Windows.Forms uses this method at design time. // - private ResourceManager(String baseName, String resourceDir, Type usingResourceSet) + private ResourceManager(string baseName, string resourceDir, Type usingResourceSet) { if (null == baseName) throw new ArgumentNullException(nameof(baseName)); @@ -309,7 +309,7 @@ namespace System.Resources moduleDir = resourceDir; _userResourceSet = usingResourceSet; - _resourceSets = new Dictionary(); + _resourceSets = new Dictionary(); _lastUsedResourceCache = new CultureNameResourceSetPair(); UseManifest = false; @@ -317,7 +317,7 @@ namespace System.Resources resourceGroveler = new FileBasedResourceGroveler(mediator); } - public ResourceManager(String baseName, Assembly assembly) + public ResourceManager(string baseName, Assembly assembly) { if (null == baseName) throw new ArgumentNullException(nameof(baseName)); @@ -333,7 +333,7 @@ namespace System.Resources CommonAssemblyInit(); } - public ResourceManager(String baseName, Assembly assembly, Type usingResourceSet) + public ResourceManager(string baseName, Assembly assembly, Type usingResourceSet) { if (null == baseName) throw new ArgumentNullException(nameof(baseName)); @@ -377,7 +377,7 @@ namespace System.Resources [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { - _resourceSets = new Dictionary(); + _resourceSets = new Dictionary(); _lastUsedResourceCache = new CultureNameResourceSetPair(); // set up resource groveler, depending on whether this ResourceManager // is looking for files or assemblies @@ -411,7 +411,7 @@ namespace System.Resources // Now we can use the managed resources even when using PRI's to support the APIs GetObject, GetStream...etc. UseManifest = true; - _resourceSets = new Dictionary(); + _resourceSets = new Dictionary(); _lastUsedResourceCache = new CultureNameResourceSetPair(); _fallbackLoc = UltimateResourceFallbackLocation.MainAssembly; @@ -423,7 +423,7 @@ namespace System.Resources } // Gets the base name for the ResourceManager. - public virtual String BaseName + public virtual string BaseName { get { @@ -472,11 +472,11 @@ namespace System.Resources // creating a new ResourceManager isn't quite the correct behavior. public virtual void ReleaseAllResources() { - Dictionary localResourceSets = _resourceSets; + Dictionary localResourceSets = _resourceSets; // If any calls to Close throw, at least leave ourselves in a // consistent state. - _resourceSets = new Dictionary(); + _resourceSets = new Dictionary(); _lastUsedResourceCache = new CultureNameResourceSetPair(); lock (localResourceSets) @@ -490,7 +490,7 @@ namespace System.Resources } } - public static ResourceManager CreateFileBasedResourceManager(String baseName, String resourceDir, Type usingResourceSet) + public static ResourceManager CreateFileBasedResourceManager(string baseName, string resourceDir, Type usingResourceSet) { return new ResourceManager(baseName, resourceDir, usingResourceSet); } @@ -505,7 +505,7 @@ namespace System.Resources // // This method can be overriden to look for a different extension, // such as ".ResX", or a completely different format for naming files. - protected virtual String GetResourceFileName(CultureInfo culture) + protected virtual string GetResourceFileName(CultureInfo culture) { StringBuilder sb = new StringBuilder(255); sb.Append(BaseNameField); @@ -519,7 +519,7 @@ namespace System.Resources char c = cultureName[i]; // TODO: NLS Arrowhead - This is broken, names can only be RFC4646 names (ie: a-zA-Z0-9). // TODO: NLS Arrowhead - This allows any unicode letter/digit - if (Char.IsLetterOrDigit(c) || c == '-' || c == '_') + if (char.IsLetterOrDigit(c) || c == '-' || c == '_') { continue; } @@ -554,7 +554,7 @@ namespace System.Resources } // Look in the ResourceSet table - Dictionary localResourceSets = _resourceSets; + Dictionary localResourceSets = _resourceSets; ResourceSet rs = null; if (localResourceSets != null) { @@ -594,7 +594,7 @@ namespace System.Resources if (null == culture) throw new ArgumentNullException(nameof(culture)); - Dictionary localResourceSets = _resourceSets; + Dictionary localResourceSets = _resourceSets; ResourceSet rs; if (localResourceSets != null) { @@ -626,7 +626,7 @@ namespace System.Resources // This will take a minimal number of locks. protected virtual ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) { - Dictionary localResourceSets = _resourceSets; + Dictionary localResourceSets = _resourceSets; ResourceSet rs = null; CultureInfo foundCulture = null; lock (localResourceSets) @@ -691,7 +691,7 @@ namespace System.Resources } // Simple helper to ease maintenance and improve readability. - private static void AddResourceSet(Dictionary localResourceSets, String cultureName, ref ResourceSet rs) + private static void AddResourceSet(Dictionary localResourceSets, string cultureName, ref ResourceSet rs) { // InternalGetResourceSet is both recursive and reentrant - // assembly load callbacks in particular are a way we can call @@ -702,7 +702,7 @@ namespace System.Resources ResourceSet lostRace; if (localResourceSets.TryGetValue(cultureName, out lostRace)) { - if (!Object.ReferenceEquals(lostRace, rs)) + if (!object.ReferenceEquals(lostRace, rs)) { // Note: In certain cases, we can be trying to add a ResourceSet for multiple // cultures on one thread, while a second thread added another ResourceSet for one @@ -728,7 +728,7 @@ namespace System.Resources throw new ArgumentNullException(nameof(a), SR.ArgumentNull_Assembly); } - String v = null; + string v = null; IEnumerable attrs = a.GetCustomAttributes(); foreach (SatelliteContractVersionAttribute attr in attrs) @@ -753,7 +753,7 @@ namespace System.Resources // SatelliteContractVersionAttribute contains bogus values. // If this assert fires, please fix the build process for the // BCL directory. - if (a == typeof(Object).GetTypeInfo().Assembly) + if (a == typeof(object).GetTypeInfo().Assembly) { Debug.Fail(System.CoreLib.Name + "'s SatelliteContractVersionAttribute is a malformed version string!"); return null; @@ -774,8 +774,8 @@ namespace System.Resources } // IGNORES VERSION - internal static bool CompareNames(String asmTypeName1, - String typeName2, + internal static bool CompareNames(string asmTypeName1, + string typeName2, AssemblyName asmName2) { Debug.Assert(asmTypeName1 != null, "asmTypeName1 was unexpectedly null"); @@ -786,22 +786,22 @@ namespace System.Resources return false; // case sensitive - if (String.Compare(asmTypeName1, 0, typeName2, 0, typeName2.Length, StringComparison.Ordinal) != 0) + if (string.Compare(asmTypeName1, 0, typeName2, 0, typeName2.Length, StringComparison.Ordinal) != 0) return false; if (comma == -1) return true; // Now, compare assembly display names (IGNORES VERSION AND PROCESSORARCHITECTURE) // also, for mscorlib ignores everything, since that's what the binder is going to do - while (Char.IsWhiteSpace(asmTypeName1[++comma])) ; + while (char.IsWhiteSpace(asmTypeName1[++comma])) ; // case insensitive AssemblyName an1 = new AssemblyName(asmTypeName1.Substring(comma)); - if (String.Compare(an1.Name, asmName2.Name, StringComparison.OrdinalIgnoreCase) != 0) + if (string.Compare(an1.Name, asmName2.Name, StringComparison.OrdinalIgnoreCase) != 0) return false; // to match IsMscorlib() in VM - if (String.Compare(an1.Name, System.CoreLib.Name, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Compare(an1.Name, System.CoreLib.Name, StringComparison.OrdinalIgnoreCase) == 0) return true; @@ -833,7 +833,7 @@ namespace System.Resources #if FEATURE_APPX // Throws WinRT hresults - private string GetStringFromPRI(String stringName, String startingCulture, String neutralResourcesCulture) { + private string GetStringFromPRI(string stringName, string startingCulture, string neutralResourcesCulture) { Debug.Assert(_bUsingModernResourceManagement); Debug.Assert(_WinRTResourceManager != null); Debug.Assert(_PRIonAppXInitialized); @@ -847,8 +847,8 @@ namespace System.Resources // exception types that the ResourceManager class is not documented to throw. resourceString = _WinRTResourceManager.GetString( stringName, - String.IsNullOrEmpty(startingCulture) ? null : startingCulture, - String.IsNullOrEmpty(neutralResourcesCulture) ? null : neutralResourcesCulture); + string.IsNullOrEmpty(startingCulture) ? null : startingCulture, + string.IsNullOrEmpty(neutralResourcesCulture) ? null : neutralResourcesCulture); return resourceString; } @@ -920,7 +920,7 @@ namespace System.Resources if (s_IsAppXModel) { // If we have the type information from the ResourceManager(Type) constructor, we use it. Otherwise, we use BaseNameField. - String reswFilename = _locationInfo == null ? BaseNameField : _locationInfo.FullName; + string reswFilename = _locationInfo == null ? BaseNameField : _locationInfo.FullName; // The only way this can happen is if a class inherited from ResourceManager and // did not set the BaseNameField before calling the protected ResourceManager() constructor. @@ -932,7 +932,7 @@ namespace System.Resources // throw a MissingManifestResourceException when GetString is called indicating that a // resW filename called "" could not be found. if (reswFilename == null) - reswFilename = String.Empty; + reswFilename = string.Empty; // See AssemblyNative::IsFrameworkAssembly for details on which kinds of assemblies are considered Framework assemblies. // The Modern Resource Manager is not used for such assemblies - they continue to use satellite assemblies (i.e. .resources.dll files). @@ -1018,7 +1018,7 @@ namespace System.Resources // current thread's CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. // - public virtual String GetString(String name) + public virtual string GetString(string name) { return GetString(name, (CultureInfo)null); } @@ -1027,7 +1027,7 @@ namespace System.Resources // specified CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. // - public virtual String GetString(String name, CultureInfo culture) + public virtual string GetString(string name, CultureInfo culture) { if (null == name) throw new ArgumentNullException(nameof(name)); @@ -1051,7 +1051,7 @@ namespace System.Resources // match, since CultureInfo objects can't represent all the different languages the AppX resource model supports. // For classic resources, this causes us to ignore the languages list and instead use the older Win32 behavior, // which is the design choice we've made. (See the call a little later to GetCurrentUICultureNoAppX()). - if (Object.ReferenceEquals(culture, CultureInfo.CurrentUICulture)) + if (object.ReferenceEquals(culture, CultureInfo.CurrentUICulture)) { culture = null; } @@ -1088,7 +1088,7 @@ namespace System.Resources if (last != null) { - String value = last.GetString(name, _ignoreCase); + string value = last.GetString(name, _ignoreCase); if (value != null) return value; } @@ -1106,7 +1106,7 @@ namespace System.Resources if (rs != last) { - String value = rs.GetString(name, _ignoreCase); + string value = rs.GetString(name, _ignoreCase); if (value != null) { // update last used ResourceSet @@ -1139,7 +1139,7 @@ namespace System.Resources // current thread's CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. // - public virtual Object GetObject(String name) + public virtual object GetObject(string name) { return GetObject(name, (CultureInfo)null, true); } @@ -1147,12 +1147,12 @@ namespace System.Resources // Looks up a resource value for a particular name. Looks in the // specified CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. - public virtual Object GetObject(String name, CultureInfo culture) + public virtual object GetObject(string name, CultureInfo culture) { return GetObject(name, culture, true); } - private Object GetObject(String name, CultureInfo culture, bool wrapUnmanagedMemStream) + private object GetObject(string name, CultureInfo culture, bool wrapUnmanagedMemStream) { if (null == name) throw new ArgumentNullException(nameof(name)); @@ -1163,7 +1163,7 @@ namespace System.Resources // If the caller explictily passed in a culture that was obtained by calling CultureInfo.CurrentUICulture, // null it out, so that we re-compute it based on the Win32 value and not the AppX language list value. // (See the call a little later to GetCurrentUICultureNoAppX()). - if(Object.ReferenceEquals(culture, CultureInfo.CurrentUICulture)) + if (object.ReferenceEquals(culture, CultureInfo.CurrentUICulture)) { culture = null; } @@ -1180,7 +1180,7 @@ namespace System.Resources ResourceSet last = GetFirstResourceSet(culture); if (last != null) { - Object value = last.GetObject(name, _ignoreCase); + object value = last.GetObject(name, _ignoreCase); if (value != null) { @@ -1205,7 +1205,7 @@ namespace System.Resources if (rs != last) { - Object value = rs.GetObject(name, _ignoreCase); + object value = rs.GetObject(name, _ignoreCase); if (value != null) { // update the last used ResourceSet @@ -1232,14 +1232,14 @@ namespace System.Resources return null; } - public UnmanagedMemoryStream GetStream(String name) + public UnmanagedMemoryStream GetStream(string name) { return GetStream(name, (CultureInfo)null); } - public UnmanagedMemoryStream GetStream(String name, CultureInfo culture) + public UnmanagedMemoryStream GetStream(string name, CultureInfo culture) { - Object obj = GetObject(name, culture, false); + object obj = GetObject(name, culture, false); UnmanagedMemoryStream ums = obj as UnmanagedMemoryStream; if (ums == null && obj != null) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotStream_Name, name)); @@ -1266,7 +1266,7 @@ namespace System.Resources if (_installedSatelliteInfo == null) return true; - String[] installedSatellites = (String[])_installedSatelliteInfo[MainAssembly.FullName]; + string[] installedSatellites = (string[])_installedSatelliteInfo[MainAssembly.FullName]; if (installedSatellites == null) return true; @@ -1297,7 +1297,7 @@ namespace System.Resources } // NEEDED ONLY BY FILE-BASED - internal String ModuleDir + internal string ModuleDir { get { return _rm.moduleDir; } } @@ -1313,7 +1313,7 @@ namespace System.Resources get { return _rm._userResourceSet; } } - internal String BaseNameField + internal string BaseNameField { get { return _rm.BaseNameField; } } @@ -1324,7 +1324,7 @@ namespace System.Resources set { _rm._neutralResourcesCulture = value; } } - internal String GetResourceFileName(CultureInfo culture) + internal string GetResourceFileName(CultureInfo culture) { return _rm.GetResourceFileName(culture); } @@ -1360,7 +1360,7 @@ namespace System.Resources // this is weird because we have BaseNameField accessor above, but we're sticking // with it for compat. - internal String BaseName + internal string BaseName { get { return _rm.BaseName; } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs index 5601bae5a9..3e038d998c 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs @@ -949,7 +949,7 @@ namespace System.Runtime.CompilerServices [DependencyReductionRoot] internal static Action TryGetStateMachineForDebugger(Action action) { - Object target = action.Target; + object target = action.Target; MoveNextRunner runner = target as MoveNextRunner; if (runner != null) return runner.m_stateMachine.MoveNext; diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.NonPortable.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.NonPortable.cs index 4c309ca347..5374478e74 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.NonPortable.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.NonPortable.cs @@ -19,10 +19,9 @@ namespace System.Runtime.CompilerServices { //========================================================================================================= // Intrinsic to call the cctor given a pointer to the code (this method's body is ignored and replaced - // with a calli during compilation). The transform doesn't handle non-generic versions yet (i.e. - // functions that are void). + // with a calli during compilation). //========================================================================================================= - private static T Call(System.IntPtr pfn) + private static void Call(System.IntPtr pfn) { throw NotImplemented.ByDesign; } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.cs index 51abcf771f..a82e434b8f 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.cs @@ -50,7 +50,7 @@ namespace System.Runtime.CompilerServices return nonGcStaticBase; } - private unsafe static object CheckStaticClassConstructionReturnThreadStaticBase(TypeManagerSlot* pModuleData, Int32 typeTlsIndex, StaticClassConstructionContext* context) + private unsafe static object CheckStaticClassConstructionReturnThreadStaticBase(TypeManagerSlot* pModuleData, int typeTlsIndex, StaticClassConstructionContext* context) { object threadStaticBase = ThreadStatics.GetThreadStaticBaseForType(pModuleData, typeTlsIndex); EnsureClassConstructorRun(context); @@ -94,7 +94,7 @@ namespace System.Runtime.CompilerServices { NoisyLog("Calling cctor, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId); - Call(pfnCctor); + Call(pfnCctor); // Insert a memory barrier here to order any writes executed as part of static class // construction above with respect to the initialized flag update we're about to make @@ -279,6 +279,19 @@ namespace System.Runtime.CompilerServices #else const int Grow = 10; #endif + + // WASMTODO: Remove this when the Initialize method gets called by the runtime startup +#if WASM + if (s_cctorGlobalLock == null) + { + Interlocked.CompareExchange(ref s_cctorGlobalLock, new Lock(), null); + } + if (s_cctorArrays == null) + { + Interlocked.CompareExchange(ref s_cctorArrays, new Cctor[10][], null); + } +#endif // WASM + using (LockHolder.Hold(s_cctorGlobalLock)) { Cctor[] resultArray = null; @@ -542,7 +555,7 @@ namespace System.Runtime.CompilerServices string str; fixed (char* p = &chars[i]) { - str = new String(p, 0, numChars - i); + str = new string(p, 0, numChars - i); } return str; } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs index 562c195db4..5d9b51bcce 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs @@ -7,7 +7,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; - using Internal.Runtime.CompilerServices; namespace System.Runtime.CompilerServices @@ -17,6 +16,13 @@ namespace System.Runtime.CompilerServices where TKey : class where TValue : class { + #region Fields + private const int InitialCapacity = 8; // Initial length of the table. Must be a power of two. + private readonly Lock _lock; // This lock protects all mutation of data in the table. Readers do not take this lock. + private volatile Container _container; // The actual storage for the table; swapped out as the table grows. + private int _activeEnumeratorRefCount; // The number of outstanding enumerators on the table + #endregion + #region Constructors public ConditionalWeakTable() { @@ -165,8 +171,8 @@ namespace System.Runtime.CompilerServices // invokes createValueCallback() passing it the key. The returned value is bound to the key in the table // and returned as the result of GetValue(). // - // If multiple threads race to initialize the same key, the table may invoke createValueCallback - // multiple times with the same key. Exactly one of these calls will "win the race" and the returned + // If multiple threads try to initialize the same key, the table may invoke createValueCallback + // multiple times with the same key. Exactly one of these calls will succeed and the returned // value of that call will be the one added to the table and returned by all the racing GetValue() calls. // // This rule permits the table to invoke createValueCallback outside the internal table lock @@ -174,12 +180,7 @@ namespace System.Runtime.CompilerServices //-------------------------------------------------------------------------------------------- public TValue GetValue(TKey key, CreateValueCallback createValueCallback) { - // Our call to TryGetValue() validates key so no need for us to. - // - // if (key == null) - // { - // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); - // } + // key is validated by TryGetValue if (createValueCallback == null) { @@ -187,12 +188,9 @@ namespace System.Runtime.CompilerServices } TValue existingValue; - if (TryGetValue(key, out existingValue)) - { - return existingValue; - } - - return GetValueLocked(key, createValueCallback); + return TryGetValue(key, out existingValue) ? + existingValue : + GetValueLocked(key, createValueCallback); } private TValue GetValueLocked(TKey key, CreateValueCallback createValueCallback) @@ -226,10 +224,7 @@ namespace System.Runtime.CompilerServices // throw. //-------------------------------------------------------------------------------------------- - public TValue GetOrCreateValue(TKey key) - { - return GetValue(key, k => Activator.CreateInstance()); - } + public TValue GetOrCreateValue(TKey key) => GetValue(key, _ => Activator.CreateInstance()); public delegate TValue CreateValueCallback(TKey key); @@ -305,7 +300,7 @@ namespace System.Runtime.CompilerServices if (table != null) { // Ensure we don't keep the last current alive unnecessarily - _current = default(KeyValuePair); + _current = default; // Decrement the ref count that was incremented when constructed using (LockHolder.Hold(table._lock)) @@ -399,10 +394,7 @@ namespace System.Runtime.CompilerServices c.CreateEntryNoResize(key, value); } - private static bool IsPowerOfTwo(int value) - { - return (value > 0) && ((value & (value - 1)) == 0); - } + private static bool IsPowerOfTwo(int value) => (value > 0) && ((value & (value - 1)) == 0); #endregion @@ -417,7 +409,7 @@ namespace System.Runtime.CompilerServices // // - Used with live key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry) // depHnd.IsAllocated == true, depHnd.GetPrimary() != null - // hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & Int32.MaxValue + // hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & int.MaxValue // next links to next Entry in bucket. // // - Used with dead key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry) @@ -453,10 +445,19 @@ namespace System.Runtime.CompilerServices // private sealed class Container { + private readonly ConditionalWeakTable _parent; // the ConditionalWeakTable with which this container is associated + private int[] _buckets; // _buckets[hashcode & (_buckets.Length - 1)] contains index of the first entry in bucket (-1 if empty) + private Entry[] _entries; // the table entries containing the stored dependency handles + private int _firstFreeEntry; // _firstFreeEntry < _entries.Length => table has capacity, entries grow from the bottom of the table. + private bool _invalid; // flag detects if OOM or other background exception threw us out of the lock. + private bool _finalized; // set to true when initially finalized + private volatile object _oldKeepAlive; // used to ensure the next allocated container isn't finalized until this one is GC'd + internal Container(ConditionalWeakTable parent) { Debug.Assert(parent != null); Debug.Assert(IsPowerOfTwo(InitialCapacity)); + int size = InitialCapacity; _buckets = new int[size]; for (int i = 0; i < _buckets.Length; i++) @@ -481,13 +482,7 @@ namespace System.Runtime.CompilerServices _firstFreeEntry = firstFreeEntry; } - internal bool HasCapacity - { - get - { - return _firstFreeEntry < _entries.Length; - } - } + internal bool HasCapacity => _firstFreeEntry < _entries.Length; internal int FirstFreeEntry => _firstFreeEntry; @@ -503,7 +498,7 @@ namespace System.Runtime.CompilerServices VerifyIntegrity(); _invalid = true; - int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue; + int hashCode = RuntimeHelpers.GetHashCode(key) & int.MaxValue; int newEntry = _firstFreeEntry++; _entries[newEntry].hashCode = hashCode; @@ -530,7 +525,7 @@ namespace System.Runtime.CompilerServices object secondary; int entryIndex = FindEntry(key, out secondary); value = Unsafe.As(secondary); - return (entryIndex != -1); + return entryIndex != -1; } //---------------------------------------------------------------------------------------- @@ -542,17 +537,17 @@ namespace System.Runtime.CompilerServices //---------------------------------------------------------------------------------------- internal int FindEntry(TKey key, out object value) { - int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue; + int hashCode = RuntimeHelpers.GetHashCode(key) & int.MaxValue; int bucket = hashCode & (_buckets.Length - 1); for (int entriesIndex = Volatile.Read(ref _buckets[bucket]); entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) { if (_entries[entriesIndex].hashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out value) == key) { GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. - return entriesIndex; } } + GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. value = null; return -1; @@ -565,8 +560,8 @@ namespace System.Runtime.CompilerServices { if (index < _entries.Length) { - object oValue; - object oKey = _entries[index].depHnd.GetPrimaryAndSecondary(out oValue); + object oKey, oValue; + oKey = _entries[index].depHnd.GetPrimaryAndSecondary(out oValue); GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. if (oKey != null) @@ -577,8 +572,8 @@ namespace System.Runtime.CompilerServices } } - key = default(TKey); - value = default(TValue); + key = default; + value = default; return false; } @@ -617,11 +612,9 @@ namespace System.Runtime.CompilerServices ref Entry entry = ref _entries[entryIndex]; - // // We do not free the handle here, as we may be racing with readers who already saw the hash code. // Instead, we simply overwrite the entry's hash code, so subsequent reads will ignore it. // The handle will be free'd in Container's finalizer, after the table is resized or discarded. - // Volatile.Write(ref entry.hashCode, -1); // Also, clear the key to allow GC to collect objects pointed to by the entry @@ -797,18 +790,10 @@ namespace System.Runtime.CompilerServices ~Container() { // We're just freeing per-appdomain unmanaged handles here. If we're already shutting down the AD, - // don't bother. - // - // (Despite its name, Environment.HasShutdownStart also returns true if the current AD is finalizing.) - - if (Environment.HasShutdownStarted) - { - return; - } - - //We also skip doing anything if the container is invalid, including if someone + // don't bother. (Despite its name, Environment.HasShutdownStart also returns true if the current + // AD is finalizing.) We also skip doing anything if the container is invalid, including if someone // the container object was allocated but its associated table never set. - if (_invalid || _parent == null) + if (Environment.HasShutdownStarted || _invalid || _parent == null) { return; } @@ -855,21 +840,7 @@ namespace System.Runtime.CompilerServices } } } - - private readonly ConditionalWeakTable _parent; // the ConditionalWeakTable with which this container is associated - private int[] _buckets; // _buckets[hashcode & (_buckets.Length - 1)] contains index of the first entry in bucket (-1 if empty) - private Entry[] _entries; // the table entries containing the stored dependency handles - private int _firstFreeEntry; // _firstFreeEntry < _entries.Length => table has capacity, entries grow from the bottom of the table. - private bool _invalid; // flag detects if OOM or other background exception threw us out of the lock. - private bool _finalized; // set to true when initially finalized - private volatile object _oldKeepAlive; // used to ensure the next allocated container isn't finalized until this one is GC'd } - - private volatile Container _container; - private readonly Lock _lock; // This lock protects all mutation of data in the table. Readers do not take this lock. - private int _activeEnumeratorRefCount; // The number of outstanding enumerators on the table - - private const int InitialCapacity = 8; // Must be a power of two #endregion } #endregion @@ -902,25 +873,19 @@ namespace System.Runtime.CompilerServices internal struct DependentHandle { #region Constructors - public DependentHandle(Object primary, Object secondary) + public DependentHandle(object primary, object secondary) { _handle = RuntimeImports.RhHandleAllocDependent(primary, secondary); } #endregion #region Public Members - public bool IsAllocated - { - get - { - return _handle != (IntPtr)0; - } - } + public bool IsAllocated => _handle != IntPtr.Zero; // Getting the secondary object is more expensive than getting the first so // we provide a separate primary-only accessor for those times we only want the // primary. - public Object GetPrimary() + public object GetPrimary() { return RuntimeImports.RhHandleGet(_handle); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/FeatureRemovedException.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/FeatureRemovedException.cs new file mode 100644 index 0000000000..fce17a87f8 --- /dev/null +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/FeatureRemovedException.cs @@ -0,0 +1,25 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Runtime.CompilerServices +{ + // Exception to be thrown when a feature was removed during publishing. + internal sealed class FeatureRemovedException : Exception + { + public string FeatureName { get; } + + public FeatureRemovedException(string featureName) + { + FeatureName = featureName; + } + + public override string Message + { + get + { + return SR.Format(SR.FeatureRemoved_Message, FeatureName); + } + } + } +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index f126f4f812..15412878bd 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -53,7 +53,7 @@ namespace System.Runtime.CompilerServices ReflectionAugments.ReflectionCoreCallbacks.RunModuleConstructor(module.AssociatedModule); } - public static Object GetObjectValue(Object obj) + public static object GetObjectValue(object obj) { if (obj == null) return null; @@ -65,7 +65,7 @@ namespace System.Runtime.CompilerServices return RuntimeImports.RhMemberwiseClone(obj); } - public new static bool Equals(Object o1, Object o2) + public new static bool Equals(object o1, object o2) { if (o1 == o2) return true; @@ -102,7 +102,7 @@ namespace System.Runtime.CompilerServices return t_hashSeed; } - public static unsafe int GetHashCode(Object o) + public static unsafe int GetHashCode(object o) { #if FEATURE_SYNCTABLE return ObjectHeader.GetHashCode(o); @@ -162,7 +162,7 @@ namespace System.Runtime.CompilerServices // Number of bytes from the address pointed to by a reference to // a String to the first 16-bit character in the String. // This property allows C#'s fixed statement to work on Strings. - return String.FIRST_CHAR_OFFSET; + return string.FIRST_CHAR_OFFSET; } } @@ -239,7 +239,7 @@ namespace System.Runtime.CompilerServices throw new ArgumentNullException(nameof(d)); } - public static void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) + public static void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, object userData) { if (code == null) throw new ArgumentNullException(nameof(code)); @@ -263,8 +263,8 @@ namespace System.Runtime.CompilerServices } } - public delegate void TryCode(Object userData); - public delegate void CleanupCode(Object userData, bool exceptionThrown); + public delegate void TryCode(object userData); + public delegate void CleanupCode(object userData, bool exceptionThrown); public static object GetUninitializedObject(Type type) { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InitializeFinalizerThread.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/InitializeFinalizerThread.cs index 2b0e67bc86..cc52fda24c 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InitializeFinalizerThread.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/InitializeFinalizerThread.cs @@ -13,9 +13,9 @@ namespace System.Runtime [RuntimeExport("InitializeFinalizerThread")] public static void DoInitialize() { - // Make sure that the finalizer thread is RoInitialized before any objects are finalized. If this + // Make sure that the finalizer thread is CoInitialized before any objects are finalized. If this // fails, it will throw an exception and that will go unhandled, triggering a FailFast. - RuntimeThread.RoInitialize(); + RuntimeThread.InitializeCom(); } } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.cs index 61f5b8bfbd..ed2f7513bf 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.cs @@ -2,10 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -// - /*============================================================ ** ** @@ -50,18 +46,19 @@ ===========================================================*/ using System; -using System.Runtime.CompilerServices; -using System.Runtime.Versioning; +using System.IO; using System.Reflection; -using System.Threading; +using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; +using System.Runtime.Versioning; +using System.Threading; /* Problems addressed by the CriticalHandle class: 1) Critical finalization - ensure we never leak OS resources in SQL. Done without running truly arbitrary & unbounded amounts of managed code. 2) Reduced graph promotion - during finalization, keep object graph small - 3) GC.KeepAlive behavior - P/Invoke vs. finalizer thread race (HandleRef) + 3) GC.KeepAlive behavior - P/Invoke vs. finalizer thread race condition (HandleRef) 4) Enforcement of the above via the type system - Don't use IntPtr anymore. Subclasses of CriticalHandle will implement the ReleaseHandle @@ -240,7 +237,7 @@ namespace System.Runtime.InteropServices // that no jit allocations etc. will occur, but don't allocate memory unless // you can deal with the failure and still free the handle). // The boolean returned should be true for success and false if a - // catastrophic error occured and you wish to trigger a diagnostic for + // catastrophic error occurred and you wish to trigger a diagnostic for // debugging purposes (the SafeHandleCriticalFailure MDA). protected abstract bool ReleaseHandle(); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.cs index 5bae816fb4..53a51ae19d 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.cs @@ -31,7 +31,7 @@ namespace System.Runtime.InteropServices private const GCHandleType MaxHandleType = GCHandleType.Pinned; // Allocate a handle storing the object and the type. - internal GCHandle(Object value, GCHandleType type) + internal GCHandle(object value, GCHandleType type) { // Make sure the type parameter is within the valid range for the enum. if ((uint)type > (uint)MaxHandleType) @@ -61,12 +61,12 @@ namespace System.Runtime.InteropServices // type - The type of GC handle to create. // // returns a new GC handle that protects the object. - public static GCHandle Alloc(Object value) + public static GCHandle Alloc(object value) { return new GCHandle(value, GCHandleType.Normal); } - public static GCHandle Alloc(Object value, GCHandleType type) + public static GCHandle Alloc(object value, GCHandleType type) { return new GCHandle(value, type); } @@ -95,7 +95,7 @@ namespace System.Runtime.InteropServices } // Target property - allows getting / updating of the handle's referent. - public Object Target + public object Target { get { @@ -145,12 +145,12 @@ namespace System.Runtime.InteropServices // Get the address of the pinned object. // The layout of String and Array is different from Object - Object target = this.Target; + object target = this.Target; if (target == null) return default(IntPtr); - if (target is String targetAsString) + if (target is string targetAsString) { return (IntPtr)Unsafe.AsPointer(ref targetAsString.GetRawStringData()); } @@ -206,7 +206,7 @@ namespace System.Runtime.InteropServices return _handle.GetHashCode(); } - public override bool Equals(Object o) + public override bool Equals(object o) { GCHandle hnd; @@ -256,7 +256,7 @@ namespace System.Runtime.InteropServices #endif } - private static void GCHandleValidatePinnedObject(Object obj) + private static void GCHandleValidatePinnedObject(object obj) { if (obj != null && !obj.IsBlittable()) throw new ArgumentException(SR.Argument_NotIsomorphic); diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InteropExtensions.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InteropExtensions.cs index b296c66fdd..10092bcf7b 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InteropExtensions.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InteropExtensions.cs @@ -43,7 +43,7 @@ namespace System.Runtime.InteropServices } // Used for methods in System.Private.Interop.dll that need to work from offsets on boxed structs - public static unsafe void PinObjectAndCall(Object obj, Action del) + public static unsafe void PinObjectAndCall(object obj, Action del) { fixed (IntPtr* pEEType = &obj.m_pEEType) { @@ -70,7 +70,7 @@ namespace System.Runtime.InteropServices return handle.ToEETypePtr().MightBeBlittable(); } - public static bool IsBlittable(this Object obj) + public static bool IsBlittable(this object obj) { return obj.EETypePtr.MightBeBlittable(); } @@ -130,7 +130,7 @@ namespace System.Runtime.InteropServices /// /// Comparing RuntimeTypeHandle with an object's RuntimeTypeHandle, avoiding going through expensive Object.GetType().TypeHandle path /// - public static bool IsOfType(this Object obj, RuntimeTypeHandle handle) + public static bool IsOfType(this object obj, RuntimeTypeHandle handle) { RuntimeTypeHandle objType = new RuntimeTypeHandle(obj.EETypePtr); @@ -228,12 +228,12 @@ namespace System.Runtime.InteropServices /// weak handle if the callback returns false, which is perfect for controlling lifetime of a CCW /// internal const int RefCountedHandleType = 5; - public static IntPtr RuntimeHandleAllocRefCounted(Object value) + public static IntPtr RuntimeHandleAllocRefCounted(object value) { return RuntimeImports.RhHandleAlloc(value, (GCHandleType)RefCountedHandleType); } - public static void RuntimeHandleSet(IntPtr handle, Object value) + public static void RuntimeHandleSet(IntPtr handle, object value) { RuntimeImports.RhHandleSet(handle, value); } @@ -253,7 +253,7 @@ namespace System.Runtime.InteropServices return RuntimeImports.RhIsPromoted(obj); } - public static void RuntimeHandleSetDependentSecondary(IntPtr handle, Object secondary) + public static void RuntimeHandleSetDependentSecondary(IntPtr handle, object secondary) { RuntimeImports.RhHandleSetDependentSecondary(handle, secondary); } @@ -338,7 +338,7 @@ namespace System.Runtime.InteropServices return stringBuilder.GetBuffer(out len); } - public static IntPtr RuntimeHandleAllocVariable(Object value, uint type) + public static IntPtr RuntimeHandleAllocVariable(object value, uint type) { return RuntimeImports.RhHandleAllocVariable(value, type); } @@ -357,12 +357,12 @@ namespace System.Runtime.InteropServices { return RuntimeImports.RhHandleCompareExchangeVariableType(handle, oldType, newType); } - + public static void SetExceptionErrorCode(Exception exception, int hr) { - exception.SetErrorCode(hr); + exception.HResult = hr; } - + public static void SetExceptionMessage(Exception exception, string message) { exception.SetMessage(message); @@ -373,7 +373,7 @@ namespace System.Runtime.InteropServices return new DataMisalignedException(message); } - public static Delegate CreateDelegate(RuntimeTypeHandle typeHandleForDelegate, IntPtr ldftnResult, Object thisObject, bool isStatic, bool isVirtual, bool isOpen) + public static Delegate CreateDelegate(RuntimeTypeHandle typeHandleForDelegate, IntPtr ldftnResult, object thisObject, bool isStatic, bool isVirtual, bool isOpen) { return Delegate.CreateDelegate(typeHandleForDelegate.ToEETypePtr(), ldftnResult, thisObject, isStatic, isOpen); } @@ -401,6 +401,11 @@ namespace System.Runtime.InteropServices return ex.TryGetRestrictedErrorDetails(out restrictedError, out restrictedErrorReference, out restrictedCapabilitySid); } + public static IntPtr[] ExceptionGetStackIPs(Exception ex) + { + return ex.GetStackIPs(); + } + public static TypeInitializationException CreateTypeInitializationException(string message) { return new TypeInitializationException(message); @@ -419,7 +424,7 @@ namespace System.Runtime.InteropServices return RuntimeImports.RhpETWShouldWalkCom(); } - public static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, Int32 comRefCount, Int32 jupiterRefCount, Int32 flags) + public static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, int comRefCount, int jupiterRefCount, int flags) { RuntimeImports.RhpETWLogLiveCom(eventType, CCWHandle, objectID, typeRawValue, IUnknown, VTable, comRefCount, jupiterRefCount, flags); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs index 5af9ce674d..00b7449da4 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs @@ -12,12 +12,12 @@ namespace System.Runtime.InteropServices /// internal class Marshal { - public static unsafe String PtrToStringUni(IntPtr ptr, int len) + public static unsafe string PtrToStringUni(IntPtr ptr, int len) { return PInvokeMarshal.PtrToStringUni(ptr, len); } - public static unsafe String PtrToStringUni(IntPtr ptr) + public static unsafe string PtrToStringUni(IntPtr ptr) { return PInvokeMarshal.PtrToStringUni(ptr); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/PInvokeMarshal.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/PInvokeMarshal.cs index bca69bce3e..cf40790848 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/PInvokeMarshal.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/PInvokeMarshal.cs @@ -443,17 +443,17 @@ namespace System.Runtime.InteropServices #endregion #region String marshalling - public static unsafe String PtrToStringUni(IntPtr ptr, int len) + public static unsafe string PtrToStringUni(IntPtr ptr, int len) { if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); if (len < 0) throw new ArgumentException(nameof(len)); - return new String((char*)ptr, 0, len); + return new string((char*)ptr, 0, len); } - public static unsafe String PtrToStringUni(IntPtr ptr) + public static unsafe string PtrToStringUni(IntPtr ptr) { if (IntPtr.Zero == ptr) { @@ -465,7 +465,7 @@ namespace System.Runtime.InteropServices } else { - return new String((char*)ptr); + return new string((char*)ptr); } } @@ -553,7 +553,7 @@ namespace System.Runtime.InteropServices int lenUnicode; CalculateStringLength(pchBuffer, out lenAnsi, out lenUnicode); - string result = String.Empty; + string result = string.Empty; if (lenUnicode > 0) { @@ -768,7 +768,7 @@ namespace System.Runtime.InteropServices int lenAnsi = GetAnsiStringLen(pchBuffer); int lenUnicode = charCount; - string result = String.Empty; + string result = string.Empty; if (lenUnicode > 0) { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/UnsafeGCHandle.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/UnsafeGCHandle.cs index d7fbf75971..4a0b1d2ce3 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/UnsafeGCHandle.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/UnsafeGCHandle.cs @@ -36,19 +36,19 @@ namespace System.Runtime.InteropServices private IntPtr _handle; // Allocate a handle storing the object and the type. - private UnsafeGCHandle(Object value, GCHandleType type) + private UnsafeGCHandle(object value, GCHandleType type) { Debug.Assert((uint)type <= (uint)MaxHandleType, "Unexpected handle type"); _handle = RuntimeImports.RhHandleAlloc(value, type); } - public static UnsafeGCHandle Alloc(Object value, GCHandleType type) + public static UnsafeGCHandle Alloc(object value, GCHandleType type) { return new UnsafeGCHandle(value, type); } // Target property - allows getting / updating of the handle's referent. - public Object Target + public object Target { get { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs index 6ad477eadb..161de82aed 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs @@ -34,6 +34,9 @@ namespace System.Runtime.Loader { throw new PlatformNotSupportedException(); } + + public void SetProfileOptimizationRoot(string directoryPath) { } + public void StartProfileOptimization(string profile) { } } /// diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/MemoryFailPoint.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/MemoryFailPoint.cs index 4c68823e5c..da5c8452c6 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/MemoryFailPoint.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/MemoryFailPoint.cs @@ -212,6 +212,20 @@ namespace System.Runtime } bool needContiguousVASpace = (ulong)LastKnownFreeAddressSpace < segmentSize; +#if false + Console.WriteLine($"MemoryFailPoint:" + + $"Checking for {(segmentSize >> 20)} MB, " + + $"for allocation size of {sizeInMegabytes} MB, " + + $"stage {stage}. " + + $"Need page file? {needPageFile} " + + $"Need Address Space? {needAddressSpace} " + + $"Need Contiguous address space? {needContiguousVASpace} " + + $"Avail page file: {(availPageFile >> 20)} MB " + + $"Total free VA space: {totalAddressSpaceFree >> 20} MB " + + $"Contiguous free address space (found): {LastKnownFreeAddressSpace >> 20} MB " + + $"Space reserved via process's MemoryFailPoints: {reserved} MB"); +#endif + if (!needPageFile && !needAddressSpace && !needContiguousVASpace) break; @@ -231,29 +245,20 @@ namespace System.Runtime if (!needPageFile) continue; - // Attempt to grow the OS's page file. Note that we ignore - // any allocation routines from the host intentionally. - RuntimeHelpers.PrepareConstrainedRegions(); - try + // This shouldn't overflow due to the if clauses above. + UIntPtr numBytes = new UIntPtr(segmentSize); + unsafe { - } - finally - { - // This shouldn't overflow due to the if clauses above. - UIntPtr numBytes = new UIntPtr(segmentSize); - unsafe - { #if ENABLE_WINRT - void* pMemory = Interop.mincore.VirtualAllocFromApp(null, numBytes, Interop.Kernel32.MEM_COMMIT, Interop.Kernel32.PAGE_READWRITE); + void* pMemory = Interop.mincore.VirtualAllocFromApp(null, numBytes, Interop.Kernel32.MEM_COMMIT, Interop.Kernel32.PAGE_READWRITE); #else - void* pMemory = Interop.Kernel32.VirtualAlloc(null, numBytes, Interop.Kernel32.MEM_COMMIT, Interop.Kernel32.PAGE_READWRITE); + void* pMemory = Interop.Kernel32.VirtualAlloc(null, numBytes, Interop.Kernel32.MEM_COMMIT, Interop.Kernel32.PAGE_READWRITE); #endif - if (pMemory != null) - { - bool r = Interop.Kernel32.VirtualFree(pMemory, UIntPtr.Zero, Interop.Kernel32.MEM_RELEASE); - if (!r) - throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); - } + if (pMemory != null) + { + bool r = Interop.Kernel32.VirtualFree(pMemory, UIntPtr.Zero, Interop.Kernel32.MEM_RELEASE); + if (!r) + throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } continue; @@ -300,15 +305,8 @@ namespace System.Runtime if (LastKnownFreeAddressSpace < 0) CheckForFreeAddressSpace(segmentSize, true); - RuntimeHelpers.PrepareConstrainedRegions(); - try - { - } - finally - { - AddMemoryFailPointReservation((long)size); - _mustSubtractReservation = true; - } + AddMemoryFailPointReservation((long)size); + _mustSubtractReservation = true; } private static void CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree) @@ -320,6 +318,7 @@ namespace System.Runtime throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); availPageFile = memory.availPageFile; totalAddressSpaceFree = memory.availVirtual; + // Console.WriteLine($"Memory gate: Mem load: {memory.memoryLoad}% Available memory (physical + page file): {(memory.availPageFile >> 20)} MB Total free address space: {memory.availVirtual >> 20} MB GC Heap: {(GC.GetTotalMemory(true) >> 20)} MB"); } // Based on the shouldThrow parameter, this will throw an exception, or @@ -334,6 +333,8 @@ namespace System.Runtime // know whether VirtualAlloc could succeed. ulong freeSpaceAfterGCHeap = MemFreeAfterAddress(null, size); + // Console.WriteLine($"MemoryFailPoint: Checked for free VA space. Found enough? {(freeSpaceAfterGCHeap >= size)} Asked for: {size} Found: {freeSpaceAfterGCHeap}"); + // We may set these without taking a lock - I don't believe // this will hurt, as long as we never increment this number in // the Dispose method. If we do an extra bit of checking every @@ -406,15 +407,8 @@ namespace System.Runtime // within the GC heap. if (_mustSubtractReservation) { - RuntimeHelpers.PrepareConstrainedRegions(); - try - { - } - finally - { - AddMemoryFailPointReservation(-((long)_reservedMemory)); - _mustSubtractReservation = false; - } + AddMemoryFailPointReservation(-((long)_reservedMemory)); + _mustSubtractReservation = false; } /* @@ -463,7 +457,7 @@ namespace System.Runtime private ulong _totalFreeAddressSpace; private long _lastKnownFreeAddressSpace; private ulong _reservedMem; - private String _stackTrace; // Where did we fail, for additional debugging. + private string _stackTrace; // Where did we fail, for additional debugging. internal MemoryFailPointState(int allocationSizeInMB, ulong segmentSize, bool needPageFile, bool needAddressSpace, bool needContiguousVASpace, ulong availPageFile, ulong totalFreeAddressSpace, long lastKnownFreeAddressSpace, ulong reservedMem) { @@ -490,9 +484,9 @@ namespace System.Runtime } } - public override String ToString() + public override string ToString() { - return String.Format(System.Globalization.CultureInfo.InvariantCulture, "MemoryFailPoint detected insufficient memory to guarantee an operation could complete. Checked for {0} MB, for allocation size of {1} MB. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved by process's MemoryFailPoints: {8} MB", + return string.Format(System.Globalization.CultureInfo.InvariantCulture, "MemoryFailPoint detected insufficient memory to guarantee an operation could complete. Checked for {0} MB, for allocation size of {1} MB. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved by process's MemoryFailPoints: {8} MB", _segmentSize >> 20, _allocationSizeInMB, _needPageFile, _needAddressSpace, _needContiguousVASpace, _availPageFile >> 20, _totalFreeAddressSpace >> 20, diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs index f8ebc13ee8..add1472525 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs @@ -71,9 +71,9 @@ namespace System.Runtime // Mark an object instance as already finalized. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhSuppressFinalize")] - internal static extern void RhSuppressFinalize(Object obj); + internal static extern void RhSuppressFinalize(object obj); - internal static void RhReRegisterForFinalize(Object obj) + internal static void RhReRegisterForFinalize(object obj) { if (!_RhReRegisterForFinalize(obj)) throw new OutOfMemoryException(); @@ -81,7 +81,7 @@ namespace System.Runtime [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhReRegisterForFinalize")] - private static extern bool _RhReRegisterForFinalize(Object obj); + private static extern bool _RhReRegisterForFinalize(object obj); // Wait for all pending finalizers. This must be a p/invoke to avoid starving the GC. [DllImport(RuntimeLibrary, ExactSpelling = true)] @@ -109,7 +109,7 @@ namespace System.Runtime [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetGeneration")] - internal static extern int RhGetGeneration(Object obj); + internal static extern int RhGetGeneration(object obj); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetGcLatencyMode")] @@ -207,9 +207,9 @@ namespace System.Runtime // Allocate handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpHandleAlloc")] - private static extern IntPtr RhpHandleAlloc(Object value, GCHandleType type); + private static extern IntPtr RhpHandleAlloc(object value, GCHandleType type); - internal static IntPtr RhHandleAlloc(Object value, GCHandleType type) + internal static IntPtr RhHandleAlloc(object value, GCHandleType type) { IntPtr h = RhpHandleAlloc(value, type); if (h == IntPtr.Zero) @@ -220,9 +220,9 @@ namespace System.Runtime // Allocate handle for dependent handle case where a secondary can be set at the same time. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpHandleAllocDependent")] - private static extern IntPtr RhpHandleAllocDependent(Object primary, Object secondary); + private static extern IntPtr RhpHandleAllocDependent(object primary, object secondary); - internal static IntPtr RhHandleAllocDependent(Object primary, Object secondary) + internal static IntPtr RhHandleAllocDependent(object primary, object secondary) { IntPtr h = RhpHandleAllocDependent(primary, secondary); if (h == IntPtr.Zero) @@ -233,9 +233,9 @@ namespace System.Runtime // Allocate variable handle with its initial type. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpHandleAllocVariable")] - private static extern IntPtr RhpHandleAllocVariable(Object value, uint type); + private static extern IntPtr RhpHandleAllocVariable(object value, uint type); - internal static IntPtr RhHandleAllocVariable(Object value, uint type) + internal static IntPtr RhHandleAllocVariable(object value, uint type) { IntPtr h = RhpHandleAllocVariable(value, type); if (h == IntPtr.Zero) @@ -251,9 +251,9 @@ namespace System.Runtime // Get object reference from handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleGet")] - private static extern Object _RhHandleGet(IntPtr handle); + private static extern object _RhHandleGet(IntPtr handle); - internal static unsafe Object RhHandleGet(IntPtr handle) + internal static unsafe object RhHandleGet(IntPtr handle) { #if DEBUG // The runtime performs additional checks in debug builds @@ -266,17 +266,17 @@ namespace System.Runtime // Get primary and secondary object references from dependent handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleGetDependent")] - internal static extern Object RhHandleGetDependent(IntPtr handle, out Object secondary); + internal static extern object RhHandleGetDependent(IntPtr handle, out object secondary); // Set object reference into handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleSet")] - internal static extern void RhHandleSet(IntPtr handle, Object value); + internal static extern void RhHandleSet(IntPtr handle, object value); // Set the secondary object reference into a dependent handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleSetDependentSecondary")] - internal static extern void RhHandleSetDependentSecondary(IntPtr handle, Object secondary); + internal static extern void RhHandleSetDependentSecondary(IntPtr handle, object secondary); // Get the handle type associated with a variable handle. [MethodImpl(MethodImplOptions.InternalCall)] @@ -308,7 +308,7 @@ namespace System.Runtime [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhTypeCast_CheckArrayStore")] - internal static extern void RhCheckArrayStore(Object array, Object obj); + internal static extern void RhCheckArrayStore(object array, object obj); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhTypeCast_IsInstanceOf")] @@ -346,7 +346,7 @@ namespace System.Runtime [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhNewString")] - internal static extern String RhNewString(EETypePtr pEEType, int length); + internal static extern string RhNewString(EETypePtr pEEType, int length); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhBox")] @@ -381,6 +381,7 @@ namespace System.Runtime [DllImport(RuntimeLibrary, EntryPoint = "RhFlushProcessWriteBuffers", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] internal static extern void RhFlushProcessWriteBuffers(); +#if !PLATFORM_UNIX // Wait for any object to be signalled, in a way that's compatible with the CLR's behavior in an STA. // ExactSpelling = 'true' to force MCG to resolve it to default [DllImport(RuntimeLibrary, ExactSpelling = true)] @@ -395,6 +396,7 @@ namespace System.Runtime { return RhCompatibleReentrantWaitAny(alertable ? 1 : 0, timeout, count, handles); } +#endif // // EEType interrogation methods. @@ -559,17 +561,21 @@ namespace System.Runtime #if !PROJECTN [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetThreadStaticStorageForModule")] - internal static unsafe extern Array RhGetThreadStaticStorageForModule(Int32 moduleIndex); + internal static unsafe extern object[] RhGetThreadStaticStorageForModule(int moduleIndex); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhSetThreadStaticStorageForModule")] - internal static unsafe extern bool RhSetThreadStaticStorageForModule(Array storage, Int32 moduleIndex); + internal static unsafe extern bool RhSetThreadStaticStorageForModule(object[] storage, int moduleIndex); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhCurrentNativeThreadId")] internal static unsafe extern IntPtr RhCurrentNativeThreadId(); #endif + [MethodImplAttribute(MethodImplOptions.InternalCall)] + [RuntimeImport(RuntimeLibrary, "RhCurrentOSThreadId")] + internal static unsafe extern ulong RhCurrentOSThreadId(); + [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport("*", "RhGetCurrentThunkContext")] internal static extern IntPtr GetCurrentInteropThunkContext(); @@ -715,7 +721,7 @@ namespace System.Runtime // [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpETWLogLiveCom")] - internal extern static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, Int32 comRefCount, Int32 jupiterRefCount, Int32 flags); + internal extern static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, int comRefCount, int jupiterRefCount, int flags); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpETWShouldWalkCom")] diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/TypeLoaderExports.cs b/external/corert/src/System.Private.CoreLib/src/System/Runtime/TypeLoaderExports.cs index fe283e992d..8e08a76daf 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/TypeLoaderExports.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Runtime/TypeLoaderExports.cs @@ -109,7 +109,7 @@ namespace System.Runtime #if PROJECTN [RuntimeExport("GenericLookupAndCallCtor")] #endif - public static void GenericLookupAndCallCtor(Object arg, IntPtr context, IntPtr signature) + public static void GenericLookupAndCallCtor(object arg, IntPtr context, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) @@ -122,27 +122,27 @@ namespace System.Runtime #if PROJECTN [RuntimeExport("GenericLookupAndAllocObject")] #endif - public static Object GenericLookupAndAllocObject(IntPtr context, IntPtr signature) + public static object GenericLookupAndAllocObject(IntPtr context, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) { entry = CacheMiss(context, signature); } - return RawCalliHelper.Call(entry.Result, entry.AuxResult); + return RawCalliHelper.Call(entry.Result, entry.AuxResult); } #if PROJECTN [RuntimeExport("GenericLookupAndAllocArray")] #endif - public static Object GenericLookupAndAllocArray(IntPtr context, IntPtr arg, IntPtr signature) + public static object GenericLookupAndAllocArray(IntPtr context, IntPtr arg, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) { entry = CacheMiss(context, signature); } - return RawCalliHelper.Call(entry.Result, entry.AuxResult, arg); + return RawCalliHelper.Call(entry.Result, entry.AuxResult, arg); } #if PROJECTN @@ -161,14 +161,14 @@ namespace System.Runtime #if PROJECTN [RuntimeExport("GenericLookupAndCast")] #endif - public static Object GenericLookupAndCast(Object arg, IntPtr context, IntPtr signature) + public static object GenericLookupAndCast(object arg, IntPtr context, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) { entry = CacheMiss(context, signature); } - return RawCalliHelper.Call(entry.Result, arg, entry.AuxResult); + return RawCalliHelper.Call(entry.Result, arg, entry.AuxResult); } #if PROJECTN @@ -433,7 +433,7 @@ namespace System.Runtime } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static void Call(System.IntPtr pfn, Object arg) + public static void Call(System.IntPtr pfn, object arg) { } @@ -451,12 +451,12 @@ namespace System.Runtime } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static void Call(System.IntPtr pfn, IntPtr arg1, Object arg2) + public static void Call(System.IntPtr pfn, IntPtr arg1, object arg2) { } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static T Call(System.IntPtr pfn, Object arg1, IntPtr arg2) + public static T Call(System.IntPtr pfn, object arg1, IntPtr arg2) { return default(T); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/RuntimeExceptionHelpers.cs b/external/corert/src/System.Private.CoreLib/src/System/RuntimeExceptionHelpers.cs index ec40c126dc..35d954368f 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/RuntimeExceptionHelpers.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/RuntimeExceptionHelpers.cs @@ -129,7 +129,7 @@ namespace System } - public static void FailFast(String message) + public static void FailFast(string message) { FailFast(message, null, RhFailFastReason.Unknown, IntPtr.Zero, IntPtr.Zero); } @@ -184,7 +184,7 @@ namespace System Debug.WriteLine("Unhandled Exception: " + exception.ToString()); } - failFastMessage = String.Format("Runtime-generated FailFast: ({0}): {1}{2}", + failFastMessage = string.Format("Runtime-generated FailFast: ({0}): {1}{2}", reason.ToString(), // Explicit call to ToString() to avoid MissingMetadataException inside String.Format() GetStringForFailFastReason(reason), exception != null ? " [exception object available]" : ""); @@ -208,7 +208,7 @@ namespace System if (!minimalFailFast) { - String output = (exception != null) ? + string output = (exception != null) ? "Unhandled Exception: " + exception.ToString() : message; DeveloperExperience.Default.WriteLine(output); @@ -309,10 +309,10 @@ namespace System public struct ExceptionMetadataStruct { - public UInt32 ExceptionId { get; set; } // Id assigned to the exception. May not be contiguous or start at 0. - public UInt32 InnerExceptionId { get; set; } // ID of the inner exception or 0xFFFFFFFF for 'no inner exception' - public UInt32 ThreadId { get; set; } // Managed thread ID the eception was thrown on - public Int32 NestingLevel { get; set; } // If multiple exceptions are currently active on a thread, this gives the ordering for them. + public uint ExceptionId { get; set; } // Id assigned to the exception. May not be contiguous or start at 0. + public uint InnerExceptionId { get; set; } // ID of the inner exception or 0xFFFFFFFF for 'no inner exception' + public uint ThreadId { get; set; } // Managed thread ID the eception was thrown on + public int NestingLevel { get; set; } // If multiple exceptions are currently active on a thread, this gives the ordering for them. // The highest number is the most recent exception. -1 means the exception is not currently in flight // (but it may still be an InnerException). public IntPtr ExceptionCCWPtr { get; set; } // If the exception was thrown in an interop scenario, this contains the CCW pointer, otherwise, IntPtr.Zero @@ -390,7 +390,7 @@ namespace System private static void SerializeExceptionsForDump(Exception currentException, IntPtr exceptionCCWPtr, LowLevelList serializedExceptions) { - const UInt32 NoInnerExceptionValue = 0xFFFFFFFF; + const uint NoInnerExceptionValue = 0xFFFFFFFF; // Approximate upper size limit for the serialized exceptions (but we'll always serialize currentException) // If we hit the limit, because we serialize in arbitrary order, there may be missing InnerExceptions or nested exceptions. @@ -442,10 +442,10 @@ namespace System { ExceptionData exceptionData = s_exceptionDataTable.GetOrCreateValue(exceptions[i]); - exceptionData.ExceptionMetadata.ExceptionId = (UInt32)System.Threading.Interlocked.Increment(ref s_currentExceptionId); + exceptionData.ExceptionMetadata.ExceptionId = (uint)System.Threading.Interlocked.Increment(ref s_currentExceptionId); if (exceptionData.ExceptionMetadata.ExceptionId == NoInnerExceptionValue) { - exceptionData.ExceptionMetadata.ExceptionId = (UInt32)System.Threading.Interlocked.Increment(ref s_currentExceptionId); + exceptionData.ExceptionMetadata.ExceptionId = (uint)System.Threading.Interlocked.Increment(ref s_currentExceptionId); } exceptionData.ExceptionMetadata.ThreadId = currentThreadId; @@ -462,7 +462,7 @@ namespace System } // Only match the CCW pointer up to the current exception - if (Object.ReferenceEquals(exceptions[i], currentException)) + if (object.ReferenceEquals(exceptions[i], currentException)) { exceptionData.ExceptionMetadata.ExceptionCCWPtr = exceptionCCWPtr; } diff --git a/external/corert/src/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs b/external/corert/src/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs index dac2f2958a..3e9b5a5e2e 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs @@ -18,7 +18,7 @@ namespace System public IntPtr Value => _value; - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (!(obj is RuntimeFieldHandle)) return false; diff --git a/external/corert/src/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs b/external/corert/src/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs index c079f4756d..02d1b8da08 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs @@ -20,7 +20,7 @@ namespace System public unsafe IntPtr Value => _value; - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (!(obj is RuntimeMethodHandle)) return false; diff --git a/external/corert/src/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs b/external/corert/src/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs index c713560e67..778b011a6d 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs @@ -26,7 +26,7 @@ namespace System _value = pEEType.RawValue; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (obj is RuntimeTypeHandle) { @@ -105,6 +105,7 @@ namespace System throw new PlatformNotSupportedException(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal EETypePtr ToEETypePtr() { return new EETypePtr(_value); @@ -119,11 +120,11 @@ namespace System } // Last resort string for Type.ToString() when no metadata around. - internal String LastResortToString + internal string LastResortToString { get { - String s; + string s; EETypePtr eeType = this.ToEETypePtr(); IntPtr rawEEType = eeType.RawValue; IntPtr moduleBase = RuntimeImports.RhGetOSModuleFromEEType(rawEEType); @@ -140,7 +141,7 @@ namespace System ReflectionExecutionDomainCallbacks callbacks = RuntimeAugments.CallbacksIfAvailable; if (callbacks != null) { - String penultimateLastResortString = callbacks.GetBetterDiagnosticInfoIfAvailable(this); + string penultimateLastResortString = callbacks.GetBetterDiagnosticInfoIfAvailable(this); if (penultimateLastResortString != null) s += "(" + penultimateLastResortString + ")"; } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Security/AccessControl/RegistryRights.cs b/external/corert/src/System.Private.CoreLib/src/System/Security/AccessControl/RegistryRights.cs deleted file mode 100644 index 6359122efc..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/Security/AccessControl/RegistryRights.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Win32; - -namespace System.Security.AccessControl -{ - // We derived this enum from the definitions of KEY_READ and such from - // winnt.h and from MSDN, plus some experimental validation with regedit. - // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/registry_key_security_and_access_rights.asp - [Flags] -#if REGISTRY_ASSEMBLY - public -#else - internal -#endif - enum RegistryRights - { - // No None field - An ACE with the value 0 cannot grant nor deny. - QueryValues = Interop.mincore.RegistryOperations.KEY_QUERY_VALUE, // 0x0001 query the values of a registry key - SetValue = Interop.mincore.RegistryOperations.KEY_SET_VALUE, // 0x0002 create, delete, or set a registry value - CreateSubKey = Interop.mincore.RegistryOperations.KEY_CREATE_SUB_KEY, // 0x0004 required to create a subkey of a specific key - EnumerateSubKeys = Interop.mincore.RegistryOperations.KEY_ENUMERATE_SUB_KEYS, // 0x0008 required to enumerate sub keys of a key - Notify = Interop.mincore.RegistryOperations.KEY_NOTIFY, // 0x0010 needed to request change notifications - CreateLink = Interop.mincore.RegistryOperations.KEY_CREATE_LINK, // 0x0020 reserved for system use - /// - /// The Windows Kernel team agrees that it was a bad design to expose the WOW64_n options as permissions. - /// in the .NET Framework these options are exposed via the RegistryView enum - /// - /// Reg64 = Interop.mincore.RegistryOptions.KEY_WOW64_64KEY, // 0x0100 operate on the 64-bit registry view - /// Reg32 = Interop.mincore.RegistryOptions.KEY_WOW64_32KEY, // 0x0200 operate on the 32-bit registry view - ExecuteKey = ReadKey, - ReadKey = Interop.mincore.RegistryOperations.STANDARD_RIGHTS_READ | QueryValues | EnumerateSubKeys | Notify, - WriteKey = Interop.mincore.RegistryOperations.STANDARD_RIGHTS_WRITE | SetValue | CreateSubKey, - Delete = 0x10000, - ReadPermissions = 0x20000, - ChangePermissions = 0x40000, - TakeOwnership = 0x80000, - FullControl = 0xF003F | Interop.mincore.RegistryOperations.STANDARD_RIGHTS_READ | Interop.mincore.RegistryOperations.STANDARD_RIGHTS_WRITE - } -} diff --git a/external/corert/src/System.Private.CoreLib/src/System/String.CoreRT.cs b/external/corert/src/System.Private.CoreLib/src/System/String.CoreRT.cs index a892006d9c..3aedf2c508 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/String.CoreRT.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/String.CoreRT.cs @@ -16,9 +16,52 @@ using Internal.Runtime.CompilerServices; namespace System { + // STRING LAYOUT + // ------------- + // Strings are null-terminated for easy interop with native, but the value returned by String.Length + // does NOT include this null character in its count. As a result, there's some trickiness here in the + // layout and allocation of strings that needs explanation... + // + // String is allocated like any other array, using the RhNewArray API. It is essentially a very special + // char[] object. In order to be an array, the String EEType must have an 'array element size' of 2, + // which is setup by a special case in the binder. Strings must also have a typical array instance + // layout, which means that the first field after the m_pEEType field is the 'number of array elements' + // field. However, here, it is called _stringLength because it contains the number of characters in the + // string (NOT including the terminating null element) and, thus, directly represents both the array + // length and String.Length. + // + // As with all arrays, the GC calculates the size of an object using the following formula: + // + // obj_size = align(base_size + (num_elements * element_size), sizeof(void*)) + // + // The values 'base_size' and 'element_size' are both stored in the EEType for String and 'num_elements' + // is _stringLength. + // + // Our base_size is the size of the fixed portion of the string defined below. It, therefore, contains + // the size of the _firstChar field in it. This means that, since our string data actually starts + // inside the fixed 'base_size' area, and our num_elements is equal to String.Length, we end up with one + // extra character at the end. This is how we get our extra null terminator which allows us to pass a + // pinned string out to native code as a null-terminated string. This is also why we don't increment the + // requested string length by one before passing it to RhNewArray. There is no need to allocate an extra + // array element, it is already allocated here in the fixed layout of the String. + // + // Typically, the base_size of an array type is aligned up to the nearest pointer size multiple (so that + // array elements start out aligned in case they need alignment themselves), but we don't want to do that + // with String because we are allocating String.Length components with RhNewArray and the overall object + // size will then need another alignment, resulting in wasted space. So the binder specially shrinks the + // base_size of String, leaving it unaligned in order to allow the use of that otherwise wasted space. + // + // One more note on base_size -- on 64-bit, the base_size ends up being 22 bytes, which is less than the + // min_obj_size of (3 * sizeof(void*)). This is OK because our array allocator will still align up the + // overall object size, so a 0-length string will end up with an object size of 24 bytes, which meets the + // min_obj_size requirement. + // + // NOTE: This class is marked EagerStaticClassConstruction because McgCurrentModule class being eagerly + // constructed itself depends on this class also being eagerly constructed. Plus, it's nice to have this + // eagerly constructed to avoid the cost of defered ctors. I can't imagine any app that doesn't use string + // [StructLayout(LayoutKind.Sequential)] [System.Runtime.CompilerServices.EagerStaticClassConstructionAttribute] - [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public partial class String { #if BIT64 @@ -47,11 +90,8 @@ namespace System #pragma warning restore - public static readonly String Empty = ""; + public static readonly string Empty = ""; - // Gets the character at a specified position. - // - // Spec#: Apply the precondition here using a contract assembly. Potential perf issue. [System.Runtime.CompilerServices.IndexerName("Chars")] public unsafe char this[int index] { @@ -72,7 +112,12 @@ namespace System #endif } - internal static String FastAllocateString(int length) + public int Length + { + get { return _stringLength; } + } + + internal static string FastAllocateString(int length) { // We allocate one extra char as an interop convenience so that our strings are null- // terminated, however, we don't pass the extra +1 to the string allocation because the base diff --git a/external/corert/src/System.Private.CoreLib/src/System/Text/EncodingData.cs b/external/corert/src/System.Private.CoreLib/src/System/Text/EncodingData.cs index bff11e7441..852f578dce 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Text/EncodingData.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Text/EncodingData.cs @@ -121,7 +121,7 @@ namespace System.Text // The index of the entry in s_encodingNamesIndices will be the index of codepage in // s_codePagesByName. // - private static readonly UInt16[] s_codePagesByName = new UInt16[] + private static readonly ushort[] s_codePagesByName = new ushort[] { 20127, // ansi_x3.4-1968 20127, // ansi_x3.4-1986 @@ -177,7 +177,7 @@ namespace System.Text // s_englishNames. In addition, this arrays indices correspond to the indices // into s_uiFamilyCodePages and s_flags. // - private static readonly UInt16[] s_mappedCodePages = new UInt16[] + private static readonly ushort[] s_mappedCodePages = new ushort[] { 1200, // utf-16 1201, // utf-16be diff --git a/external/corert/src/System.Private.CoreLib/src/System/Text/StringBuilder.CoreRT.cs b/external/corert/src/System.Private.CoreLib/src/System/Text/StringBuilder.CoreRT.cs index aab4e5d315..9a9516e4f6 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Text/StringBuilder.CoreRT.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Text/StringBuilder.CoreRT.cs @@ -32,7 +32,7 @@ namespace System.Text /// internal unsafe void ReplaceBuffer(char* newBuffer) { - int len = String.wcslen(newBuffer); + int len = string.wcslen(newBuffer); // the '+1' is for back-compat with desktop CLR in terms of length calculation because desktop // CLR had '\0' diff --git a/external/corert/src/System.Private.CoreLib/src/System/Text/StringBuilderCache.cs b/external/corert/src/System.Private.CoreLib/src/System/Text/StringBuilderCache.cs deleted file mode 100644 index a1b1f50e36..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/Text/StringBuilderCache.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** Purpose: provide a cached reusable instance of stringbuilder -** per thread it's an optimisation that reduces the -** number of instances constructed and collected. -** -** Acquire - is used to get a string builder to use of a -** particular size. It can be called any number of -** times, if a stringbuilder is in the cache then -** it will be returned and the cache emptied. -** subsequent calls will return a new stringbuilder. -** -** A StringBuilder instance is cached in -** Thread Local Storage and so there is one per thread -** -** Release - Place the specified builder in the cache if it is -** not too big. -** The stringbuilder should not be used after it has -** been released. -** Unbalanced Releases are perfectly acceptable. It -** will merely cause the runtime to create a new -** stringbuilder next time Acquire is called. -** -** GetStringAndRelease -** - ToString() the stringbuilder, Release it to the -** cache and return the resulting string -** -===========================================================*/ - -using System.Threading; - -namespace System.Text -{ - internal static class StringBuilderCache - { - private const int MAX_BUILDER_SIZE = 260; - - // WARNING: We allow diagnostic tools to directly inspect this member (t_cachedInstance). - // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. - // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. - // Get in touch with the diagnostics team if you have questions. - [ThreadStatic] - private static StringBuilder t_cachedInstance; - - public static StringBuilder Acquire(int capacity = StringBuilder.DefaultCapacity) - { - if (capacity <= MAX_BUILDER_SIZE) - { - StringBuilder sb = StringBuilderCache.t_cachedInstance; - if (sb != null) - { - // Avoid stringbuilder block fragmentation by getting a new StringBuilder - // when the requested size is larger than the current capacity - if (capacity <= sb.Capacity) - { - StringBuilderCache.t_cachedInstance = null; - sb.Clear(); - return sb; - } - } - } - return new StringBuilder(capacity); - } - - public static void Release(StringBuilder sb) - { - if (sb.Capacity <= MAX_BUILDER_SIZE) - { - StringBuilderCache.t_cachedInstance = sb; - } - } - - public static string GetStringAndRelease(StringBuilder sb) - { - string result = sb.ToString(); - Release(sb); - return result; - } - } -} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/CancellationTokenRegistration.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/CancellationTokenRegistration.cs index d7180b16d3..1125b26efa 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/CancellationTokenRegistration.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/CancellationTokenRegistration.cs @@ -37,12 +37,13 @@ namespace System.Threading public CancellationToken Token => m_callbackInfo?.CancellationTokenSource.Token ?? default(CancellationToken); /// - /// Attempts to deregister the item. If it's already being run, this may fail. + /// Attempts to unregister the item. If it's already being run, this may fail. /// Entails a full memory fence. /// - /// True if the callback was found and deregistered, false otherwise. + /// True if the callback was found and unregistered, false otherwise. + // Called from System.Runtime.WindowsRuntime. Also see the proposal at https://github.com/dotnet/corefx/issues/14903. //[FriendAccessAllowed] - internal bool TryDeregister() + public bool Unregister() { if (m_registrationInfo.Source == null) //can be null for dummy registrations. return false; @@ -61,14 +62,14 @@ namespace System.Threading /// /// Disposes of the registration and unregisters the target callback from the associated /// CancellationToken. - /// If the target callback is currently executing this method will wait until it completes, except - /// in the degenerate cases where a callback method deregisters itself. + /// If the target callback is currently executing, this method will wait until it completes, except + /// in the degenerate cases where a callback method unregisters itself. /// public void Dispose() { // Remove the entry from the array. // This call includes a full memory fence which prevents potential reorderings of the reads below - bool deregisterOccured = TryDeregister(); + bool unregisterOccured = Unregister(); // We guarantee that we will not return if the callback is being executed (assuming we are not currently called by the callback itself) // We achieve this by the following rules: @@ -76,8 +77,8 @@ namespace System.Threading // - if the currently executing callback is this CTR, then waiting would deadlock. (We choose to return rather than deadlock) // - if not, then this CTR cannot be the one executing, hence no need to wait // - // 2. if deregistration failed, and we are on a different thread, then the callback may be running under control of cts.Cancel() - // => poll until cts.ExecutingCallback is not the one we are trying to deregister. + // 2. if unregistration failed, and we are on a different thread, then the callback may be running under control of cts.Cancel() + // => poll until cts.ExecutingCallback is not the one we are trying to unregister. var callbackInfo = m_callbackInfo; if (callbackInfo != null) @@ -85,7 +86,7 @@ namespace System.Threading var tokenSource = callbackInfo.CancellationTokenSource; if (tokenSource.IsCancellationRequested && //running callbacks has commenced. !tokenSource.IsCancellationCompleted && //running callbacks hasn't finished - !deregisterOccured && //deregistration failed (ie the callback is missing from the list) + !unregisterOccured && //unregistration failed (ie the callback is missing from the list) tokenSource.ThreadIDExecutingCallbacks != Environment.CurrentManagedThreadId) //the executingThreadID is not this threadID. { // Callback execution is in progress, the executing thread is different to us and has taken the callback for execution diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs index 8e66d5b8b8..9dbc0db084 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs @@ -1,16 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#pragma warning disable 0420 - -// - -//////////////////////////////////////////////////////////////////////////////// using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Private; -using System.Runtime.InteropServices; namespace System.Threading { @@ -34,46 +27,44 @@ namespace System.Threading /// public class CancellationTokenSource : IDisposable { - //static sources that can be used as the backing source for 'fixed' CancellationTokens that never change state. - private static readonly CancellationTokenSource _staticSource_Set = new CancellationTokenSource(true); - private static readonly CancellationTokenSource _staticSource_NotCancelable = new CancellationTokenSource(false); + // static sources that can be used as the backing source for 'fixed' CancellationTokens that never change state. + internal static readonly CancellationTokenSource s_canceledSource = new CancellationTokenSource() { _state = NotifyingCompleteState }; + internal static readonly CancellationTokenSource s_neverCanceledSource = new CancellationTokenSource() { _state = CannotBeCanceled }; - //Note: the callback lists array is only created on first registration. - // the actual callback lists are only created on demand. - // Storing a registered callback costs around >60bytes, hence some overhead for the lists array is OK + // Note: the callback lists array is only created on first registration. + // the actual callback lists are only created on demand. + // Storing a registered callback costs around >60bytes, hence some overhead for the lists array is OK // At most 24 lists seems reasonable, and caps the cost of the listsArray to 96bytes(32-bit,24-way) or 192bytes(64-bit,24-way). private static readonly int s_nLists = (PlatformHelper.ProcessorCount > 24) ? 24 : PlatformHelper.ProcessorCount; - private volatile ManualResetEvent m_kernelEvent; //lazily initialized if required. + private volatile ManualResetEvent _kernelEvent; //lazily initialized if required. - private volatile SparselyPopulatedArray[] m_registeredCallbacksLists; + private volatile SparselyPopulatedArray[] _registeredCallbacksLists; - // legal values for m_state - private const int CANNOT_BE_CANCELED = 0; - private const int NOT_CANCELED = 1; - private const int NOTIFYING = 2; - private const int NOTIFYINGCOMPLETE = 3; + // legal values for _state + private const int CannotBeCanceled = 0; + private const int NotCanceledState = 1; + private const int NotifyingState = 2; + private const int NotifyingCompleteState = 3; - //m_state uses the pattern "volatile int32 reads, with cmpxch writes" which is safe for updates and cannot suffer torn reads. - private volatile int m_state; + //_state uses the pattern "volatile int32 reads, with cmpxch writes" which is safe for updates and cannot suffer torn reads. + private volatile int _state; + /// The ID of the thread currently executing the main body of CTS.Cancel() + /// + /// This helps us to know if a call to ctr.Dispose() is running 'within' a cancellation callback. + /// This is updated as we move between the main thread calling cts.Cancel() and any syncContexts + /// that are used to actually run the callbacks. + /// + private volatile int _threadIDExecutingCallbacks = -1; - /// The ID of the thread currently executing the main body of CTS.Cancel() - /// this helps us to know if a call to ctr.Dispose() is running 'within' a cancellation callback. - /// This is updated as we move between the main thread calling cts.Cancel() and any syncContexts that are used to - /// actually run the callbacks. - private volatile int m_threadIDExecutingCallbacks = -1; - - private bool m_disposed; + private bool _disposed; // we track the running callback to assist ctr.Dispose() to wait for the target callback to complete. - private volatile CancellationCallbackInfo m_executingCallback; + private volatile CancellationCallbackInfo _executingCallback; // provided for CancelAfter and timer-related constructors - private volatile Timer m_timer; - - // ---------------------- - // ** public properties + private volatile Timer _timer; /// /// Gets whether cancellation has been requested for this /// - public bool IsCancellationRequested - { - get { return m_state >= NOTIFYING; } - } + public bool IsCancellationRequested => _state >= NotifyingState; /// /// A simple helper to determine whether cancellation has finished. /// - internal bool IsCancellationCompleted - { - get { return m_state == NOTIFYINGCOMPLETE; } - } + internal bool IsCancellationCompleted => _state == NotifyingCompleteState; /// /// A simple helper to determine whether disposal has occurred. /// - internal bool IsDisposed - { - get { return m_disposed; } - } + internal bool IsDisposed => _disposed; /// /// The ID of the thread that is running callbacks. /// internal int ThreadIDExecutingCallbacks { - set { m_threadIDExecutingCallbacks = value; } - get { return m_threadIDExecutingCallbacks; } + get => _threadIDExecutingCallbacks; + set => _threadIDExecutingCallbacks = value; } /// @@ -141,36 +123,25 @@ namespace System.Threading return new CancellationToken(this); } } - - // ---------------------- - // ** internal and private properties. - - /// - /// - /// internal bool CanBeCanceled { - get { return m_state != CANNOT_BE_CANCELED; } + get { return _state != CannotBeCanceled; } } - - /// - /// - /// internal WaitHandle WaitHandle { get { ThrowIfDisposed(); - // fast path if already allocated. - if (m_kernelEvent != null) - return m_kernelEvent; + // Return the handle if it was already allocated. + if (_kernelEvent != null) + return _kernelEvent; - // lazy-init the mre. + // Lazily-initialize the handle. ManualResetEvent mre = new ManualResetEvent(false); - if (Interlocked.CompareExchange(ref m_kernelEvent, mre, null) != null) + if (Interlocked.CompareExchange(ref _kernelEvent, mre, null) != null) { - ((IDisposable)mre).Dispose(); + mre.Dispose(); } // There is a race condition between checking IsCancellationRequested and setting the event. @@ -178,9 +149,9 @@ namespace System.Threading // 1. if IsCancellationRequested = true, then we will call Set() // 2. if IsCancellationRequested = false, then NotifyCancellation will see that the event exists, and will call Set(). if (IsCancellationRequested) - m_kernelEvent.Set(); + _kernelEvent.Set(); - return m_kernelEvent; + return _kernelEvent; } } @@ -188,10 +159,7 @@ namespace System.Threading /// /// The currently executing callback /// - internal CancellationCallbackInfo ExecutingCallback - { - get { return m_executingCallback; } - } + internal CancellationCallbackInfo ExecutingCallback => _executingCallback; #if DEBUG /// @@ -203,7 +171,7 @@ namespace System.Threading { get { - SparselyPopulatedArray[] callbackLists = m_registeredCallbacksLists; + SparselyPopulatedArray[] callbackLists = _registeredCallbacksLists; if (callbackLists == null) return 0; @@ -228,23 +196,10 @@ namespace System.Threading } #endif - // ** Public Constructors - /// /// Initializes the . /// - public CancellationTokenSource() - { - m_state = NOT_CANCELED; - } - - // ** Private constructors for static sources. - // set=false ==> cannot be canceled. - // set=true ==> is canceled. - private CancellationTokenSource(bool set) - { - m_state = set ? NOTIFYINGCOMPLETE : CANNOT_BE_CANCELED; - } + public CancellationTokenSource() => _state = NotCanceledState; /// /// Constructs a that will be canceled after a specified time span. @@ -268,7 +223,7 @@ namespace System.Threading public CancellationTokenSource(TimeSpan delay) { long totalMilliseconds = (long)delay.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(delay)); } @@ -295,7 +250,7 @@ namespace System.Threading /// canceled already. /// /// - public CancellationTokenSource(Int32 millisecondsDelay) + public CancellationTokenSource(int millisecondsDelay) { if (millisecondsDelay < -1) { @@ -306,14 +261,12 @@ namespace System.Threading } // Common initialization logic when constructing a CTS with a delay parameter - private void InitializeWithTimer(Int32 millisecondsDelay) + private void InitializeWithTimer(int millisecondsDelay) { - m_state = NOT_CANCELED; - m_timer = new Timer(s_timerCallback, this, millisecondsDelay, -1); + _state = NotCanceledState; + _timer = new Timer(s_timerCallback, this, millisecondsDelay, -1); } - // ** Public Methods - /// /// Communicates a request for cancellation. /// @@ -335,10 +288,7 @@ namespace System.Threading /// by the registered callbacks on the associated . /// This has been disposed. - public void Cancel() - { - Cancel(false); - } + public void Cancel() => Cancel(false); /// /// Communicates a request for cancellation. @@ -392,14 +342,13 @@ namespace System.Threading /// /// /// Subsequent calls to CancelAfter will reset the delay for this - /// , if it has not been - /// canceled already. + /// , if it has not been canceled already. /// /// public void CancelAfter(TimeSpan delay) { long totalMilliseconds = (long)delay.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(delay)); } @@ -431,7 +380,7 @@ namespace System.Threading /// canceled already. /// /// - public void CancelAfter(Int32 millisecondsDelay) + public void CancelAfter(int millisecondsDelay) { ThrowIfDisposed(); @@ -440,7 +389,10 @@ namespace System.Threading throw new ArgumentOutOfRangeException(nameof(millisecondsDelay)); } - if (IsCancellationRequested) return; + if (IsCancellationRequested) + { + return; + } // There is a race condition here as a Cancel could occur between the check of // IsCancellationRequested and the creation of the timer. This is benign; in the @@ -451,26 +403,25 @@ namespace System.Threading // expired and Disposed itself). But this would be considered bad behavior, as // Dispose() is not thread-safe and should not be called concurrently with CancelAfter(). - if (m_timer == null) + if (_timer == null) { // Lazily initialize the timer in a thread-safe fashion. // Initially set to "never go off" because we don't want to take a // chance on a timer "losing" the initialization and then // cancelling the token before it (the timer) can be disposed. Timer newTimer = new Timer(s_timerCallback, this, -1, -1); - if (Interlocked.CompareExchange(ref m_timer, newTimer, null) != null) + if (Interlocked.CompareExchange(ref _timer, newTimer, null) != null) { // We did not initialize the timer. Dispose the new timer. newTimer.Dispose(); } } - - // It is possible that m_timer has already been disposed, so we must do + // It is possible that _timer has already been disposed, so we must do // the following in a try/catch block. try { - m_timer.Change(millisecondsDelay, -1); + _timer.Change(millisecondsDelay, -1); } catch (ObjectDisposedException) { @@ -496,7 +447,7 @@ namespace System.Threading // against this race condition. try { - cts.Cancel(); // will take care of disposing of m_timer + cts.Cancel(); // will take care of disposing of _timer } catch (ObjectDisposedException) { @@ -524,11 +475,9 @@ namespace System.Threading /// true to release both managed and unmanaged resources; false to release only unmanaged resources. protected virtual void Dispose(bool disposing) { - // There is nothing to do if disposing=false because the CancellationTokenSource holds no unmanaged resources. - - if (disposing && !m_disposed) + if (disposing && !_disposed) { - //NOTE: We specifically tolerate that a callback can be deregistered + //NOTE: We specifically tolerate that a callback can be unregistered // after the CTS has been disposed and/or concurrently with cts.Dispose(). // This is safe without locks because the reg.Dispose() only // mutates a sparseArrayFragment and then reads from properties of the CTS that are not @@ -536,8 +485,8 @@ namespace System.Threading // // We also tolerate that a callback can be registered after the CTS has been // disposed. This is safe without locks because InternalRegister is tolerant - // of m_registeredCallbacksLists becoming null during its execution. However, - // we run the acceptable risk of m_registeredCallbacksLists getting reinitialized + // of _registeredCallbacksLists becoming null during its execution. However, + // we run the acceptable risk of _registeredCallbacksLists getting reinitialized // to non-null if there is a race between Dispose and Register, in which case this // instance may unnecessarily hold onto a registered callback. But that's no worse // than if Dispose wasn't safe to use concurrently, as Dispose would never be called, @@ -550,57 +499,43 @@ namespace System.Threading // internal source of cancellation, then Disposes of that linked source, which could // happen at the same time the external entity is requesting cancellation). - m_timer?.Dispose(); // Timer.Dispose is thread-safe + _timer?.Dispose(); // Timer.Dispose is thread-safe // registered callbacks are now either complete or will never run, due to guarantees made by ctr.Dispose() // so we can now perform main disposal work without risk of linking callbacks trying to use this CTS. - m_registeredCallbacksLists = null; // free for GC; Cancel correctly handles a null field + _registeredCallbacksLists = null; // free for GC; Cancel correctly handles a null field // If a kernel event was created via WaitHandle, we'd like to Dispose of it. However, // we only want to do so if it's not being used by Cancel concurrently. First, we // interlocked exchange it to be null, and then we check whether cancellation is currently // in progress. NotifyCancellation will only try to set the event if it exists after it's - // transitioned to and while it's in the NOTIFYING state. - if (m_kernelEvent != null) + // transitioned to and while it's in the NotifyingState. + if (_kernelEvent != null) { - ManualResetEvent mre = Interlocked.Exchange(ref m_kernelEvent, null); - if (mre != null && m_state != NOTIFYING) + ManualResetEvent mre = Interlocked.Exchange(ref _kernelEvent, null); + if (mre != null && _state != NotifyingState) { mre.Dispose(); } } - m_disposed = true; + _disposed = true; } } - // -- Internal methods. - /// /// Throws an exception if the source has been disposed. /// internal void ThrowIfDisposed() { - if (m_disposed) + if (_disposed) ThrowObjectDisposedException(); } - // separation enables inlining of ThrowIfDisposed - private static void ThrowObjectDisposedException() - { + /// Throws an . Separated out from ThrowIfDisposed to help with inlining. + private static void ThrowObjectDisposedException() => throw new ObjectDisposedException(null, SR.CancellationTokenSource_Disposed); - } - - /// - /// InternalGetStaticSource() - /// - /// Whether the source should be set. - /// A static source to be shared among multiple tokens. - internal static CancellationTokenSource InternalGetStaticSource(bool set) - { - return set ? _staticSource_Set : _staticSource_NotCancelable; - } /// /// Registers a callback object. If cancellation has already occurred, the @@ -626,11 +561,11 @@ namespace System.Threading // while at the same time not paying any non-negligible overhead. The simple compromise // is to check whether we're disposed (not volatile), and if we see we are, to return an empty // registration, just as if CanBeCanceled was false for the check made in CancellationToken.Register. - // If there's a race and m_disposed is false even though it's been disposed, or if the disposal request - // comes in after this line, we simply run the minor risk of having m_registeredCallbacksLists reinitialized + // If there's a race and _disposed is false even though it's been disposed, or if the disposal request + // comes in after this line, we simply run the minor risk of having _registeredCallbacksLists reinitialized // (after it was cleared to null during Dispose). - if (m_disposed) + if (_disposed) return new CancellationTokenRegistration(); int myIndex = Environment.CurrentManagedThreadId % s_nLists; @@ -640,11 +575,11 @@ namespace System.Threading new CancellationCallbackInfo(callback, stateForCallback, executionContext, this); //allocate the callback list array - var registeredCallbacksLists = m_registeredCallbacksLists; + var registeredCallbacksLists = _registeredCallbacksLists; if (registeredCallbacksLists == null) { SparselyPopulatedArray[] list = new SparselyPopulatedArray[s_nLists]; - registeredCallbacksLists = Interlocked.CompareExchange(ref m_registeredCallbacksLists, list, null); + registeredCallbacksLists = Interlocked.CompareExchange(ref _registeredCallbacksLists, list, null); if (registeredCallbacksLists == null) registeredCallbacksLists = list; } @@ -666,9 +601,9 @@ namespace System.Threading // If a cancellation has since come in, we will try to undo the registration and run the callback ourselves. // (this avoids leaving the callback orphaned) - bool deregisterOccurred = registration.TryDeregister(); + bool unregisterOccurred = registration.Unregister(); - if (!deregisterOccurred) + if (!unregisterOccurred) { // The thread that is running Cancel() snagged our callback for execution. // So we don't need to run it, but we do return the registration so that @@ -682,29 +617,22 @@ namespace System.Threading return new CancellationTokenRegistration(); } - /// - /// - /// private void NotifyCancellation(bool throwOnFirstException) { - // fast-path test to check if Notify has been called previously - if (IsCancellationRequested) - return; - // If we're the first to signal cancellation, do the main extra work. - if (Interlocked.CompareExchange(ref m_state, NOTIFYING, NOT_CANCELED) == NOT_CANCELED) + if (!IsCancellationRequested && Interlocked.CompareExchange(ref _state, NotifyingState, NotCanceledState) == NotCanceledState) { // Dispose of the timer, if any. Dispose may be running concurrently here, but Timer.Dispose is thread-safe. - m_timer?.Dispose(); + _timer?.Dispose(); // Record the threadID being used for running the callbacks. ThreadIDExecutingCallbacks = Environment.CurrentManagedThreadId; // Set the event if it's been lazily initialized and hasn't yet been disposed of. Dispose may - // be running concurrently, in which case either it'll have set m_kernelEvent back to null and + // be running concurrently, in which case either it'll have set _kernelEvent back to null and // we won't see it here, or it'll see that we've transitioned to NOTIFYING and will skip disposing it, // leaving cleanup to finalization. - m_kernelEvent?.Set(); // update the MRE value. + _kernelEvent?.Set(); // update the MRE value. // - late enlisters to the Canceled event will have their callbacks called immediately in the Register() methods. // - Callbacks are not called inside a lock. @@ -729,13 +657,13 @@ namespace System.Threading // Design decision: call the delegates in LIFO order so that callbacks fire 'deepest first'. // This is intended to help with nesting scenarios so that child enlisters cancel before their parents. LowLevelListWithIList exceptionList = null; - SparselyPopulatedArray[] callbackLists = m_registeredCallbacksLists; + SparselyPopulatedArray[] callbackLists = _registeredCallbacksLists; // If there are no callbacks to run, we can safely exit. Any race conditions to lazy initialize it // will see IsCancellationRequested and will then run the callback themselves. if (callbackLists == null) { - Interlocked.Exchange(ref m_state, NOTIFYINGCOMPLETE); + Interlocked.Exchange(ref _state, NotifyingCompleteState); return; } @@ -759,8 +687,8 @@ namespace System.Threading // 3. execute the callback // re:#2 we do the remove on the syncCtx so that we can be sure we have control of the syncCtx before // grabbing the callback. This prevents a deadlock if ctr.Dispose() might run on the syncCtx too. - m_executingCallback = currArrayFragment[i]; - if (m_executingCallback != null) + _executingCallback = currArrayFragment[i]; + if (_executingCallback != null) { //Transition to the target sync context (if necessary), and continue our work there. CancellationCallbackCoreWorkArguments args = new CancellationCallbackCoreWorkArguments(currArrayFragment, i); @@ -769,7 +697,7 @@ namespace System.Threading // We assume that syncCtx.Send() has forwarded on user exceptions when appropriate. try { - var wsc = m_executingCallback as CancellationCallbackInfo.WithSyncContext; + var wsc = _executingCallback as CancellationCallbackInfo.WithSyncContext; if (wsc != null) { Debug.Assert(wsc.TargetSyncContext != null, "Should only have derived CCI if non-null SyncCtx"); @@ -802,14 +730,14 @@ namespace System.Threading } finally { - m_state = NOTIFYINGCOMPLETE; - m_executingCallback = null; + _state = NotifyingCompleteState; + _executingCallback = null; Interlocked.MemoryBarrier(); // for safety, prevent reorderings crossing this point and seeing inconsistent state. } if (exceptionList != null) { - Debug.Assert(exceptionList.Count > 0, "Expected exception count > 0"); + Debug.Assert(exceptionList.Count > 0, $"Expected {exceptionList.Count} > 0"); throw new AggregateException(exceptionList); } } @@ -824,15 +752,14 @@ namespace System.Threading { // remove the intended callback..and ensure that it worked. // otherwise the callback has disappeared in the interim and we can immediately return. - CancellationCallbackInfo callback = args.m_currArrayFragment.SafeAtomicRemove(args.m_currArrayIndex, m_executingCallback); - if (callback == m_executingCallback) + CancellationCallbackInfo callback = args._currArrayFragment.SafeAtomicRemove(args._currArrayIndex, _executingCallback); + if (callback == _executingCallback) { callback.CancellationTokenSource.ThreadIDExecutingCallbacks = Environment.CurrentManagedThreadId; callback.ExecuteCallback(); } } - /// /// Creates a CancellationTokenSource that will be in the canceled state /// when any of the source tokens are in the canceled state. @@ -907,7 +834,7 @@ namespace System.Threading protected override void Dispose(bool disposing) { - if (!disposing || m_disposed) return; + if (!disposing || _disposed) return; _reg1.Dispose(); base.Dispose(disposing); } @@ -926,7 +853,7 @@ namespace System.Threading protected override void Dispose(bool disposing) { - if (!disposing || m_disposed) return; + if (!disposing || _disposed) return; _reg1.Dispose(); _reg2.Dispose(); base.Dispose(disposing); @@ -937,17 +864,17 @@ namespace System.Threading { internal static readonly Action s_linkedTokenCancelDelegate = s => ((CancellationTokenSource)s).NotifyCancellation(throwOnFirstException: false); // skip ThrowIfDisposed() check in Cancel() - private CancellationTokenRegistration[] m_linkingRegistrations; + private CancellationTokenRegistration[] _linkingRegistrations; internal LinkedNCancellationTokenSource(params CancellationToken[] tokens) { - m_linkingRegistrations = new CancellationTokenRegistration[tokens.Length]; + _linkingRegistrations = new CancellationTokenRegistration[tokens.Length]; for (int i = 0; i < tokens.Length; i++) { if (tokens[i].CanBeCanceled) { - m_linkingRegistrations[i] = tokens[i].InternalRegisterWithoutEC(s_linkedTokenCancelDelegate, this); + _linkingRegistrations[i] = tokens[i].InternalRegisterWithoutEC(s_linkedTokenCancelDelegate, this); } // Empty slots in the array will be default(CancellationTokenRegistration), which are nops to Dispose. // Based on usage patterns, such occurrences should also be rare, such that it's not worth resizing @@ -957,13 +884,13 @@ namespace System.Threading protected override void Dispose(bool disposing) { - if (!disposing || m_disposed) + if (!disposing || _disposed) return; - CancellationTokenRegistration[] linkingRegistrations = m_linkingRegistrations; + CancellationTokenRegistration[] linkingRegistrations = _linkingRegistrations; if (linkingRegistrations != null) { - m_linkingRegistrations = null; // release for GC once we're done enumerating + _linkingRegistrations = null; // release for GC once we're done enumerating for (int i = 0; i < linkingRegistrations.Length; i++) { linkingRegistrations[i].Dispose(); @@ -981,13 +908,13 @@ namespace System.Threading // Helper struct for passing data to the target sync context internal struct CancellationCallbackCoreWorkArguments { - internal SparselyPopulatedArrayFragment m_currArrayFragment; - internal int m_currArrayIndex; + internal SparselyPopulatedArrayFragment _currArrayFragment; + internal int _currArrayIndex; public CancellationCallbackCoreWorkArguments(SparselyPopulatedArrayFragment currArrayFragment, int currArrayIndex) { - m_currArrayFragment = currArrayFragment; - m_currArrayIndex = currArrayIndex; + _currArrayFragment = currArrayFragment; + _currArrayIndex = currArrayIndex; } } @@ -1079,8 +1006,8 @@ namespace System.Threading /// The kind of elements contained within. internal class SparselyPopulatedArray where T : class { - private readonly SparselyPopulatedArrayFragment m_head; - private volatile SparselyPopulatedArrayFragment m_tail; + private readonly SparselyPopulatedArrayFragment _head; + private volatile SparselyPopulatedArrayFragment _tail; /// /// Allocates a new array with the given initial size. @@ -1088,7 +1015,7 @@ namespace System.Threading /// How many array slots to pre-allocate. internal SparselyPopulatedArray(int initialSize) { - m_head = m_tail = new SparselyPopulatedArrayFragment(initialSize); + _head = _tail = new SparselyPopulatedArrayFragment(initialSize); } #if DEBUG @@ -1098,7 +1025,7 @@ namespace System.Threading /// internal SparselyPopulatedArrayFragment Head { - get { return m_head; } + get { return _head; } } #endif @@ -1107,7 +1034,7 @@ namespace System.Threading /// internal SparselyPopulatedArrayFragment Tail { - get { return m_tail; } + get { return _tail; } } /// @@ -1115,36 +1042,36 @@ namespace System.Threading /// If no slots are available, the array is grown. The method doesn't return until successful. /// /// The element to add. - /// Information about where the add happened, to enable O(1) deregistration. + /// Information about where the add happened, to enable O(1) unregistration. internal SparselyPopulatedArrayAddInfo Add(T element) { while (true) { // Get the tail, and ensure it's up to date. - SparselyPopulatedArrayFragment tail = m_tail; - while (tail.m_next != null) - m_tail = (tail = tail.m_next); + SparselyPopulatedArrayFragment tail = _tail; + while (tail._next != null) + _tail = (tail = tail._next); // Search for a free index, starting from the tail. SparselyPopulatedArrayFragment curr = tail; while (curr != null) { const int RE_SEARCH_THRESHOLD = -10; // Every 10 skips, force a search. - if (curr.m_freeCount < 1) - --curr.m_freeCount; + if (curr._freeCount < 1) + --curr._freeCount; - if (curr.m_freeCount > 0 || curr.m_freeCount < RE_SEARCH_THRESHOLD) + if (curr._freeCount > 0 || curr._freeCount < RE_SEARCH_THRESHOLD) { int c = curr.Length; // We'll compute a start offset based on how many free slots we think there - // are. This optimizes for ordinary the LIFO deregistration pattern, and is + // are. This optimizes for ordinary the LIFO unregistration pattern, and is // far from perfect due to the non-threadsafe ++ and -- of the free counter. - int start = ((c - curr.m_freeCount) % c); + int start = ((c - curr._freeCount) % c); if (start < 0) { start = 0; - curr.m_freeCount--; // Too many free elements; fix up. + curr._freeCount--; // Too many free elements; fix up. } Debug.Assert(start >= 0 && start < c, "start is outside of bounds"); @@ -1153,29 +1080,29 @@ namespace System.Threading { // If the slot is null, try to CAS our element into it. int tryIndex = (start + i) % c; - Debug.Assert(tryIndex >= 0 && tryIndex < curr.m_elements.Length, "tryIndex is outside of bounds"); + Debug.Assert(tryIndex >= 0 && tryIndex < curr._elements.Length, "tryIndex is outside of bounds"); - if (curr.m_elements[tryIndex] == null && Interlocked.CompareExchange(ref curr.m_elements[tryIndex], element, null) == null) + if (curr._elements[tryIndex] == null && Interlocked.CompareExchange(ref curr._elements[tryIndex], element, null) == null) { // We adjust the free count by --. Note: if this drops to 0, we will skip // the fragment on the next search iteration. Searching threads will -- the // count and force a search every so often, just in case fragmentation occurs. - int newFreeCount = curr.m_freeCount - 1; - curr.m_freeCount = newFreeCount > 0 ? newFreeCount : 0; + int newFreeCount = curr._freeCount - 1; + curr._freeCount = newFreeCount > 0 ? newFreeCount : 0; return new SparselyPopulatedArrayAddInfo(curr, tryIndex); } } } - curr = curr.m_prev; + curr = curr._prev; } // If we got here, we need to add a new chunk to the tail and try again. SparselyPopulatedArrayFragment newTail = new SparselyPopulatedArrayFragment( - tail.m_elements.Length == 4096 ? 4096 : tail.m_elements.Length * 2, tail); - if (Interlocked.CompareExchange(ref tail.m_next, newTail, null) == null) + tail._elements.Length == 4096 ? 4096 : tail._elements.Length * 2, tail); + if (Interlocked.CompareExchange(ref tail._next, newTail, null) == null) { - m_tail = newTail; + _tail = newTail; } } } @@ -1187,25 +1114,25 @@ namespace System.Threading /// internal struct SparselyPopulatedArrayAddInfo where T : class { - private SparselyPopulatedArrayFragment m_source; - private int m_index; + private SparselyPopulatedArrayFragment _source; + private int _index; internal SparselyPopulatedArrayAddInfo(SparselyPopulatedArrayFragment source, int index) { Debug.Assert(source != null); Debug.Assert(index >= 0 && index < source.Length); - m_source = source; - m_index = index; + _source = source; + _index = index; } internal SparselyPopulatedArrayFragment Source { - get { return m_source; } + get { return _source; } } internal int Index { - get { return m_index; } + get { return _index; } } } @@ -1215,10 +1142,10 @@ namespace System.Threading /// The kind of elements contained within. internal class SparselyPopulatedArrayFragment where T : class { - internal readonly T[] m_elements; // The contents, sparsely populated (with nulls). - internal volatile int m_freeCount; // A hint of the number of free elements. - internal volatile SparselyPopulatedArrayFragment m_next; // The next fragment in the chain. - internal volatile SparselyPopulatedArrayFragment m_prev; // The previous fragment in the chain. + internal readonly T[] _elements; // The contents, sparsely populated (with nulls). + internal volatile int _freeCount; // A hint of the number of free elements. + internal volatile SparselyPopulatedArrayFragment _next; // The next fragment in the chain. + internal volatile SparselyPopulatedArrayFragment _prev; // The previous fragment in the chain. internal SparselyPopulatedArrayFragment(int size) : this(size, null) { @@ -1226,31 +1153,31 @@ namespace System.Threading internal SparselyPopulatedArrayFragment(int size, SparselyPopulatedArrayFragment prev) { - m_elements = new T[size]; - m_freeCount = size; - m_prev = prev; + _elements = new T[size]; + _freeCount = size; + _prev = prev; } internal T this[int index] { - get { return Volatile.Read(ref m_elements[index]); } + get { return Volatile.Read(ref _elements[index]); } } internal int Length { - get { return m_elements.Length; } + get { return _elements.Length; } } #if DEBUG // Used in DEBUG mode by CancellationTokenSource.CallbackCount internal SparselyPopulatedArrayFragment Next { - get { return m_next; } + get { return _next; } } #endif internal SparselyPopulatedArrayFragment Prev { - get { return m_prev; } + get { return _prev; } } // only removes the item at the specified index if it is still the expected one. @@ -1259,9 +1186,9 @@ namespace System.Threading // otherwise the remove did not occur. internal T SafeAtomicRemove(int index, T expectedElement) { - T prevailingValue = Interlocked.CompareExchange(ref m_elements[index], null, expectedElement); + T prevailingValue = Interlocked.CompareExchange(ref _elements[index], null, expectedElement); if (prevailingValue != null) - ++m_freeCount; + ++_freeCount; return prevailingValue; } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/ClrThreadPool.CpuUtilizationReader.Windows.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/ClrThreadPool.CpuUtilizationReader.Windows.cs index b7d7f8ae45..915f111063 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/ClrThreadPool.CpuUtilizationReader.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/ClrThreadPool.CpuUtilizationReader.Windows.cs @@ -28,7 +28,7 @@ namespace System.Threading { int error = Marshal.GetLastWin32Error(); var exception = new OutOfMemoryException(); - exception.SetErrorCode(error); + exception.HResult = error; throw exception; } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.cs index 04e124cc0a..5f1aeb3e40 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.cs @@ -2,23 +2,19 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using Microsoft.Win32.SafeHandles; using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; namespace System.Threading { public partial class EventWaitHandle { - private static void VerifyNameForCreate(string name) - { - if (name != null) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); - } - } - private void CreateEventCore(bool initialState, EventResetMode mode, string name, out bool createdNew) { - Debug.Assert(name == null); + if (name != null) + throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); SafeWaitHandle = WaitSubsystem.NewEvent(initialState, mode); createdNew = true; @@ -29,16 +25,46 @@ namespace System.Threading throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); } - private static bool ResetCore(IntPtr handle) + public bool Reset() { - WaitSubsystem.ResetEvent(handle); - return true; + SafeWaitHandle waitHandle = ValidateHandle(); + try + { + WaitSubsystem.ResetEvent(waitHandle.DangerousGetHandle()); + return true; + } + finally + { + waitHandle.DangerousRelease(); + } } - private static bool SetCore(IntPtr handle) + public bool Set() { - WaitSubsystem.SetEvent(handle); - return true; + SafeWaitHandle waitHandle = ValidateHandle(); + try + { + WaitSubsystem.SetEvent(waitHandle.DangerousGetHandle()); + return true; + } + finally + { + waitHandle.DangerousRelease(); + } + } + + private SafeWaitHandle ValidateHandle() + { + // The field value is modifiable via the public property, save it locally + // to ensure that one instance is used in all places in this method + SafeWaitHandle waitHandle = _waitHandle; + if (waitHandle == null) + { + ThrowInvalidHandleException(); + } + + waitHandle.DangerousAddRef(); + return waitHandle; } } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Windows.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Windows.cs deleted file mode 100644 index 2800fc9518..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Windows.cs +++ /dev/null @@ -1,116 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -namespace System.Threading -{ - public partial class EventWaitHandle - { - private const uint AccessRights = (uint)(Interop.Constants.MaximumAllowed | Interop.Constants.Synchronize | Interop.Constants.EventModifyState); - - private EventWaitHandle(SafeWaitHandle handle) - { - SafeWaitHandle = handle; - } - - private static void VerifyNameForCreate(string name) - { - if (null != name && Interop.Kernel32.MAX_PATH < name.Length) - { - throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Interop.Kernel32.MAX_PATH), nameof(name)); - } - } - - private void CreateEventCore(bool initialState, EventResetMode mode, string name, out bool createdNew) - { - Debug.Assert((mode == EventResetMode.AutoReset) || (mode == EventResetMode.ManualReset)); - Debug.Assert(name == null || name.Length <= Interop.Kernel32.MAX_PATH); - - uint eventFlags = initialState ? (uint)Interop.Constants.CreateEventInitialSet : 0; - if (mode == EventResetMode.ManualReset) - { - eventFlags |= (uint)Interop.Constants.CreateEventManualReset; - } - - SafeWaitHandle _handle = Interop.mincore.CreateEventEx(IntPtr.Zero, name, eventFlags, AccessRights); - - if (_handle.IsInvalid) - { - int errorCode = Marshal.GetLastWin32Error(); - _handle.SetHandleAsInvalid(); - if (null != name && 0 != name.Length && Interop.Errors.ERROR_INVALID_HANDLE == errorCode) - throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); - throw ExceptionFromCreationError(errorCode, name); - } - else if (name != null) - { - int errorCode = Marshal.GetLastWin32Error(); - createdNew = errorCode != Interop.Errors.ERROR_ALREADY_EXISTS; - } - else - { - createdNew = true; - } - - SafeWaitHandle = _handle; - } - - private static OpenExistingResult OpenExistingWorker(string name, out EventWaitHandle result) - { - if (name == null) - { - throw new ArgumentNullException(nameof(name), SR.ArgumentNull_WithParamName); - } - - if (name.Length == 0) - { - throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); - } - - if (null != name && Interop.Kernel32.MAX_PATH < name.Length) - { - throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Interop.Kernel32.MAX_PATH), nameof(name)); - } - - result = null; - - SafeWaitHandle myHandle = Interop.mincore.OpenEvent(AccessRights, false, name); - - if (myHandle.IsInvalid) - { - int errorCode = Marshal.GetLastWin32Error(); - - if (Interop.Errors.ERROR_FILE_NOT_FOUND == errorCode || Interop.Errors.ERROR_INVALID_NAME == errorCode) - return OpenExistingResult.NameNotFound; - if (Interop.Errors.ERROR_PATH_NOT_FOUND == errorCode) - return OpenExistingResult.PathNotFound; - if (null != name && 0 != name.Length && Interop.Errors.ERROR_INVALID_HANDLE == errorCode) - return OpenExistingResult.NameInvalid; - - throw ExceptionFromCreationError(errorCode, name); - } - result = new EventWaitHandle(myHandle); - return OpenExistingResult.Success; - } - - private static bool ResetCore(IntPtr handle) - { - bool res = Interop.mincore.ResetEvent(handle); - if (!res) - ThrowSignalOrUnsignalException(); - return res; - } - - private static bool SetCore(IntPtr handle) - { - bool res = Interop.mincore.SetEvent(handle); - if (!res) - ThrowSignalOrUnsignalException(); - return res; - } - } -} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.cs deleted file mode 100644 index 04026d587c..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.cs +++ /dev/null @@ -1,130 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// - -/*============================================================================= -** -** -** -** Purpose: Base class for representing Events -** -** -=============================================================================*/ - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; -using System.IO; -using System.Diagnostics; - -namespace System.Threading -{ - public partial class EventWaitHandle : WaitHandle - { - public EventWaitHandle(bool initialState, EventResetMode mode) - { - VerifyMode(mode); - - bool createdNew; - CreateEventCore(initialState, mode, null, out createdNew); - } - - public EventWaitHandle(bool initialState, EventResetMode mode, string name) - { - VerifyNameForCreate(name); - VerifyMode(mode); - - bool createdNew; - CreateEventCore(initialState, mode, name, out createdNew); - } - - public EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew) - { - VerifyNameForCreate(name); - VerifyMode(mode); - - CreateEventCore(initialState, mode, name, out createdNew); - } - - private static void VerifyMode(EventResetMode mode) - { - if (mode != EventResetMode.AutoReset && mode != EventResetMode.ManualReset) - { - throw new ArgumentException(SR.Argument_InvalidFlag, nameof(mode)); - } - } - - public static EventWaitHandle OpenExisting(string name) - { - EventWaitHandle result; - switch (OpenExistingWorker(name, out result)) - { - case OpenExistingResult.NameNotFound: - throw new WaitHandleCannotBeOpenedException(); - - case OpenExistingResult.NameInvalid: - throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); - - case OpenExistingResult.PathNotFound: - throw new IOException(SR.Format(SR.IO_PathNotFound_Path, name)); - - default: - return result; - } - } - - public static bool TryOpenExisting(string name, out EventWaitHandle result) - { - return OpenExistingWorker(name, out result) == OpenExistingResult.Success; - } - - public bool Reset() - { - // The field value is modifiable via , save it locally to ensure that ref modification - // is done on the same instance - SafeWaitHandle waitHandle = _waitHandle; - if (waitHandle == null) - { - ThrowInvalidHandleException(); - } - - waitHandle.DangerousAddRef(); - try - { - return ResetCore(_waitHandle.DangerousGetHandle()); - } - finally - { - waitHandle.DangerousRelease(); - } - } - - public bool Set() - { - // The field value is modifiable via the public property, save it locally - // to ensure that one instance is used in all places in this method - SafeWaitHandle waitHandle = _waitHandle; - if (waitHandle == null) - { - ThrowInvalidHandleException(); - } - - waitHandle.DangerousAddRef(); - try - { - return SetCore(waitHandle.DangerousGetHandle()); - } - finally - { - waitHandle.DangerousRelease(); - } - } - - internal static bool Set(IntPtr handle) - { - return SetCore(handle); - } - } -} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Interlocked.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Interlocked.cs index e07fbf97ba..c3917e8735 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Interlocked.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Interlocked.cs @@ -322,7 +322,7 @@ namespace System.Threading [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T CompareExchange(ref T location1, T value, T comparand) where T : class { - return Unsafe.As(RuntimeImports.InterlockedCompareExchange(ref Unsafe.As(ref location1), value, comparand)); + return Unsafe.As(RuntimeImports.InterlockedCompareExchange(ref Unsafe.As(ref location1), value, comparand)); } [Intrinsic] @@ -394,7 +394,7 @@ namespace System.Threading [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T Exchange(ref T location1, T value) where T : class { - return Unsafe.As(RuntimeImports.InterlockedExchange(ref Unsafe.As(ref location1), value)); + return Unsafe.As(RuntimeImports.InterlockedExchange(ref Unsafe.As(ref location1), value)); } [Intrinsic] diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/LowLevelLifoSemaphore.Windows.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/LowLevelLifoSemaphore.Windows.cs index 88ca534200..38ed1d5549 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/LowLevelLifoSemaphore.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/LowLevelLifoSemaphore.Windows.cs @@ -27,7 +27,7 @@ namespace System.Threading { var error = Marshal.GetLastWin32Error(); var exception = new OutOfMemoryException(); - exception.SetErrorCode(error); + exception.HResult = error; throw exception; } Release(initialSignalCount); @@ -48,7 +48,7 @@ namespace System.Threading { var lastError = Marshal.GetLastWin32Error(); var exception = new OutOfMemoryException(); - exception.SetErrorCode(lastError); + exception.HResult = lastError; throw exception; } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.Windows.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.Windows.cs index 602908d6d2..a492e3acbd 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.Windows.cs @@ -51,7 +51,7 @@ namespace System.Threading if (lastError != Interop.Errors.ERROR_TIMEOUT) { var exception = new OutOfMemoryException(); - exception.SetErrorCode(lastError); + exception.HResult = lastError; throw exception; } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/ManagedThreadId.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/ManagedThreadId.cs index 370aeca095..8bbb8ba259 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/ManagedThreadId.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/ManagedThreadId.cs @@ -103,7 +103,7 @@ namespace System.Threading var right = _right; // Any free bits in current node? - if (bitmap != UInt32.MaxValue) + if (bitmap != uint.MaxValue) { int bit = 0; while ((bitmap & (uint)(1 << bit)) != 0) @@ -218,7 +218,7 @@ namespace System.Threading { var updatedIdDispenser = priorIdDispenser.AllocateId(out id); var interlockedResult = Interlocked.CompareExchange(ref s_idDispenser, updatedIdDispenser, priorIdDispenser); - if (Object.ReferenceEquals(priorIdDispenser, interlockedResult)) + if (object.ReferenceEquals(priorIdDispenser, interlockedResult)) break; priorIdDispenser = interlockedResult; // we already have a volatile read that we can reuse for the next loop } @@ -240,7 +240,7 @@ namespace System.Threading { var updatedIdDispenser = s_idDispenser.RecycleId(id); var interlockedResult = Interlocked.CompareExchange(ref s_idDispenser, updatedIdDispenser, priorIdDispenser); - if (Object.ReferenceEquals(priorIdDispenser, interlockedResult)) + if (object.ReferenceEquals(priorIdDispenser, interlockedResult)) break; priorIdDispenser = interlockedResult; // we already have a volatile read that we can reuse for the next loop } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs index a674901ea4..faa5f2482a 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs @@ -57,7 +57,7 @@ namespace System.Threading // -- State -- // //For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant. - private volatile int m_combinedState; //ie a UInt32. Used for the state items listed below. + private volatile int m_combinedState; //ie a uint. Used for the state items listed below. //1-bit for signalled state private const int SignalledState_BitMask = unchecked((int)0x80000000);//1000 0000 0000 0000 0000 0000 0000 0000 @@ -163,7 +163,7 @@ namespace System.Threading // it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here. if (value >= NumWaitersState_MaxValue) - throw new InvalidOperationException(String.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue)); + throw new InvalidOperationException(string.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue)); UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask); } @@ -185,7 +185,7 @@ namespace System.Threading /// /// Initializes a new instance of the - /// class with a Boolen value indicating whether to set the intial state to signaled. + /// class with a Boolean value indicating whether to set the intial state to signaled. /// /// true to set the initial state signaled; false to set the initial state /// to nonsignaled. @@ -218,7 +218,7 @@ namespace System.Threading { throw new ArgumentOutOfRangeException( nameof(spinCount), - String.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue)); + string.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue)); } // We will suppress default spin because the user specified a count. @@ -611,7 +611,7 @@ namespace System.Threading // Now enter the lock and wait. EnsureLockObjectCreated(); - // We must register and deregister the token outside of the lock, to avoid deadlocks. + // We must register and unregister the token outside of the lock, to avoid deadlocks. using (cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCallback, this)) { using (LockHolder.Hold(m_lock)) @@ -665,7 +665,7 @@ namespace System.Threading } } } - } // automatically disposes (and deregisters) the callback + } // automatically disposes (and unregisters) the callback return true; //done. The wait was satisfied. } @@ -690,7 +690,7 @@ namespace System.Threading /// true to release both managed and unmanaged resources; /// false to release only unmanaged resources. /// - /// Unlike most of the members of , is not + /// Unlike most of the members of , is not /// thread-safe and may not be used concurrently with other members of this instance. /// protected virtual void Dispose(bool disposing) diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Monitor.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Monitor.cs index e825d625bb..b9839321a5 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Monitor.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Monitor.cs @@ -32,7 +32,7 @@ namespace System.Threading private static ConditionalWeakTable s_conditionTable = new ConditionalWeakTable(); private static ConditionalWeakTable.CreateValueCallback s_createCondition = (o) => new Condition(GetLock(o)); - internal static Lock GetLock(Object obj) + internal static Lock GetLock(object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); @@ -47,7 +47,7 @@ namespace System.Threading #endif } - private static Condition GetCondition(Object obj) + private static Condition GetCondition(object obj) { Debug.Assert( !(obj is Condition || obj is Lock), @@ -58,7 +58,7 @@ namespace System.Threading #region Public Enter/Exit methods - public static void Enter(Object obj) + public static void Enter(object obj) { Lock lck = GetLock(obj); if (lck.TryAcquire(0)) @@ -66,7 +66,7 @@ namespace System.Threading TryAcquireContended(lck, obj, Timeout.Infinite); } - public static void Enter(Object obj, ref bool lockTaken) + public static void Enter(object obj, ref bool lockTaken) { if (lockTaken) throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken)); @@ -81,12 +81,12 @@ namespace System.Threading lockTaken = true; } - public static bool TryEnter(Object obj) + public static bool TryEnter(object obj) { return GetLock(obj).TryAcquire(0); } - public static void TryEnter(Object obj, ref bool lockTaken) + public static void TryEnter(object obj, ref bool lockTaken) { if (lockTaken) throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken)); @@ -94,7 +94,7 @@ namespace System.Threading lockTaken = GetLock(obj).TryAcquire(0); } - public static bool TryEnter(Object obj, int millisecondsTimeout) + public static bool TryEnter(object obj, int millisecondsTimeout) { if (millisecondsTimeout < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); @@ -105,7 +105,7 @@ namespace System.Threading return TryAcquireContended(lck, obj, millisecondsTimeout); } - public static void TryEnter(Object obj, int millisecondsTimeout, ref bool lockTaken) + public static void TryEnter(object obj, int millisecondsTimeout, ref bool lockTaken) { if (lockTaken) throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken)); @@ -121,18 +121,18 @@ namespace System.Threading lockTaken = TryAcquireContended(lck, obj, millisecondsTimeout); } - public static bool TryEnter(Object obj, TimeSpan timeout) => + public static bool TryEnter(object obj, TimeSpan timeout) => TryEnter(obj, WaitHandle.ToTimeoutMilliseconds(timeout)); - public static void TryEnter(Object obj, TimeSpan timeout, ref bool lockTaken) => + public static void TryEnter(object obj, TimeSpan timeout, ref bool lockTaken) => TryEnter(obj, WaitHandle.ToTimeoutMilliseconds(timeout), ref lockTaken); - public static void Exit(Object obj) + public static void Exit(object obj) { GetLock(obj).Release(); } - public static bool IsEntered(Object obj) + public static bool IsEntered(object obj) { return GetLock(obj).IsAcquired; } @@ -142,14 +142,14 @@ namespace System.Threading #region Public Wait/Pulse methods // Remoting is not supported, ignore exitContext - public static bool Wait(Object obj, int millisecondsTimeout, bool exitContext) => + public static bool Wait(object obj, int millisecondsTimeout, bool exitContext) => Wait(obj, millisecondsTimeout); // Remoting is not supported, ignore exitContext - public static bool Wait(Object obj, TimeSpan timeout, bool exitContext) => + public static bool Wait(object obj, TimeSpan timeout, bool exitContext) => Wait(obj, WaitHandle.ToTimeoutMilliseconds(timeout)); - public static bool Wait(Object obj, int millisecondsTimeout) + public static bool Wait(object obj, int millisecondsTimeout) { Condition condition = GetCondition(obj); DebugBlockingItem blockingItem; @@ -160,9 +160,9 @@ namespace System.Threading } } - public static bool Wait(Object obj, TimeSpan timeout) => Wait(obj, WaitHandle.ToTimeoutMilliseconds(timeout)); + public static bool Wait(object obj, TimeSpan timeout) => Wait(obj, WaitHandle.ToTimeoutMilliseconds(timeout)); - public static bool Wait(Object obj) => Wait(obj, Timeout.Infinite); + public static bool Wait(object obj) => Wait(obj, Timeout.Infinite); public static void Pulse(object obj) { @@ -178,7 +178,7 @@ namespace System.Threading #region Slow path for Entry/TryEnter methods. - internal static bool TryAcquireContended(Lock lck, Object obj, int millisecondsTimeout) + internal static bool TryAcquireContended(Lock lck, object obj, int millisecondsTimeout) { DebugBlockingItem blockingItem; diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Mutex.Unix.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Mutex.Unix.cs index 46a996348d..004e952873 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Mutex.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Mutex.Unix.cs @@ -2,24 +2,21 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.IO; +using System.Runtime.InteropServices; namespace System.Threading { public sealed partial class Mutex { - private static void VerifyNameForCreate(string name) + private void CreateMutexCore(bool initiallyOwned, string name, out bool createdNew) { if (name != null) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); } - } - - private void CreateMutexCore(bool initiallyOwned, string name, out bool createdNew) - { - Debug.Assert(name == null); SafeWaitHandle = WaitSubsystem.NewMutex(initiallyOwned); createdNew = true; @@ -30,9 +27,25 @@ namespace System.Threading throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); } - private static void ReleaseMutexCore(IntPtr handle) + public void ReleaseMutex() { - WaitSubsystem.ReleaseMutex(handle); + // The field value is modifiable via the public property, save it locally + // to ensure that one instance is used in all places in this method + SafeWaitHandle waitHandle = _waitHandle; + if (waitHandle == null) + { + ThrowInvalidHandleException(); + } + + waitHandle.DangerousAddRef(); + try + { + WaitSubsystem.ReleaseMutex(waitHandle.DangerousGetHandle()); + } + finally + { + waitHandle.DangerousRelease(); + } } } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Mutex.Windows.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Mutex.Windows.cs deleted file mode 100644 index ba5e863043..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Mutex.Windows.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -namespace System.Threading -{ - public sealed partial class Mutex - { - private const uint AccessRights = (uint)(Interop.Constants.MaximumAllowed | Interop.Constants.Synchronize | Interop.Constants.MutexModifyState); - - private static void VerifyNameForCreate(string name) - { - if (null != name && Interop.Kernel32.MAX_PATH < name.Length) - { - throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Interop.Kernel32.MAX_PATH), nameof(name)); - } - } - - private void CreateMutexCore(bool initiallyOwned, string name, out bool createdNew) - { - Debug.Assert(name == null || name.Length <= Interop.Kernel32.MAX_PATH); - - uint mutexFlags = initiallyOwned ? (uint)Interop.Constants.CreateMutexInitialOwner : 0; - - SafeWaitHandle mutexHandle = Interop.mincore.CreateMutexEx(IntPtr.Zero, name, mutexFlags, AccessRights); - int errorCode = Marshal.GetLastWin32Error(); - - if (mutexHandle.IsInvalid) - { - mutexHandle.SetHandleAsInvalid(); - if (null != name && 0 != name.Length && Interop.Errors.ERROR_INVALID_HANDLE == errorCode) - throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); - throw ExceptionFromCreationError(errorCode, name); - } - - createdNew = errorCode != Interop.Errors.ERROR_ALREADY_EXISTS; - SafeWaitHandle = mutexHandle; - } - - private static OpenExistingResult OpenExistingWorker(string name, out Mutex result) - { - if (name == null) - { - throw new ArgumentNullException(nameof(name), SR.ArgumentNull_WithParamName); - } - - if (name.Length == 0) - { - throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); - } - if (Interop.Kernel32.MAX_PATH < (uint)name.Length) - { - throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Interop.Kernel32.MAX_PATH), nameof(name)); - } - - result = null; - - SafeWaitHandle myHandle = Interop.mincore.OpenMutex(AccessRights, false, name); - - int errorCode = 0; - if (myHandle.IsInvalid) - { - errorCode = Marshal.GetLastWin32Error(); - - if (Interop.Errors.ERROR_FILE_NOT_FOUND == errorCode || Interop.Errors.ERROR_INVALID_NAME == errorCode) - return OpenExistingResult.NameNotFound; - if (Interop.Errors.ERROR_PATH_NOT_FOUND == errorCode) - return OpenExistingResult.PathNotFound; - if (null != name && 0 != name.Length && Interop.Errors.ERROR_INVALID_HANDLE == errorCode) - return OpenExistingResult.NameInvalid; - - throw ExceptionFromCreationError(errorCode, name); - } - - result = new Mutex(myHandle); - return OpenExistingResult.Success; - } - - private static void ReleaseMutexCore(IntPtr handle) - { - if (!Interop.mincore.ReleaseMutex(handle)) - { - ThrowSignalOrUnsignalException(); - } - } - } -} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Mutex.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Mutex.cs deleted file mode 100644 index 6db36cb59b..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Mutex.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================================= -** -** -** -** Purpose: synchronization primitive that can also be used for interprocess synchronization -** -** -=============================================================================*/ - -using System; -using System.Threading; -using System.Runtime.CompilerServices; -using System.IO; -using Microsoft.Win32; -using Microsoft.Win32.SafeHandles; -using System.Runtime.InteropServices; -using System.Runtime.Versioning; -using System.Security; - -namespace System.Threading -{ - public sealed partial class Mutex : WaitHandle - { - public Mutex(bool initiallyOwned, string name, out bool createdNew) - { - VerifyNameForCreate(name); - - CreateMutexCore(initiallyOwned, name, out createdNew); - } - - public Mutex(bool initiallyOwned, string name) - { - VerifyNameForCreate(name); - - bool createdNew; - CreateMutexCore(initiallyOwned, name, out createdNew); - } - - public Mutex(bool initiallyOwned) - { - bool createdNew; - CreateMutexCore(initiallyOwned, null, out createdNew); - } - - public Mutex() - { - bool createdNew; - CreateMutexCore(false, null, out createdNew); - } - - private Mutex(SafeWaitHandle handle) - { - SafeWaitHandle = handle; - } - - public static Mutex OpenExisting(string name) - { - Mutex result; - switch (OpenExistingWorker(name, out result)) - { - case OpenExistingResult.NameNotFound: - throw new WaitHandleCannotBeOpenedException(); - - case OpenExistingResult.NameInvalid: - throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); - - case OpenExistingResult.PathNotFound: - throw new IOException(SR.Format(SR.IO_PathNotFound_Path, name)); - - default: - return result; - } - } - - public static bool TryOpenExisting(string name, out Mutex result) => - OpenExistingWorker(name, out result) == OpenExistingResult.Success; - - public void ReleaseMutex() - { - // The field value is modifiable via the public property, save it locally - // to ensure that one instance is used in all places in this method - SafeWaitHandle waitHandle = _waitHandle; - if (waitHandle == null) - { - ThrowInvalidHandleException(); - } - - waitHandle.DangerousAddRef(); - try - { - ReleaseMutexCore(waitHandle.DangerousGetHandle()); - } - finally - { - waitHandle.DangerousRelease(); - } - } - } -} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Overlapped.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Overlapped.cs index 787436965f..0a1c2ce727 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Overlapped.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Overlapped.cs @@ -19,73 +19,63 @@ ** =============================================================================*/ +using System.Diagnostics; using System.Runtime; using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; -using System.Runtime.Versioning; -using System.Security; -using System.Runtime.ConstrainedExecution; -using System.Diagnostics; -using System.Collections.Concurrent; - using Internal.Runtime.CompilerServices; namespace System.Threading { #region class _IOCompletionCallback - internal class _IOCompletionCallback + internal unsafe class _IOCompletionCallback { private IOCompletionCallback _ioCompletionCallback; private ExecutionContext _executionContext; private uint _errorCode; // Error code private uint _numBytes; // No. of bytes transferred - private unsafe NativeOverlapped* _pOVERLAP; + private NativeOverlapped* _pNativeOverlapped; - internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback) + internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback, ExecutionContext executionContext) { _ioCompletionCallback = ioCompletionCallback; - _executionContext = ExecutionContext.Capture(); + _executionContext = executionContext; } - private static ContextCallback s_ccb = new ContextCallback(IOCompletionCallback_Context); - - private static unsafe void IOCompletionCallback_Context(Object state) + // Context callback: same sig for SendOrPostCallback and ContextCallback + internal static ContextCallback s_ccb = new ContextCallback(IOCompletionCallback_Context); + private static void IOCompletionCallback_Context(object state) { _IOCompletionCallback helper = (_IOCompletionCallback)state; Debug.Assert(helper != null, "_IOCompletionCallback cannot be null"); - helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pOVERLAP); + helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pNativeOverlapped); } - internal static unsafe void PerformIOCompletionCallback(uint errorCode, uint numBytes, NativeOverlapped* pOVERLAP) + internal static unsafe void PerformIOCompletionCallback(uint errorCode, uint numBytes, NativeOverlapped* pNativeOverlapped) { - Overlapped overlapped; - _IOCompletionCallback helper; - do { - overlapped = OverlappedData.GetOverlappedFromNative(pOVERLAP).m_overlapped; - helper = overlapped.iocbHelper; + OverlappedData overlapped = OverlappedData.GetOverlappedFromNative(pNativeOverlapped); - if (helper == null || helper._executionContext == null || helper._executionContext == ExecutionContext.Default) + if (overlapped._callback is IOCompletionCallback iocb) { - // We got here because of UnsafePack (or) Pack with EC flow supressed - IOCompletionCallback callback = overlapped.UserCallback; - callback(errorCode, numBytes, pOVERLAP); + // We got here because of UnsafePack (or) Pack with EC flow suppressed + iocb(errorCode, numBytes, pNativeOverlapped); } else { // We got here because of Pack + var helper = (_IOCompletionCallback)overlapped._callback; helper._errorCode = errorCode; helper._numBytes = numBytes; - helper._pOVERLAP = pOVERLAP; + helper._pNativeOverlapped = pNativeOverlapped; ExecutionContext.Run(helper._executionContext, s_ccb, helper); } //Quickly check the VM again, to see if a packet has arrived. //OverlappedData.CheckVMForIOPacket(out pOVERLAP, out errorCode, out numBytes); - pOVERLAP = null; - } while (pOVERLAP != null); + pNativeOverlapped = null; + } while (pNativeOverlapped != null); } } @@ -93,115 +83,100 @@ namespace System.Threading #region class OverlappedData - internal sealed class OverlappedData + internal unsafe sealed class OverlappedData { - // The offset of m_nativeOverlapped field from m_pEEType - private static int s_nativeOverlappedOffset; + internal IAsyncResult _asyncResult; + internal object _callback; // IOCompletionCallback or _IOCompletionCallback + internal Overlapped _overlapped; + private object _userObject; + private NativeOverlapped * _pNativeOverlapped; + private IntPtr _eventHandle; + private int _offsetLow; + private int _offsetHigh; + private GCHandle[] _pinnedData; - internal IAsyncResult m_asyncResult; - internal IOCompletionCallback m_iocb; - internal _IOCompletionCallback m_iocbHelper; - internal Overlapped m_overlapped; - private Object m_userObject; - private IntPtr m_pinSelf; - private GCHandle[] m_pinnedData; - internal NativeOverlapped m_nativeOverlapped; + internal ref IAsyncResult AsyncResult => ref _asyncResult; - // Adding an empty default ctor for annotation purposes - internal OverlappedData() { } + internal ref int OffsetLow => ref (_pNativeOverlapped != null) ? ref _pNativeOverlapped->OffsetLow : ref _offsetLow; + internal ref int OffsetHigh => ref (_pNativeOverlapped != null) ? ref _pNativeOverlapped->OffsetHigh : ref _offsetHigh; + internal ref IntPtr EventHandle => ref (_pNativeOverlapped != null) ? ref _pNativeOverlapped->EventHandle : ref _eventHandle; - ~OverlappedData() + internal unsafe NativeOverlapped* Pack(IOCompletionCallback iocb, object userData) { - if (m_pinnedData != null) - { - for (int i = 0; i < m_pinnedData.Length; i++) - { - if (m_pinnedData[i].IsAllocated) - { - m_pinnedData[i].Free(); - } - } - } - } - - internal void ReInitialize() - { - m_asyncResult = null; - m_iocb = null; - m_iocbHelper = null; - m_overlapped = null; - m_userObject = null; - Debug.Assert(m_pinSelf == IntPtr.Zero, "OverlappedData has not been freed: m_pinSelf"); - m_pinSelf = IntPtr.Zero; - // Reuse m_pinnedData array - m_nativeOverlapped = default(NativeOverlapped); - } - - internal unsafe NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData) - { - if (m_pinSelf != IntPtr.Zero) + if (_pNativeOverlapped != null) { throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack); } - m_iocb = iocb; - m_iocbHelper = (iocb != null) ? new _IOCompletionCallback(iocb) : null; - m_userObject = userData; + + if (iocb != null) + { + ExecutionContext ec = ExecutionContext.Capture(); + _callback = (ec != null && !ec.IsDefault) ? new _IOCompletionCallback(iocb, ec) : (object)iocb; + } + else + { + _callback = null; + } + _userObject = userData; return AllocateNativeOverlapped(); } - internal unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData) + internal unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb, object userData) { - if (m_pinSelf != IntPtr.Zero) + if (_pNativeOverlapped != null) { throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack); } - m_iocb = iocb; - m_iocbHelper = null; - m_userObject = userData; + _userObject = userData; + _callback = iocb; return AllocateNativeOverlapped(); } - internal IntPtr UserHandle - { - get { return m_nativeOverlapped.EventHandle; } - set { m_nativeOverlapped.EventHandle = value; } - } - private unsafe NativeOverlapped* AllocateNativeOverlapped() { - if (m_userObject != null) - { - if (m_userObject.GetType() == typeof(Object[])) - { - Object[] objArray = (Object[])m_userObject; - if (m_pinnedData == null || m_pinnedData.Length < objArray.Length) - Array.Resize(ref m_pinnedData, objArray.Length); + Debug.Assert(_pinnedData == null); - for (int i = 0; i < objArray.Length; i++) + bool success = false; + try + { + if (_userObject != null) + { + if (_userObject.GetType() == typeof(object[])) { - if (!m_pinnedData[i].IsAllocated) - m_pinnedData[i] = GCHandle.Alloc(objArray[i], GCHandleType.Pinned); - else - m_pinnedData[i].Target = objArray[i]; + object[] objArray = (object[])_userObject; + + _pinnedData = new GCHandle[objArray.Length]; + for (int i = 0; i < objArray.Length; i++) + { + _pinnedData[i] = GCHandle.Alloc(objArray[i], GCHandleType.Pinned); + } + } + else + { + _pinnedData = new GCHandle[1]; + _pinnedData[0] = GCHandle.Alloc(_userObject, GCHandleType.Pinned); } } - else - { - if (m_pinnedData == null || m_pinnedData.Length < 1) - m_pinnedData = new GCHandle[1]; - if (!m_pinnedData[0].IsAllocated) - m_pinnedData[0] = GCHandle.Alloc(m_userObject, GCHandleType.Pinned); - else - m_pinnedData[0].Target = m_userObject; - } + NativeOverlapped* pNativeOverlapped = (NativeOverlapped*)Interop.MemAlloc((UIntPtr)(sizeof(NativeOverlapped) + sizeof(GCHandle))); + *(GCHandle*)(pNativeOverlapped + 1) = default(GCHandle); + _pNativeOverlapped = pNativeOverlapped; + + _pNativeOverlapped->InternalLow = default; + _pNativeOverlapped->InternalHigh = default; + _pNativeOverlapped->OffsetLow = _offsetLow; + _pNativeOverlapped->OffsetHigh = _offsetHigh; + _pNativeOverlapped->EventHandle = _eventHandle; + + *(GCHandle*)(_pNativeOverlapped + 1) = GCHandle.Alloc(this); + + success = true; + return _pNativeOverlapped; } - - m_pinSelf = RuntimeImports.RhHandleAlloc(this, GCHandleType.Pinned); - - fixed (NativeOverlapped* pNativeOverlapped = &m_nativeOverlapped) + finally { - return pNativeOverlapped; + if (!success) + FreeNativeOverlapped(); } } @@ -213,47 +188,33 @@ namespace System.Threading private void FreeNativeOverlapped() { - IntPtr pinSelf = m_pinSelf; - if (pinSelf != IntPtr.Zero) + if (_pinnedData != null) { - if (Interlocked.CompareExchange(ref m_pinSelf, IntPtr.Zero, pinSelf) == pinSelf) + for (int i = 0; i < _pinnedData.Length; i++) { - if (m_pinnedData != null) + if (_pinnedData[i].IsAllocated) { - for (int i = 0; i < m_pinnedData.Length; i++) - { - if (m_pinnedData[i].IsAllocated && (m_pinnedData[i].Target != null)) - { - m_pinnedData[i].Target = null; - } - } + _pinnedData[i].Free(); } - - RuntimeImports.RhHandleFree(pinSelf); } + _pinnedData = null; + } + + if (_pNativeOverlapped != null) + { + GCHandle handle = *(GCHandle*)(_pNativeOverlapped + 1); + if (handle.IsAllocated) + handle.Free(); + + Interop.MemFree((IntPtr)_pNativeOverlapped); + _pNativeOverlapped = null; } } - internal static unsafe OverlappedData GetOverlappedFromNative(NativeOverlapped* nativeOverlappedPtr) + internal static unsafe OverlappedData GetOverlappedFromNative(NativeOverlapped* pNativeOverlapped) { - if (s_nativeOverlappedOffset == 0) - { - CalculateNativeOverlappedOffset(); - } - - void* pOverlappedData = (byte*)nativeOverlappedPtr - s_nativeOverlappedOffset; - return Unsafe.Read(&pOverlappedData); - } - - private static unsafe void CalculateNativeOverlappedOffset() - { - OverlappedData overlappedData = new OverlappedData(); - - fixed (IntPtr* pEETypePtr = &overlappedData.m_pEEType) - fixed (NativeOverlapped* pNativeOverlapped = &overlappedData.m_nativeOverlapped) - { - s_nativeOverlappedOffset = (int)((byte*)pNativeOverlapped - (byte*)pEETypePtr); - } + GCHandle handle = *(GCHandle*)(pNativeOverlapped + 1); + return (OverlappedData)handle.Target; } } @@ -263,24 +224,20 @@ namespace System.Threading public class Overlapped { - private static PinnableBufferCache s_overlappedDataCache = new PinnableBufferCache("System.Threading.OverlappedData", () => new OverlappedData()); - - private OverlappedData m_overlappedData; + private OverlappedData _overlappedData; public Overlapped() { - m_overlappedData = (OverlappedData)s_overlappedDataCache.Allocate(); - m_overlappedData.m_overlapped = this; + _overlappedData = new OverlappedData(); + _overlappedData._overlapped = this; } - public Overlapped(int offsetLo, int offsetHi, IntPtr hEvent, IAsyncResult ar) + public Overlapped(int offsetLo, int offsetHi, IntPtr hEvent, IAsyncResult ar) : this() { - m_overlappedData = (OverlappedData)s_overlappedDataCache.Allocate(); - m_overlappedData.m_overlapped = this; - m_overlappedData.m_nativeOverlapped.OffsetLow = offsetLo; - m_overlappedData.m_nativeOverlapped.OffsetHigh = offsetHi; - m_overlappedData.UserHandle = hEvent; - m_overlappedData.m_asyncResult = ar; + _overlappedData.OffsetLow = offsetLo; + _overlappedData.OffsetHigh = offsetHi; + _overlappedData.EventHandle = hEvent; + _overlappedData.AsyncResult = ar; } [Obsolete("This constructor is not 64-bit compatible. Use the constructor that takes an IntPtr for the event handle. http://go.microsoft.com/fwlink/?linkid=14202")] @@ -290,43 +247,33 @@ namespace System.Threading public IAsyncResult AsyncResult { - get { return m_overlappedData.m_asyncResult; } - set { m_overlappedData.m_asyncResult = value; } + get { return _overlappedData.AsyncResult; } + set { _overlappedData.AsyncResult = value; } } public int OffsetLow { - get { return m_overlappedData.m_nativeOverlapped.OffsetLow; } - set { m_overlappedData.m_nativeOverlapped.OffsetLow = value; } + get { return _overlappedData.OffsetLow; } + set { _overlappedData.OffsetLow = value; } } public int OffsetHigh { - get { return m_overlappedData.m_nativeOverlapped.OffsetHigh; } - set { m_overlappedData.m_nativeOverlapped.OffsetHigh = value; } + get { return _overlappedData.OffsetHigh; } + set { _overlappedData.OffsetHigh = value; } } [Obsolete("This property is not 64-bit compatible. Use EventHandleIntPtr instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int EventHandle { - get { return m_overlappedData.UserHandle.ToInt32(); } - set { m_overlappedData.UserHandle = new IntPtr(value); } + get { return EventHandleIntPtr.ToInt32(); } + set { EventHandleIntPtr = new IntPtr(value); } } public IntPtr EventHandleIntPtr { - get { return m_overlappedData.UserHandle; } - set { m_overlappedData.UserHandle = value; } - } - - internal _IOCompletionCallback iocbHelper - { - get { return m_overlappedData.m_iocbHelper; } - } - - internal IOCompletionCallback UserCallback - { - get { return m_overlappedData.m_iocb; } + get { return _overlappedData.EventHandle; } + set { _overlappedData.EventHandle = value; } } /*==================================================================== @@ -342,9 +289,9 @@ namespace System.Threading } [CLSCompliant(false)] - public unsafe NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData) + public unsafe NativeOverlapped* Pack(IOCompletionCallback iocb, object userData) { - return m_overlappedData.Pack(iocb, userData); + return _overlappedData.Pack(iocb, userData); } [Obsolete("This method is not safe. Use UnsafePack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")] @@ -355,9 +302,9 @@ namespace System.Threading } [CLSCompliant(false)] - public unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData) + public unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb, object userData) { - return m_overlappedData.UnsafePack(iocb, userData); + return _overlappedData.UnsafePack(iocb, userData); } /*==================================================================== @@ -370,9 +317,7 @@ namespace System.Threading if (nativeOverlappedPtr == null) throw new ArgumentNullException(nameof(nativeOverlappedPtr)); - Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped; - - return overlapped; + return OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped; } [CLSCompliant(false)] @@ -381,14 +326,10 @@ namespace System.Threading if (nativeOverlappedPtr == null) throw new ArgumentNullException(nameof(nativeOverlappedPtr)); - Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped; + OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped._overlappedData = null; OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr); - OverlappedData overlappedData = overlapped.m_overlappedData; - overlapped.m_overlappedData = null; - overlappedData.ReInitialize(); - s_overlappedDataCache.Free(overlappedData); } } #endregion class Overlapped -} // namespace +} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/PinnableBufferCache.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/PinnableBufferCache.cs deleted file mode 100644 index 5ebeb44412..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/PinnableBufferCache.cs +++ /dev/null @@ -1,693 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -//#define ENABLE -//#define MINBUFFERS - -using System.Collections.Generic; -using System.Runtime.ConstrainedExecution; -using System.Runtime.InteropServices; - -namespace System.Threading -{ - // Reduced copy of System.Collections.Concurrent.ConcurrentStack - internal class ConcurrentStack - { - private class Node - { - internal readonly T _value; // Value of the node. - internal Node _next; // Next pointer. - - internal Node(T value) - { - _value = value; - _next = null; - } - } - - private volatile Node _head; // The stack is a singly linked list, and only remembers the head. - - private const int BACKOFF_MAX_YIELDS = 8; // Arbitrary number to cap backoff. - - public int Count - { - get - { - int count = 0; - - for (Node curr = _head; curr != null; curr = curr._next) - { - count++; //we don't handle overflow, to be consistent with existing generic collection types in CLR - } - - return count; - } - } - - public void Push(T item) - { - Node newNode = new Node(item); - newNode._next = _head; - if (Interlocked.CompareExchange(ref _head, newNode, newNode._next) == newNode._next) - { - return; - } - - // If we failed, go to the slow path and loop around until we succeed. - PushCore(newNode, newNode); - } - - private void PushCore(Node head, Node tail) - { - SpinWait spin = new SpinWait(); - - // Keep trying to CAS the existing head with the new node until we succeed. - do - { - spin.SpinOnce(); - // Reread the head and link our new node. - tail._next = _head; - } - while (Interlocked.CompareExchange( - ref _head, head, tail._next) != tail._next); - } - - public bool TryPop(out T result) - { - Node head = _head; - //stack is empty - if (head == null) - { - result = default(T); - return false; - } - if (Interlocked.CompareExchange(ref _head, head._next, head) == head) - { - result = head._value; - return true; - } - - // Fall through to the slow path. - return TryPopCore(out result); - } - - private bool TryPopCore(out T result) - { - Node poppedNode; - - if (TryPopCore(1, out poppedNode) == 1) - { - result = poppedNode._value; - return true; - } - - result = default(T); - return false; - } - - private int TryPopCore(int count, out Node poppedHead) - { - SpinWait spin = new SpinWait(); - - // Try to CAS the head with its current next. We stop when we succeed or - // when we notice that the stack is empty, whichever comes first. - Node head; - Node next; - int backoff = 1; - Random r = null; - while (true) - { - head = _head; - // Is the stack empty? - if (head == null) - { - poppedHead = null; - return 0; - } - next = head; - int nodesCount = 1; - for (; nodesCount < count && next._next != null; nodesCount++) - { - next = next._next; - } - - // Try to swap the new head. If we succeed, break out of the loop. - if (Interlocked.CompareExchange(ref _head, next._next, head) == head) - { - // Return the popped Node. - poppedHead = head; - return nodesCount; - } - - // We failed to CAS the new head. Spin briefly and retry. - for (int i = 0; i < backoff; i++) - { - spin.SpinOnce(); - } - - if (spin.NextSpinWillYield) - { - if (r == null) - { - r = new Random(); - } - backoff = r.Next(1, BACKOFF_MAX_YIELDS); - } - else - { - backoff *= 2; - } - } - } - } - - internal sealed class PinnableBufferCache - { - /// - /// Create a PinnableBufferCache that works on any object (it is intended for OverlappedData) - /// This is only used in mscorlib. - /// - internal PinnableBufferCache(string cacheName, Func factory) - { - m_NotGen2 = new List(DefaultNumberOfBuffers); - m_factory = factory; -#if ENABLE - // Check to see if we should disable the cache. - string envVarName = "PinnableBufferCache_" + cacheName + "_Disabled"; - try - { - string envVar = Environment.GetEnvironmentVariable(envVarName); - if (envVar != null) - { - PinnableBufferCacheEventSource.Log.DebugMessage("Creating " + cacheName + " PinnableBufferCacheDisabled=" + envVar); - int index = envVar.IndexOf(cacheName, StringComparison.OrdinalIgnoreCase); - if (0 <= index) - { - // The cache is disabled because we haven't set the cache name. - PinnableBufferCacheEventSource.Log.DebugMessage("Disabling " + cacheName); - return; - } - } - } - catch - { - // Ignore failures when reading the environment variable. - } -#endif -#if MINBUFFERS - // Allow the environment to specify a minimum buffer count. - string minEnvVarName = "PinnableBufferCache_" + cacheName + "_MinCount"; - try - { - string minEnvVar = Environment.GetEnvironmentVariable(minEnvVarName); - if (minEnvVar != null) - { - if (int.TryParse(minEnvVar, out m_minBufferCount)) - CreateNewBuffers(); - } - } - catch - { - // Ignore failures when reading the environment variable. - } -#endif - - PinnableBufferCacheEventSource.Log.Create(cacheName); - m_CacheName = cacheName; - } - - /// - /// Get a object from the buffer manager. If no buffers exist, allocate a new one. - /// - internal object Allocate() - { -#if ENABLE - // Check to see whether or not the cache is disabled. - if (m_CacheName == null) - return m_factory(); -#endif - // Fast path, get it from our Gen2 aged m_FreeList. - object returnBuffer; - if (!m_FreeList.TryPop(out returnBuffer)) - Restock(out returnBuffer); - -#if LOGGING - // Computing free count is expensive enough that we don't want to compute it unless logging is on. - if (PinnableBufferCacheEventSource.Log.IsEnabled()) - { - int numAllocCalls = Interlocked.Increment(ref m_numAllocCalls); - if (numAllocCalls >= 1024) - { - lock (this) - { - int previousNumAllocCalls = Interlocked.Exchange(ref m_numAllocCalls, 0); - if (previousNumAllocCalls >= 1024) - { - int nonGen2Count = 0; - foreach (object o in m_FreeList) - { - if (GC.GetGeneration(o) < GC.MaxGeneration) - { - nonGen2Count++; - } - } - - PinnableBufferCacheEventSource.Log.WalkFreeListResult(m_CacheName, m_FreeList.Count, nonGen2Count); - } - } - } - - PinnableBufferCacheEventSource.Log.AllocateBuffer(m_CacheName, PinnableBufferCacheEventSource.AddressOf(returnBuffer), returnBuffer.GetHashCode(), GC.GetGeneration(returnBuffer), m_FreeList.Count); - } -#endif - return returnBuffer; - } - - /// - /// Return a buffer back to the buffer manager. - /// - internal void Free(object buffer) - { -#if ENABLE - // Check to see whether or not the cache is disabled. - if (m_CacheName == null) - return; -#endif - if (PinnableBufferCacheEventSource.Log.IsEnabled()) - PinnableBufferCacheEventSource.Log.FreeBuffer(m_CacheName, PinnableBufferCacheEventSource.AddressOf(buffer), buffer.GetHashCode(), m_FreeList.Count); - - - // After we've done 3 gen1 GCs, assume that all buffers have aged into gen2 on the free path. - if ((m_gen1CountAtLastRestock + 3) > GC.CollectionCount(GC.MaxGeneration - 1)) - { - lock (this) - { - if (GC.GetGeneration(buffer) < GC.MaxGeneration) - { - // The buffer is not aged, so put it in the non-aged free list. - m_moreThanFreeListNeeded = true; - PinnableBufferCacheEventSource.Log.FreeBufferStillTooYoung(m_CacheName, m_NotGen2.Count); - m_NotGen2.Add(buffer); - m_gen1CountAtLastRestock = GC.CollectionCount(GC.MaxGeneration - 1); - return; - } - } - } - - // If we discovered that it is indeed Gen2, great, put it in the Gen2 list. - m_FreeList.Push(buffer); - } - - #region Private - - /// - /// Called when we don't have any buffers in our free list to give out. - /// - /// - private void Restock(out object returnBuffer) - { - lock (this) - { - // Try again after getting the lock as another thread could have just filled the free list. If we don't check - // then we unnecessarily grab a new set of buffers because we think we are out. - if (m_FreeList.TryPop(out returnBuffer)) - return; - - // Lazy init, Ask that TrimFreeListIfNeeded be called on every Gen 2 GC. - if (m_restockSize == 0) - Gen2GcCallback.Register(Gen2GcCallbackFunc, this); - - // Indicate to the trimming policy that the free list is insufficent. - m_moreThanFreeListNeeded = true; - PinnableBufferCacheEventSource.Log.AllocateBufferFreeListEmpty(m_CacheName, m_NotGen2.Count); - - // Get more buffers if needed. - if (m_NotGen2.Count == 0) - CreateNewBuffers(); - - // We have no buffers in the aged freelist, so get one from the newer list. Try to pick the best one. - // Debug.Assert(m_NotGen2.Count != 0); - int idx = m_NotGen2.Count - 1; - if (GC.GetGeneration(m_NotGen2[idx]) < GC.MaxGeneration && GC.GetGeneration(m_NotGen2[0]) == GC.MaxGeneration) - idx = 0; - returnBuffer = m_NotGen2[idx]; - m_NotGen2.RemoveAt(idx); - - // Remember any sub-optimial buffer so we don't put it on the free list when it gets freed. - if (PinnableBufferCacheEventSource.Log.IsEnabled() && GC.GetGeneration(returnBuffer) < GC.MaxGeneration) - { - PinnableBufferCacheEventSource.Log.AllocateBufferFromNotGen2(m_CacheName, m_NotGen2.Count); - } - - // If we have a Gen1 collection, then everything on m_NotGen2 should have aged. Move them to the m_Free list. - if (!AgePendingBuffers()) - { - // Before we could age at set of buffers, we have handed out half of them. - // This implies we should be proactive about allocating more (since we will trim them if we over-allocate). - if (m_NotGen2.Count == m_restockSize / 2) - { - PinnableBufferCacheEventSource.Log.DebugMessage("Proactively adding more buffers to aging pool"); - CreateNewBuffers(); - } - } - } - } - - /// - /// See if we can promote the buffers to the free list. Returns true if sucessful. - /// - private bool AgePendingBuffers() - { - if (m_gen1CountAtLastRestock < GC.CollectionCount(GC.MaxGeneration - 1)) - { - // Allocate a temp list of buffers that are not actually in gen2, and swap it in once - // we're done scanning all buffers. - int promotedCount = 0; - List notInGen2 = new List(); - PinnableBufferCacheEventSource.Log.AllocateBufferAged(m_CacheName, m_NotGen2.Count); - for (int i = 0; i < m_NotGen2.Count; i++) - { - // We actually check every object to ensure that we aren't putting non-aged buffers into the free list. - object currentBuffer = m_NotGen2[i]; - if (GC.GetGeneration(currentBuffer) >= GC.MaxGeneration) - { - m_FreeList.Push(currentBuffer); - promotedCount++; - } - else - { - notInGen2.Add(currentBuffer); - } - } - PinnableBufferCacheEventSource.Log.AgePendingBuffersResults(m_CacheName, promotedCount, notInGen2.Count); - m_NotGen2 = notInGen2; - - return true; - } - return false; - } - - /// - /// Generates some buffers to age into Gen2. - /// - private void CreateNewBuffers() - { - // We choose a very modest number of buffers initially because for the client case. This is often enough. - if (m_restockSize == 0) - m_restockSize = 4; - else if (m_restockSize < DefaultNumberOfBuffers) - m_restockSize = DefaultNumberOfBuffers; - else if (m_restockSize < 256) - m_restockSize = m_restockSize * 2; // Grow quickly at small sizes - else if (m_restockSize < 4096) - m_restockSize = m_restockSize * 3 / 2; // Less aggressively at large ones - else - m_restockSize = 4096; // Cap how aggressive we are - - // Ensure we hit our minimums - if (m_minBufferCount > m_buffersUnderManagement) - m_restockSize = Math.Max(m_restockSize, m_minBufferCount - m_buffersUnderManagement); - - PinnableBufferCacheEventSource.Log.AllocateBufferCreatingNewBuffers(m_CacheName, m_buffersUnderManagement, m_restockSize); - for (int i = 0; i < m_restockSize; i++) - { - // Make a new buffer. - object newBuffer = m_factory(); - - // Create space between the objects. We do this because otherwise it forms a single plug (group of objects) - // and the GC pins the entire plug making them NOT move to Gen1 and Gen2. by putting space between them - // we ensure that object get a chance to move independently (even if some are pinned). - var dummyObject = new object(); - m_NotGen2.Add(newBuffer); - } - m_buffersUnderManagement += m_restockSize; - m_gen1CountAtLastRestock = GC.CollectionCount(GC.MaxGeneration - 1); - } - - /// - /// This is the static function that is called from the gen2 GC callback. - /// The input object is the cache itself. - /// NOTE: The reason that we make this functionstatic and take the cache as a parameter is that - /// otherwise, we root the cache to the Gen2GcCallback object, and leak the cache even when - /// the application no longer needs it. - /// - private static bool Gen2GcCallbackFunc(object targetObj) - { - return ((PinnableBufferCache)(targetObj)).TrimFreeListIfNeeded(); - } - - /// - /// This is called on every gen2 GC to see if we need to trim the free list. - /// NOTE: DO NOT CALL THIS DIRECTLY FROM THE GEN2GCCALLBACK. INSTEAD CALL IT VIA A STATIC FUNCTION (SEE ABOVE). - /// If you register a non-static function as a callback, then this object will be leaked. - /// - private bool TrimFreeListIfNeeded() - { - int curMSec = Environment.TickCount; - int deltaMSec = curMSec - m_msecNoUseBeyondFreeListSinceThisTime; - PinnableBufferCacheEventSource.Log.TrimCheck(m_CacheName, m_buffersUnderManagement, m_moreThanFreeListNeeded, deltaMSec); - - // If we needed more than just the set of aged buffers since the last time we were called, - // we obviously should not be trimming any memory, so do nothing except reset the flag - if (m_moreThanFreeListNeeded) - { - m_moreThanFreeListNeeded = false; - m_trimmingExperimentInProgress = false; - m_msecNoUseBeyondFreeListSinceThisTime = curMSec; - return true; - } - - // We require a minimum amount of clock time to pass (10 seconds) before we trim. Ideally this time - // is larger than the typical buffer hold time. - if (0 <= deltaMSec && deltaMSec < 10000) - return true; - - // If we got here we have spend the last few second without needing to lengthen the free list. Thus - // we have 'enough' buffers, but maybe we have too many. - // See if we can trim - lock (this) - { - // Hit a race, try again later. - if (m_moreThanFreeListNeeded) - { - m_moreThanFreeListNeeded = false; - m_trimmingExperimentInProgress = false; - m_msecNoUseBeyondFreeListSinceThisTime = curMSec; - return true; - } - - var freeCount = m_FreeList.Count; // This is expensive to fetch, do it once. - - // If there is something in m_NotGen2 it was not used for the last few seconds, it is trimable. - if (m_NotGen2.Count > 0) - { - // If we are not performing an experiment and we have stuff that is waiting to go into the - // free list but has not made it there, it could be becasue the 'slow path' of restocking - // has not happened, so force this (which should flush the list) and start over. - if (!m_trimmingExperimentInProgress) - { - PinnableBufferCacheEventSource.Log.TrimFlush(m_CacheName, m_buffersUnderManagement, freeCount, m_NotGen2.Count); - AgePendingBuffers(); - m_trimmingExperimentInProgress = true; - return true; - } - - PinnableBufferCacheEventSource.Log.TrimFree(m_CacheName, m_buffersUnderManagement, freeCount, m_NotGen2.Count); - m_buffersUnderManagement -= m_NotGen2.Count; - - // Possibly revise the restocking down. We don't want to grow agressively if we are trimming. - var newRestockSize = m_buffersUnderManagement / 4; - if (newRestockSize < m_restockSize) - m_restockSize = Math.Max(newRestockSize, DefaultNumberOfBuffers); - - m_NotGen2.Clear(); - m_trimmingExperimentInProgress = false; - return true; - } - - // Set up an experiment where we use 25% less buffers in our free list. We put them in - // m_NotGen2, and if they are needed they will be put back in the free list again. - var trimSize = freeCount / 4 + 1; - - // We are OK with a 15% overhead, do nothing in that case. - if (freeCount * 15 <= m_buffersUnderManagement || m_buffersUnderManagement - trimSize <= m_minBufferCount) - { - PinnableBufferCacheEventSource.Log.TrimFreeSizeOK(m_CacheName, m_buffersUnderManagement, freeCount); - return true; - } - - // Move buffers from the free list back to the non-aged list. If we don't use them by next time, then we'll consider trimming them. - PinnableBufferCacheEventSource.Log.TrimExperiment(m_CacheName, m_buffersUnderManagement, freeCount, trimSize); - object buffer; - for (int i = 0; i < trimSize; i++) - { - if (m_FreeList.TryPop(out buffer)) - m_NotGen2.Add(buffer); - } - m_msecNoUseBeyondFreeListSinceThisTime = curMSec; - m_trimmingExperimentInProgress = true; - } - - // Indicate that we want to be called back on the next Gen 2 GC. - return true; - } - - private const int DefaultNumberOfBuffers = 16; - private string m_CacheName; - private Func m_factory; - - /// - /// Contains 'good' buffers to reuse. They are guarenteed to be Gen 2 ENFORCED! - /// - private ConcurrentStack m_FreeList = new ConcurrentStack(); - /// - /// Contains buffers that are not gen 2 and thus we do not wish to give out unless we have to. - /// To implement trimming we sometimes put aged buffers in here as a place to 'park' them - /// before true deletion. - /// - private List m_NotGen2; - /// - /// What whas the gen 1 count the last time re restocked? If it is now greater, then - /// we know that all objects are in Gen 2 so we don't have to check. Should be updated - /// every time something gets added to the m_NotGen2 list. - /// - private int m_gen1CountAtLastRestock; - - /// - /// Used to ensure we have a minimum time between trimmings. - /// - private int m_msecNoUseBeyondFreeListSinceThisTime; - /// - /// To trim, we remove things from the free list (which is Gen 2) and see if we 'hit bottom' - /// This flag indicates that we hit bottom (we really needed a bigger free list). - /// - private bool m_moreThanFreeListNeeded; - /// - /// The total number of buffers that this cache has ever allocated. - /// Used in trimming heuristics. - /// - private int m_buffersUnderManagement; - /// - /// The number of buffers we added the last time we restocked. - /// - private int m_restockSize; - /// - /// Did we put some buffers into m_NotGen2 to see if we can trim? - /// - private bool m_trimmingExperimentInProgress; -#pragma warning disable 0649 - /// - /// A forced minimum number of buffers. - /// - private int m_minBufferCount; -#pragma warning restore 0649 -#if LOGGING - /// - /// The number of calls to Allocate. - /// - private int m_numAllocCalls; -#endif - - #endregion - } - - /// - /// Schedules a callback roughly every gen 2 GC (you may see a Gen 0 an Gen 1 but only once) - /// (We can fix this by capturing the Gen 2 count at startup and testing, but I mostly don't care) - /// - internal sealed class Gen2GcCallback : CriticalFinalizerObject - { - public Gen2GcCallback() - : base() - { - } - - /// - /// Schedule 'callback' to be called in the next GC. If the callback returns true it is - /// rescheduled for the next Gen 2 GC. Otherwise the callbacks stop. - /// - /// NOTE: This callback will be kept alive until either the callback function returns false, - /// or the target object dies. - /// - public static void Register(Func callback, object targetObj) - { - // Create a unreachable object that remembers the callback function and target object. - Gen2GcCallback gcCallback = new Gen2GcCallback(); - gcCallback.Setup(callback, targetObj); - } - - #region Private - - private Func m_callback; - private GCHandle m_weakTargetObj; - - private void Setup(Func callback, object targetObj) - { - m_callback = callback; - m_weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak); - } - - ~Gen2GcCallback() - { - // Check to see if the target object is still alive. - object targetObj = m_weakTargetObj.Target; - if (targetObj == null) - { - // The target object is dead, so this callback object is no longer needed. - m_weakTargetObj.Free(); - return; - } - - // Execute the callback method. - try - { - if (!m_callback(targetObj)) - { - // If the callback returns false, this callback object is no longer needed. - return; - } - } - catch - { - // Ensure that we still get a chance to resurrect this object, even if the callback throws an exception. - } - - // Resurrect ourselves by re-registering for finalization. - if (!Environment.HasShutdownStarted /*&& !AppDomain.CurrentDomain.IsFinalizingForUnload()*/) - { - GC.ReRegisterForFinalize(this); - } - } - - #endregion - } - - internal sealed class PinnableBufferCacheEventSource - { - public static readonly PinnableBufferCacheEventSource Log = new PinnableBufferCacheEventSource(); - - public bool IsEnabled() { return false; } - public void DebugMessage(string message) { } - public void Create(string cacheName) { } - public void AllocateBuffer(string cacheName, ulong objectId, int objectHash, int objectGen, int freeCountAfter) { } - public void AllocateBufferFromNotGen2(string cacheName, int notGen2CountAfter) { } - public void AllocateBufferCreatingNewBuffers(string cacheName, int totalBuffsBefore, int objectCount) { } - public void AllocateBufferAged(string cacheName, int agedCount) { } - public void AllocateBufferFreeListEmpty(string cacheName, int notGen2CountBefore) { } - public void FreeBuffer(string cacheName, ulong objectId, int objectHash, int freeCountBefore) { } - public void FreeBufferStillTooYoung(string cacheName, int notGen2CountBefore) { } - public void TrimCheck(string cacheName, int totalBuffs, bool neededMoreThanFreeList, int deltaMSec) { } - public void TrimFree(string cacheName, int totalBuffs, int freeListCount, int toBeFreed) { } - public void TrimExperiment(string cacheName, int totalBuffs, int freeListCount, int numTrimTrial) { } - public void TrimFreeSizeOK(string cacheName, int totalBuffs, int freeListCount) { } - public void TrimFlush(string cacheName, int totalBuffs, int freeListCount, int notGen2CountBefore) { } - public void AgePendingBuffersResults(string cacheName, int promotedToFreeListCount, int heldBackCount) { } - public void WalkFreeListResult(string cacheName, int freeListCount, int gen0BuffersInFreeList) { } - - static internal ulong AddressOf(object obj) - { - return 0; - } - } -} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.cs index 229cd0c493..04f34bce4b 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.cs @@ -2,24 +2,21 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.IO; +using System.Runtime.InteropServices; namespace System.Threading { public sealed partial class Semaphore { - private static void VerifyNameForCreate(string name) + private void CreateSemaphoreCore(int initialCount, int maximumCount, string name, out bool createdNew) { if (name != null) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); } - } - - private void CreateSemaphoreCore(int initialCount, int maximumCount, string name, out bool createdNew) - { - Debug.Assert(name == null); SafeWaitHandle = WaitSubsystem.NewSemaphore(initialCount, maximumCount); createdNew = true; @@ -30,9 +27,25 @@ namespace System.Threading throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); } - private static int ReleaseCore(IntPtr handle, int releaseCount) + private int ReleaseCore(int releaseCount) { - return WaitSubsystem.ReleaseSemaphore(handle, releaseCount); + // The field value is modifiable via the public property, save it locally + // to ensure that one instance is used in all places in this method + SafeWaitHandle waitHandle = _waitHandle; + if (waitHandle == null) + { + ThrowInvalidHandleException(); + } + + waitHandle.DangerousAddRef(); + try + { + return WaitSubsystem.ReleaseSemaphore(waitHandle.DangerousGetHandle(), releaseCount); + } + finally + { + waitHandle.DangerousRelease(); + } } } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Semaphore.Windows.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Semaphore.Windows.cs deleted file mode 100644 index 3eab7f5d25..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Semaphore.Windows.cs +++ /dev/null @@ -1,106 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -namespace System.Threading -{ - public sealed partial class Semaphore - { - private const uint AccessRights = (uint)(Interop.Constants.MaximumAllowed | Interop.Constants.Synchronize | Interop.Constants.SemaphoreModifyState); - - private Semaphore(SafeWaitHandle handle) - { - SafeWaitHandle = handle; - } - - private static void VerifyNameForCreate(string name) - { - if (null != name && Interop.Kernel32.MAX_PATH < name.Length) - { - throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Interop.Kernel32.MAX_PATH), nameof(name)); - } - } - - private void CreateSemaphoreCore(int initialCount, int maximumCount, string name, out bool createdNew) - { - Debug.Assert(initialCount >= 0); - Debug.Assert(maximumCount >= 1); - Debug.Assert(initialCount <= maximumCount); - Debug.Assert(name == null || name.Length <= Interop.Kernel32.MAX_PATH); - - SafeWaitHandle myHandle = Interop.mincore.CreateSemaphoreEx(IntPtr.Zero, initialCount, maximumCount, name, 0, AccessRights); - - if (myHandle.IsInvalid) - { - int errorCode = Marshal.GetLastWin32Error(); - if (null != name && 0 != name.Length && Interop.Errors.ERROR_INVALID_HANDLE == errorCode) - throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); - throw ExceptionFromCreationError(errorCode, name); - } - else if (name != null) - { - int errorCode = Marshal.GetLastWin32Error(); - createdNew = errorCode != Interop.Errors.ERROR_ALREADY_EXISTS; - } - else - { - createdNew = true; - } - - SafeWaitHandle = myHandle; - } - - private static OpenExistingResult OpenExistingWorker(string name, out Semaphore result) - { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - if (name.Length == 0) - { - throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); - } - if (null != name && Interop.Kernel32.MAX_PATH < name.Length) - { - throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Interop.Kernel32.MAX_PATH), nameof(name)); - } - - result = null; - - SafeWaitHandle myHandle = Interop.mincore.OpenSemaphore(AccessRights, false, name); - - if (myHandle.IsInvalid) - { - int errorCode = Marshal.GetLastWin32Error(); - - if (Interop.Errors.ERROR_FILE_NOT_FOUND == errorCode || Interop.Errors.ERROR_INVALID_NAME == errorCode) - return OpenExistingResult.NameNotFound; - if (Interop.Errors.ERROR_PATH_NOT_FOUND == errorCode) - return OpenExistingResult.PathNotFound; - if (null != name && 0 != name.Length && Interop.Errors.ERROR_INVALID_HANDLE == errorCode) - return OpenExistingResult.NameInvalid; - - throw ExceptionFromCreationError(errorCode, name); - } - result = new Semaphore(myHandle); - return OpenExistingResult.Success; - } - - private static int ReleaseCore(IntPtr handle, int releaseCount) - { - Debug.Assert(releaseCount > 0); - - int previousCount; - if (!Interop.mincore.ReleaseSemaphore(handle, releaseCount, out previousCount)) - { - ThrowSignalOrUnsignalException(); - } - - return previousCount; - } - } -} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs index 92df1152a1..f939c1647c 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs @@ -43,12 +43,12 @@ namespace System.Threading return ((_props & SynchronizationContextProperties.RequireWaitNotification) != 0); } - public virtual void Send(SendOrPostCallback d, Object state) + public virtual void Send(SendOrPostCallback d, object state) { d(state); } - public virtual void Post(SendOrPostCallback d, Object state) + public virtual void Post(SendOrPostCallback d, object state) { ThreadPool.QueueUserWorkItem(new WaitCallback(d), state); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.Dummy.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.Dummy.cs index 2cfa1be1f1..12da2bd904 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.Dummy.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.Dummy.cs @@ -22,7 +22,7 @@ namespace System.Threading.Tasks } } - public static void TraceOperationCreation(CausalityTraceLevel traceLevel, Task task, String operationName, ulong relatedContext) + public static void TraceOperationCreation(CausalityTraceLevel traceLevel, Task task, string operationName, ulong relatedContext) { } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.cs index 0ee81c9376..d58332dc1d 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.cs @@ -60,7 +60,7 @@ namespace System.Threading.Tasks } private static readonly LowLevelDictionary s_activeTasks = new LowLevelDictionary(); - private static readonly Object s_activeTasksLock = new Object(); + private static readonly object s_activeTasksLock = new object(); //============================================================================================================== // This section of the class wraps calls to get the lazy-created Task object for the purpose of reporting diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs index ed2c06d745..6cb386ce0c 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs @@ -128,7 +128,6 @@ namespace System.Threading.Tasks : this(function, null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, null) { - PossiblyCaptureContext(); } @@ -150,7 +149,6 @@ namespace System.Threading.Tasks : this(function, null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, null) { - PossiblyCaptureContext(); } /// @@ -174,7 +172,6 @@ namespace System.Threading.Tasks public Task(Func function, TaskCreationOptions creationOptions) : this(function, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, InternalTaskOptions.None, null) { - PossiblyCaptureContext(); } /// @@ -202,7 +199,6 @@ namespace System.Threading.Tasks public Task(Func function, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : this(function, Task.InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, null) { - PossiblyCaptureContext(); } /// @@ -220,7 +216,6 @@ namespace System.Threading.Tasks : this(function, state, null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, null) { - PossiblyCaptureContext(); } /// @@ -242,7 +237,6 @@ namespace System.Threading.Tasks : this(function, state, null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, null) { - PossiblyCaptureContext(); } /// @@ -268,7 +262,6 @@ namespace System.Threading.Tasks : this(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, InternalTaskOptions.None, null) { - PossiblyCaptureContext(); } @@ -299,7 +292,6 @@ namespace System.Threading.Tasks : this(function, state, Task.InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, null) { - PossiblyCaptureContext(); } /// @@ -315,7 +307,6 @@ namespace System.Threading.Tasks TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) : base(valueSelector, null, parent, cancellationToken, creationOptions, internalOptions, scheduler) { - PossiblyCaptureContext(); } @@ -333,7 +324,6 @@ namespace System.Threading.Tasks TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) : base(valueSelector, state, parent, cancellationToken, creationOptions, internalOptions, scheduler) { - PossiblyCaptureContext(); } @@ -783,7 +773,7 @@ namespace System.Threading.Tasks /// /// The argument is null. /// - public Task ContinueWith(Action, Object> continuationAction, Object state) + public Task ContinueWith(Action, object> continuationAction, object state) { return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None); } @@ -810,7 +800,7 @@ namespace System.Threading.Tasks /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWith(Action, Object> continuationAction, Object state, CancellationToken cancellationToken) + public Task ContinueWith(Action, object> continuationAction, object state, CancellationToken cancellationToken) { return ContinueWith(continuationAction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); } @@ -839,7 +829,7 @@ namespace System.Threading.Tasks /// /// The argument is null. /// - public Task ContinueWith(Action, Object> continuationAction, Object state, TaskScheduler scheduler) + public Task ContinueWith(Action, object> continuationAction, object state, TaskScheduler scheduler) { return ContinueWith(continuationAction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None); } @@ -873,7 +863,7 @@ namespace System.Threading.Tasks /// The argument specifies an invalid value for TaskContinuationOptions. /// - public Task ContinueWith(Action, Object> continuationAction, Object state, TaskContinuationOptions continuationOptions) + public Task ContinueWith(Action, object> continuationAction, object state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions); } @@ -917,14 +907,14 @@ namespace System.Threading.Tasks /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWith(Action, Object> continuationAction, Object state, CancellationToken cancellationToken, + public Task ContinueWith(Action, object> continuationAction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { return ContinueWith(continuationAction, state, scheduler, cancellationToken, continuationOptions); } // Same as the above overload, only with a stack mark. - internal Task ContinueWith(Action, Object> continuationAction, Object state, TaskScheduler scheduler, CancellationToken cancellationToken, + internal Task ContinueWith(Action, object> continuationAction, object state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { if (continuationAction == null) @@ -1195,7 +1185,7 @@ namespace System.Threading.Tasks /// /// The argument is null. /// - public Task ContinueWith(Func, Object, TNewResult> continuationFunction, Object state) + public Task ContinueWith(Func, object, TNewResult> continuationFunction, object state) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None); } @@ -1225,7 +1215,7 @@ namespace System.Threading.Tasks /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWith(Func, Object, TNewResult> continuationFunction, Object state, + public Task ContinueWith(Func, object, TNewResult> continuationFunction, object state, CancellationToken cancellationToken) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); @@ -1257,7 +1247,7 @@ namespace System.Threading.Tasks /// /// The argument is null. /// - public Task ContinueWith(Func, Object, TNewResult> continuationFunction, Object state, + public Task ContinueWith(Func, object, TNewResult> continuationFunction, object state, TaskScheduler scheduler) { return ContinueWith(continuationFunction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None); @@ -1301,7 +1291,7 @@ namespace System.Threading.Tasks /// The argument specifies an invalid value for TaskContinuationOptions. /// - public Task ContinueWith(Func, Object, TNewResult> continuationFunction, Object state, + public Task ContinueWith(Func, object, TNewResult> continuationFunction, object state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions); @@ -1356,14 +1346,14 @@ namespace System.Threading.Tasks /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWith(Func, Object, TNewResult> continuationFunction, Object state, + public Task ContinueWith(Func, object, TNewResult> continuationFunction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { return ContinueWith(continuationFunction, state, scheduler, cancellationToken, continuationOptions); } // Same as the above overload, just with a stack mark. - internal Task ContinueWith(Func, Object, TNewResult> continuationFunction, Object state, + internal Task ContinueWith(Func, object, TNewResult> continuationFunction, object state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs.REMOVED.git-id index 2a6ed083c9..af844a049a 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs.REMOVED.git-id +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs.REMOVED.git-id @@ -1 +1 @@ -b27b1858fea5bbb83b6ef0a139929bdcebcba74d \ No newline at end of file +f1b4d0e741afbcb420092ddc48305a2b52fefccd \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/ProducerConsumerQueues.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/ProducerConsumerQueues.cs index 915f7c41fa..83ff877e33 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/ProducerConsumerQueues.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/ProducerConsumerQueues.cs @@ -135,7 +135,7 @@ namespace System.Threading.Tasks /// The initial size to use for segments (in number of elements). private const int INIT_SEGMENT_SIZE = 32; // must be a power of 2 /// The maximum size to use for segments (in number of elements). - private const int MAX_SEGMENT_SIZE = 0x1000000; // this could be made as large as Int32.MaxValue / 2 + private const int MAX_SEGMENT_SIZE = 0x1000000; // this could be made as large as int.MaxValue / 2 /// The head of the linked list of segments. private volatile Segment m_head; @@ -149,7 +149,7 @@ namespace System.Threading.Tasks Debug.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0."); Debug.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2"); Debug.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum."); - Debug.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur."); + Debug.Assert(MAX_SEGMENT_SIZE < int.MaxValue / 2, "Max segment size * 2 must be < int.MaxValue, or else overflow could occur."); // Initialize the queue m_head = m_tail = new Segment(INIT_SEGMENT_SIZE); @@ -552,7 +552,7 @@ namespace System.Threading.Tasks } /// Padding structure used to minimize false sharing in SingleProducerSingleConsumerQueue{T}. - [StructLayout(LayoutKind.Explicit, Size = PaddingHelpers.CACHE_LINE_SIZE - sizeof(Int32))] // Based on common case of 64-byte cache lines + [StructLayout(LayoutKind.Explicit, Size = PaddingHelpers.CACHE_LINE_SIZE - sizeof(int))] // Based on common case of 64-byte cache lines internal struct PaddingFor32 { } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs.REMOVED.git-id index 6ee723707e..04bb8afc82 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs.REMOVED.git-id +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs.REMOVED.git-id @@ -1 +1 @@ -185449d187c8932c82d449d467170732f3d171d7 \ No newline at end of file +f486de668c7a7fde0053fb1ac0dbca62c7badded \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs index 2ec382ad1f..b268b097d5 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs @@ -36,7 +36,6 @@ namespace System.Threading.Tasks Debug.Assert(action is Action || action is Action, "Invalid delegate type in ContinuationTaskFromTask"); m_antecedent = antecedent; - PossiblyCaptureContext(); } /// @@ -84,7 +83,6 @@ namespace System.Threading.Tasks Debug.Assert(function is Func || function is Func, "Invalid delegate type in ContinuationResultTaskFromTask"); m_antecedent = antecedent; - PossiblyCaptureContext(); } /// @@ -132,7 +130,6 @@ namespace System.Threading.Tasks Debug.Assert(action is Action> || action is Action, object>, "Invalid delegate type in ContinuationTaskFromResultTask"); m_antecedent = antecedent; - PossiblyCaptureContext(); } /// @@ -180,7 +177,6 @@ namespace System.Threading.Tasks Debug.Assert(function is Func, TResult> || function is Func, object, TResult>, "Invalid delegate type in ContinuationResultTaskFromResultTask"); m_antecedent = antecedent; - PossiblyCaptureContext(); } /// diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs.REMOVED.git-id b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs.REMOVED.git-id index c9d581633a..cc04be44c8 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs.REMOVED.git-id +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs.REMOVED.git-id @@ -1 +1 @@ -627a760c70dad24b763acc3e566b6cf1c18ae6e7 \ No newline at end of file +05c829cbbd74bf6093393c58afe8fd493a2adab2 \ No newline at end of file diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskScheduler.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskScheduler.cs index 653345cef6..026cfce6db 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskScheduler.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskScheduler.cs @@ -148,11 +148,11 @@ namespace System.Threading.Tasks /// Indicates the maximum concurrency level this /// is able to support. /// - public virtual Int32 MaximumConcurrencyLevel + public virtual int MaximumConcurrencyLevel { get { - return Int32.MaxValue; + return int.MaxValue; } } @@ -366,7 +366,7 @@ namespace System.Threading.Tasks /// /// Gets the unique ID for this . /// - public Int32 Id + public int Id { get { @@ -580,7 +580,7 @@ namespace System.Threading.Tasks } // returns the scheduler's Id - public Int32 Id + public int Id { get { return m_taskScheduler.Id; } } @@ -623,7 +623,7 @@ namespace System.Threading.Tasks } /// - /// Implemetation of for this scheduler class. + /// Implementation of for this scheduler class. /// /// Simply posts the tasks to be executed on the associated . /// @@ -658,13 +658,13 @@ namespace System.Threading.Tasks } /// - /// Implementes the property for + /// Implements the property for /// this scheduler class. /// /// By default it returns 1, because a based /// scheduler only supports execution on a single thread. /// - public override Int32 MaximumConcurrencyLevel + public override int MaximumConcurrencyLevel { get { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs index f7dff9475e..2dbb6a2d20 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs @@ -206,7 +206,8 @@ namespace System.Threading { if (handleValue != IntPtr.Zero && handleValue != (IntPtr)(-1)) { - EventWaitHandle.Set(handleValue); + Debug.Assert(handleValue == handle.DangerousGetHandle()); + WaitSubsystem.SetEvent(handleValue); } } finally diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs index 5ca0604b4e..751fa683f3 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs @@ -186,7 +186,7 @@ namespace System.Threading if ((safeWaitHandle != null) && !safeWaitHandle.IsInvalid) { - Interop.mincore.SetEvent(safeWaitHandle); + Interop.Kernel32.SetEvent(safeWaitHandle); } } @@ -326,7 +326,7 @@ namespace System.Threading private static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce, bool flowExecutionContext) diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadPool.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadPool.cs index c41b377533..9eaf1d4d57 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadPool.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadPool.cs @@ -385,7 +385,7 @@ namespace System.Threading } } - internal readonly LowLevelConcurrentQueue workItems = new LowLevelConcurrentQueue(); + internal readonly ConcurrentQueue workItems = new ConcurrentQueue(); private volatile int numOutstandingThreadRequests = 0; @@ -673,9 +673,9 @@ namespace System.Threading } } - public delegate void WaitCallback(Object state); + public delegate void WaitCallback(object state); - public delegate void WaitOrTimerCallback(Object state, bool timedOut); // signalled or timed out + public delegate void WaitOrTimerCallback(object state, bool timedOut); // signalled or timed out // // Interface to something that can be queued to the TP. This is implemented by @@ -887,11 +887,11 @@ namespace System.Threading { private WaitOrTimerCallback _waitOrTimerCallback; private ExecutionContext _executionContext; - private Object _state; + private object _state; private static readonly ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t); private static readonly ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f); - internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, Object state, bool flowExecutionContext) + internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, object state, bool flowExecutionContext) { _waitOrTimerCallback = waitOrTimerCallback; _state = state; @@ -903,13 +903,13 @@ namespace System.Threading } } - private static void WaitOrTimerCallback_Context_t(Object state) => + private static void WaitOrTimerCallback_Context_t(object state) => WaitOrTimerCallback_Context(state, timedOut: true); - private static void WaitOrTimerCallback_Context_f(Object state) => + private static void WaitOrTimerCallback_Context_f(object state) => WaitOrTimerCallback_Context(state, timedOut: false); - private static void WaitOrTimerCallback_Context(Object state, bool timedOut) + private static void WaitOrTimerCallback_Context(object state, bool timedOut) { _ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state; helper._waitOrTimerCallback(helper._state, timedOut); @@ -938,7 +938,7 @@ namespace System.Threading public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce) { @@ -951,7 +951,7 @@ namespace System.Threading public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce) { @@ -963,71 +963,71 @@ namespace System.Threading public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, int millisecondsTimeOutInterval, bool executeOnlyOnce) { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, true); + return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, true); } public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, int millisecondsTimeOutInterval, bool executeOnlyOnce) { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, false); + return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, false); } public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, long millisecondsTimeOutInterval, bool executeOnlyOnce) { if (millisecondsTimeOutInterval < -1 || millisecondsTimeOutInterval > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, true); + return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, true); } public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, long millisecondsTimeOutInterval, bool executeOnlyOnce) { if (millisecondsTimeOutInterval < -1 || millisecondsTimeOutInterval > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, false); + return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, false); } public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, TimeSpan timeout, bool executeOnlyOnce) { int tm = WaitHandle.ToTimeoutMilliseconds(timeout); - return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)tm, executeOnlyOnce, true); + return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)tm, executeOnlyOnce, true); } public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, TimeSpan timeout, bool executeOnlyOnce) { int tm = WaitHandle.ToTimeoutMilliseconds(timeout); - return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)tm, executeOnlyOnce, false); + return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)tm, executeOnlyOnce, false); } public static bool QueueUserWorkItem(WaitCallback callBack) => @@ -1069,7 +1069,7 @@ namespace System.Threading return true; } - public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, Object state) + public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, object state) { if (callBack == null) { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadStart.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadStart.cs deleted file mode 100644 index 5532539fc7..0000000000 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/ThreadStart.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================================= -** -** -** -** Purpose: This class is a Delegate which defines the start method -** for starting a thread. That method must match this delegate. -** -** -=============================================================================*/ - -namespace System.Threading -{ - public delegate void ThreadStart(); -} diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Timer.Unix.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Timer.Unix.cs index 403478d98a..705f93e7a7 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Timer.Unix.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Timer.Unix.cs @@ -32,7 +32,7 @@ namespace System.Threading // Note: AutoResetEvent.WaitOne takes an Int32 value as a timeout. // The TimerQueue code ensures that timer duration is not greater than max Int32 value - Debug.Assert(actualDuration <= (uint)Int32.MaxValue); + Debug.Assert(actualDuration <= (uint)int.MaxValue); s_nextTimerDuration = (int)actualDuration; // If this is the first time the timer is set then we need to create a thread that diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Timer.Windows.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Timer.Windows.cs index 7020e1a2ce..a3bea70888 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Timer.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Timer.Windows.cs @@ -66,7 +66,7 @@ namespace System.Threading { private void SignalNoCallbacksRunning() { - Interop.mincore.SetEvent(_notifyWhenNoCallbacksRunning.SafeWaitHandle); + Interop.Kernel32.SetEvent(_notifyWhenNoCallbacksRunning.SafeWaitHandle); } } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Timer.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Timer.cs index fc284fd4e9..9fd71a0b41 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Timer.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Timer.cs @@ -6,7 +6,7 @@ using System.Diagnostics; namespace System.Threading { - public delegate void TimerCallback(Object state); + public delegate void TimerCallback(object state); // // TimerQueue maintains a list of active timers in this AppDomain. We use a single native timer to schedule @@ -51,7 +51,7 @@ namespace System.Threading #region interface to native per-AppDomain timer private int _currentNativeTimerStartTicks; - private uint _currentNativeTimerDuration = UInt32.MaxValue; + private uint _currentNativeTimerDuration = uint.MaxValue; private void EnsureAppDomainTimerFiresBy(uint requestedDuration) { @@ -66,7 +66,7 @@ namespace System.Threading const uint maxPossibleDuration = 0x0fffffff; uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration); - if (_currentNativeTimerDuration != UInt32.MaxValue) + if (_currentNativeTimerDuration != uint.MaxValue) { uint elapsed = (uint)(TickCount - _currentNativeTimerStartTicks); if (elapsed >= _currentNativeTimerDuration) @@ -109,7 +109,7 @@ namespace System.Threading // // since we got here, that means our previous timer has fired. // - _currentNativeTimerDuration = UInt32.MaxValue; + _currentNativeTimerDuration = uint.MaxValue; bool haveTimerToSchedule = false; uint nextAppDomainTimerDuration = uint.MaxValue; @@ -298,7 +298,7 @@ namespace System.Threading // Info about the user's callback // private readonly TimerCallback _timerCallback; - private readonly Object _state; + private readonly object _state; private readonly ExecutionContext _executionContext; @@ -496,12 +496,12 @@ namespace System.Threading public sealed class Timer : MarshalByRefObject, IDisposable { - private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe; + private const uint MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe; private TimerHolder _timer; public Timer(TimerCallback callback, - Object state, + object state, int dueTime, int period) { @@ -510,11 +510,11 @@ namespace System.Threading if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period); + TimerSetup(callback, state, (uint)dueTime, (uint)period); } public Timer(TimerCallback callback, - Object state, + object state, TimeSpan dueTime, TimeSpan period) { @@ -530,20 +530,20 @@ namespace System.Threading if (periodTm > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(periodTm), SR.ArgumentOutOfRange_PeriodTooLarge); - TimerSetup(callback, state, (UInt32)dueTm, (UInt32)periodTm); + TimerSetup(callback, state, (uint)dueTm, (uint)periodTm); } [CLSCompliant(false)] public Timer(TimerCallback callback, - Object state, - UInt32 dueTime, - UInt32 period) + object state, + uint dueTime, + uint period) { TimerSetup(callback, state, dueTime, period); } public Timer(TimerCallback callback, - Object state, + object state, long dueTime, long period) { @@ -555,7 +555,7 @@ namespace System.Threading throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge); if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge); - TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period); + TimerSetup(callback, state, (uint)dueTime, (uint)period); } public Timer(TimerCallback callback) @@ -565,13 +565,13 @@ namespace System.Threading // for a timer to be fired before the returned value is assigned to the variable, // potentially causing the callback to reference a bogus value (if passing the timer to the callback). - TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period); + TimerSetup(callback, this, (uint)dueTime, (uint)period); } private void TimerSetup(TimerCallback callback, - Object state, - UInt32 dueTime, - UInt32 period) + object state, + uint dueTime, + uint period) { if (callback == null) throw new ArgumentNullException(nameof(TimerCallback)); @@ -586,7 +586,7 @@ namespace System.Threading if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - return _timer.m_timer.Change((UInt32)dueTime, (UInt32)period); + return _timer.m_timer.Change((uint)dueTime, (uint)period); } public bool Change(TimeSpan dueTime, TimeSpan period) @@ -595,7 +595,7 @@ namespace System.Threading } [CLSCompliant(false)] - public bool Change(UInt32 dueTime, UInt32 period) + public bool Change(uint dueTime, uint period) { return _timer.m_timer.Change(dueTime, period); } @@ -611,7 +611,7 @@ namespace System.Threading if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge); - return _timer.m_timer.Change((UInt32)dueTime, (UInt32)period); + return _timer.m_timer.Change((uint)dueTime, (uint)period); } public bool Dispose(WaitHandle notifyObject) diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Volatile.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Volatile.cs index d9a009d731..00543f82da 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Volatile.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Volatile.cs @@ -17,76 +17,76 @@ namespace System.Threading public static unsafe class Volatile { #region Boolean - private struct VolatileBoolean { public volatile Boolean Value; } + private struct VolatileBoolean { public volatile bool Value; } - public static Boolean Read(ref Boolean location) + public static bool Read(ref bool location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } - public static void Write(ref Boolean location, Boolean value) + public static void Write(ref bool location, bool value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region Byte - private struct VolatileByte { public volatile Byte Value; } + private struct VolatileByte { public volatile byte Value; } - public static Byte Read(ref Byte location) + public static byte Read(ref byte location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } - public static void Write(ref Byte location, Byte value) + public static void Write(ref byte location, byte value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region Double - public static Double Read(ref Double location) + public static double Read(ref double location) { - Int64 result = Read(ref Unsafe.As(ref location)); + long result = Read(ref Unsafe.As(ref location)); return *(double*)&result; } - public static void Write(ref Double location, Double value) + public static void Write(ref double location, double value) { - Write(ref Unsafe.As(ref location), *(Int64*)&value); + Write(ref Unsafe.As(ref location), *(long*)&value); } #endregion #region Int16 - private struct VolatileInt16 { public volatile Int16 Value; } + private struct VolatileInt16 { public volatile short Value; } - public static Int16 Read(ref Int16 location) + public static short Read(ref short location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } - public static void Write(ref Int16 location, Int16 value) + public static void Write(ref short location, short value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region Int32 - private struct VolatileInt32 { public volatile Int32 Value; } + private struct VolatileInt32 { public volatile int Value; } - public static Int32 Read(ref Int32 location) + public static int Read(ref int location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } - public static void Write(ref Int32 location, Int32 value) + public static void Write(ref int location, int value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region Int64 - public static Int64 Read(ref Int64 location) + public static long Read(ref long location) { #if BIT64 return (Int64)Unsafe.As(ref location).Value; @@ -95,7 +95,7 @@ namespace System.Threading #endif } - public static void Write(ref Int64 location, Int64 value) + public static void Write(ref long location, long value) { #if BIT64 Unsafe.As(ref location).Value = (IntPtr)value; @@ -123,78 +123,78 @@ namespace System.Threading #endregion #region SByte - private struct VolatileSByte { public volatile SByte Value; } + private struct VolatileSByte { public volatile sbyte Value; } [CLSCompliant(false)] - public static SByte Read(ref SByte location) + public static sbyte Read(ref sbyte location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } [CLSCompliant(false)] - public static void Write(ref SByte location, SByte value) + public static void Write(ref sbyte location, sbyte value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region Single - private struct VolatileSingle { public volatile Single Value; } + private struct VolatileSingle { public volatile float Value; } - public static Single Read(ref Single location) + public static float Read(ref float location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } - public static void Write(ref Single location, Single value) + public static void Write(ref float location, float value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region UInt16 - private struct VolatileUInt16 { public volatile UInt16 Value; } + private struct VolatileUInt16 { public volatile ushort Value; } [CLSCompliant(false)] - public static UInt16 Read(ref UInt16 location) + public static ushort Read(ref ushort location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } [CLSCompliant(false)] - public static void Write(ref UInt16 location, UInt16 value) + public static void Write(ref ushort location, ushort value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region UInt32 - private struct VolatileUInt32 { public volatile UInt32 Value; } + private struct VolatileUInt32 { public volatile uint Value; } [CLSCompliant(false)] - public static UInt32 Read(ref UInt32 location) + public static uint Read(ref uint location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } [CLSCompliant(false)] - public static void Write(ref UInt32 location, UInt32 value) + public static void Write(ref uint location, uint value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region UInt64 [CLSCompliant(false)] - public static UInt64 Read(ref UInt64 location) + public static ulong Read(ref ulong location) { - return (UInt64)Read(ref Unsafe.As(ref location)); + return (ulong)Read(ref Unsafe.As(ref location)); } [CLSCompliant(false)] - public static void Write(ref UInt64 location, UInt64 value) + public static void Write(ref ulong location, ulong value) { - Write(ref Unsafe.As(ref location), (Int64)value); + Write(ref Unsafe.As(ref location), (long)value); } #endregion @@ -215,7 +215,7 @@ namespace System.Threading #endregion #region T - private struct VolatileObject { public volatile Object Value; } + private struct VolatileObject { public volatile object Value; } public static T Read(ref T location) where T : class { diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/WaitHandle.Windows.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/WaitHandle.Windows.cs index bda696cca6..9768363875 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/WaitHandle.Windows.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/WaitHandle.Windows.cs @@ -260,7 +260,7 @@ namespace System.Threading default: var ex = new Exception(); - ex.SetErrorCode(errorCode); + ex.HResult = errorCode; throw ex; } } @@ -300,7 +300,7 @@ namespace System.Threading default: Exception ex = new Exception(); - ex.SetErrorCode(errorCode); + ex.HResult = errorCode; throw ex; } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/WaitHandle.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/WaitHandle.cs index ef7f47f5ee..4d96a88304 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/WaitHandle.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/WaitHandle.cs @@ -406,7 +406,7 @@ namespace System.Threading internal static void ThrowInvalidHandleException() { var ex = new InvalidOperationException(SR.InvalidOperation_InvalidHandle); - ex.SetErrorCode(HResults.E_HANDLE); + ex.HResult = HResults.E_HANDLE; throw ex; } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/Threading/Win32ThreadPoolNativeOverlapped.cs b/external/corert/src/System.Private.CoreLib/src/System/Threading/Win32ThreadPoolNativeOverlapped.cs index 3249e50374..a47c16d8f0 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Threading/Win32ThreadPoolNativeOverlapped.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/Threading/Win32ThreadPoolNativeOverlapped.cs @@ -199,6 +199,12 @@ namespace System.Threading Debug.Assert(!data._completed); data._completed = true; + if (data._executionContext == null) + { + data._callback(errorCode, bytesWritten, ToNativeOverlapped(overlapped)); + return; + } + ContextCallback callback = s_executionContextCallback; if (callback == null) s_executionContextCallback = callback = OnExecutionContextCallback; diff --git a/external/corert/src/System.Private.CoreLib/src/System/ThrowHelper.cs b/external/corert/src/System.Private.CoreLib/src/System/ThrowHelper.cs index a3e3a0602b..0aee323ef3 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/ThrowHelper.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/ThrowHelper.cs @@ -203,6 +203,11 @@ namespace System throw new InvalidOperationException(SR.InvalidOperation_NoValue); } + internal static void ThrowInvalidOperationException_ConcurrentOperationsNotSupported() + { + throw new InvalidOperationException(SR.InvalidOperation_ConcurrentOperationsNotSupported); + } + internal static void ThrowSerializationException(ExceptionResource resource) { throw new SerializationException(GetResourceString(resource)); @@ -321,6 +326,12 @@ namespace System return "source"; case ExceptionArgument.state: return "state"; + case ExceptionArgument.length: + return "length"; + case ExceptionArgument.comparisonType: + return "comparisonType"; + case ExceptionArgument.manager: + return "manager"; default: Debug.Fail("The enum value is not defined, please check the ExceptionArgument Enum."); return ""; @@ -369,6 +380,10 @@ namespace System return SR.TaskCompletionSourceT_TrySetException_NullException; case ExceptionResource.TaskCompletionSourceT_TrySetException_NoExceptions: return SR.TaskCompletionSourceT_TrySetException_NoExceptions; + case ExceptionResource.NotSupported_StringComparison: + return SR.NotSupported_StringComparison; + case ExceptionResource.ConcurrentCollection_SyncRoot_NotSupported: + return SR.ConcurrentCollection_SyncRoot_NotSupported; default: Debug.Assert(false, "The enum value is not defined, please check the ExceptionResource Enum."); @@ -414,7 +429,10 @@ namespace System comparer, comparable, source, - state + state, + length, + comparisonType, + manager } // @@ -441,5 +459,7 @@ namespace System TaskT_TransitionToFinal_AlreadyCompleted, TaskCompletionSourceT_TrySetException_NullException, TaskCompletionSourceT_TrySetException_NoExceptions, + NotSupported_StringComparison, + ConcurrentCollection_SyncRoot_NotSupported, } } diff --git a/external/corert/src/System.Private.CoreLib/src/System/TimeZoneInfo.WinRT.cs b/external/corert/src/System.Private.CoreLib/src/System/TimeZoneInfo.WinRT.cs index 4701b3e13a..f0593b8990 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/TimeZoneInfo.WinRT.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/TimeZoneInfo.WinRT.cs @@ -94,9 +94,9 @@ namespace System return true; } - private TimeZoneInfo(TimeZoneInformation zone, Boolean dstDisabled) + private TimeZoneInfo(TimeZoneInformation zone, bool dstDisabled) { - if (String.IsNullOrEmpty(zone.StandardName)) + if (string.IsNullOrEmpty(zone.StandardName)) { _id = LocalId; // the ID must contain at least 1 character - initialize m_id to "Local" } @@ -134,9 +134,9 @@ namespace System public unsafe TimeZoneInformation(TIME_DYNAMIC_ZONE_INFORMATION dtzi) { - StandardName = new String(dtzi.StandardName); - DaylightName = new String(dtzi.DaylightName); - TimeZoneKeyName = new String(dtzi.TimeZoneKeyName); + StandardName = new string(dtzi.StandardName); + DaylightName = new string(dtzi.DaylightName); + TimeZoneKeyName = new string(dtzi.TimeZoneKeyName); Dtzi = dtzi; } } @@ -150,7 +150,7 @@ namespace System // // assumes cachedData lock is taken // - private static TimeZoneInfoResult TryGetTimeZone(ref TimeZoneInformation timeZoneInformation, Boolean dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData) + private static TimeZoneInfoResult TryGetTimeZone(ref TimeZoneInformation timeZoneInformation, bool dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData) { TimeZoneInfoResult result = TimeZoneInfoResult.Success; e = null; @@ -822,10 +822,10 @@ namespace System { string s = new String(tdzi.StandardName); - if (!String.IsNullOrEmpty(s) && + if (!string.IsNullOrEmpty(s) && EqualStandardDates(timeZoneInformation, ref tdzi) && (notSupportedDaylightSaving || EqualDaylightDates(timeZoneInformation, ref tdzi)) && - String.Compare(s, timeZoneInformation.StandardName, StringComparison.Ordinal) == 0) + string.Compare(s, timeZoneInformation.StandardName, StringComparison.Ordinal) == 0) { // found a match timeZoneInformation.TimeZoneKeyName = s; @@ -861,10 +861,10 @@ namespace System return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId); } - Boolean dstDisabled = timeZoneInformation.Dtzi.DynamicDaylightTimeDisabled != 0; + bool dstDisabled = timeZoneInformation.Dtzi.DynamicDaylightTimeDisabled != 0; //// check to see if we can use the key name returned from the API call - if (!String.IsNullOrEmpty(timeZoneInformation.TimeZoneKeyName) || FindMatchToCurrentTimeZone(timeZoneInformation)) + if (!string.IsNullOrEmpty(timeZoneInformation.TimeZoneKeyName) || FindMatchToCurrentTimeZone(timeZoneInformation)) { TimeZoneInfo zone = null; Exception ex; diff --git a/external/corert/src/System.Private.CoreLib/src/System/ValueType.cs b/external/corert/src/System.Private.CoreLib/src/System/ValueType.cs index 2c71bbcfe2..7fad0ee311 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/ValueType.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/ValueType.cs @@ -26,7 +26,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class ValueType { - public override String ToString() + public override string ToString() { return this.GetType().ToString(); } diff --git a/external/corert/src/System.Private.CoreLib/src/System/WeakReference.cs b/external/corert/src/System.Private.CoreLib/src/System/WeakReference.cs index 4996e94ee5..8ebe58b51c 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/WeakReference.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/WeakReference.cs @@ -35,14 +35,14 @@ namespace System // Creates a new WeakReference that keeps track of target. // Assumes a Short Weak Reference (ie TrackResurrection is false.) // - public WeakReference(Object target) + public WeakReference(object target) : this(target, false) { } //Creates a new WeakReference that keeps track of target. // - public WeakReference(Object target, bool trackResurrection) + public WeakReference(object target, bool trackResurrection) { m_IsLongReference = trackResurrection; m_handle = GCHandle.ToIntPtr(GCHandle.Alloc(target, trackResurrection ? GCHandleType.WeakTrackResurrection : GCHandleType.Weak)); @@ -58,7 +58,7 @@ namespace System throw new ArgumentNullException(nameof(info)); } - Object target = info.GetValue("TrackedObject", typeof(Object)); // Do not rename (binary serialization) + object target = info.GetValue("TrackedObject", typeof(object)); // Do not rename (binary serialization) bool trackResurrection = info.GetBoolean("TrackResurrection"); // Do not rename (binary serialization) m_IsLongReference = trackResurrection; @@ -105,7 +105,7 @@ namespace System //Gets the Object stored in the handle if it's accessible. // Or sets it. // - public virtual Object Target + public virtual object Target { get { @@ -115,7 +115,7 @@ namespace System if (default(IntPtr) == h) return null; - Object o = RuntimeImports.RhHandleGet(h); + object o = RuntimeImports.RhHandleGet(h); if (o == null) { @@ -188,7 +188,7 @@ namespace System /// and gets\create a new RCW in case it is alive. /// /// - private Object TryGetComTarget() + private object TryGetComTarget() { #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; @@ -231,7 +231,7 @@ namespace System throw new ArgumentNullException(nameof(info)); } - info.AddValue("TrackedObject", Target, typeof(Object)); // Do not rename (binary serialization) + info.AddValue("TrackedObject", Target, typeof(object)); // Do not rename (binary serialization) info.AddValue("TrackResurrection", m_IsLongReference); // Do not rename (binary serialization) } diff --git a/external/corert/src/System.Private.CoreLib/src/System/WeakReferenceOfT.cs b/external/corert/src/System.Private.CoreLib/src/System/WeakReferenceOfT.cs index e36cda5082..81040e3e4b 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/WeakReferenceOfT.cs +++ b/external/corert/src/System.Private.CoreLib/src/System/WeakReferenceOfT.cs @@ -134,7 +134,7 @@ namespace System /// and gets\create a new RCW in case it is alive. /// /// - private Object TryGetComTarget() + private object TryGetComTarget() { #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; diff --git a/external/corert/src/System.Private.Interop/src/Interop/Interop.COM.Windows.cs b/external/corert/src/System.Private.Interop/src/Interop/Interop.COM.Windows.cs index df0b5d6755..8aaa8930de 100644 --- a/external/corert/src/System.Private.Interop/src/Interop/Interop.COM.Windows.cs +++ b/external/corert/src/System.Private.Interop/src/Interop/Interop.COM.Windows.cs @@ -37,36 +37,6 @@ namespace System.Runtime.InteropServices internal const string CORE_COM_AUT = "OleAut32.dll"; } -#if CORECLR - public static unsafe void SafeCoTaskMemFree(void* pv) - { - // Even though CoTaskMemFree is a no-op for NULLs, skipping the interop call entirely is faster - if (pv != null) - Marshal.FreeCoTaskMem(new IntPtr(pv)); - } - - public static unsafe IntPtr SysAllocStringLen(char* pStrIn, UInt32 dwSize) - { - string srcString = new string(pStrIn, 0, checked((int)dwSize)); - return Marshal.StringToBSTR(srcString); - } - - public static unsafe void SysFreeString(void* pBSTR) - { - SysFreeString(new IntPtr(pBSTR)); - } - - public static unsafe void SysFreeString(IntPtr pBSTR) - { - Marshal.FreeBSTR(pBSTR); - } - - internal static void VariantClear(IntPtr pObject) - { - //Nop - } - -#else [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] internal static extern unsafe int CoCreateInstanceFromApp( @@ -79,60 +49,26 @@ namespace System.Runtime.InteropServices ); [DllImport(Libraries.CORE_COM, PreserveSig = false)] - [SuppressUnmanagedCodeSecurity] internal static extern void CreateBindCtx(UInt32 reserved, out IBindCtx ppbc); [DllImport(Libraries.CORE_COM, PreserveSig = false)] - [SuppressUnmanagedCodeSecurity] internal static extern void MkParseDisplayName(IBindCtx pbc, [MarshalAs(UnmanagedType.LPWStr)] String szUserName, out UInt32 pchEaten, out IMoniker ppmk); #if !TARGET_CORE_API_SET // BindMoniker not available in core API set [DllImport(Libraries.CORE_COM, PreserveSig = false)] - [SuppressUnmanagedCodeSecurity] internal static extern void BindMoniker(IMoniker pmk, UInt32 grfOpt, ref Guid iidResult, [MarshalAs(UnmanagedType.Interface)] out Object ppvResult); #endif - [DllImport(Libraries.CORE_COM_AUT)] - [McgGeneratedNativeCallCodeAttribute] - [MethodImplAttribute(MethodImplOptions.NoInlining)] - public static extern unsafe void SysFreeString(void* pBSTR); - - public static unsafe void SysFreeString(IntPtr pBstr) - { - SysFreeString((void*)pBstr); - } - - [DllImport(Libraries.CORE_COM_AUT)] - [McgGeneratedNativeCallCodeAttribute] - [MethodImplAttribute(MethodImplOptions.NoInlining)] - public static extern unsafe uint SysStringLen(void* pBSTR); - public static unsafe uint SysStringLen(IntPtr pBSTR) - { - return SysStringLen((void*)pBSTR); - } - - [DllImport(Libraries.CORE_COM_AUT)] - [McgGeneratedNativeCallCodeAttribute] - [MethodImplAttribute(MethodImplOptions.NoInlining)] - public static extern unsafe IntPtr SysAllocString(IntPtr pStrIn); - - [DllImport(Libraries.CORE_COM_AUT)] - [McgGeneratedNativeCallCodeAttribute] - [MethodImplAttribute(MethodImplOptions.NoInlining)] - public static extern unsafe char* SysAllocStringLen(char* pStrIn, uint len); - [DllImport(Libraries.CORE_COM_AUT)] [McgGeneratedNativeCallCodeAttribute] internal static extern void VariantClear(IntPtr pObject); - public static unsafe void SafeCoTaskMemFree(void* pv) { // Even though CoTaskMemFree is a no-op for NULLs, skipping the interop call entirely is faster if (pv != null) PInvokeMarshal.CoTaskMemFree(new IntPtr(pv)); } -#endif //CORECLR } } diff --git a/external/corert/src/System.Private.Interop/src/Interop/Interop.Common.Windows.cs b/external/corert/src/System.Private.Interop/src/Interop/Interop.Common.Windows.cs index 46c5696e73..7d9c26bb96 100644 --- a/external/corert/src/System.Private.Interop/src/Interop/Interop.Common.Windows.cs +++ b/external/corert/src/System.Private.Interop/src/Interop/Interop.Common.Windows.cs @@ -32,13 +32,6 @@ namespace System.Runtime.InteropServices internal const string CORE_DEBUG = "kernel32.dll"; #endif //TARGET_CORE_API_SET } -#if CORECLR - - internal static int GetLastWin32Error() - { - return 0; - } -#else [DllImport(Libraries.CORE_DEBUG, EntryPoint = "OutputDebugStringW")] [McgGeneratedNativeCallCodeAttribute] @@ -51,6 +44,5 @@ namespace System.Runtime.InteropServices OutputDebugString(pOutputString); } } -#endif } } diff --git a/external/corert/src/System.Private.Interop/src/Interop/Interop.String.Windows.cs b/external/corert/src/System.Private.Interop/src/Interop/Interop.String.Windows.cs index 1b319926de..d8c5fcd34c 100644 --- a/external/corert/src/System.Private.Interop/src/Interop/Interop.String.Windows.cs +++ b/external/corert/src/System.Private.Interop/src/Interop/Interop.String.Windows.cs @@ -37,23 +37,33 @@ namespace System.Runtime.InteropServices #endif //TARGET_CORE_API_SET } -#if CORECLR + [DllImport(Libraries.CORE_COM_AUT)] + [McgGeneratedNativeCallCodeAttribute] + [MethodImplAttribute(MethodImplOptions.NoInlining)] + public static extern unsafe void SysFreeString(void* pBSTR); - public static unsafe uint SysStringLen(void* pBSTR) + public static unsafe void SysFreeString(IntPtr pBstr) { - throw new PlatformNotSupportedException("SysStringLen"); + SysFreeString((void*)pBstr); } + [DllImport(Libraries.CORE_COM_AUT)] + [McgGeneratedNativeCallCodeAttribute] + [MethodImplAttribute(MethodImplOptions.NoInlining)] + public static extern unsafe uint SysStringLen(void* pBSTR); public static unsafe uint SysStringLen(IntPtr pBSTR) { - throw new PlatformNotSupportedException("SysStringLen"); + return SysStringLen((void*)pBSTR); } - // Do nothing - internal static unsafe void OutputDebugString(string outputString) - { + [DllImport(Libraries.CORE_COM_AUT)] + [McgGeneratedNativeCallCodeAttribute] + [MethodImplAttribute(MethodImplOptions.NoInlining)] + public static extern unsafe IntPtr SysAllocString(IntPtr pStrIn); - } -#endif //CORECLR + [DllImport(Libraries.CORE_COM_AUT)] + [McgGeneratedNativeCallCodeAttribute] + [MethodImplAttribute(MethodImplOptions.NoInlining)] + public static extern unsafe char* SysAllocStringLen(char* pStrIn, uint len); } } diff --git a/external/corert/src/System.Private.Interop/src/InteropExtensions/InteropExtensions.cs b/external/corert/src/System.Private.Interop/src/InteropExtensions/InteropExtensions.cs index 93c46d95b2..1b6d888d87 100644 --- a/external/corert/src/System.Private.Interop/src/InteropExtensions/InteropExtensions.cs +++ b/external/corert/src/System.Private.Interop/src/InteropExtensions/InteropExtensions.cs @@ -374,7 +374,7 @@ namespace System.Runtime.InteropServices { throw new NotSupportedException("RuntimeHandleCompareExchangeVariableType"); } - + public static void SetExceptionErrorCode(Exception exception, int hr) { throw new NotSupportedException("SetExceptionErrorCode"); diff --git a/external/corert/src/System.Private.Interop/src/Shared/ComCallableObject.cs b/external/corert/src/System.Private.Interop/src/Shared/ComCallableObject.cs index 7bce62ca85..372621f9e6 100644 --- a/external/corert/src/System.Private.Interop/src/Shared/ComCallableObject.cs +++ b/external/corert/src/System.Private.Interop/src/Shared/ComCallableObject.cs @@ -1722,6 +1722,10 @@ namespace System.Runtime.InteropServices #endif // IDispatch is not supported for UWP apps new CCWWellKnownType() {guid = Interop.COM.IID_IDispatch, type = InternalTypes.IDispatch, ccwSupport = CCWSupport.NotSupport }, +#if ENABLE_WINRT + // ILanguageExceptionStackBackTrace is supported iff managed object is an Exception object + new CCWWellKnownType() {guid = Interop.COM.IID_ILanguageExceptionStackBackTrace, type = InternalTypes.ILanguageExceptionStackBackTrace, ccwSupport = CCWSupport.DependsOnCast, castToType = typeof(Exception).TypeHandle}, +#endif }; private static bool IsWellKnownInterface(ref Guid guid, object targetObject,ref RuntimeTypeHandle interfaceType,out bool isCCWSupported) diff --git a/external/corert/src/System.Private.Interop/src/Shared/ComException.cs b/external/corert/src/System.Private.Interop/src/Shared/ComException.cs index 0d78808a81..84f04e8211 100644 --- a/external/corert/src/System.Private.Interop/src/Shared/ComException.cs +++ b/external/corert/src/System.Private.Interop/src/Shared/ComException.cs @@ -21,7 +21,9 @@ namespace System.Runtime.InteropServices { // Exception for COM Interop errors where we don't recognize the HResult. [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public class COMException : ExternalException { internal COMException(int hr) diff --git a/external/corert/src/System.Private.Interop/src/Shared/InternalModule.cs b/external/corert/src/System.Private.Interop/src/Shared/InternalModule.cs index 7fcf4a1d17..2a47be14c0 100644 --- a/external/corert/src/System.Private.Interop/src/Shared/InternalModule.cs +++ b/external/corert/src/System.Private.Interop/src/Shared/InternalModule.cs @@ -30,6 +30,7 @@ namespace System.Runtime.InteropServices internal static RuntimeTypeHandle IManagedActivationFactory = typeof(System.Runtime.InteropServices.WindowsRuntime.IManagedActivationFactory).TypeHandle; internal static RuntimeTypeHandle IRestrictedErrorInfo = typeof(System.Runtime.InteropServices.ExceptionHelpers.__com_IRestrictedErrorInfo).TypeHandle; internal static RuntimeTypeHandle HSTRING = typeof(System.Runtime.InteropServices.HSTRING).TypeHandle; + internal static RuntimeTypeHandle ILanguageExceptionStackBackTrace = typeof(System.Runtime.InteropServices.ExceptionHelpers.__com_ILanguageExceptionStackBackTrace).TypeHandle; #endif } @@ -195,6 +196,15 @@ namespace System.Runtime.InteropServices { ItfType = InternalTypes.HSTRING }; + + // ILanguageExceptionStackBackTrace + internal static McgInterfaceData s_ILanguageExceptionStackBackTrace = new McgInterfaceData + { + ItfType = InternalTypes.ILanguageExceptionStackBackTrace, + ItfGuid = Interop.COM.IID_ILanguageExceptionStackBackTrace, + Flags = McgInterfaceFlags.isInternal, + CcwVtable = System.Runtime.InteropServices.ExceptionHelpers.__vtable_ILanguageExceptionStackBackTrace.GetVtableFuncPtr(), + }; #endif static readonly McgInterfaceData[] s_interfaceData = new McgInterfaceData[] { @@ -220,7 +230,8 @@ namespace System.Runtime.InteropServices s_IDispatch, #if ENABLE_WINRT - s_HSTRING + s_HSTRING, + s_ILanguageExceptionStackBackTrace #endif }; } diff --git a/external/corert/src/System.Private.Interop/src/Shared/Interop.Manual.cs b/external/corert/src/System.Private.Interop/src/Shared/Interop.Manual.cs index fe0861c0db..75c5868f4b 100644 --- a/external/corert/src/System.Private.Interop/src/Shared/Interop.Manual.cs +++ b/external/corert/src/System.Private.Interop/src/Shared/Interop.Manual.cs @@ -58,6 +58,8 @@ partial class Interop internal static Guid IID_IDispatch = new Guid(0x00020400, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); internal static Guid IID_IManagedActivationFactory = new Guid(0x60D27C8D, 0x5F61, 0x4CCE, 0xB7, 0x51, 0x69, 0x0F, 0xAE, 0x66, 0xAA, 0x53); internal static Guid IID_IActivationFactoryInternal = new Guid(0x00000035, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); + // CBE53FB5-F967-4258-8D34-42F5E25833DE + internal static Guid IID_ILanguageExceptionStackBackTrace = new Guid(unchecked((int)0xCBE53FB5), unchecked((short)0xF967), 0x4258, 0x8D, 0x34, 0x42, 0xF5, 0xE2, 0x58, 0x33,0xDE); // // Jupiter IIDs. // diff --git a/external/corert/src/System.Private.Interop/src/Shared/McgHelpers.cs b/external/corert/src/System.Private.Interop/src/Shared/McgHelpers.cs index d6d8caac6c..bb6ffd7c38 100644 --- a/external/corert/src/System.Private.Interop/src/Shared/McgHelpers.cs +++ b/external/corert/src/System.Private.Interop/src/Shared/McgHelpers.cs @@ -394,7 +394,7 @@ namespace System.Runtime.InteropServices *((IntPtr*)pItem) = McgMarshal.ObjectToComInterface(item, interfaceType.GetElementInterfaceType()); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) @@ -424,7 +424,7 @@ namespace System.Runtime.InteropServices *((uint*)pSize) = (uint)CalliIntrinsics.Call(thunk, list, Toolbox.IList_Oper.GetCount, 0, ref dummy); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -452,7 +452,7 @@ namespace System.Runtime.InteropServices *((IntPtr*)pView) = McgMarshal.ObjectToComInterface(view, interfaceType.GetVectorViewType()); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -492,7 +492,7 @@ namespace System.Runtime.InteropServices *((int*)pIndex) = index; } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -525,7 +525,7 @@ namespace System.Runtime.InteropServices CalliIntrinsics.Call(thunk, list, Toolbox.IList_Oper.SetItem, (int)index, ref value); } } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) @@ -565,7 +565,7 @@ namespace System.Runtime.InteropServices CalliIntrinsics.Call(thunk, list, Toolbox.IList_Oper.Insert, (int)index, ref value); } } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) @@ -600,7 +600,7 @@ namespace System.Runtime.InteropServices } } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) @@ -631,7 +631,7 @@ namespace System.Runtime.InteropServices CalliIntrinsics.Call(thunk, list, Toolbox.IList_Oper.Add, 0, ref value); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -667,7 +667,7 @@ namespace System.Runtime.InteropServices CalliIntrinsics.Call(thunk, list, Toolbox.IList_Oper.RemoveAt, (int)(listCount - 1), ref dummy); } } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) @@ -698,7 +698,7 @@ namespace System.Runtime.InteropServices CalliIntrinsics.Call(thunk, list, Toolbox.IList_Oper.Clear, 0, ref dummy); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -754,7 +754,7 @@ namespace System.Runtime.InteropServices *((uint*)pCount) = itemCount; } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -789,7 +789,7 @@ namespace System.Runtime.InteropServices CalliIntrinsics.Call(thunk, list, Toolbox.IList_Oper.Add, 0, ref value); } } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -870,7 +870,7 @@ namespace System.Runtime.InteropServices CalliIntrinsics.Call(thunk, list, Toolbox.IList_Oper.GetItem, ref index, pItem); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) @@ -901,7 +901,7 @@ namespace System.Runtime.InteropServices *((uint*)pSize) = (uint)size; } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -928,7 +928,7 @@ namespace System.Runtime.InteropServices *((IntPtr*)pView) = McgMarshal.ObjectToComInterface(view, interfaceType.GetVectorViewType()); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -967,7 +967,7 @@ namespace System.Runtime.InteropServices *((int*)pIndex) = index; } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -992,7 +992,7 @@ namespace System.Runtime.InteropServices int index = (int)_index; CalliIntrinsics.Call(thunk, list, Toolbox.IList_Oper.SetItem, ref index, (IntPtr)(&_value)); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) @@ -1023,7 +1023,7 @@ namespace System.Runtime.InteropServices CalliIntrinsics.Call(thunk, list, Toolbox.IList_Oper.Insert, ref index, (IntPtr)(&_value)); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) @@ -1053,7 +1053,7 @@ namespace System.Runtime.InteropServices CalliIntrinsics.Call(thunk, list, Toolbox.IList_Oper.RemoveAt, ref index, default(IntPtr)); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) @@ -1084,7 +1084,7 @@ namespace System.Runtime.InteropServices CalliIntrinsics.Call(thunk, list, Toolbox.IList_Oper.Add, ref dummy, (IntPtr)(&_value)); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -1122,7 +1122,7 @@ namespace System.Runtime.InteropServices CalliIntrinsics.Call(thunk, list, Toolbox.IList_Oper.RemoveAt, ref index, default(IntPtr)); } } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) @@ -1152,7 +1152,7 @@ namespace System.Runtime.InteropServices int dummy = 0; CalliIntrinsics.Call(thunk, list, Toolbox.IList_Oper.Clear, ref dummy, default(IntPtr)); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -1204,7 +1204,7 @@ namespace System.Runtime.InteropServices *((uint*)pCount) = itemCount; } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -1239,7 +1239,7 @@ namespace System.Runtime.InteropServices pItems = (IntPtr)((byte*)pItems + byteSize); } } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -1389,7 +1389,7 @@ namespace System.Runtime.InteropServices // Marshal to native iterator *((IntPtr*)pResult) = McgMarshal.ObjectToComInterface(enumerator, interfaceType.GetIteratorType()); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -1468,7 +1468,7 @@ namespace System.Runtime.InteropServices *((IntPtr*)pValue) = McgMarshal.ObjectToComInterface(item, interfaceType.GetElementInterfaceType()); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -1493,7 +1493,7 @@ namespace System.Runtime.InteropServices object item = null; *((byte*)pValue) = (byte)CalliIntrinsics.Call(thunk, iterator, Toolbox.IIterator_Oper.get_HasCurrent, ref item, 0); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -1518,7 +1518,7 @@ namespace System.Runtime.InteropServices object item = null; *((byte*)pValue) = (byte)CalliIntrinsics.Call(thunk, iterator, Toolbox.IIterator_Oper.MoveNext, ref item, 0); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -1553,7 +1553,7 @@ namespace System.Runtime.InteropServices dst[i] = McgMarshal.ObjectToComInterface(src[i], interfaceType.GetElementInterfaceType()); } } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -1619,7 +1619,7 @@ namespace System.Runtime.InteropServices int dummy = 0; CalliIntrinsics.Call(thunk, iterator, Toolbox.IIterator_Oper.get_Current, pValue, ref dummy); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -1646,7 +1646,7 @@ namespace System.Runtime.InteropServices *((byte*)pValue) = (byte)has; } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -1673,7 +1673,7 @@ namespace System.Runtime.InteropServices *((byte*)pValue) = (byte)has; } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -1702,7 +1702,7 @@ namespace System.Runtime.InteropServices PInvokeMarshal.CopyToNative(data, 0, pDest, count); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } @@ -1753,7 +1753,7 @@ namespace System.Runtime.InteropServices // Call handler.Invoke(asyncInfo, asyncStatus) CalliIntrinsics.Call(thunk, handler, asyncInfo, asyncStatus); } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } diff --git a/external/corert/src/System.Private.Interop/src/Shared/McgIntrinsics.cs b/external/corert/src/System.Private.Interop/src/Shared/McgIntrinsics.cs index 6c18ea1471..ca48d577b3 100644 --- a/external/corert/src/System.Private.Interop/src/Shared/McgIntrinsics.cs +++ b/external/corert/src/System.Private.Interop/src/Shared/McgIntrinsics.cs @@ -620,6 +620,8 @@ namespace System.Runtime.InteropServices // ICommand internal delegate int AddrOfICommandremove_CanExecuteChanged(IntPtr pComThis, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken unsafe_token); #endif + // ILanguageExceptionStackBackTrace + internal delegate int AddrOfILanguageExceptionStackBackTraceGetStackBackTrace(IntPtr pComThis, uint maxFramesToCapture, IntPtr stackBackTrace, IntPtr framesCaptured); } #if ENABLE_MIN_WINRT diff --git a/external/corert/src/System.Private.Interop/src/Shared/McgMarshal.cs b/external/corert/src/System.Private.Interop/src/Shared/McgMarshal.cs index d6ef590c2e..40ddc4f9de 100644 --- a/external/corert/src/System.Private.Interop/src/Shared/McgMarshal.cs +++ b/external/corert/src/System.Private.Interop/src/Shared/McgMarshal.cs @@ -4,8 +4,12 @@ // ---------------------------------------------------------------------------------- // Interop library code // -// Marshalling helpers used by MCG -// +// Marshalling helpers used by MCG generated stub +// McgMarshal covers full marshalling surface area and is entrypoint for all marshalling support. +// In long term: +// 1. MCG generated code should call McgMarshal to do marshalling +// 2. Public Marhshal API should call McgMarshal to do marshalling + // NOTE: // These source code are being published to InternalAPIs and consumed by RH builds // Use PublishInteropAPI.bat to keep the InternalAPI copies in sync @@ -143,7 +147,7 @@ namespace System.Runtime.InteropServices } #if ENABLE_MIN_WINRT - public static unsafe void SetExceptionErrorCode(Exception exception, int errorCode) + public static unsafe void SetExceptionErrorCode(Exception exception, int errorCode) { InteropExtensions.SetExceptionErrorCode(exception, errorCode); } @@ -364,6 +368,149 @@ namespace System.Runtime.InteropServices { return PInvokeMarshal.ByValAnsiStringToString(pchBuffer, charCount); } + + /// + /// CoTaskMemAlloc + ZeroMemory + /// @TODO - we can probably optimize the zero memory part later + /// + public unsafe static void* CoTaskMemAllocAndZeroMemory(IntPtr size) + { + void *ptr = (void*)PInvokeMarshal.CoTaskMemAlloc(new UIntPtr((void*)size)); + if (ptr == null) + return ptr; + + byte *pByte = (byte*)ptr; + long lSize = size.ToInt64(); + while (lSize > 0) + { + lSize--; + (*pByte++) = 0; + } + + return ptr; + } + + /// + /// Free allocated memory. The allocated memory should be allocated by CoTaskMemAlloc + /// + public static void SafeCoTaskMemFree(IntPtr allocatedMemory) + { + if (allocatedMemory != IntPtr.Zero) + PInvokeMarshal.CoTaskMemFree(allocatedMemory); + } + + /// + /// Free allocated memory. The allocated memory should be allocated by CoTaskMemAlloc + /// + public static unsafe void SafeCoTaskMemFree(void* pv) + { + if (pv != null) + PInvokeMarshal.CoTaskMemFree(new IntPtr(pv)); + } + + /// + /// Allocate a buffer with enough size to store the unicode characters saved in source + /// Buffer is allocated with CoTaskMemAlloc + /// + public unsafe static void *AllocUnicodeBuffer(string source) + { + if (source == null) + return null; + + int byteLen = checked((source.Length + 1) * 2); + + char* pBuf = (char*)PInvokeMarshal.CoTaskMemAlloc(new UIntPtr((uint)byteLen)); + if (pBuf == null) + throw new System.OutOfMemoryException(); + + return pBuf; + } + + /// + /// Copy unicode characters in source into dest, and terminating with null + /// + public unsafe static void CopyUnicodeString(string source, void* _dest) + { + if (source == null) + return; + + char* dest = (char *)_dest; + fixed (char* pSource = source) + { + int len = source.Length; + char* src = pSource; + + // Copy characters one by one, including the null terminator + for (int i = 0; i <= len; ++i) + { + *(dest++) = *(src++); + } + } + } + + /// + /// Convert String to BSTR + /// + public unsafe static ushort* ConvertStringToBSTR( + ushort* ptrToFirstCharInBSTR, + string strManaged) + { + if (strManaged == null) + return null; + + if (ptrToFirstCharInBSTR == null) + { + // If caller don't provided buffer, allocate the buffer and create string using SysAllocStringLen + fixed (char* ch = strManaged) + { + return (ushort*) ExternalInterop.SysAllocStringLen(ch, (uint)strManaged.Length); + } + } + else + { + // If caller provided a buffer, construct the BSTR manually. + + // set length + *((int*)ptrToFirstCharInBSTR - 1) = checked(strManaged.Length * 2); + + // copy characters from the managed string + fixed (char* ch = strManaged) + { + InteropExtensions.Memcpy( + (System.IntPtr)ptrToFirstCharInBSTR, + (System.IntPtr)ch, + (strManaged.Length + 1) * 2); + } + + return ptrToFirstCharInBSTR; + } + } + + /// + /// Convert BSTR to String + /// + public unsafe static string ConvertBSTRToString(ushort* bstr) + { + if (bstr == null) + return null; + return new string((char*)bstr, 0, (int)ExternalInterop.SysStringLen(bstr)); + } + + /// + /// Free Allocated BSTR + /// + public static unsafe void SysFreeString(void* pBSTR) + { + SysFreeString(new IntPtr(pBSTR)); + } + + /// + /// Free Allocated BSTR + /// + public unsafe static void SysFreeString(IntPtr pBSTR) + { + ExternalInterop.SysFreeString(pBSTR); + } #endif #if ENABLE_MIN_WINRT @@ -975,7 +1122,7 @@ namespace System.Runtime.InteropServices #endregion /// - /// This method returns HR for the exception being thrown. + /// This method propagate the exception being thrown. /// 1. On Windows8+, WinRT scenarios we do the following. /// a. Check whether the exception has any IRestrictedErrorInfo associated with it. /// If so, it means that this exception was actually caused by a native exception in which case we do simply use the same @@ -983,6 +1130,27 @@ namespace System.Runtime.InteropServices /// b. If not, this is actually a managed exception and in this case we RoOriginateLanguageException with the msg, hresult and the IErrorInfo /// associated with the managed exception. This helps us to retrieve the same exception in case it comes back to native. /// 2. On win8 and for classic COM scenarios. + /// a. This method should not be called + /// + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static bool PropagateException(Exception ex) + { +#if ENABLE_WINRT + return ExceptionHelpers.PropagateException(ex); +#else + // TODO : ExceptionHelpers should be platform specific , move it to + // seperate source files + return true; +#endif + } + + /// + /// This method returns HR for the exception being thrown. + /// 1. On Windows8+, WinRT scenarios + /// The work to propagate the exception should have already performed in the exception filter + /// by calling PropagateException() + /// 2. On win8 and for classic COM scenarios. /// a. We create IErrorInfo for the given Exception object and SetErrorInfo with the given IErrorInfo. /// /// diff --git a/external/corert/src/System.Private.Interop/src/Shared/StandardInterfaces.cs b/external/corert/src/System.Private.Interop/src/Shared/StandardInterfaces.cs index 24c04ecce5..d21279cc6c 100644 --- a/external/corert/src/System.Private.Interop/src/Shared/StandardInterfaces.cs +++ b/external/corert/src/System.Private.Interop/src/Shared/StandardInterfaces.cs @@ -742,7 +742,7 @@ namespace System.Runtime.InteropServices else *unsafe_stringRepresentation = McgMarshal.StringToHString(stringRepresentation); } - catch (Exception ex) + catch (Exception ex) when (McgMarshal.PropagateException(ex)) { return McgMarshal.GetHRForExceptionWinRT(ex); } @@ -1214,7 +1214,7 @@ namespace System.Runtime.InteropServices return hr; } - catch (Exception ex) + catch (Exception ex) when (McgMarshal.PropagateException(ex)) { return McgMarshal.GetHRForExceptionWinRT(ex); } @@ -1443,7 +1443,7 @@ namespace System.Runtime.InteropServices *pResult = (IntPtr)((IActivationFactoryInternal)target).ActivateInstance(); return Interop.COM.S_OK; } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { *pResult = default(IntPtr); return McgMarshal.GetHRForExceptionWinRT(hrExcep); @@ -1513,7 +1513,7 @@ namespace System.Runtime.InteropServices ((IManagedActivationFactory)ComCallableObject.GetTarget(pComThis)).RunClassConstructor(); return Interop.COM.S_OK; } - catch (System.Exception hrExcep) + catch (System.Exception hrExcep) when (McgMarshal.PropagateException(hrExcep)) { return McgMarshal.GetHRForExceptionWinRT(hrExcep); } diff --git a/external/corert/src/System.Private.Interop/src/Shared/StringPool.cs b/external/corert/src/System.Private.Interop/src/Shared/StringPool.cs index d78fdedd7a..eea2db4a66 100644 --- a/external/corert/src/System.Private.Interop/src/Shared/StringPool.cs +++ b/external/corert/src/System.Private.Interop/src/Shared/StringPool.cs @@ -19,7 +19,7 @@ namespace System.Runtime.InteropServices /// Functions: /// 1. GetString converts compressed string represented by an index to original System.String /// 2. StableStringHash computes hash code without decoding to System.String - /// 3. IsStringEqual compares compressed string represented by anindex with System.String + /// 3. IsStringEqual compares compressed string represented by an index with System.String /// /// TODO: /// 1. More string reuse diff --git a/external/corert/src/System.Private.Interop/src/Shared/__ComObject.cs.REMOVED.git-id b/external/corert/src/System.Private.Interop/src/Shared/__ComObject.cs.REMOVED.git-id index 618767a1ef..8d02b38b5f 100644 --- a/external/corert/src/System.Private.Interop/src/Shared/__ComObject.cs.REMOVED.git-id +++ b/external/corert/src/System.Private.Interop/src/Shared/__ComObject.cs.REMOVED.git-id @@ -1 +1 @@ -b68a81e0b13805a3945dadc0047f518b8d720231 \ No newline at end of file +0efd00ae2b50e39c76c0db97b31ee768c41dc4c2 \ No newline at end of file diff --git a/external/corert/src/System.Private.Interop/src/System.Private.Interop.Experimental.csproj b/external/corert/src/System.Private.Interop/src/System.Private.Interop.Experimental.csproj new file mode 100644 index 0000000000..3fcaee81cb --- /dev/null +++ b/external/corert/src/System.Private.Interop/src/System.Private.Interop.Experimental.csproj @@ -0,0 +1,9 @@ + + + System.Private.Interop.Experimental + true + true + + + + diff --git a/external/corert/src/System.Private.Interop/src/System.Private.Interop.csproj b/external/corert/src/System.Private.Interop/src/System.Private.Interop.csproj index 73411b2108..f3561abda8 100644 --- a/external/corert/src/System.Private.Interop/src/System.Private.Interop.csproj +++ b/external/corert/src/System.Private.Interop/src/System.Private.Interop.csproj @@ -1,7 +1,7 @@ - System.Private.Interop + System.Private.Interop Library true $(DefineConstants);TARGET_CORE_API_SET @@ -21,7 +21,8 @@ true - + + diff --git a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/InvalidComObjectException.cs b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/InvalidComObjectException.cs index 3d62cfc5ea..90213a357a 100644 --- a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/InvalidComObjectException.cs +++ b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/InvalidComObjectException.cs @@ -18,7 +18,9 @@ using System.Runtime.Serialization; namespace System.Runtime.InteropServices { [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public class InvalidComObjectException : SystemException { public InvalidComObjectException() diff --git a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs index d74ac6d388..7268fa97f6 100644 --- a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs +++ b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs @@ -21,7 +21,9 @@ using System.Runtime.Serialization; namespace System.Runtime.InteropServices { [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public class InvalidOleVariantTypeException : SystemException { public InvalidOleVariantTypeException() diff --git a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/Marshal.cs b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/Marshal.cs index d565e199f0..31365c9c7f 100644 --- a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/Marshal.cs +++ b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/Marshal.cs @@ -111,6 +111,44 @@ namespace System.Runtime.InteropServices return PtrToStringUni(ptr); } + public static unsafe String PtrToStringUTF8(IntPtr ptr) + { + if (IntPtr.Zero == ptr) + { + return null; + } + else + { + int nbBytes = lstrlenA(ptr); + return PtrToStringUTF8(ptr, nbBytes); + } + } + + public static unsafe String PtrToStringUTF8(IntPtr ptr, int byteLen) + { + if (byteLen < 0) + { + throw new ArgumentOutOfRangeException(nameof(byteLen), SR.ArgumentOutOfRange_NeedNonNegNum); + } + else if (IntPtr.Zero == ptr) + { + return null; + } + else if (IsWin32Atom(ptr)) + { + return null; + } + else if (byteLen == 0) + { + return string.Empty; + } + else + { + byte* pByte = (byte*)ptr.ToPointer(); + return Encoding.UTF8.GetString(pByte, byteLen); + } + } + //==================================================================== // SizeOf() //==================================================================== @@ -125,16 +163,16 @@ namespace System.Runtime.InteropServices public static int SizeOf(T structure) { - return SizeOf(); + return SizeOf((object)structure); } - public static int SizeOf(Object structure) + public static int SizeOf(object structure) { if (structure == null) throw new ArgumentNullException(nameof(structure)); // we never had a check for generics here - return SizeOfHelper(structure.GetType(), true); + return SizeOfHelper(structure.GetType()); } public static int SizeOf(Type t) @@ -144,27 +182,27 @@ namespace System.Runtime.InteropServices if (t.TypeHandle.IsGenericType() || t.TypeHandle.IsGenericTypeDefinition()) throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); - return SizeOfHelper(t, true); + return SizeOfHelper(t); } - private static int SizeOfHelper(Type t, bool throwIfNotMarshalable) + private static int SizeOfHelper(Type t) { RuntimeTypeHandle typeHandle = t.TypeHandle; - int size; - if (RuntimeInteropData.Instance.TryGetStructUnsafeStructSize(typeHandle, out size)) + if (RuntimeInteropData.Instance.TryGetStructUnsafeStructSize(typeHandle, out int size)) { return size; } - if (!typeHandle.IsBlittable() && !typeHandle.IsValueType()) - { - throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, t); - } - else + // IsBlittable() checks whether the type contains GC references. It is approximate check with false positives. + // This fallback path will return incorrect answer for types that do not contain GC references, but that are + // not actually blittable; e.g. for types with bool fields. + if (typeHandle.IsBlittable() && typeHandle.IsValueType()) { return typeHandle.GetValueTypeSize(); } + + throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, t); } //==================================================================== @@ -181,15 +219,7 @@ namespace System.Runtime.InteropServices if (t.TypeHandle.IsGenericType() || t.TypeHandle.IsGenericTypeDefinition()) throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); - - return OffsetOfHelper(t, fieldName); - } - - private static IntPtr OffsetOfHelper(Type t, String fieldName) - { - bool structExists; - uint offset; - if (RuntimeInteropData.Instance.TryGetStructFieldOffset(t.TypeHandle, fieldName, out structExists, out offset)) + if (RuntimeInteropData.Instance.TryGetStructFieldOffset(t.TypeHandle, fieldName, out bool structExists, out uint offset)) { return new IntPtr(offset); } @@ -199,10 +229,8 @@ namespace System.Runtime.InteropServices { throw new ArgumentException(SR.Format(SR.Argument_OffsetOfFieldNotFound, t.TypeHandle.GetDisplayName()), nameof(fieldName)); } - else - { - throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, t); - } + + throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, t); } public static IntPtr OffsetOf(String fieldName) @@ -813,6 +841,35 @@ namespace System.Runtime.InteropServices } } + public static unsafe IntPtr StringToCoTaskMemUTF8(String s) + { + if (s == null) + { + return IntPtr.Zero; + } + else + { + int nb = Encoding.UTF8.GetMaxByteCount(s.Length); + + IntPtr pMem = PInvokeMarshal.CoTaskMemAlloc(new UIntPtr((uint)nb + 1)); + + if (pMem == IntPtr.Zero) + { + throw new OutOfMemoryException(); + } + else + { + fixed (char* firstChar = s) + { + byte* pbMem = (byte*)pMem; + int nbWritten = Encoding.UTF8.GetBytes(firstChar, s.Length, pbMem, nb); + pbMem[nbWritten] = 0; + } + return pMem; + } + } + } + public static unsafe IntPtr StringToCoTaskMemAnsi(String s) { if (s == null) @@ -945,7 +1002,7 @@ namespace System.Runtime.InteropServices { if (IsNotWin32Atom(ptr)) { - ExternalInterop.SysFreeString(ptr); + McgMarshal.SysFreeString(ptr); } } @@ -991,6 +1048,12 @@ namespace System.Runtime.InteropServices FreeCoTaskMem(s); } + public static unsafe void ZeroFreeCoTaskMemUTF8(IntPtr s) + { + SecureZeroMemory(s, lstrlenA(s)); + FreeCoTaskMem(s); + } + public static void ZeroFreeGlobalAllocAnsi(IntPtr s) { SecureZeroMemory(s, lstrlenA(s)); @@ -1029,8 +1092,27 @@ namespace System.Runtime.InteropServices // Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0 int offset = structureTypeHandle.IsValueType() ? 1 : 0; + bool useMemCpy = false; - if (structureTypeHandle.IsBlittable() && structureTypeHandle.IsValueType()) + if (RuntimeInteropData.Instance.TryGetStructUnmarshalStub(structureTypeHandle, out IntPtr unmarshalStub)) + { + if (unmarshalStub != IntPtr.Zero) + { + InteropExtensions.PinObjectAndCall(structure, + unboxedStructPtr => + { + CalliIntrinsics.Call( + unmarshalStub, + (void*)ptr, // unsafe (no need to adjust as it is always struct) + ((void*)((IntPtr*)unboxedStructPtr + offset)) // safe (need to adjust offset as it could be class) + ); + }); + return; + } + useMemCpy = true; + } + + if (useMemCpy || structureTypeHandle.IsBlittable()) { int structSize = Marshal.SizeOf(structure); InteropExtensions.PinObjectAndCall(structure, @@ -1045,21 +1127,6 @@ namespace System.Runtime.InteropServices return; } - IntPtr unmarshalStub; - if (RuntimeInteropData.Instance.TryGetStructUnmarshalStub(structureTypeHandle, out unmarshalStub)) - { - InteropExtensions.PinObjectAndCall(structure, - unboxedStructPtr => - { - CalliIntrinsics.Call( - unmarshalStub, - (void*)ptr, // unsafe (no need to adjust as it is always struct) - ((void*)((IntPtr*)unboxedStructPtr + offset)) // safe (need to adjust offset as it could be class) - ); - }); - return; - } - throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, structure.GetType()); } @@ -1067,12 +1134,8 @@ namespace System.Runtime.InteropServices // Creates a new instance of "structuretype" and marshals data from a // native memory block to it. //==================================================================== - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Object PtrToStructure(IntPtr ptr, Type structureType) { - // Boxing the struct here is important to ensure that the original copy is written to, - // not the autoboxed copy - if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); @@ -1138,10 +1201,9 @@ namespace System.Runtime.InteropServices // Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0 int offset = structureTypeHandle.IsValueType() ? 1 : 0; + bool useMemCpy = false; - bool isBlittable = false; // whether Mcg treat this struct as blittable struct - IntPtr marshalStub; - if (RuntimeInteropData.Instance.TryGetStructMarshalStub(structureTypeHandle, out marshalStub)) + if (RuntimeInteropData.Instance.TryGetStructMarshalStub(structureTypeHandle, out IntPtr marshalStub)) { if (marshalStub != IntPtr.Zero) { @@ -1156,13 +1218,10 @@ namespace System.Runtime.InteropServices }); return; } - else - { - isBlittable = true; - } + useMemCpy = true; } - if (isBlittable || structureTypeHandle.IsBlittable()) // blittable + if (useMemCpy || structureTypeHandle.IsBlittable()) { int structSize = Marshal.SizeOf(structure); InteropExtensions.PinObjectAndCall(structure, @@ -1189,7 +1248,7 @@ namespace System.Runtime.InteropServices // DestroyStructure() // //==================================================================== - public static void DestroyStructure(IntPtr ptr, Type structuretype) + public static unsafe void DestroyStructure(IntPtr ptr, Type structuretype) { if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); @@ -1209,14 +1268,6 @@ namespace System.Runtime.InteropServices throw new ArgumentException(SR.Argument_MustHaveLayoutOrBeBlittable, structureTypeHandle.GetDisplayName()); } - - DestroyStructureHelper(ptr, structuretype); - } - - private static unsafe void DestroyStructureHelper(IntPtr ptr, Type structuretype) - { - RuntimeTypeHandle structureTypeHandle = structuretype.TypeHandle; - // Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0 int offset = structureTypeHandle.IsValueType() ? 1 : 0; @@ -1226,9 +1277,7 @@ namespace System.Runtime.InteropServices return; } - IntPtr destroyStructureStub; - bool hasInvalidLayout; - if (RuntimeInteropData.Instance.TryGetDestroyStructureStub(structureTypeHandle, out destroyStructureStub, out hasInvalidLayout)) + if (RuntimeInteropData.Instance.TryGetDestroyStructureStub(structureTypeHandle, out IntPtr destroyStructureStub, out bool hasInvalidLayout)) { if (hasInvalidLayout) throw new ArgumentException(SR.Argument_MustHaveLayoutOrBeBlittable, structureTypeHandle.GetDisplayName()); diff --git a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/SEHException.cs b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/SEHException.cs index 24f0f04558..8932671dc0 100644 --- a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/SEHException.cs +++ b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/SEHException.cs @@ -18,7 +18,9 @@ using System.Runtime.Serialization; namespace System.Runtime.InteropServices { [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public class SEHException : ExternalException { public SEHException() diff --git a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs index 1f295686e0..82094e2802 100644 --- a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs +++ b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs @@ -17,7 +17,9 @@ using System.Runtime.Serialization; namespace System.Runtime.InteropServices { [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public class SafeArrayRankMismatchException : SystemException { public SafeArrayRankMismatchException() diff --git a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs index 24e95836c8..855b3a38db 100644 --- a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs +++ b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs @@ -18,7 +18,9 @@ using System.Runtime.Serialization; namespace System.Runtime.InteropServices { [Serializable] +#if !MONO [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] +#endif public class SafeArrayTypeMismatchException : SystemException { public SafeArrayTypeMismatchException() diff --git a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs index 70678b9ef4..6a1887b3f2 100644 --- a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs +++ b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs @@ -133,7 +133,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime ); // We need to make sure it has the same HR that we were returning in desktop - InteropExtensions.SetExceptionErrorCode(ex, __HResults.COR_E_METHODACCESS); + ex.HResult = __HResults.COR_E_METHODACCESS; throw ex; } } diff --git a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs index c89fe9e292..002bdf888e 100644 --- a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs +++ b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs @@ -185,7 +185,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public void RemoveEventHandler(T handler) { - // To match the Windows Runtime behaivor when adding a null handler, removing one is a no-op + // To match the Windows Runtime behavior when adding a null handler, removing one is a no-op if (handler == null) { return; diff --git a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValueImpl.cs b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValueImpl.cs index d4df5c9ddd..670506256e 100644 --- a/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValueImpl.cs +++ b/external/corert/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValueImpl.cs @@ -419,9 +419,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime PropertyType type, PropertyType unboxType) { - System.InvalidCastException ex = new System.InvalidCastException(SR.Format(SR.PropertyValue_InvalidCast, type, unboxType)); - McgMarshal.SetExceptionErrorCode(ex, Interop.COM.TYPE_E_TYPEMISMATCH); - return ex; + return new System.InvalidCastException(SR.Format(SR.PropertyValue_InvalidCast, type, unboxType), Interop.COM.TYPE_E_TYPEMISMATCH); } private static System.InvalidCastException CreateExceptionForInvalidCoersion( @@ -430,9 +428,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime PropertyType unboxType, int hr) { - InvalidCastException ex = new InvalidCastException(SR.Format(SR.PropertyValue_InvalidCoersion, type, value, unboxType)); - McgMarshal.SetExceptionErrorCode(ex, hr); - return ex; + return new InvalidCastException(SR.Format(SR.PropertyValue_InvalidCoersion, type, value, unboxType), hr); } } diff --git a/external/corert/src/System.Private.Interop/src/WinRT/ExceptionHelpers.cs b/external/corert/src/System.Private.Interop/src/WinRT/ExceptionHelpers.cs index 6f9be707d4..ae1fed82fd 100644 --- a/external/corert/src/System.Private.Interop/src/WinRT/ExceptionHelpers.cs +++ b/external/corert/src/System.Private.Interop/src/WinRT/ExceptionHelpers.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic.Internal; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -16,6 +17,46 @@ namespace System.Runtime.InteropServices /// public static unsafe partial class ExceptionHelpers { +#if DEBUG + [ThreadStatic] + private static Dictionary t_propagatedExceptions = new Dictionary(); +#endif + + public static bool PropagateException(Exception ex) + { +#if DEBUG + Debug.Assert(!ExceptionHelpers.t_propagatedExceptions.ContainsKey(ex)); + ExceptionHelpers.t_propagatedExceptions.Add(ex, true); +#endif + try + { + IntPtr pRestrictedErrorInfo; + object restrictedErrorInfo; + if (InteropExtensions.TryGetRestrictedErrorObject(ex, out restrictedErrorInfo) && restrictedErrorInfo != null) + { + // We have the restricted errorInfo associated with this object and hence this exception was created by an hr entering managed through native. + pRestrictedErrorInfo = McgMarshal.ObjectToComInterface(restrictedErrorInfo, InternalTypes.IRestrictedErrorInfo); + if (pRestrictedErrorInfo != IntPtr.Zero) + { + // We simply call SetRestrictedErrorInfo since we do not want to originate the exception again. + ExternalInterop.SetRestrictedErrorInfo(pRestrictedErrorInfo); + McgMarshal.ComSafeRelease(pRestrictedErrorInfo); + } + } + else + { + // we are in windows 8.1+ and hence we can preserve our exception so that we can reuse this exception in case it comes back and provide richer exception support. + OriginateLanguageException(ex); + } + } + catch (Exception) + { + // We can't throw an exception here and hence simply swallow it. + } + + return true; + } + /// /// This class is a helper class to call into IRestrictedErrorInfo methods. /// @@ -56,11 +97,11 @@ namespace System.Runtime.InteropServices finally { if (pErrDes != IntPtr.Zero) - ExternalInterop.SysFreeString(pErrDes); + McgMarshal.SysFreeString(pErrDes); if (pResErrDes != IntPtr.Zero) - ExternalInterop.SysFreeString(pResErrDes); + McgMarshal.SysFreeString(pResErrDes); if (pErrCapSid != IntPtr.Zero) - ExternalInterop.SysFreeString(pErrCapSid); + McgMarshal.SysFreeString(pErrCapSid); } return result >= 0; @@ -88,7 +129,7 @@ namespace System.Runtime.InteropServices finally { if (pReference != IntPtr.Zero) - ExternalInterop.SysFreeString(pReference); + McgMarshal.SysFreeString(pReference); } } } @@ -160,6 +201,78 @@ namespace System.Runtime.InteropServices internal System.IntPtr pfnGetReference; } + internal unsafe struct __com_ILanguageExceptionStackBackTrace + { + internal __vtable_ILanguageExceptionStackBackTrace* pVtable; + } + + internal unsafe struct __vtable_ILanguageExceptionStackBackTrace + { + private IntPtr pfnQueryInterface; + private IntPtr pfnAddRef; + private IntPtr pfnRelease; + internal IntPtr pfnGetStackBackTrace; + + public static IntPtr pNativeVtable; + private static __vtable_ILanguageExceptionStackBackTrace s_theCcwVtable = new __vtable_ILanguageExceptionStackBackTrace + { + // IUnknown + pfnQueryInterface = AddrOfIntrinsics.AddrOf(__vtable_IUnknown.QueryInterface), + pfnAddRef = AddrOfIntrinsics.AddrOf(__vtable_IUnknown.AddRef), + pfnRelease = AddrOfIntrinsics.AddrOf(__vtable_IUnknown.Release), + // ILanguageExceptionStackBackTrace + pfnGetStackBackTrace = AddrOfIntrinsics.AddrOf(GetStackBackTrace), + }; + + internal static IntPtr GetVtableFuncPtr() + { + return AddrOfIntrinsics.AddrOf(GetCcwvtable_ILanguageExceptionStackBackTrace); + } + + internal static unsafe IntPtr GetCcwvtable_ILanguageExceptionStackBackTrace() + { + if (pNativeVtable == default(IntPtr)) + { + fixed (void* pVtbl = &s_theCcwVtable) + { + McgMarshal.GetCCWVTableCopy(pVtbl, ref __vtable_ILanguageExceptionStackBackTrace.pNativeVtable,sizeof(__vtable_ILanguageExceptionStackBackTrace)); + + } + } + return __vtable_ILanguageExceptionStackBackTrace.pNativeVtable; + } + + [NativeCallable] + public static int GetStackBackTrace(IntPtr pComThis, uint maxFramesToCapture, IntPtr stackBackTrace, IntPtr framesCaptured) + { + try + { + object target = ComCallableObject.FromThisPointer(pComThis).TargetObject; + Debug.Assert(target is Exception); + IntPtr[] stackIPs = InteropExtensions.ExceptionGetStackIPs(target as Exception); + uint* pFramesCaptured = (uint*)framesCaptured; + *pFramesCaptured = Math.Min((uint)stackIPs.Length, maxFramesToCapture); + if (stackBackTrace != IntPtr.Zero) + { + unsafe + { + IntPtr* pStackBackTrace = (IntPtr*)stackBackTrace; + for (uint i = 0; i < *pFramesCaptured ; i++) + { + *pStackBackTrace = stackIPs[i]; + pStackBackTrace++; + } + } + } + return Interop.COM.S_OK; + } + catch (System.Exception hrExcep) + { + return McgMarshal.GetHRForExceptionWinRT(hrExcep); + } + } + } + #pragma warning restore 649, 169 /// @@ -200,24 +313,10 @@ namespace System.Runtime.InteropServices // Check whether the exception has an associated RestrictedErrorInfo associated with it. if (isWinRTScenario) { - IntPtr pRestrictedErrorInfo; - object restrictedErrorInfo; - if (InteropExtensions.TryGetRestrictedErrorObject(ex, out restrictedErrorInfo) && restrictedErrorInfo != null) - { - // We have the restricted errorInfo associated with this object and hence this exception was created by an hr entering managed through native. - pRestrictedErrorInfo = McgMarshal.ObjectToComInterface(restrictedErrorInfo, InternalTypes.IRestrictedErrorInfo); - if (pRestrictedErrorInfo != IntPtr.Zero) - { - // We simply call SetRestrictedErrorInfo since we do not want to originate the exception again. - ExternalInterop.SetRestrictedErrorInfo(pRestrictedErrorInfo); - McgMarshal.ComSafeRelease(pRestrictedErrorInfo); - } - } - else - { - // we are in windows blue and hence we can preserve our exception so that we can reuse this exception in case it comes back and provide richer exception support. - OriginateLanguageException(ex); - } +#if DEBUG + Debug.Assert(ExceptionHelpers.t_propagatedExceptions.ContainsKey(ex)); + ExceptionHelpers.t_propagatedExceptions.Remove(ex); +#endif } else { @@ -719,7 +818,7 @@ namespace System.Runtime.InteropServices InteropExtensions.SetExceptionMessage(exception, message); } - InteropExtensions.SetExceptionErrorCode(exception, errorCode); + exception.HResult = errorCode; return exception; } diff --git a/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/CompilerHelpers/LibraryInitializer.cs b/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/CompilerHelpers/LibraryInitializer.cs new file mode 100644 index 0000000000..82c5b1299c --- /dev/null +++ b/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/CompilerHelpers/LibraryInitializer.cs @@ -0,0 +1,17 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.Runtime.Interpreter; +using Internal.Runtime.TypeLoader; + +namespace Internal.Runtime.CompilerHelpers +{ + public class LibraryInitializer + { + public static void InitializeLibrary() + { + MethodExecutionStrategy.GlobalExecutionStrategy = new InterpreterExecutionStrategy(); + } + } +} diff --git a/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/ILImporter.Interpreter.cs b/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/ILImporter.Interpreter.cs new file mode 100644 index 0000000000..70b54d2a32 --- /dev/null +++ b/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/ILImporter.Interpreter.cs @@ -0,0 +1,501 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics; +using Internal.Runtime.Interpreter; +using Internal.TypeSystem; + +namespace Internal.IL +{ + partial class ILImporter + { + private class BasicBlock + { + // Common fields + public enum ImportState : byte + { + Unmarked, + IsPending + } + + public BasicBlock Next; + + public int StartOffset; + public ImportState State = ImportState.Unmarked; + + public bool TryStart; + public bool FilterStart; + public bool HandlerStart; + } + + private class ExceptionRegion + { + public ILExceptionRegion ILRegion; + } + + private readonly byte[] _ilBytes; + private readonly MethodDesc _method; + private readonly MethodIL _methodIL; + private readonly ILInterpreter _interpreter; + private ExceptionRegion[] _exceptionRegions; + + public ILImporter(ILInterpreter interpreter, MethodDesc method, MethodIL methodIL) + { + _ilBytes = methodIL.GetILBytes(); + _method = method; + _methodIL = methodIL; + _interpreter = interpreter; + + var ilExceptionRegions = methodIL.GetExceptionRegions(); + _exceptionRegions = new ExceptionRegion[methodIL.GetExceptionRegions().Length]; + for (int i = 0; i < ilExceptionRegions.Length; i++) + { + _exceptionRegions[i] = new ExceptionRegion() { ILRegion = ilExceptionRegions[i] }; + } + } + + public void Interpret() + { + FindBasicBlocks(); + ImportBasicBlocks(); + } + + private void MarkInstructionBoundary() { } + + private void StartImportingInstruction() { } + + private void EndImportingInstruction() { } + + private void StartImportingBasicBlock(BasicBlock basicBlock) { } + + private void EndImportingBasicBlock(BasicBlock basicBlock) { } + + private void ReportInvalidBranchTarget(int targetOffset) + { + ThrowHelper.ThrowInvalidProgramException(); + } + + private void ReportFallthroughAtEndOfMethod() + { + ThrowHelper.ThrowInvalidProgramException(); + } + + private void ReportMethodEndInsideInstruction() + { + ThrowHelper.ThrowInvalidProgramException(); + } + + private void ReportInvalidInstruction(ILOpcode opcode) + { + ThrowHelper.ThrowInvalidProgramException(); + } + + private TypeDesc ResolveTypeToken(int token) + { + return (TypeDesc)_methodIL.GetObject(token); + } + + private TypeDesc GetWellKnownType(WellKnownType wellKnownType) + { + return _interpreter.TypeSystemContext.GetWellKnownType(wellKnownType); + } + + public StackItem PopWithValidation() + { + bool hasStackItem = _interpreter.EvaluationStack.TryPop(out StackItem stackItem); + if (!hasStackItem) + ThrowHelper.ThrowInvalidProgramException(); + + return stackItem; + } + + private void ImportNop() + { + // Do nothing! + } + + private void ImportBreak() + { + throw new NotImplementedException(); + } + + private void ImportLoadVar(int index, bool argument) + { + throw new NotImplementedException(); + } + + private void ImportStoreVar(int index, bool argument) + { + throw new NotImplementedException(); + } + + private void ImportAddressOfVar(int index, bool argument) + { + throw new NotImplementedException(); + } + + private void ImportDup() + { + throw new NotImplementedException(); + } + + private void ImportPop() + { + throw new NotImplementedException(); + } + + private void ImportCalli(int token) + { + throw new NotImplementedException(); + } + + private void ImportLoadNull() + { + _interpreter.EvaluationStack.Push(StackItem.FromObjectRef(null)); + } + + private void ImportReturn() + { + var returnType = _method.Signature.ReturnType; + if (returnType.IsVoid) + return; + + StackItem stackItem = PopWithValidation(); + TypeFlags category = returnType.Category; + + switch (category) + { + case TypeFlags.Boolean: + _interpreter.SetReturnValue(stackItem.AsInt32() != 0); + break; + case TypeFlags.Char: + _interpreter.SetReturnValue((char)stackItem.AsInt32()); + break; + case TypeFlags.SByte: + _interpreter.SetReturnValue((sbyte)stackItem.AsInt32()); + break; + case TypeFlags.Byte: + _interpreter.SetReturnValue((byte)stackItem.AsInt32()); + break; + case TypeFlags.Int16: + _interpreter.SetReturnValue((short)stackItem.AsInt32()); + break; + case TypeFlags.UInt16: + _interpreter.SetReturnValue((ushort)stackItem.AsInt32()); + break; + case TypeFlags.Int32: + case TypeFlags.UInt32: + _interpreter.SetReturnValue(stackItem.AsInt32()); + break; + case TypeFlags.Int64: + case TypeFlags.UInt64: + _interpreter.SetReturnValue(stackItem.AsInt64()); + break; + case TypeFlags.IntPtr: + case TypeFlags.UIntPtr: + _interpreter.SetReturnValue(stackItem.AsIntPtr()); + break; + case TypeFlags.Single: + _interpreter.SetReturnValue((float)stackItem.AsDouble()); + break; + case TypeFlags.Double: + _interpreter.SetReturnValue(stackItem.AsDouble()); + break; + case TypeFlags.ValueType: + _interpreter.SetReturnValue(stackItem.AsValueType()); + break; + case TypeFlags.Interface: + case TypeFlags.Class: + case TypeFlags.Array: + case TypeFlags.SzArray: + _interpreter.SetReturnValue(stackItem.AsObjectRef()); + break; + case TypeFlags.Enum: + case TypeFlags.Nullable: + case TypeFlags.ByRef: + case TypeFlags.Pointer: + case TypeFlags.FunctionPointer: + case TypeFlags.GenericParameter: + default: + // TODO: Support more complex return types + break; + } + } + + private void ImportLoadInt(long value, StackValueKind kind) + { + if (kind == StackValueKind.Int32) + _interpreter.EvaluationStack.Push(StackItem.FromInt32((int)value)); + else if (kind == StackValueKind.Int64) + _interpreter.EvaluationStack.Push(StackItem.FromInt64(value)); + } + + private void ImportLoadFloat(double value) + { + _interpreter.EvaluationStack.Push(StackItem.FromDouble(value)); + } + + private void ImportShiftOperation(ILOpcode opcode) + { + throw new NotImplementedException(); + } + + private void ImportCompareOperation(ILOpcode opcode) + { + throw new NotImplementedException(); + } + + private void ImportConvert(WellKnownType wellKnownType, bool checkOverflow, bool unsigned) + { + throw new NotImplementedException(); + } + + private void ImportUnaryOperation(ILOpcode opCode) + { + throw new NotImplementedException(); + } + + private void ImportCpOpj(int token) + { + throw new NotImplementedException(); + } + + private void ImportCkFinite() + { + throw new NotImplementedException(); + } + + private void ImportLocalAlloc() + { + throw new NotImplementedException(); + } + + private void ImportEndFilter() + { + throw new NotImplementedException(); + } + + private void ImportCpBlk() + { + throw new NotImplementedException(); + } + + private void ImportInitBlk() + { + throw new NotImplementedException(); + } + + private void ImportRethrow() + { + throw new NotImplementedException(); + } + + private void ImportSizeOf(int token) + { + throw new NotImplementedException(); + } + + private void ImportUnalignedPrefix(byte alignment) + { + throw new NotImplementedException(); + } + + private void ImportVolatilePrefix() + { + throw new NotImplementedException(); + } + + private void ImportTailPrefix() + { + throw new NotImplementedException(); + } + + private void ImportNoPrefix(byte mask) + { + throw new NotImplementedException(); + } + + private void ImportThrow() + { + throw new NotImplementedException(); + } + + private void ImportInitObj(int token) + { + throw new NotImplementedException(); + } + + private void ImportLoadLength() + { + throw new NotImplementedException(); + } + + private void ImportEndFinally() + { + throw new NotImplementedException(); + } + + private void ImportFallthrough(BasicBlock nextBasicBlock) + { + throw new NotImplementedException(); + } + + private void ImportReadOnlyPrefix() + { + throw new NotImplementedException(); + } + + private void ImportRefAnyType() + { + throw new NotImplementedException(); + } + + private void ImportConstrainedPrefix(int v) + { + throw new NotImplementedException(); + } + + private void ImportLdFtn(int v, ILOpcode opCode) + { + throw new NotImplementedException(); + } + + private void ImportArgList() + { + throw new NotImplementedException(); + } + + private void ImportLeave(BasicBlock basicBlock) + { + throw new NotImplementedException(); + } + + private void ImportLdToken(int v) + { + throw new NotImplementedException(); + } + + private void ImportMkRefAny(int v) + { + throw new NotImplementedException(); + } + + private void ImportRefAnyVal(int v) + { + throw new NotImplementedException(); + } + + private void ImportAddressOfElement(int v) + { + throw new NotImplementedException(); + } + + private void ImportNewArray(int v) + { + throw new NotImplementedException(); + } + + private void ImportBox(int v) + { + throw new NotImplementedException(); + } + + private void ImportStoreField(int v1, bool v2) + { + throw new NotImplementedException(); + } + + private void ImportAddressOfField(int v1, bool v2) + { + throw new NotImplementedException(); + } + + private void ImportLoadField(int v1, bool v2) + { + throw new NotImplementedException(); + } + + private void ImportUnbox(int v, ILOpcode opCode) + { + throw new NotImplementedException(); + } + + private void ImportCasting(ILOpcode opCode, int v) + { + throw new NotImplementedException(); + } + + private void ImportLoadString(int token) + { + string str = (string)_methodIL.GetObject(token); + _interpreter.EvaluationStack.Push(StackItem.FromObjectRef(str)); + } + + private void ImportBinaryOperation(ILOpcode opCode) + { + throw new NotImplementedException(); + } + + private void ImportSwitchJump(int jmpBase, int[] jmpDelta, BasicBlock basicBlock) + { + throw new NotImplementedException(); + } + + private void ImportBranch(ILOpcode iLOpcode, BasicBlock basicBlock1, BasicBlock basicBlock2) + { + throw new NotImplementedException(); + } + + private void ImportCall(ILOpcode opCode, int v) + { + throw new NotImplementedException(); + } + + private void ImportJmp(int v) + { + throw new NotImplementedException(); + } + + private void ImportLoadIndirect(int token) + { + ImportLoadIndirect(ResolveTypeToken(token)); + } + + private void ImportLoadIndirect(TypeDesc type) + { + throw new NotImplementedException(); + } + + private void ImportStoreIndirect(int token) + { + ImportStoreIndirect(ResolveTypeToken(token)); + } + + private void ImportStoreIndirect(TypeDesc type) + { + throw new NotImplementedException(); + } + + private void ImportLoadElement(int token) + { + ImportLoadElement(ResolveTypeToken(token)); + } + + private void ImportLoadElement(TypeDesc elementType) + { + throw new NotImplementedException(); + } + + private void ImportStoreElement(int token) + { + ImportStoreElement(ResolveTypeToken(token)); + } + + private void ImportStoreElement(TypeDesc elementType) + { + throw new NotImplementedException(); + } + } +} diff --git a/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/ILInterpreter.cs b/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/ILInterpreter.cs new file mode 100644 index 0000000000..f5f947c74a --- /dev/null +++ b/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/ILInterpreter.cs @@ -0,0 +1,46 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; + +using Internal.IL; +using Internal.Runtime.CallInterceptor; +using Internal.TypeSystem; + +namespace Internal.Runtime.Interpreter +{ + internal unsafe class ILInterpreter + { + private readonly MethodDesc _method; + private readonly MethodIL _methodIL; + private readonly TypeSystemContext _context; + private readonly LowLevelStack _stack; + + private CallInterceptorArgs _callInterceptorArgs; + + public LowLevelStack EvaluationStack => _stack; + + public TypeSystemContext TypeSystemContext => _context; + + public ILInterpreter(TypeSystemContext context, MethodDesc method, MethodIL methodIL) + { + _context = context; + _method = method; + _methodIL = methodIL; + _stack = new LowLevelStack(); + } + + public void InterpretMethod(ref CallInterceptorArgs callInterceptorArgs) + { + _callInterceptorArgs = callInterceptorArgs; + ILImporter importer = new ILImporter(this, _method, _methodIL); + importer.Interpret(); + } + + public void SetReturnValue(T value) + { + _callInterceptorArgs.ArgumentsAndReturnValue.SetVar(0, value); + } + } +} diff --git a/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/InterpreterCallInterceptor.cs b/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/InterpreterCallInterceptor.cs new file mode 100644 index 0000000000..3703d213b4 --- /dev/null +++ b/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/InterpreterCallInterceptor.cs @@ -0,0 +1,72 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.IL; +using Internal.Runtime.CallConverter; +using Internal.Runtime.CallInterceptor; +using Internal.TypeSystem; +using Internal.TypeSystem.Ecma; + +namespace Internal.Runtime.Interpreter +{ + public class InterpreterCallInterceptor : CallInterceptor.CallInterceptor + { + private readonly MethodDesc _method; + private readonly MethodIL _methodIL; + private readonly TypeSystemContext _context; + + public InterpreterCallInterceptor(TypeSystemContext context, MethodDesc method) : base(false) + { + _context = context; + _method = method; + _methodIL = EcmaMethodIL.Create(method as EcmaMethod); + } + + public override LocalVariableType[] ArgumentAndReturnTypes + { + get + { + LocalVariableType[] localVariableTypes = new LocalVariableType[_method.Signature.Length + 1]; + localVariableTypes[0] = new LocalVariableType(_method.Signature.ReturnType.RuntimeTypeHandle, false, _method.Signature.ReturnType.IsByRef); + for (int i = 0; i < _method.Signature.Length; i++) + { + var argument = _method.Signature[i]; + localVariableTypes[i + 1] = new LocalVariableType(argument.RuntimeTypeHandle, false, argument.IsByRef); + } + + return localVariableTypes; + } + } + + public override CallingConvention CallingConvention + { + get + { + return _method.Signature.IsStatic ? CallingConvention.ManagedStatic : CallingConvention.ManagedInstance; + } + } + + public override LocalVariableType[] LocalVariableTypes + { + get + { + LocalVariableDefinition[] locals = _methodIL.GetLocals(); + LocalVariableType[] localVariableTypes = new LocalVariableType[locals.Length]; + for (int i = 0; i < locals.Length; i++) + { + var variable = locals[i]; + localVariableTypes[i] = new LocalVariableType(variable.Type.RuntimeTypeHandle, variable.IsPinned, variable.Type.IsByRef); + } + + return localVariableTypes; + } + } + + public override void ThunkExecute(ref CallInterceptorArgs callInterceptorArgs) + { + ILInterpreter interpreter = new ILInterpreter(_context, _method, _methodIL); + interpreter.InterpretMethod(ref callInterceptorArgs); + } + } +} diff --git a/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/InterpreterExecutionStrategy.cs b/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/InterpreterExecutionStrategy.cs new file mode 100644 index 0000000000..7fa3a57429 --- /dev/null +++ b/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/InterpreterExecutionStrategy.cs @@ -0,0 +1,22 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +using Internal.Runtime.TypeLoader; +using Internal.TypeSystem; + +namespace Internal.Runtime.Interpreter +{ + public class InterpreterExecutionStrategy : MethodExecutionStrategy + { + public override IntPtr OnEntryPoint(MethodEntrypointPtr methodEntrypointPtr, IntPtr callerArgumentsInfo) + { + var context = TypeSystemContextFactory.Create(); + MethodDesc method = methodEntrypointPtr.MethodIdentifier.ToMethodDesc(context); + InterpreterCallInterceptor callInterceptor = new InterpreterCallInterceptor(context, method); + return callInterceptor.GetThunkAddress(); + } + } +} diff --git a/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/StackItem.cs b/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/StackItem.cs new file mode 100644 index 0000000000..97578b61d0 --- /dev/null +++ b/external/corert/src/System.Private.Interpreter/src/Internal/Runtime/Interpreter/StackItem.cs @@ -0,0 +1,105 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using Internal.IL; +using Internal.TypeSystem; + +namespace Internal.Runtime.Interpreter +{ + [StructLayout(LayoutKind.Explicit)] + internal unsafe struct StackItem + { + [FieldOffset(0)] + private StackValueKind _kind; + + [FieldOffset(8)] + private int _int32; + + [FieldOffset(8)] + private long _int64; + + [FieldOffset(8)] + private IntPtr _nativeInt; + + [FieldOffset(8)] + private double _double; + + [FieldOffset(16)] + private ValueType _valueType; + + [FieldOffset(16)] + private object _objref; + + public StackValueKind Kind => _kind; + + public static StackItem FromInt32(int int32) + { + return new StackItem { _int32 = int32, _kind = StackValueKind.Int32 }; + } + + public int AsInt32() + { + Debug.Assert(_kind == StackValueKind.Int32); + return _int32; + } + + public static StackItem FromInt64(long int64) + { + return new StackItem { _int64 = int64, _kind = StackValueKind.Int64 }; + } + + public long AsInt64() + { + Debug.Assert(_kind == StackValueKind.Int64); + return _int64; + } + + public static StackItem FromIntPtr(IntPtr nativeInt) + { + return new StackItem { _nativeInt = nativeInt, _kind = StackValueKind.NativeInt }; + } + + public IntPtr AsIntPtr() + { + Debug.Assert(_kind == StackValueKind.NativeInt); + return _nativeInt; + } + + public static StackItem FromDouble(double d) + { + return new StackItem { _double = d, _kind = StackValueKind.Float }; + } + + public double AsDouble() + { + Debug.Assert(_kind == StackValueKind.Float); + return _double; + } + + public static StackItem FromValueType(ValueType valueType) + { + return new StackItem { _valueType = valueType, _kind = StackValueKind.ValueType }; + } + + public ValueType AsValueType() + { + Debug.Assert(_kind == StackValueKind.ValueType); + return _valueType; + } + + public static StackItem FromObjectRef(object obj) + { + return new StackItem { _objref = obj, _kind = StackValueKind.ObjRef }; + } + + public object AsObjectRef() + { + Debug.Assert(_kind == StackValueKind.ObjRef); + return _objref; + } + } +} diff --git a/external/corert/src/System.Private.Interpreter/src/System.Private.Interpreter.csproj b/external/corert/src/System.Private.Interpreter/src/System.Private.Interpreter.csproj new file mode 100644 index 0000000000..3808516a43 --- /dev/null +++ b/external/corert/src/System.Private.Interpreter/src/System.Private.Interpreter.csproj @@ -0,0 +1,35 @@ + + + + System.Private.Interpreter + 4.0.0.0 + Library + true + + + + false + true + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/external/corert/src/System.Private.Jit/src/Internal/Runtime/CompilerHelpers/LibraryInitializer.cs b/external/corert/src/System.Private.Jit/src/Internal/Runtime/CompilerHelpers/LibraryInitializer.cs new file mode 100644 index 0000000000..ff2abd9e84 --- /dev/null +++ b/external/corert/src/System.Private.Jit/src/Internal/Runtime/CompilerHelpers/LibraryInitializer.cs @@ -0,0 +1,17 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.Runtime.JitSupport; +using Internal.Runtime.TypeLoader; + +namespace Internal.Runtime.CompilerHelpers +{ + public class LibraryInitializer + { + public static void InitializeLibrary() + { + MethodExecutionStrategy.GlobalExecutionStrategy = new RyuJitExecutionStrategy(); + } + } +} diff --git a/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/JitCompilation.cs b/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/JitCompilation.cs index e628978b9e..2c5f06f72e 100644 --- a/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/JitCompilation.cs +++ b/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/JitCompilation.cs @@ -21,7 +21,8 @@ namespace ILCompiler { _typeSystemContext = context; _typeGetTypeMethodThunks = new TypeGetTypeMethodThunkCache(context.GetWellKnownType(WellKnownType.Object)); - _methodILCache = new ILProvider(new PInvokeILProvider(new PInvokeILEmitterConfiguration(forceLazyResolution: true), null)); + _pInvokeILProvider = new PInvokeILProvider(new PInvokeILEmitterConfiguration(forceLazyResolution: true), null); + _methodILCache = new ILProvider(_pInvokeILProvider); _nodeFactory = new NodeFactory(context); _devirtualizationManager = new DevirtualizationManager(); } @@ -31,9 +32,11 @@ namespace ILCompiler protected readonly Logger _logger = Logger.Null; private readonly TypeGetTypeMethodThunkCache _typeGetTypeMethodThunks; private ILProvider _methodILCache; + private PInvokeILProvider _pInvokeILProvider; private readonly DevirtualizationManager _devirtualizationManager; internal Logger Logger => _logger; + internal PInvokeILProvider PInvokeILProvider => _pInvokeILProvider; public TypeSystemContext TypeSystemContext { get { return _typeSystemContext; } } public NodeFactory NodeFactory { get { return _nodeFactory; } } @@ -51,7 +54,7 @@ namespace ILCompiler { // Flush the cache when it grows too big if (_methodILCache.Count > 1000) - _methodILCache = new ILProvider(new PInvokeILProvider(new PInvokeILEmitterConfiguration(forceLazyResolution: true), null)); + _methodILCache = new ILProvider(_pInvokeILProvider); return _methodILCache.GetMethodIL(method); } @@ -142,4 +145,4 @@ namespace ILCompiler return DelegateCreationInfo.Create(delegateType, target, NodeFactory, followVirtualDispatch); } } -} \ No newline at end of file +} diff --git a/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/JitMethodCodeNode.cs b/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/JitMethodCodeNode.cs index 4e66d5d38b..b605c485b8 100644 --- a/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/JitMethodCodeNode.cs +++ b/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/JitMethodCodeNode.cs @@ -28,6 +28,7 @@ namespace Internal.Runtime.JitSupport private ObjectData _ehInfo; private DebugLocInfo[] _debugLocInfos; private DebugVarInfo[] _debugVarInfos; + private DebugEHClauseInfo[] _debugEHClauseInfos; public void SetCode(ObjectData data) { @@ -60,6 +61,7 @@ namespace Internal.Runtime.JitSupport } public DebugLocInfo[] DebugLocInfos => _debugLocInfos; public DebugVarInfo[] DebugVarInfos => _debugVarInfos; + public DebugEHClauseInfo[] DebugEHClauseInfos => _debugEHClauseInfos; public void InitializeDebugLocInfos(DebugLocInfo[] debugLocInfos) { @@ -73,6 +75,12 @@ namespace Internal.Runtime.JitSupport _debugVarInfos = debugVarInfos; } + public void InitializeDebugEHClauseInfos(DebugEHClauseInfo[] debugEHClauseInfos) + { + Debug.Assert(_debugEHClauseInfos == null); + _debugEHClauseInfos = debugEHClauseInfos; + } + protected override string GetName(NodeFactory factory) { throw new PlatformNotSupportedException(); diff --git a/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/RyuJitExecutionStrategy.cs b/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/RyuJitExecutionStrategy.cs index e67b3b8c4a..9548f2f08c 100644 --- a/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/RyuJitExecutionStrategy.cs +++ b/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/RyuJitExecutionStrategy.cs @@ -22,6 +22,8 @@ namespace Internal.Runtime.JitSupport { public class RyuJitExecutionStrategy : MethodExecutionStrategy { + private const string NativeJitSupportLibrary = "*"; + private CorInfoImpl _corInfoImpl; private TypeSystemContext _context; private NodeFactory _nodeFactory; @@ -33,13 +35,13 @@ namespace Internal.Runtime.JitSupport return; } - [DllImport("jitinterface")] + [DllImport(NativeJitSupportLibrary)] static extern IntPtr AllocJittedCode(UInt32 cbCode, UInt32 align, out IntPtr pCodeManager); - [DllImport("jitinterface")] + [DllImport(NativeJitSupportLibrary)] static extern void SetEHInfoPtr(IntPtr pCodeManager, IntPtr pbCode, IntPtr ehInfo); - [DllImport("jitinterface")] + [DllImport(NativeJitSupportLibrary)] static extern unsafe IntPtr PublishRuntimeFunction( IntPtr pCodeManager, IntPtr pbCode, @@ -51,10 +53,10 @@ namespace Internal.Runtime.JitSupport byte[] pGCData, UInt32 cbGCData); - [DllImport("jitinterface")] + [DllImport(NativeJitSupportLibrary)] static extern void UpdateRuntimeFunctionTable(IntPtr pCodeManager); - [DllImport("jitinterface")] + [DllImport(NativeJitSupportLibrary)] static extern void InitJitCodeManager(IntPtr mrtModule); public override IntPtr OnEntryPoint(MethodEntrypointPtr methodEntrypoint, IntPtr callerArgs) diff --git a/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/VirtualMethodSlotHelper.cs b/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/VirtualMethodSlotHelper.cs index 10e3466bdc..ab82c2d6f9 100644 --- a/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/VirtualMethodSlotHelper.cs +++ b/external/corert/src/System.Private.Jit/src/Internal/Runtime/JitSupport/VirtualMethodSlotHelper.cs @@ -23,7 +23,7 @@ namespace ILCompiler /// Given a virtual method decl, return its VTable slot if the method is used on its containing type. /// Return -1 if the virtual method is not used. /// - public static int GetVirtualMethodSlot(NodeFactory factory, MethodDesc method) + public static int GetVirtualMethodSlot(NodeFactory factory, MethodDesc method, TypeDesc implType) { Debug.Assert(method.IsVirtual); diff --git a/external/corert/src/System.Private.Jit/src/System.Private.Jit.csproj b/external/corert/src/System.Private.Jit/src/System.Private.Jit.csproj index 662339fa58..942a0b74b7 100644 --- a/external/corert/src/System.Private.Jit/src/System.Private.Jit.csproj +++ b/external/corert/src/System.Private.Jit/src/System.Private.Jit.csproj @@ -1,4 +1,4 @@ - + System.Private.Jit @@ -31,7 +31,7 @@ - + ..\..\Common\src\Internal\NativeFormat @@ -43,6 +43,7 @@ ..\..\JitInterface\src + @@ -69,6 +70,7 @@ + @@ -125,6 +127,7 @@ + @@ -153,4 +156,4 @@ - + \ No newline at end of file diff --git a/external/corert/src/System.Private.Reflection.Core/src/Resources/Strings.resx b/external/corert/src/System.Private.Reflection.Core/src/Resources/Strings.resx index 4d76156999..820a41e269 100644 --- a/external/corert/src/System.Private.Reflection.Core/src/Resources/Strings.resx +++ b/external/corert/src/System.Private.Reflection.Core/src/Resources/Strings.resx @@ -150,18 +150,12 @@ The type '{0}' cannot be found in assembly '{1}'. - - An invalid escape sequence was found inside a type name. - Cannot load assembly '{0}'. No metadata found for this assembly. Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table. - - ByRef return value not supported in reflection invocation. - Cannot bind to the target method because its signature is not compatible with that of the delegate type. @@ -228,9 +222,6 @@ Property set method not found. - - Type instance is not IReflectable. - Array may not be empty. @@ -246,12 +237,6 @@ There is no metadata token available for the given member. - - Module version IDs (MVIDs) cannot be retrieved on this platform. - - - Could not resolve assembly '{0}'. - Field not found. @@ -286,18 +271,12 @@ Named parameter array cannot be bigger than argument array. - - Must specify property Set or Get or method call for a COM Object. - Cannot specify both Get and Set on a property. Cannot specify Set on a property and Invoke on a method. - - Only one of the following binding flags can be set: BindingFlags.SetProperty, BindingFlags.PutDispProperty, BindingFlags.PutRefDispProperty. - Named parameter value must not be null. diff --git a/external/corert/src/System.Private.Reflection.Core/src/System.Private.Reflection.Core.Experimental.csproj b/external/corert/src/System.Private.Reflection.Core/src/System.Private.Reflection.Core.Experimental.csproj index 75f14057af..2cc7b4b441 100644 --- a/external/corert/src/System.Private.Reflection.Core/src/System.Private.Reflection.Core.Experimental.csproj +++ b/external/corert/src/System.Private.Reflection.Core/src/System.Private.Reflection.Core.Experimental.csproj @@ -2,7 +2,7 @@ System.Private.Reflection.Core.Experimental true - true + true diff --git a/external/corert/src/System.Private.Reflection.Core/src/System.Private.Reflection.Core.csproj b/external/corert/src/System.Private.Reflection.Core/src/System.Private.Reflection.Core.csproj index 696f74096a..014a80f7fc 100644 --- a/external/corert/src/System.Private.Reflection.Core/src/System.Private.Reflection.Core.csproj +++ b/external/corert/src/System.Private.Reflection.Core/src/System.Private.Reflection.Core.csproj @@ -24,14 +24,15 @@ true - + + diff --git a/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/QueriedMemberList.cs b/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/QueriedMemberList.cs index c8e7d3a236..2da7ffe58c 100644 --- a/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/QueriedMemberList.cs +++ b/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/QueriedMemberList.cs @@ -30,13 +30,13 @@ namespace System.Reflection.Runtime.BindingFlagSupport _allFlagsThatMustMatch = new BindingFlags[Grow]; } - private QueriedMemberList(int totalCount, int declaredOnlyCount, M[] members, BindingFlags[] allFlagsThatMustMatch, RuntimeTypeInfo typeThatBlockedBrowing) + private QueriedMemberList(int totalCount, int declaredOnlyCount, M[] members, BindingFlags[] allFlagsThatMustMatch, RuntimeTypeInfo typeThatBlockedBrowsing) { _totalCount = totalCount; _declaredOnlyCount = declaredOnlyCount; _members = members; _allFlagsThatMustMatch = allFlagsThatMustMatch; - _typeThatBlockedBrowsing = typeThatBlockedBrowing; + _typeThatBlockedBrowsing = typeThatBlockedBrowsing; } /// diff --git a/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/Dispensers.cs b/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/Dispensers.cs index 79eca88682..90d5f48039 100644 --- a/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/Dispensers.cs +++ b/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/Dispensers.cs @@ -97,7 +97,7 @@ namespace System.Reflection.Runtime.Assemblies AssemblyBinder binder = ReflectionCoreExecution.ExecutionDomain.ReflectionDomainSetup.AssemblyBinder; AssemblyBindResult bindResult; Exception exception; - if (!binder.Bind(assemblyRefName, out bindResult, out exception)) + if (!binder.Bind(assemblyRefName, cacheMissedLookups: true, out bindResult, out exception)) return exception; return GetRuntimeAssembly(bindResult); diff --git a/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/EcmaFormat/DefaultValueProcessing.cs b/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/EcmaFormat/DefaultValueProcessing.cs index 50196d699b..70b0203932 100644 --- a/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/EcmaFormat/DefaultValueProcessing.cs +++ b/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/EcmaFormat/DefaultValueProcessing.cs @@ -60,7 +60,7 @@ namespace System.Reflection.Runtime.General.EcmaFormat private static object ConstantValueAsObject(ConstantHandle constantHandle, MetadataReader metadataReader, Type declaredType, bool raw) { object defaultValue = ConstantValueAsRawObject(constantHandle, metadataReader); - if ((!raw) && declaredType.IsEnum) + if ((!raw) && declaredType.IsEnum && defaultValue != null) defaultValue = Enum.ToObject(declaredType, defaultValue); return defaultValue; } diff --git a/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/MetadataReaderExtensions.NativeFormat.cs b/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/MetadataReaderExtensions.NativeFormat.cs index 901d0f4baf..5896aa8121 100644 --- a/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/MetadataReaderExtensions.NativeFormat.cs +++ b/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/MetadataReaderExtensions.NativeFormat.cs @@ -162,6 +162,24 @@ namespace System.Reflection.Runtime.General return customModifiers.ToArray(); } + public static Handle SkipCustomModifiers(this Handle handle, MetadataReader reader) + { + HandleType handleType = handle.HandleType; + Debug.Assert(handleType == HandleType.TypeDefinition || handleType == HandleType.TypeReference || handleType == HandleType.TypeSpecification || handleType == HandleType.ModifiedType); + if (handleType != HandleType.ModifiedType) + return handle; + + do + { + ModifiedType modifiedType = handle.ToModifiedTypeHandle(reader).GetModifiedType(reader); + handle = modifiedType.Type; + handleType = handle.HandleType; + } + while (handleType == HandleType.ModifiedType); + + return handle; + } + public static MethodSignature ParseMethodSignature(this Handle handle, MetadataReader reader) { return handle.ToMethodSignatureHandle(reader).GetMethodSignature(reader); diff --git a/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/NativeFormat/DefaultValueParser.cs b/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/NativeFormat/DefaultValueParser.cs index e76be19145..244d351ad5 100644 --- a/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/NativeFormat/DefaultValueParser.cs +++ b/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/NativeFormat/DefaultValueParser.cs @@ -14,7 +14,7 @@ namespace System.Reflection.Runtime.General.NativeFormat if (!(constantHandle.IsNull(reader))) { defaultValue = constantHandle.ParseConstantValue(reader); - if ((!raw) && declaredType.IsEnum) + if ((!raw) && declaredType.IsEnum && defaultValue != null) defaultValue = Enum.ToObject(declaredType, defaultValue); return true; } diff --git a/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/MethodInfos/RuntimeMethodInfo.cs b/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/MethodInfos/RuntimeMethodInfo.cs index 33d73b16af..4af12bfc98 100644 --- a/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/MethodInfos/RuntimeMethodInfo.cs +++ b/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/MethodInfos/RuntimeMethodInfo.cs @@ -354,7 +354,12 @@ namespace System.Reflection.Runtime.MethodInfos if (methodInvoker == null) { if (ReturnType.IsByRef) - throw new NotSupportedException(SR.NotSupported_ByRefReturn); + { + // The invoker is going to dereference and box (for structs) the result of the invocation + // on behalf of the caller. Can't box byref-like types and can't box void. + if (ReturnType.GetElementType().IsByRefLike || ReturnType.GetElementType() == CommonRuntimeTypes.Void) + throw new NotSupportedException(); + } methodInvoker = _lazyMethodInvoker = this.UncachedMethodInvoker; } return methodInvoker; diff --git a/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeGenericParameterTypeInfo.cs b/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeGenericParameterTypeInfo.cs index 6785771358..f027f9caa5 100644 --- a/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeGenericParameterTypeInfo.cs +++ b/external/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeGenericParameterTypeInfo.cs @@ -81,7 +81,11 @@ namespace System.Reflection.Runtime.TypeInfos.NativeFormat LowLevelList constraints = new LowLevelList(); foreach (Handle constraintHandle in _genericParameter.Constraints) { - constraints.Add(new QTypeDefRefOrSpec(reader, constraintHandle)); + // We're skipping custom modifiers here because Roslyn generates + // a modifier for the "unmanaged" constraint. This doesn't conform to the + // ECMA-335 spec, but we need to deal with it. The modifier is not visible + // to reflection. + constraints.Add(new QTypeDefRefOrSpec(reader, constraintHandle.SkipCustomModifiers(reader))); } return constraints.ToArray(); } diff --git a/external/corert/src/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs b/external/corert/src/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs index b583053d4d..8313fbe315 100644 --- a/external/corert/src/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs +++ b/external/corert/src/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs @@ -44,10 +44,6 @@ namespace Internal.Reflection.Execution //========================================================================================================== internal sealed partial class ExecutionEnvironmentImplementation : ExecutionEnvironment { - private struct MethodTargetAndDictionary { public IntPtr TargetPointer; public IntPtr DictionaryPointer; } - - private LowLevelDictionary _callConverterWrappedMethodEntrypoints = new LowLevelDictionary(); - private RuntimeTypeHandle GetOpenTypeDefinition(RuntimeTypeHandle typeHandle, out RuntimeTypeHandle[] typeArgumentsHandles) { if (RuntimeAugments.IsGenericType(typeHandle)) @@ -475,27 +471,17 @@ namespace Internal.Reflection.Execution } } - private IntPtr GetDynamicMethodInvokerThunk(RuntimeTypeHandle[] argHandles, MethodBase methodInfo) + private IntPtr GetDynamicMethodInvokerThunk(MethodBase methodInfo) { - ParameterInfo[] parameters = methodInfo.GetParametersNoCopy(); - // last entry in argHandles is the return type if the type is not typeof(void) - Debug.Assert(parameters.Length == argHandles.Length || parameters.Length == (argHandles.Length - 1)); - - bool[] byRefParameters = new bool[parameters.Length + 1]; - RuntimeTypeHandle[] parameterTypeHandles = new RuntimeTypeHandle[parameters.Length + 1]; - - // This is either a constructor ("returns" void) or an instance method - MethodInfo reflectionMethodInfo = methodInfo as MethodInfo; - parameterTypeHandles[0] = (reflectionMethodInfo != null ? reflectionMethodInfo.ReturnType.TypeHandle : CommonRuntimeTypes.Void.TypeHandle); - byRefParameters[0] = false; - - for (int i = 0; i < parameters.Length; i++) - { - parameterTypeHandles[i + 1] = argHandles[i]; - byRefParameters[i + 1] = parameters[i].ParameterType.IsByRef; - } - - return CallConverterThunk.MakeThunk(ThunkKind.ReflectionDynamicInvokeThunk, IntPtr.Zero, IntPtr.Zero, false, parameterTypeHandles, byRefParameters, null); + MethodParametersInfo methodParamsInfo = new MethodParametersInfo(methodInfo); + return CallConverterThunk.MakeThunk( + ThunkKind.ReflectionDynamicInvokeThunk, + IntPtr.Zero, + IntPtr.Zero, + false, + methodParamsInfo.ReturnTypeAndParameterTypeHandles.ToArray(), + methodParamsInfo.ReturnTypeAndParametersByRefFlags, + null); } private RuntimeTypeHandle[] GetDynamicInvokeInstantiationArguments(MethodBase reflectionMethodBase) @@ -514,6 +500,17 @@ namespace Internal.Reflection.Execution if (!returnType.Equals(CommonRuntimeTypes.Void)) dynamicInvokeMethodGenArguments.Add(returnType.TypeHandle); + for (int i = 0; i < dynamicInvokeMethodGenArguments.Count; i++) + { + // We can't instantiate over pointer types, so the DynamicInvoke method compensates for it already. + RuntimeTypeHandle type = dynamicInvokeMethodGenArguments[i]; + while (RuntimeAugments.IsUnmanagedPointerType(type)) + { + type = RuntimeAugments.GetRelatedParameterTypeHandle(type); + } + dynamicInvokeMethodGenArguments[i] = type; + } + return dynamicInvokeMethodGenArguments.ToArray(); } @@ -603,33 +600,17 @@ namespace Internal.Reflection.Execution methodHandle.NativeFormatHandle); } - if (methodInvokeMetadata.MethodEntryPoint != methodInvokeMetadata.RawMethodEntryPoint && - !FunctionPointerOps.IsGenericMethodPointer(methodInvokeMetadata.MethodEntryPoint)) - { - // Keep track of the raw method entrypoints for the cases where they get wrapped into a calling convention converter thunk. - // This is needed for reverse lookups, like in TryGetMethodForOriginalLdFtnResult - Debug.Assert(canonFormKind == CanonicalFormKind.Universal); - lock (_callConverterWrappedMethodEntrypoints) - { - _callConverterWrappedMethodEntrypoints.LookupOrAdd(methodInvokeMetadata.MethodEntryPoint, new MethodTargetAndDictionary - { - TargetPointer = methodInvokeMetadata.RawMethodEntryPoint, - DictionaryPointer = methodInvokeMetadata.DictionaryComponent - }); - } - } - - RuntimeTypeHandle[] dynInvokeMethodArgs = GetDynamicInvokeInstantiationArguments(methodInfo); - IntPtr dynamicInvokeMethod; IntPtr dynamicInvokeMethodGenericDictionary; if ((methodInvokeMetadata.InvokeTableFlags & InvokeTableFlags.NeedsParameterInterpretation) != 0) { - dynamicInvokeMethod = GetDynamicMethodInvokerThunk(dynInvokeMethodArgs, methodInfo); + dynamicInvokeMethod = GetDynamicMethodInvokerThunk(methodInfo); dynamicInvokeMethodGenericDictionary = IntPtr.Zero; } else { + RuntimeTypeHandle[] dynInvokeMethodArgs = GetDynamicInvokeInstantiationArguments(methodInfo); + GetDynamicMethodInvokeMethodInfo( methodInvokeMetadata.MappingTableModule, methodInvokeMetadata.DynamicInvokeCookie, @@ -913,26 +894,11 @@ namespace Internal.Reflection.Execution } else { - bool isCallConverterWrappedEntrypoint; - MethodTargetAndDictionary callConverterWrappedEntrypoint; - lock (_callConverterWrappedMethodEntrypoints) + // The thunk could have been created by the TypeLoader as a dictionary slot for USG code + if (!CallConverterThunk.TryGetCallConversionTargetPointerAndInstantiatingArg(originalLdFtnResult, out canonOriginalLdFtnResult, out instantiationArgument)) { - isCallConverterWrappedEntrypoint = _callConverterWrappedMethodEntrypoints.TryGetValue(originalLdFtnResult, out callConverterWrappedEntrypoint); - } - - if (isCallConverterWrappedEntrypoint) - { - canonOriginalLdFtnResult = callConverterWrappedEntrypoint.TargetPointer; - instantiationArgument = callConverterWrappedEntrypoint.DictionaryPointer; - } - else - { - // The thunk could have been created by the TypeLoader as a dictionary slot for USG code - if (!CallConverterThunk.TryGetCallConversionTargetPointerAndInstantiatingArg(originalLdFtnResult, out canonOriginalLdFtnResult, out instantiationArgument)) - { - canonOriginalLdFtnResult = RuntimeAugments.GetCodeTarget(originalLdFtnResult); - instantiationArgument = IntPtr.Zero; - } + canonOriginalLdFtnResult = RuntimeAugments.GetCodeTarget(originalLdFtnResult); + instantiationArgument = IntPtr.Zero; } } } @@ -941,25 +907,29 @@ namespace Internal.Reflection.Execution { GetFunctionPointerAndInstantiationArgumentForOriginalLdFtnResult(originalLdFtnResult, out IntPtr canonOriginalLdFtnResult, out IntPtr instantiationArgument); - // Search TemplateMethodMap - if ((instantiationArgument != IntPtr.Zero) && TryGetMethodForOriginalLdFtnResult_GenericMethodWithInstantiationArgument(instantiationArgument, ref declaringTypeHandle, out methodHandle, out genericMethodTypeArgumentHandles)) + if (instantiationArgument != IntPtr.Zero) { - return true; + // Search TemplateMethodMap + if (TryGetMethodForOriginalLdFtnResult_GenericMethodWithInstantiationArgument(instantiationArgument, ref declaringTypeHandle, out methodHandle, out genericMethodTypeArgumentHandles)) + return true; } - - // Search ExactInstantiationsMap - foreach (KeyValuePair perModuleLookup in GetLdFtnReverseLookups_ExactInstantations()) + else { - int startIndex; - int endIndex; - - if (perModuleLookup.Value.TryGetOffsetsRange(canonOriginalLdFtnResult, out startIndex, out endIndex)) + // Search ExactInstantiationsMap + foreach (KeyValuePair perModuleLookup in GetLdFtnReverseLookups_ExactInstantations()) { - for (int curIndex = startIndex; curIndex <= endIndex; curIndex++) + int startIndex; + int endIndex; + + if (perModuleLookup.Value.TryGetOffsetsRange(canonOriginalLdFtnResult, out startIndex, out endIndex)) { - uint parserOffset = perModuleLookup.Value.Data[curIndex].Offset; - if (TryGetMethodForOriginalLdFtnResult_ExactInstantiation_Inner(perModuleLookup.Key, canonOriginalLdFtnResult, instantiationArgument, parserOffset, ref declaringTypeHandle, out methodHandle, out genericMethodTypeArgumentHandles)) - return true; + for (int curIndex = startIndex; curIndex <= endIndex; curIndex++) + { + uint parserOffset = perModuleLookup.Value.Data[curIndex].Offset; + if (TryGetMethodForOriginalLdFtnResult_ExactInstantiation_Inner(perModuleLookup.Key, forStartAddress: false, canonOriginalLdFtnResult, parserOffset, + ref declaringTypeHandle, out methodHandle, out genericMethodTypeArgumentHandles)) + return true; + } } } } @@ -975,7 +945,7 @@ namespace Internal.Reflection.Execution for (int curIndex = startIndex; curIndex <= endIndex; curIndex++) { uint parserOffset = perModuleLookup.Value.Data[curIndex].Offset; - if (TryGetMethodForOriginalLdFtnResult_InvokeMap_Inner(perModuleLookup.Key, canonOriginalLdFtnResult, instantiationArgument, parserOffset, ref declaringTypeHandle, out methodHandle, out genericMethodTypeArgumentHandles)) + if (TryGetMethodForOriginalLdFtnResult_InvokeMap_Inner(perModuleLookup.Key, forStartAddress: false, canonOriginalLdFtnResult, instantiationArgument, parserOffset, ref declaringTypeHandle, out methodHandle, out genericMethodTypeArgumentHandles)) return true; } } @@ -986,6 +956,54 @@ namespace Internal.Reflection.Execution return false; } + internal bool TryGetMethodForStartAddress(IntPtr methodStartAddress, ref RuntimeTypeHandle declaringTypeHandle, out QMethodDefinition methodHandle) + { + // Search ExactInstantiationsMap + foreach (KeyValuePair perModuleLookup in GetLdFtnReverseLookups_ExactInstantations()) + { + int startIndex; + int endIndex; + + if (perModuleLookup.Value.TryGetOffsetsRange(methodStartAddress, out startIndex, out endIndex)) + { + for (int curIndex = startIndex; curIndex <= endIndex; curIndex++) + { + uint parserOffset = perModuleLookup.Value.Data[curIndex].Offset; + if (TryGetMethodForOriginalLdFtnResult_ExactInstantiation_Inner(perModuleLookup.Key, forStartAddress: true, methodStartAddress, parserOffset, ref declaringTypeHandle, out methodHandle, out _)) + { + if (RuntimeAugments.IsGenericType(declaringTypeHandle)) + declaringTypeHandle = RuntimeAugments.GetGenericDefinition(declaringTypeHandle); + return true; + } + } + } + } + + // Search InvokeMap + foreach (KeyValuePair perModuleLookup in GetLdFtnReverseLookups_InvokeMap()) + { + int startIndex; + int endIndex; + + if (perModuleLookup.Value.TryGetOffsetsRange(methodStartAddress, out startIndex, out endIndex)) + { + for (int curIndex = startIndex; curIndex <= endIndex; curIndex++) + { + uint parserOffset = perModuleLookup.Value.Data[curIndex].Offset; + if (TryGetMethodForOriginalLdFtnResult_InvokeMap_Inner(perModuleLookup.Key, forStartAddress: true, methodStartAddress, IntPtr.Zero, parserOffset, ref declaringTypeHandle, out methodHandle, out _)) + { + if (RuntimeAugments.IsGenericType(declaringTypeHandle)) + declaringTypeHandle = RuntimeAugments.GetGenericDefinition(declaringTypeHandle); + return true; + } + } + } + } + + methodHandle = default(QMethodDefinition); + return false; + } + private static FunctionPointersToOffsets ComputeLdftnReverseLookup_InvokeMap(NativeFormatModuleInfo mappingTableModule) { FunctionPointersToOffsets functionPointerToOffsetInInvokeMap = new FunctionPointersToOffsets(); @@ -1047,7 +1065,7 @@ namespace Internal.Reflection.Execution return functionPointerToOffsetInInvokeMap; } - private unsafe bool TryGetMethodForOriginalLdFtnResult_InvokeMap_Inner(NativeFormatModuleInfo mappingTableModule, IntPtr canonOriginalLdFtnResult, IntPtr instantiationArgument, uint parserOffset, ref RuntimeTypeHandle declaringTypeHandle, out QMethodDefinition methodHandle, out RuntimeTypeHandle[] genericMethodTypeArgumentHandles) + private unsafe bool TryGetMethodForOriginalLdFtnResult_InvokeMap_Inner(NativeFormatModuleInfo mappingTableModule, bool forStartAddress, IntPtr canonOriginalLdFtnResult, IntPtr instantiationArgument, uint parserOffset, ref RuntimeTypeHandle declaringTypeHandle, out QMethodDefinition methodHandle, out RuntimeTypeHandle[] genericMethodTypeArgumentHandles) { methodHandle = default(QMethodDefinition); genericMethodTypeArgumentHandles = null; @@ -1069,7 +1087,7 @@ namespace Internal.Reflection.Execution // If the passed in method was a fat function pointer, but the entry in the mapping table doesn't need // an instantiation argument (or the other way around), trivially reject it. - if ((instantiationArgument == IntPtr.Zero) != ((entryFlags & InvokeTableFlags.RequiresInstArg) == 0)) + if (!forStartAddress && ((instantiationArgument == IntPtr.Zero) != ((entryFlags & InvokeTableFlags.RequiresInstArg) == 0))) return false; Debug.Assert((entryFlags & InvokeTableFlags.HasEntrypoint) != 0); @@ -1080,39 +1098,46 @@ namespace Internal.Reflection.Execution IntPtr entryMethodEntrypoint = externalReferences.GetFunctionPointerFromIndex(entryParser.GetUnsigned()); if ((entryFlags & InvokeTableFlags.NeedsParameterInterpretation) == 0) - entryParser.GetUnsigned(); // skip dynamic invoke cookie + entryParser.SkipInteger(); // skip dynamic invoke cookie -#if DEBUG - IntPtr targetAddress; - Debug.Assert(entryMethodEntrypoint == canonOriginalLdFtnResult || - RuntimeAugments.GetCodeTarget(entryMethodEntrypoint) == canonOriginalLdFtnResult || - TypeLoaderEnvironment.TryGetTargetOfUnboxingAndInstantiatingStub(entryMethodEntrypoint, out targetAddress) && - targetAddress == canonOriginalLdFtnResult); -#endif - - if ((entryFlags & InvokeTableFlags.RequiresInstArg) == 0 && declaringTypeHandle.IsNull()) - declaringTypeHandle = externalReferences.GetRuntimeTypeHandleFromIndex(entryDeclaringTypeRaw); - - if ((entryFlags & InvokeTableFlags.IsGenericMethod) != 0) + if (forStartAddress) { - if ((entryFlags & InvokeTableFlags.RequiresInstArg) != 0) - { - MethodNameAndSignature dummyNameAndSignature; - bool success = TypeLoaderEnvironment.Instance.TryGetGenericMethodComponents(instantiationArgument, out declaringTypeHandle, out dummyNameAndSignature, out genericMethodTypeArgumentHandles); - Debug.Assert(success); - } - else - genericMethodTypeArgumentHandles = GetTypeSequence(ref externalReferences, ref entryParser); + declaringTypeHandle = externalReferences.GetRuntimeTypeHandleFromIndex(entryDeclaringTypeRaw); } else { - genericMethodTypeArgumentHandles = null; - if ((entryFlags & InvokeTableFlags.RequiresInstArg) != 0) - declaringTypeHandle = RuntimeAugments.CreateRuntimeTypeHandle(instantiationArgument); - } +#if DEBUG + IntPtr targetAddress; + Debug.Assert(entryMethodEntrypoint == canonOriginalLdFtnResult || + RuntimeAugments.GetCodeTarget(entryMethodEntrypoint) == canonOriginalLdFtnResult || + TypeLoaderEnvironment.TryGetTargetOfUnboxingAndInstantiatingStub(entryMethodEntrypoint, out targetAddress) && + targetAddress == canonOriginalLdFtnResult); +#endif - RuntimeTypeHandle entryType = externalReferences.GetRuntimeTypeHandleFromIndex(entryDeclaringTypeRaw); - declaringTypeHandle = GetExactDeclaringType(entryType, declaringTypeHandle); + if ((entryFlags & InvokeTableFlags.RequiresInstArg) == 0 && declaringTypeHandle.IsNull()) + declaringTypeHandle = externalReferences.GetRuntimeTypeHandleFromIndex(entryDeclaringTypeRaw); + + if ((entryFlags & InvokeTableFlags.IsGenericMethod) != 0) + { + if ((entryFlags & InvokeTableFlags.RequiresInstArg) != 0) + { + MethodNameAndSignature dummyNameAndSignature; + bool success = TypeLoaderEnvironment.Instance.TryGetGenericMethodComponents(instantiationArgument, out declaringTypeHandle, out dummyNameAndSignature, out genericMethodTypeArgumentHandles); + Debug.Assert(success); + } + else + genericMethodTypeArgumentHandles = GetTypeSequence(ref externalReferences, ref entryParser); + } + else + { + genericMethodTypeArgumentHandles = null; + if ((entryFlags & InvokeTableFlags.RequiresInstArg) != 0) + declaringTypeHandle = RuntimeAugments.CreateRuntimeTypeHandle(instantiationArgument); + } + + RuntimeTypeHandle entryType = externalReferences.GetRuntimeTypeHandleFromIndex(entryDeclaringTypeRaw); + declaringTypeHandle = GetExactDeclaringType(entryType, declaringTypeHandle); + } if ((entryFlags & InvokeTableFlags.HasMetadataHandle) != 0) { @@ -1173,17 +1198,17 @@ namespace Internal.Reflection.Execution uint parserOffset = entryParser.Offset; // Declaring Handle - entryParser.GetUnsigned(); + entryParser.SkipInteger(); // NameAndSig - entryParser.GetUnsigned(); + entryParser.SkipInteger(); // generic method arity int parsedArity = (int)entryParser.GetSequenceCount(); for (int i = 0; i < parsedArity; i++) { - entryParser.GetUnsigned(); + entryParser.SkipInteger(); } IntPtr functionPointer = externalReferences.GetIntPtrFromIndex(entryParser.GetUnsigned()); @@ -1196,14 +1221,11 @@ namespace Internal.Reflection.Execution return functionPointerToOffsetInInvokeMap; } - private unsafe bool TryGetMethodForOriginalLdFtnResult_ExactInstantiation_Inner(NativeFormatModuleInfo mappingTableModule, IntPtr canonOriginalLdFtnResult, IntPtr instantiationArgument, uint parserOffset, ref RuntimeTypeHandle declaringTypeHandle, out QMethodDefinition methodHandle, out RuntimeTypeHandle[] genericMethodTypeArgumentHandles) + private unsafe bool TryGetMethodForOriginalLdFtnResult_ExactInstantiation_Inner(NativeFormatModuleInfo mappingTableModule, bool forStartAddress, IntPtr canonOriginalLdFtnResult, uint parserOffset, ref RuntimeTypeHandle declaringTypeHandle, out QMethodDefinition methodHandle, out RuntimeTypeHandle[] genericMethodTypeArgumentHandles) { methodHandle = default(QMethodDefinition); genericMethodTypeArgumentHandles = null; - if (instantiationArgument != IntPtr.Zero) - return false; - NativeReader invokeMapReader; if (!TryGetNativeReaderForBlob(mappingTableModule, ReflectionMapBlob.ExactMethodInstantiationsHashtable, out invokeMapReader)) { @@ -1225,11 +1247,22 @@ namespace Internal.Reflection.Execution return false; int parsedArity = (int)entryParser.GetSequenceCount(); - genericMethodTypeArgumentHandles = new RuntimeTypeHandle[parsedArity]; - for (int i = 0; i < parsedArity; i++) + if (forStartAddress) { - genericMethodTypeArgumentHandles[i] = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned()); + for (int i = 0; i < parsedArity; i++) + { + entryParser.SkipInteger(); + } + } + else + { + genericMethodTypeArgumentHandles = new RuntimeTypeHandle[parsedArity]; + + for (int i = 0; i < parsedArity; i++) + { + genericMethodTypeArgumentHandles[i] = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned()); + } } IntPtr functionPointer = externalReferences.GetIntPtrFromIndex(entryParser.GetUnsigned()); @@ -1486,10 +1519,7 @@ namespace Internal.Reflection.Execution { Type parameterType = parameters[i].ParameterType; - // If the parameter is a pointer type, use IntPtr. Else use the actual parameter type. - if (parameterType.IsPointer) - result.Add(CommonRuntimeTypes.IntPtr.TypeHandle); - else if (parameterType.IsByRef) + if (parameterType.IsByRef) result.Add(parameterType.GetElementType().TypeHandle); else if (parameterType.GetTypeInfo().IsEnum && !parameters[i].HasDefaultValue) result.Add(Enum.GetUnderlyingType(parameterType).TypeHandle); @@ -1509,6 +1539,8 @@ namespace Internal.Reflection.Execution MethodInfo reflectionMethodInfo = _methodBase as MethodInfo; Type returnType = reflectionMethodInfo != null ? reflectionMethodInfo.ReturnType : CommonRuntimeTypes.Void; + if (returnType.IsByRef) + returnType = returnType.GetElementType(); result.Insert(0, returnType.TypeHandle); return result; diff --git a/external/corert/src/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ReflectionExecution.cs b/external/corert/src/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ReflectionExecution.cs index d2135fd086..c8b4a019e7 100644 --- a/external/corert/src/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ReflectionExecution.cs +++ b/external/corert/src/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ReflectionExecution.cs @@ -64,10 +64,6 @@ namespace Internal.Reflection.Execution }; ExecutionEnvironment = executionEnvironment; - -#if SUPPORT_JIT - Internal.Runtime.TypeLoader.MethodExecutionStrategy.GlobalExecutionStrategy = new Internal.Runtime.JitSupport.RyuJitExecutionStrategy(); -#endif } // @@ -98,16 +94,13 @@ namespace Internal.Reflection.Execution methodHandle = default(MethodHandle); RuntimeTypeHandle declaringTypeHandle = default(RuntimeTypeHandle); - if (!ExecutionEnvironment.TryGetMethodForOriginalLdFtnResult(methodStartAddress, - ref declaringTypeHandle, out QMethodDefinition qMethodDefinition, out _)) + if (!ExecutionEnvironment.TryGetMethodForStartAddress(methodStartAddress, + ref declaringTypeHandle, out QMethodDefinition qMethodDefinition)) return false; if (!qMethodDefinition.IsNativeFormatMetadataBased) return false; - if (RuntimeAugments.IsGenericType(declaringTypeHandle)) - declaringTypeHandle = RuntimeAugments.GetGenericDefinition(declaringTypeHandle); - if (!ExecutionEnvironment.TryGetMetadataForNamedType(declaringTypeHandle, out QTypeDefinition qTypeDefinition)) return false; diff --git a/external/corert/src/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ReflectionExecutionDomainCallbacksImplementation.cs b/external/corert/src/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ReflectionExecutionDomainCallbacksImplementation.cs index 1a004f50de..b6ba92e2b9 100644 --- a/external/corert/src/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ReflectionExecutionDomainCallbacksImplementation.cs +++ b/external/corert/src/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ReflectionExecutionDomainCallbacksImplementation.cs @@ -104,18 +104,12 @@ namespace Internal.Reflection.Execution { RuntimeTypeHandle declaringTypeHandle = default(RuntimeTypeHandle); QMethodDefinition methodHandle; - RuntimeTypeHandle[] genericMethodTypeArgumentHandles; - if (!ReflectionExecution.ExecutionEnvironment.TryGetMethodForOriginalLdFtnResult(methodStartAddress, - ref declaringTypeHandle, out methodHandle, out genericMethodTypeArgumentHandles)) + if (!ReflectionExecution.ExecutionEnvironment.TryGetMethodForStartAddress(methodStartAddress, + ref declaringTypeHandle, out methodHandle)) { return null; } - if (RuntimeAugments.IsGenericType(declaringTypeHandle)) - { - declaringTypeHandle = RuntimeAugments.GetGenericDefinition(declaringTypeHandle); - } - // We don't use the type argument handles as we want the uninstantiated method info return ReflectionCoreExecution.ExecutionDomain.GetMethod(declaringTypeHandle, methodHandle, genericMethodTypeArgumentHandles: null); } diff --git a/external/corert/src/System.Private.Reflection.Execution/src/Resources/Strings.resx b/external/corert/src/System.Private.Reflection.Execution/src/Resources/Strings.resx index f03a830ef2..0a8ef5f1ba 100644 --- a/external/corert/src/System.Private.Reflection.Execution/src/Resources/Strings.resx +++ b/external/corert/src/System.Private.Reflection.Execution/src/Resources/Strings.resx @@ -141,30 +141,9 @@ Nullable object must have a value. - - Late-bound invocation is not supported for compiler-intrinsic methods. - - - Methods using the vararg calling convention are not supported on this platform. - - - Passing or returning pointers through Invoke is not supported on this platform. - Non-static field requires a target. - - Prerelease Restriction: The following type member cannot be referenced from inside a Linq Expression:\n\n - - - \n\nThe following may be used as a workaround:\n\n - - - 1. Make the member public or mark the member with the System.Reflection.Metadata.Controls.ReflectionInfo attribute specifying the argument ReflectionInfoOption.Include\n - - - 2. Enable Reflection for its declaring type with the System.Reflection.Consumption.EnableDynamicProgramming attribute.\n\n\n - Constructor on type '{0}' not found. @@ -192,9 +171,6 @@ '{0}', on '{1}' violates the constraint of type '{2}'. - - Obtaining a MethodInfo of a reflection-constructed delegate to a virtual method is not supported on this platform. - At least one object must implement IComparable. diff --git a/external/corert/src/System.Private.Reflection.Execution/src/System.Private.Reflection.Execution.Experimental.csproj b/external/corert/src/System.Private.Reflection.Execution/src/System.Private.Reflection.Execution.Experimental.csproj index 069aa60a9d..d70b8fc7a7 100644 --- a/external/corert/src/System.Private.Reflection.Execution/src/System.Private.Reflection.Execution.Experimental.csproj +++ b/external/corert/src/System.Private.Reflection.Execution/src/System.Private.Reflection.Execution.Experimental.csproj @@ -2,7 +2,7 @@ System.Private.Reflection.Execution.Experimental true - true + true diff --git a/external/corert/src/System.Private.Reflection.Execution/src/System.Private.Reflection.Execution.csproj b/external/corert/src/System.Private.Reflection.Execution/src/System.Private.Reflection.Execution.csproj index 5b935ef320..ed737d170d 100644 --- a/external/corert/src/System.Private.Reflection.Execution/src/System.Private.Reflection.Execution.csproj +++ b/external/corert/src/System.Private.Reflection.Execution/src/System.Private.Reflection.Execution.csproj @@ -13,9 +13,6 @@ ECMA_METADATA_SUPPORT;$(DefineConstants) - - SUPPORT_JIT;$(DefineConstants) - @@ -28,17 +25,18 @@ global,System_Private_CoreLib - - + + + @@ -95,7 +93,6 @@ - diff --git a/external/corert/src/System.Private.Reflection.Metadata/tests/System.Private.Reflection.Metadata.Tests.csproj b/external/corert/src/System.Private.Reflection.Metadata/tests/System.Private.Reflection.Metadata.Tests.csproj index 17e5448997..08994fa92a 100644 --- a/external/corert/src/System.Private.Reflection.Metadata/tests/System.Private.Reflection.Metadata.Tests.csproj +++ b/external/corert/src/System.Private.Reflection.Metadata/tests/System.Private.Reflection.Metadata.Tests.csproj @@ -6,7 +6,7 @@ System.Private.Reflection.Metadata.Tests System.Private.Reflection.Metadata.Tests true - netstandard1.3 + netstandard2.0 ..\..\Common\src\Internal\NativeFormat @@ -26,8 +26,11 @@ - - $(XunitNetcoreExtensionsVersion) + + $(XUnitPackageVersion) + + + $(MicrosoftDotNetXUnitExtensionsVersion) diff --git a/external/corert/src/System.Private.StackTraceMetadata/src/System.Private.StackTraceMetadata.Experimental.csproj b/external/corert/src/System.Private.StackTraceMetadata/src/System.Private.StackTraceMetadata.Experimental.csproj new file mode 100644 index 0000000000..637480fcb7 --- /dev/null +++ b/external/corert/src/System.Private.StackTraceMetadata/src/System.Private.StackTraceMetadata.Experimental.csproj @@ -0,0 +1,8 @@ + + + System.Private.StackTraceMetadata.Experimental + true + + + + diff --git a/external/corert/src/System.Private.StackTraceMetadata/src/System.Private.StackTraceMetadata.csproj b/external/corert/src/System.Private.StackTraceMetadata/src/System.Private.StackTraceMetadata.csproj index 799bc65e03..22c4b488c9 100644 --- a/external/corert/src/System.Private.StackTraceMetadata/src/System.Private.StackTraceMetadata.csproj +++ b/external/corert/src/System.Private.StackTraceMetadata/src/System.Private.StackTraceMetadata.csproj @@ -1,7 +1,7 @@ - System.Private.StackTraceMetadata + System.Private.StackTraceMetadata 4.0.0.0 Library true @@ -11,8 +11,10 @@ - - + + + + diff --git a/external/corert/src/System.Private.Threading/src/Resources/Strings.resx b/external/corert/src/System.Private.Threading/src/Resources/Strings.resx index f160191c09..ff802f945c 100644 --- a/external/corert/src/System.Private.Threading/src/Resources/Strings.resx +++ b/external/corert/src/System.Private.Threading/src/Resources/Strings.resx @@ -117,52 +117,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - The event is already signaled and cannot be incremented. - - - The increment operation would cause the CurrentCount to overflow. - - - Invalid attempt made to decrement the event's count below zero. - - - The operation was canceled. - - - The barrier has been disposed. - - - The barrier has no registered participants. - - - The specified timeout must represent a value between -1 and Int32.MaxValue, inclusive. - - - The participantCount argument is greater than the number of participants that haven't yet arrived at the barrier in this phase. - - - The participantCount argument must be less than or equal the number of participants. - - - The participantCount argument must be a positive value. - - - This method may not be called from within the postPhaseAction. - - - The participantCount argument must be a positive value. - - - The number of threads using the barrier exceeded the total number of registered participants. - The postPhaseAction failed with an exception. - - The participantCount argument must be non-negative and less than or equal to 32767. - - - Adding participantCount participants would result in the number of participants exceeding the maximum number allowed. - - \ No newline at end of file + diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Reflection/Core/AssemblyBinder.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Reflection/Core/AssemblyBinder.cs index 75cb21e540..e346f5f6b1 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Reflection/Core/AssemblyBinder.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Reflection/Core/AssemblyBinder.cs @@ -30,7 +30,7 @@ namespace Internal.Reflection.Core { public const String DefaultAssemblyNameForGetType = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; - public abstract bool Bind(RuntimeAssemblyName refName, out AssemblyBindResult result, out Exception exception); + public abstract bool Bind(RuntimeAssemblyName refName, bool cacheMissedLookups, out AssemblyBindResult result, out Exception exception); public abstract bool Bind(byte[] rawAssembly, byte[] rawSymbolStore, out AssemblyBindResult result, out Exception exception); diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Reflection/Execution/AssemblyBinderImplementation.Ecma.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Reflection/Execution/AssemblyBinderImplementation.Ecma.cs index c6342da015..444538f55b 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Reflection/Execution/AssemblyBinderImplementation.Ecma.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Reflection/Execution/AssemblyBinderImplementation.Ecma.cs @@ -59,7 +59,7 @@ namespace Internal.Reflection.Execution lock(s_ecmaLoadedAssemblies) { // 3. Attempt to bind to already loaded assembly - if (Bind(runtimeAssemblyName, out bindResult, out exception)) + if (Bind(runtimeAssemblyName, cacheMissedLookups: false, out bindResult, out exception)) { result = true; return; @@ -75,7 +75,7 @@ namespace Internal.Reflection.Execution moduleList.RegisterModule(newModuleInfo); // 5. Then try to load by name again. This load should always succeed - if (Bind(runtimeAssemblyName, out bindResult, out exception)) + if (Bind(runtimeAssemblyName, cacheMissedLookups: true, out bindResult, out exception)) { result = true; return; @@ -86,7 +86,7 @@ namespace Internal.Reflection.Execution } } - partial void BindEcmaAssemblyName(RuntimeAssemblyName refName, ref AssemblyBindResult result, ref Exception exception, ref Exception preferredException, ref bool foundMatch) + partial void BindEcmaAssemblyName(RuntimeAssemblyName refName, bool cacheMissedLookups, ref AssemblyBindResult result, ref Exception exception, ref Exception preferredException, ref bool foundMatch) { lock(s_ecmaLoadedAssemblies) { @@ -186,7 +186,7 @@ namespace Internal.Reflection.Execution } // Cache missed lookups - if (!foundMatch) + if (cacheMissedLookups && !foundMatch) { PEInfo peinfo = new PEInfo(refName, null, null); s_ecmaLoadedAssemblies.Add(peinfo); diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Reflection/Execution/AssemblyBinderImplementation.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Reflection/Execution/AssemblyBinderImplementation.cs index 701160534d..e2fcc6a579 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Reflection/Execution/AssemblyBinderImplementation.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Reflection/Execution/AssemblyBinderImplementation.cs @@ -35,7 +35,7 @@ namespace Internal.Reflection.Execution public static AssemblyBinderImplementation Instance { get; } = new AssemblyBinderImplementation(); partial void BindEcmaByteArray(byte[] rawAssembly, byte[] rawSymbolStore, ref AssemblyBindResult bindResult, ref Exception exception, ref bool? result); - partial void BindEcmaAssemblyName(RuntimeAssemblyName refName, ref AssemblyBindResult result, ref Exception exception, ref Exception preferredException, ref bool resultBoolean); + partial void BindEcmaAssemblyName(RuntimeAssemblyName refName, bool cacheMissedLookups, ref AssemblyBindResult result, ref Exception exception, ref Exception preferredException, ref bool resultBoolean); partial void InsertEcmaLoadedAssemblies(List loadedAssemblies); public sealed override bool Bind(byte[] rawAssembly, byte[] rawSymbolStore, out AssemblyBindResult bindResult, out Exception exception) @@ -53,7 +53,7 @@ namespace Internal.Reflection.Execution return result.Value; } - public sealed override bool Bind(RuntimeAssemblyName refName, out AssemblyBindResult result, out Exception exception) + public sealed override bool Bind(RuntimeAssemblyName refName, bool cacheMissedLookups, out AssemblyBindResult result, out Exception exception) { bool foundMatch = false; result = default(AssemblyBindResult); @@ -102,7 +102,7 @@ namespace Internal.Reflection.Execution } } - BindEcmaAssemblyName(refName, ref result, ref exception, ref preferredException, ref foundMatch); + BindEcmaAssemblyName(refName, cacheMissedLookups, ref result, ref exception, ref preferredException, ref foundMatch); if (exception != null) return false; diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.cs index b9b8a9cff2..f0f8256c7d 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.cs @@ -1114,11 +1114,12 @@ namespace Internal.Runtime.TypeLoader #endif } } - else if (conversionParams._conversionInfo.IsAnyDynamicInvokerThunk && thRetType.IsValueType()) + else if (conversionParams._conversionInfo.IsAnyDynamicInvokerThunk && + (thRetType.IsValueType() || thRetType.IsPointerType() || returnType == CorElementType.ELEMENT_TYPE_BYREF)) { Debug.Assert(returnValueToCopy != null); - if (conversionParams._calleeArgs.GetReturnType(out thDummy, out dummyBool) == CorElementType.ELEMENT_TYPE_VOID) + if (returnType == CorElementType.ELEMENT_TYPE_VOID) { // Invokers returning void need to return a null object returnValueToCopy = null; @@ -1128,8 +1129,37 @@ namespace Internal.Runtime.TypeLoader if (!conversionParams._callerArgs.HasRetBuffArg() && conversionParams._calleeArgs.HasRetBuffArg()) returnValueToCopy = (void*)(new IntPtr(*((void**)returnValueToCopy)) + IntPtr.Size); + if (returnType == CorElementType.ELEMENT_TYPE_BYREF) + { + // If this is a byref return, we're going to dereference the result + returnValueToCopy = *(void**)returnValueToCopy; + } + + RuntimeTypeHandle returnTypeRuntimeTypeHandle = thRetType.GetRuntimeTypeHandle(); + // Need to box value type before returning it - object returnValue = RuntimeAugments.Box(thRetType.GetRuntimeTypeHandle(), new IntPtr(returnValueToCopy)); + object returnValue; + if (returnType == CorElementType.ELEMENT_TYPE_BYREF && returnValueToCopy == null) + { + // This is a byref return and dereferencing it would result in a NullReferenceException. + // Set the return value to a sentinel that InvokeUtils will recognize. + // Can't throw from here or we would wrap this in a TargetInvocationException. + returnValue = InvokeUtils.NullByRefValueSentinel; + } + else if (RuntimeAugments.IsUnmanagedPointerType(returnTypeRuntimeTypeHandle)) + { + returnValue = System.Reflection.Pointer.Box(*(void**)returnValueToCopy, Type.GetTypeFromHandle(returnTypeRuntimeTypeHandle)); + } + else if (RuntimeAugments.IsValueType(returnTypeRuntimeTypeHandle)) + { + returnValue = RuntimeAugments.Box(returnTypeRuntimeTypeHandle, new IntPtr(returnValueToCopy)); + } + else + { + // byref return of a reference type + Debug.Assert(returnType == CorElementType.ELEMENT_TYPE_BYREF); + returnValue = Unsafe.As(ref *(byte*)returnValueToCopy); + } CallConversionParameters.s_pinnedGCHandles._returnObjectHandle.Target = returnValue; pinnedResultObject = CallConversionParameters.s_pinnedGCHandles._returnObjectHandle.GetRawTargetAddress(); returnValueToCopy = (void*)&pinnedResultObject; diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs index b26dd803f5..039dab7bf8 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs @@ -95,6 +95,9 @@ namespace Internal.Runtime.CallInterceptor { address = *(IntPtr*)address.ToPointer(); } +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine("READ " + (_types[index].ByRef ? "ByRef " : "") + "LocalVariableSet, _pbMemory:" + new IntPtr(_pbMemory).LowLevelToString() + "[" + index.LowLevelToString() + "]. " + _types[index].TypeInstanceFieldSize.LowLevelToString() + " bytes <- [" + address.LowLevelToString() + "]"); +#endif return Unsafe.Read((void*)address); } @@ -108,6 +111,9 @@ namespace Internal.Runtime.CallInterceptor { address = *(IntPtr*)address.ToPointer(); } +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine("WRITE " + (_types[index].ByRef ? "ByRef " : "") + "LocalVariableSet, _pbMemory:" + new IntPtr(_pbMemory).LowLevelToString() + "[" + index.LowLevelToString() + "]. " + _types[index].TypeInstanceFieldSize.LowLevelToString() + " bytes -> [" + address.LowLevelToString() + "]"); +#endif Unsafe.Write((void*)address, value); } @@ -510,16 +516,38 @@ namespace Internal.Runtime.CallInterceptor break; default: - callConversionOps.Add(new CallConversionOperation( - CallConversionOperation.OpCode.COPY_X_BYTES_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, - calleeArgs.GetArgSize(), - CallConversionInterpreter.ArgBlock, - i, - ofsCallee + { +#if ARM64 + if (ofsCallee < 0 && argTypeHandle.IsHFA() && argTypeHandle.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) + { + // S and D registers overlap. The FP block of the transition block has 64-bit slots that are used for both floats and doubles. + // When dealing with float HFAs, we need to copy the 32-bit floats into the 64-bit slots to match the format of the transition block's FP block. + + callConversionOps.Add(new CallConversionOperation( + CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, + (int)argTypeHandle.GetSize() / 4, + CallConversionInterpreter.ArgBlock, + i, + ofsCallee #if CCCONVERTER_TRACE - , "Arg #" + i.LowLevelToString() + , "Arg #" + i.LowLevelToString() #endif - )); + )); + break; + } +#endif + + callConversionOps.Add(new CallConversionOperation( + CallConversionOperation.OpCode.COPY_X_BYTES_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, + calleeArgs.GetArgSize(), + CallConversionInterpreter.ArgBlock, + i, + ofsCallee +#if CCCONVERTER_TRACE + , "Arg #" + i.LowLevelToString() +#endif + )); + } break; } } @@ -556,8 +584,20 @@ namespace Internal.Runtime.CallInterceptor } else { - // Copy from return buffer into return value local - callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.COPY_X_BYTES_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, checked((int)returnType.GetSize()), CallConversionInterpreter.ArgBlock, 0)); +#if ARM64 + if (returnType.IsHFA() && returnType.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) + { + // S and D registers overlap. The return buffer has 64-bit slots that are used for both floats and doubles. + // When dealing with float HFAs, we need to copy 32-bit float values from the 64-bit slots of the return buffer (A simple memcopy won't work here). + + callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, checked((int)returnType.GetSize() / 4), CallConversionInterpreter.ArgBlock, 0)); + } + else +#endif + { + // Copy from return buffer into return value local + callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.COPY_X_BYTES_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, checked((int)returnType.GetSize()), CallConversionInterpreter.ArgBlock, 0)); + } } } @@ -640,7 +680,7 @@ namespace Internal.Runtime.CallInterceptor s = "RETURN_RETBUF_FROM_OFFSET_X_IN_TRANSITION_BLOCK"; break; case OpCode.RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z: - s = "__RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z__"; + s = "RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z"; break; case OpCode.RETURN_INTEGER_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z: s = "RETURN_INTEGER_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z"; @@ -663,6 +703,20 @@ namespace Internal.Runtime.CallInterceptor case OpCode.COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK: s = "COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK"; break; +#if ARM64 + case OpCode.ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK: + s = "ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK"; + break; + case OpCode.ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK: + s = "ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK"; + break; + case OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK: + s = "ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK"; + break; + case OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z: + s = "ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z"; + break; +#endif default: s = ""; break; @@ -690,7 +744,7 @@ namespace Internal.Runtime.CallInterceptor } #else - public CallConversionOperation(OpCode op, int X, int Y, int Z, int W) + public CallConversionOperation(OpCode op, int X, int Y, int Z, int W) { this.Op = op; this.X = X; @@ -755,7 +809,13 @@ namespace Internal.Runtime.CallInterceptor CALL_DESCR_MANAGED_WITH_RETBUF_AS_LOCALBLOCK_X_POINTER_Y_STACKSLOTS_Z_FPCALLINFO_W, CALL_DESCR_NATIVE_WITH_RETBUF_AS_LOCALBLOCK_X_POINTER_Y_STACKSLOTS_Z_FPCALLINFO_W, COPY_X_BYTES_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, - COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK + COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK, +#if ARM64 + ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK, + ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK, + ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, + ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z +#endif } public OpCode Op; @@ -875,6 +935,73 @@ namespace Internal.Runtime.CallInterceptor } break; +#if ARM64 + case CallConversionOperation.OpCode.ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK: + { + Debug.Assert(op.X > 0 && op.X <= 4); + + float* pFPRegs = (float*)(locals.TransitionBlockPtr + op.Y); + for (int i = 1; i < op.X; i++) + pFPRegs[i] = pFPRegs[i * 2]; + +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine(" -> Compact " + op.X.LowLevelToString() + " ARM64 HFA floats at [" + new IntPtr(pFPRegs).LowLevelToString() + "]"); +#endif + } + break; + + case CallConversionOperation.OpCode.ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK: + { + Debug.Assert(op.X > 0 && op.X <= 4); + + byte* pReturnBlock = locals.TransitionBlockPtr + TransitionBlock.GetOffsetOfFloatArgumentRegisters(); + for (int i = op.X - 1; i >= 0; i--) + { + float value = ((float*)pReturnBlock)[i]; + *((IntPtr*)pReturnBlock + i) = IntPtr.Zero; // Clear destination slot to zeros before copying the float value + *((float*)((IntPtr*)pReturnBlock + i)) = value; + } + +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine(" -> Expand " + op.X.LowLevelToString() + " ARM64 HFA floats at [" + new IntPtr(pReturnBlock).LowLevelToString() + "]"); +#endif + } + break; + + case CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK: + { + Debug.Assert(op.X > 0 && op.X <= 4); + + float* pSrc = (float*)(locals.GetLocalBlock(op.Y).GetRawMemoryPointer()[op.Z]); + float* pDst = (float*)(locals.TransitionBlockPtr + op.W); + for (int i = 0; i < op.X; i++) + { + ((IntPtr*)pDst)[i] = IntPtr.Zero; // Clear destination slot to zeros before copying the float value + pDst[i * 2] = pSrc[i]; + } + +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine(" -> Copy " + op.X.LowLevelToString() + " ARM64 HFA floats from [" + new IntPtr(pSrc).LowLevelToString() + "] to [" + new IntPtr(pDst).LowLevelToString() + "]"); +#endif + } + break; + + case CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z: + { + Debug.Assert(op.X > 0 && op.X <= 4); + + float* pSrc = (float*)locals.IntPtrReturnVal.ToPointer(); + float* pDst = (float*)(locals.GetLocalBlock(op.Y).GetRawMemoryPointer()[op.Z].ToPointer()); + for (int i = 0; i < op.X; i++) + pDst[i] = pSrc[i * 2]; + +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine(" -> Copy " + op.X.LowLevelToString() + " ARM64 HFA floats from [" + new IntPtr(pSrc).LowLevelToString() + "] to [" + new IntPtr(pDst).LowLevelToString() + "]"); +#endif + } + break; +#endif + case CallConversionOperation.OpCode.COPY_X_BYTES_FROM_LOCALBLOCK_Y_OFFSET_Z_IN_LOCALBLOCK_TO_OFFSET_W_IN_TRANSITION_BLOCK: { void* pSrc = ((byte*)locals.GetLocalBlock(op.Y).GetRawMemoryPointer()) + op.Z; @@ -1064,15 +1191,15 @@ namespace Internal.Runtime.CallInterceptor case CallConversionOperation.OpCode.RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z: { #if CALLDESCR_FPARGREGSARERETURNREGS - byte* returnBlock = locals.TransitionBlockPtr + TransitionBlock.GetOffsetOfFloatArgumentRegisters(); - MemoryHelpers.Memset((IntPtr)returnBlock, IntPtr.Size, 0); - Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), returnBlock, op.Z, op.Z); + byte* pReturnBlock = locals.TransitionBlockPtr + TransitionBlock.GetOffsetOfFloatArgumentRegisters(); + MemoryHelpers.Memset((IntPtr)pReturnBlock, IntPtr.Size, 0); + Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), pReturnBlock, op.Z, op.Z); locals.IntPtrReturnVal = CallConverterThunk.ReturnVoidReturnThunk; #elif X86 CallConverterThunk.SetupCallerActualReturnData(locals.TransitionBlockPtr); - fixed (ReturnBlock* retBlk = &CallConverterThunk.t_NonArgRegisterReturnSpace) + fixed (ReturnBlock* pReturnBlock = &CallConverterThunk.t_NonArgRegisterReturnSpace) { - Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), retBlk, op.Z, op.Z); + Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), pReturnBlock, op.Z, op.Z); } if (op.Z == 4) { @@ -1446,8 +1573,10 @@ namespace Internal.Runtime.CallInterceptor { int ofsCaller = callerArgs.GetNextOffset(); - TypeHandle dummyTypeHandle; - if (callerArgs.IsArgPassedByRef() && callerArgs.GetArgType(out dummyTypeHandle) != CorElementType.ELEMENT_TYPE_BYREF) + TypeHandle argTypeHandle; + CorElementType argType = callerArgs.GetArgType(out argTypeHandle); + + if (callerArgs.IsArgPassedByRef() && argType != CorElementType.ELEMENT_TYPE_BYREF) { callConversionOps.Add(new CallConversionOperation( CallConversionOperation.OpCode.COPY_X_BYTES_TO_LOCALBLOCK_Y_OFFSET_Z_IN_LOCALBLOCK_FROM_OFFSET_W_IN_TRANSITION_BLOCK, @@ -1462,6 +1591,24 @@ namespace Internal.Runtime.CallInterceptor } else { +#if ARM64 + if (ofsCaller < 0 && argTypeHandle.IsHFA() && argTypeHandle.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) + { + // S and D registers overlap. The FP block of the transition block will have the float values of the HFA struct stored in 64-bit slots. We cannot directly + // memcopy or point at these values without first re-writing them as consecutive 32-bit float values + + callConversionOps.Add(new CallConversionOperation( + CallConversionOperation.OpCode.ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK, + (int)argTypeHandle.GetSize() / 4, + ofsCaller, + 0 +#if CCCONVERTER_TRACE + , "Arg #" + i.LowLevelToString() +#endif + )); + } +#endif + callConversionOps.Add(new CallConversionOperation( CallConversionOperation.OpCode.SET_LOCALBLOCK_X_POINTER_Y_TO_OFFSET_Z_IN_TRANSITION_BLOCK, CallConversionInterpreter.ArgBlock, @@ -1492,6 +1639,14 @@ namespace Internal.Runtime.CallInterceptor else if (callerArgs.GetFPReturnSize() > 0) { callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z, CallConversionInterpreter.ArgBlock, 0, checked((int)callerArgs.GetFPReturnSize()))); + +#if ARM64 + if (returnType.IsHFA() && returnType.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) + { + // S and D registers overlap, so we need to re-write the float values into 64-bit slots to match the format of the UniversalTransitionBlock's FP return block + callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK, (int)returnType.GetSize() / 4, 0, 0)); + } +#endif } else { diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs index 66dc46496c..939017568e 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs @@ -107,6 +107,7 @@ namespace Internal.Runtime.CallConverter public bool IsNull() { return _eeType == null && !_isByRef; } public bool IsValueType() { if (_isByRef) return false; return _eeType->IsValueType; } + public bool IsPointerType() { if (_isByRef) return false; return _eeType->IsPointerType; } public unsafe uint GetSize() { @@ -836,7 +837,7 @@ namespace Internal.Runtime.CallConverter #if !_TARGET_X86_ numRegistersUsed++; #else - // DESKTOP BEHAVIOR is to do nothing here, as ret buf is never reached by the scan algortithm that walks backwards + // DESKTOP BEHAVIOR is to do nothing here, as ret buf is never reached by the scan algorithm that walks backwards // but in .NET Native, the x86 argument scan is a forward scan, so we need to skip the ret buf arg (which is always // on the stack) initialArgOffset = IntPtr.Size; @@ -934,9 +935,14 @@ namespace Internal.Runtime.CallConverter #if _TARGET_ARM64_ // NOT DESKTOP BEHAVIOR: The S and D registers overlap, and the UniversalTransitionThunk copies D registers to the transition blocks. We'll need // to work with the D registers here as well. + bool processingFloatsAsDoublesFromTransitionBlock = false; if (argType == CorElementType.ELEMENT_TYPE_VALUETYPE && _argTypeHandle.IsHFA() && _argTypeHandle.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) { - argSize *= 2; + if ((argSize / sizeof(float)) + _idxFPReg <= 8) + { + argSize *= 2; + processingFloatsAsDoublesFromTransitionBlock = true; + } } #endif @@ -1238,8 +1244,10 @@ namespace Internal.Runtime.CallConverter if (_argTypeHandle.IsHFA()) { CorElementType type = _argTypeHandle.GetHFAType(); - // DESKTOP BEHAVIOR cFPRegs = (type == CorElementType.ELEMENT_TYPE_R4) ? (argSize / sizeof(float)) : (argSize / sizeof(double)); - cFPRegs = argSize / sizeof(double); + if (processingFloatsAsDoublesFromTransitionBlock) + cFPRegs = argSize / sizeof(double); + else + cFPRegs = (type == CorElementType.ELEMENT_TYPE_R4) ? (argSize / sizeof(float)) : (argSize / sizeof(double)); } else { diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/ConstrainedCallSupport.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/ConstrainedCallSupport.cs index f00b66e76e..184c7a4304 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/ConstrainedCallSupport.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/ConstrainedCallSupport.cs @@ -25,10 +25,8 @@ namespace Internal.Runtime.TypeLoader private delegate IntPtr ResolveCallOnValueTypeDel(IntPtr thisPtr, IntPtr callDescIntPtr); #endif -#if PROJECTN [DllImport("*", ExactSpelling = true, EntryPoint = "ConstrainedCallSupport_GetStubs")] private extern static unsafe void ConstrainedCallSupport_GetStubs(out IntPtr constrainedCallSupport_DerefThisAndCall_CommonCallingStub, out IntPtr constrainedCallSupport_DirectConstrainedCall_CommonCallingStub); -#endif private static IntPtr s_constrainedCallSupport_DerefThisAndCall_CommonCallingStub; private static IntPtr s_constrainedCallSupport_DirectConstrainedCall_CommonCallingStub; @@ -42,14 +40,8 @@ namespace Internal.Runtime.TypeLoader static ConstrainedCallSupport() { - // TODO: export this unmanaged API in CoreRT -#if PROJECTN ConstrainedCallSupport_GetStubs(out s_constrainedCallSupport_DerefThisAndCall_CommonCallingStub, out s_constrainedCallSupport_DirectConstrainedCall_CommonCallingStub); -#else - s_constrainedCallSupport_DerefThisAndCall_CommonCallingStub = IntPtr.Zero; - s_constrainedCallSupport_DirectConstrainedCall_CommonCallingStub = IntPtr.Zero; -#endif } // There are multiple possible paths here. diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/McgIntrinsics.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/McgIntrinsics.cs index f89a4be8e1..2953fdea49 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/McgIntrinsics.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/McgIntrinsics.cs @@ -5,6 +5,13 @@ using System; +namespace System.Runtime.CompilerServices +{ + internal sealed class IntrinsicAttribute : Attribute + { + } +} + namespace System.Runtime.InteropServices { [AttributeUsage((System.AttributeTargets.Method | System.AttributeTargets.Class))] diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/MetadataReaderExtensions.Ecma.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/MetadataReaderExtensions.Ecma.cs index ebd30963a9..7b50bee425 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/MetadataReaderExtensions.Ecma.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/MetadataReaderExtensions.Ecma.cs @@ -9,6 +9,7 @@ using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; +using System.Globalization; using Internal.LowLevelLinq; using Internal.Reflection.Core; @@ -91,10 +92,18 @@ namespace System.Reflection.Runtime.General publicKeyOrTokenByteArray = Array.Empty(); } + string cultureName = culture.GetString(reader); + if (!String.IsNullOrEmpty(cultureName)) + { + // Canonicalize spelling and force a CultureNotFoundException if not a valid culture + CultureInfo cultureInfo = CultureInfo.GetCultureInfo(cultureName); + cultureName = cultureInfo.Name; + } + return new RuntimeAssemblyName( name.GetString(reader), version, - culture.GetString(reader), + cultureName, assemblyNameFlags, publicKeyOrTokenByteArray ); diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/JitSupport.MethodEntrypointStubs.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/MethodEntrypointStubs.cs similarity index 100% rename from external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/JitSupport.MethodEntrypointStubs.cs rename to external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/MethodEntrypointStubs.cs diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutFieldAlgorithm.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutFieldAlgorithm.cs index 5f7c58637f..3ab3a6c8fa 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutFieldAlgorithm.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutFieldAlgorithm.cs @@ -120,7 +120,8 @@ namespace Internal.Runtime.TypeLoader { layout.GcStatics = new StaticsBlock() { Size = position[(int)NativeFormat.FieldStorage.GCStatic], LargestAlignment = DefType.MaximumAlignmentPossible }; layout.NonGcStatics = new StaticsBlock() { Size = position[(int)NativeFormat.FieldStorage.NonGCStatic], LargestAlignment = DefType.MaximumAlignmentPossible }; - layout.ThreadStatics = new StaticsBlock() { Size = position[(int)NativeFormat.FieldStorage.TLSStatic], LargestAlignment = DefType.MaximumAlignmentPossible }; + layout.ThreadGcStatics = new StaticsBlock() { Size = position[(int)NativeFormat.FieldStorage.TLSStatic], LargestAlignment = DefType.MaximumAlignmentPossible }; + layout.ThreadNonGcStatics = new StaticsBlock() { Size = LayoutInt.Zero, LargestAlignment = LayoutInt.Zero }; } int curStaticField = 0; @@ -179,7 +180,8 @@ namespace Internal.Runtime.TypeLoader GcStatics = new StaticsBlock() { Size = gcDataSize, LargestAlignment = DefType.MaximumAlignmentPossible }, NonGcStatics = new StaticsBlock() { Size = nonGcDataSize, LargestAlignment = DefType.MaximumAlignmentPossible }, Offsets = null, // We're not computing field offsets here, so return null - ThreadStatics = new StaticsBlock() { Size = threadDataSize, LargestAlignment = DefType.MaximumAlignmentPossible }, + ThreadGcStatics = new StaticsBlock() { Size = threadDataSize, LargestAlignment = DefType.MaximumAlignmentPossible }, + ThreadNonGcStatics = new StaticsBlock() { Size = LayoutInt.Zero, LargestAlignment = LayoutInt.Zero }, }; return staticLayout; diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NoMetadataFieldLayoutAlgorithm.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NoMetadataFieldLayoutAlgorithm.cs index adff035ae7..83c069b89a 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NoMetadataFieldLayoutAlgorithm.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NoMetadataFieldLayoutAlgorithm.cs @@ -83,7 +83,8 @@ namespace Internal.Runtime.TypeLoader GcStatics = default(StaticsBlock), NonGcStatics = default(StaticsBlock), Offsets = Array.Empty(), // No fields are considered to exist for completely NoMetadataTypes - ThreadStatics = default(StaticsBlock), + ThreadGcStatics = default(StaticsBlock), + ThreadNonGcStatics = default(StaticsBlock), }; return staticLayout; } diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs.REMOVED.git-id b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs.REMOVED.git-id index bfbd678e46..a5fb5884c2 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs.REMOVED.git-id +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs.REMOVED.git-id @@ -1 +1 @@ -315e0f9d274a7b10441556ff7c0b929a52724831 \ No newline at end of file +271ec8cef413e3bac392a44acd047bdb6014cf32 \ No newline at end of file diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs index 709a17f069..b83174f60c 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs @@ -507,7 +507,7 @@ namespace Internal.Runtime.TypeLoader DefType defType = TypeBeingBuilt as DefType; if (defType != null && !defType.IsGenericDefinition) { - return defType.ThreadStaticFieldSize.AsInt; + return defType.ThreadGcStaticFieldSize.AsInt; } else { @@ -532,7 +532,7 @@ namespace Internal.Runtime.TypeLoader public uint NumSealedVTableEntries; public int[] GenericVarianceFlags; - // Sentinel static to allow us to initializae _instanceLayout to something + // Sentinel static to allow us to initialize _instanceLayout to something // and then detect that InstanceGCLayout should return null private static LowLevelList s_emptyLayout = new LowLevelList(); diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.Metadata.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.Metadata.cs index bde93220d8..67a0d3da69 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.Metadata.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.Metadata.cs @@ -1340,7 +1340,7 @@ namespace Internal.Runtime.TypeLoader #if SUPPORTS_R2R_LOADING TryGetCodeTableEntry(methodOnType, out entryPoint, out unboxingStubAddress, out foundAddressType); #endif -#if SUPPORT_JIT +#if SUPPORT_DYNAMIC_CODE if (foundAddressType == MethodAddressType.None) MethodEntrypointStubs.TryGetMethodEntrypoint(methodOnType, out entryPoint, out unboxingStubAddress, out foundAddressType); #endif diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.MethodAddress.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.MethodAddress.cs index 1f33974f84..dbc95140f8 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.MethodAddress.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.MethodAddress.cs @@ -52,7 +52,7 @@ namespace Internal.Runtime.TypeLoader #if SUPPORTS_R2R_LOADING TryGetCodeTableEntry(method, out methodAddress, out unboxingStubAddress, out foundAddressType); #endif -#if SUPPORT_JIT +#if SUPPORT_DYNAMIC_CODE if (foundAddressType == MethodAddressType.None) MethodEntrypointStubs.TryGetMethodEntrypoint(method, out methodAddress, out unboxingStubAddress, out foundAddressType); #endif diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderTypeSystemContext.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderTypeSystemContext.cs index 3b9b0bcd1f..ccbf4aff9a 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderTypeSystemContext.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderTypeSystemContext.cs @@ -45,7 +45,7 @@ namespace Internal.Runtime.TypeLoader public override FieldLayoutAlgorithm GetLayoutAlgorithmForType(DefType type) { if ((type == UniversalCanonType) -#if SUPPORT_JIT +#if SUPPORT_DYNAMIC_CODE || (type.IsRuntimeDeterminedType && (((RuntimeDeterminedType)type).CanonicalType == UniversalCanonType))) #else ) @@ -202,7 +202,7 @@ namespace Internal.Runtime.TypeLoader #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING AssemblyBindResult bindResult; Exception failureException; - if (!AssemblyBinderImplementation.Instance.Bind(name.ToRuntimeAssemblyName(), out bindResult, out failureException)) + if (!AssemblyBinderImplementation.Instance.Bind(name.ToRuntimeAssemblyName(), cacheMissedLookups: true, out bindResult, out failureException)) { if (throwErrorIfNotFound) throw failureException; diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeSystemExtensions.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeSystemExtensions.cs index cbdbd68fdf..0154a424c8 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeSystemExtensions.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeSystemExtensions.cs @@ -145,8 +145,9 @@ namespace Internal.Runtime.TypeLoader methodOnInstantiatedType = typeSystemContext.GetMethodForInstantiatedType(typicalMethod, (InstantiatedType)declaringType); MethodDesc instantiatedMethod = methodOnInstantiatedType; - if (genericMethodArgs.Length != 0) + if (genericMethodArgs != null) { + Debug.Assert(genericMethodArgs.Length > 0); Instantiation genericMethodInstantiation = typeSystemContext.ResolveRuntimeTypeHandles(genericMethodArgs); typeSystemContext.GetInstantiatedMethod(methodOnInstantiatedType, genericMethodInstantiation); } diff --git a/external/corert/src/System.Private.TypeLoader/src/Internal/TypeSystem/RuntimeNoMetadataType.cs b/external/corert/src/System.Private.TypeLoader/src/Internal/TypeSystem/RuntimeNoMetadataType.cs index d9c688be6b..3e6b79244d 100644 --- a/external/corert/src/System.Private.TypeLoader/src/Internal/TypeSystem/RuntimeNoMetadataType.cs +++ b/external/corert/src/System.Private.TypeLoader/src/Internal/TypeSystem/RuntimeNoMetadataType.cs @@ -198,9 +198,9 @@ namespace Internal.TypeSystem.NoMetadata } } - if ((mask & TypeFlags.IsByRefLikeComputed) != 0) + if ((mask & TypeFlags.AttributeCacheComputed) != 0) { - flags |= TypeFlags.IsByRefLikeComputed; + flags |= TypeFlags.AttributeCacheComputed; unsafe { diff --git a/external/corert/src/System.Private.TypeLoader/src/System.Private.TypeLoader.Experimental.csproj b/external/corert/src/System.Private.TypeLoader/src/System.Private.TypeLoader.Experimental.csproj index 530409f48b..1625467d07 100644 --- a/external/corert/src/System.Private.TypeLoader/src/System.Private.TypeLoader.Experimental.csproj +++ b/external/corert/src/System.Private.TypeLoader/src/System.Private.TypeLoader.Experimental.csproj @@ -2,7 +2,7 @@ System.Private.TypeLoader.Experimental true - true + true diff --git a/external/corert/src/System.Private.TypeLoader/src/System.Private.TypeLoader.csproj b/external/corert/src/System.Private.TypeLoader/src/System.Private.TypeLoader.csproj index 1ba5ae8612..0a9048622d 100644 --- a/external/corert/src/System.Private.TypeLoader/src/System.Private.TypeLoader.csproj +++ b/external/corert/src/System.Private.TypeLoader/src/System.Private.TypeLoader.csproj @@ -33,8 +33,8 @@ EETYPE_TYPE_MANAGER;$(DefineConstants) - - SUPPORT_JIT;$(DefineConstants) + + SUPPORT_DYNAMIC_CODE;$(DefineConstants) FEATURE_INTERPRETER;$(DefineConstants) @@ -56,7 +56,8 @@ ..\..\Common\src\Internal\NativeFormat - + + @@ -74,6 +75,7 @@ + @@ -86,10 +88,12 @@ + + - + diff --git a/external/corert/src/Test.CoreLib/src/Test.CoreLib.csproj b/external/corert/src/Test.CoreLib/src/Test.CoreLib.csproj index 685a4fd63a..2ae214276d 100644 --- a/external/corert/src/Test.CoreLib/src/Test.CoreLib.csproj +++ b/external/corert/src/Test.CoreLib/src/Test.CoreLib.csproj @@ -75,6 +75,9 @@ Runtime.Base\src\System\Runtime\InteropServices\UnsafeGCHandle.cs + + Runtime.Base\src\System\Runtime\InteropServices\UnmanagedType.cs + Runtime.Base\src\RhBaseName.cs diff --git a/external/corert/src/dirs.proj b/external/corert/src/dirs.proj index bc9ce5cad2..a0ab1b264c 100644 --- a/external/corert/src/dirs.proj +++ b/external/corert/src/dirs.proj @@ -2,9 +2,10 @@ - + + diff --git a/external/corert/tests/CoreCLR.issues.targets b/external/corert/tests/CoreCLR.issues.targets index d7b9ad4860..39e8922830 100644 --- a/external/corert/tests/CoreCLR.issues.targets +++ b/external/corert/tests/CoreCLR.issues.targets @@ -260,8 +260,6 @@ - - @@ -403,10 +401,6 @@ - - - - diff --git a/external/corert/tests/CoreCLR/runtest/publishdependency.targets b/external/corert/tests/CoreCLR/runtest/publishdependency.targets index 4aee8d8fd2..90cb1697a4 100644 --- a/external/corert/tests/CoreCLR/runtest/publishdependency.targets +++ b/external/corert/tests/CoreCLR/runtest/publishdependency.targets @@ -2,8 +2,8 @@ - - netcoreapp1.0 + + netcoreapp2.1 - - netcoreapp1.0 + + netcoreapp2.1 $(DefaultTestTFM) $(DefaultTestTFM) diff --git a/external/corert/tests/CoreFX/build-and-run-test.cmd b/external/corert/tests/CoreFX/build-and-run-test.cmd new file mode 100644 index 0000000000..f734c05c67 --- /dev/null +++ b/external/corert/tests/CoreFX/build-and-run-test.cmd @@ -0,0 +1,67 @@ +:: Test build and execution wrapper for CoreFX tests +:: +:: This wrapper is called for each of CoreFX's tests by runtest.cmd +:: +:: %1 contains test folder +:: %2 contains test exe name +:: +@echo OFF +setlocal ENABLEDELAYEDEXPANSION + +set TestFolder=%1 + +:: +:: We're only interested in referencing the xunit runner - the test dlls will be imported by the test wrapper project +:: +set TestExecutable=xunit.console.netcore +set TestFileName=%2 + + +:: Copy the artefacts we need to compile and run the xunit exe +copy /Y "%~dp0\runtest\CoreFXTestHarness\*" "%TestFolder%" >nul + +if "%CoreRT_TestLogFileName%"=="" ( + set CoreRT_TestLogFileName=testResults.xml +) + +:: Create log dir if it doesn't exist +if not exist %XunitLogDir% md %XunitLogDir% + +if not exist %XunitLogDir%\%TestFileName% md %XunitLogDir%\%TestFileName% + +if not exist %TestFolder%\%TestExecutable%.exe ( + :: Not a test we support, exit silently + exit /b 0 +) + +:: Workaround until we have a better reflection engine +:: Add name of currently executing test to rd.xml +powershell -Command "(Get-Content %TestFolder%\default.rd.xml).replace('*Application*', '%TestFileName%') | Set-Content %TestFolder%\default.rd.xml" + +:: +:: Force environment to 64-bit if we're doing an x64 test run +:: +if "%CoreRT_BuildArch%" == "x64" ( + call "%VS150COMNTOOLS%\..\..\VC\Auxiliary\Build\vcvarsall.bat" x64 >nul +) + +echo Building %TestFileName% + +call "%CoreRT_CliDir%\dotnet.exe" publish %TestFolder%\Test.csproj /ConsoleLoggerParameters:ForceNoAlign "/p:IlcPath=%CoreRT_ToolchainDir%" "/p:DebugSymbols=false" "/p:Configuration=%CoreRT_BuildType%" "/p:FrameworkLibPath=%~dp0..\..\bin\%CoreRT_BuildOS%.%CoreRT_BuildArch%.%CoreRT_BuildType%\lib" "/p:FrameworkObjPath=%~dp0..\..\bin\obj\%CoreRT_BuildOS%.%CoreRT_BuildArch%.%CoreRT_BuildType%\Framework" /p:DisableFrameworkLibGeneration=true /p:TestRootDir=%~dp0 /p:OSGroup=%CoreRT_BuildOS% /p:ExecutableName=%TestExecutable% /nologo +if errorlevel 1 ( + echo Building %TestFileName% failed + exit /b 1 +) + +echo Executing %TestFileName% - writing logs to %XunitLogDir%\%TestFileName%\%CoreRT_TestLogFileName% +echo To repro directly, run call %TestFolder%\native\%TestExecutable% %TestFolder%\%TestFileName%.dll @"%TestFolder%\%TestFileName%.rsp" -xml %XunitLogDir%\%TestFileName%\%CoreRT_TestLogFileName% -notrait category=nonnetcoreapptests -notrait category=nonwindowstests -notrait category=failing + +if not exist "%TestFolder%\native\%TestExecutable%".exe ( + echo ERROR:Native binary not found Unable to run test. + exit /b 1 +) + +call %TestFolder%\native\%TestExecutable% %TestFolder%\%TestFileName%.dll @"%TestFolder%\%TestFileName%.rsp" -xml %XunitLogDir%\%TestFileName%\%CoreRT_TestLogFileName% -notrait category=nonnetcoreapptests -notrait category=nonwindowstests -notrait category=failing +set TestExitCode=!ERRORLEVEL! + +exit /b %TestExitCode% \ No newline at end of file diff --git a/external/corert/tests/CoreFX/corerun b/external/corert/tests/CoreFX/corerun new file mode 100755 index 0000000000..8ee079af64 --- /dev/null +++ b/external/corert/tests/CoreFX/corerun @@ -0,0 +1,78 @@ +#!/usr/bin/env bash + +# This is the Unix equivalent of build-and-run-test.cmd +# It is invoked by each test's bash script. The reason it's called corerun is that +# the unix CoreCLR tests don't have a custom runner override environment variable. +# See issue https://github.com/dotnet/coreclr/issues/9007 +# The CoreFX alternative is named corerun to keep parity with the CoreCLR testing convention + + +export TestFolderName=$1 +export TestFileName=$(basename ${TestFolderName}) +export TestRootDir=${CoreRT_TestRoot}/CoreFX +export LogDir=$2 +# +# We're only interested in referencing the xunit runner - the test dlls will be imported by the test wrapper project +# +TestExecutable=xunit.console.netcore + +source "$CoreRT_TestRoot/coredump_handling.sh" + +if [[ $CoreRT_EnableCoreDumps == 1 ]]; then + set_up_core_dump_generation +fi + +if [ ! -e "${TestFolderName}/${TestExecutable}.exe" ]; then + echo "not found in ${TestFolderName}/${TestExecutable}.exe" + # Not a test we support, exit silently + exit 0 +fi + +# Copy the artefacts we need to compile and run the xunit exe +cp -a "${CoreRT_TestRoot}/CoreFX/runtest/CoreFXTestHarness/." "${TestFolderName}" +export __exitcode=$? +if [ ${__exitcode} != 0 ]; +then + exit ${__exitcode} +fi + +# Workaround until we have a better reflection engine +# Add name of currently executing test to rd.xml +sed -i.bak "s/\*Application\*/${TestFileName}/g" "${TestFolderName}/default.rd.xml" + +echo Building ${TestFileName} + +${CoreRT_CliBinDir}/dotnet publish "/p:IlcPath=${CoreRT_ToolchainDir}" "/p:DebugSymbols=false" /p:OSGroup=${CoreRT_BuildOS} "/p:Configuration=${CoreRT_BuildType}" "/p:FrameworkLibPath=${CoreRT_TestRoot}/../bin/${CoreRT_BuildOS}.${CoreRT_BuildArch}.${CoreRT_BuildType}/lib" "/p:FrameworkObjPath=${CoreRT_TestRoot}/../bin/obj/${CoreRT_BuildOS}.${CoreRT_BuildArch}.${CoreRT_BuildType}/Framework" /p:DisableFrameworkLibGeneration=true /p:TestRootDir=${TestRootDir} /p:ExecutableName=${TestExecutable} "/p:OutputPath=/${TestFolderName}/" ${TestFolderName}/Test.csproj +export __exitcode=$? +if [ ${__exitcode} != 0 ]; +then + exit ${__exitcode} +fi + +if [ ! -d "${LogDir}/${TestFileName}" ]; then + mkdir -p "${LogDir}/${TestFileName}" +fi + +echo Executing ${TestFileName} - writing logs to ${LogDir}/${TestFileName}/testResults.xml +echo To repro directly, run ${TestFolderName}/native/${TestExecutable} ${TestFolderName}/${TestFileName}.dll @${TestFolderName}/${TestFileName}.rsp -xml ${LogDir}/${TestFileName}/testResults.xml -notrait category=nonnetcoreapptests -notrait category=${OSCategory} -notrait category=failing +chmod +x ${TestFolderName}/native/${TestExecutable} + +case "$(uname -s)" in + # Check if we're running under Linux + Linux) + export OSCategory="nonlinuxtests" + ;; + # Check if we're running under OSX + Darwin) + export OSCategory="nonosxtests" + ;; + # Default to Linux if we don't recognize the OS + *) + export OSCategory="nonlinuxtests" + ;; +esac + +${TestFolderName}/native/${TestExecutable} ${TestFolderName}/${TestFileName}.dll @${TestFolderName}/${TestFileName}.rsp -xml ${LogDir}/${TestFileName}/testResults.xml -notrait category=nonnetcoreapptests -notrait category=${OSCategory} -notrait category=failing +export __exitcode=$? + +exit ${__exitcode} diff --git a/external/corert/tests/CoreFX/dependencies.props b/external/corert/tests/CoreFX/dependencies.props new file mode 100644 index 0000000000..1e3ffa01f5 --- /dev/null +++ b/external/corert/tests/CoreFX/dependencies.props @@ -0,0 +1,18 @@ + + + + + + 0.1.0-e160909-1 + 11.0.2 + 3.0.10 + 2.3.0-beta1-build3642 + + 2.2.0-beta2-build3300 + 2.0.1 + 2.1.0-preview2-02516-02 + 4.5.0-preview2-26219-0 + + diff --git a/external/corert/tests/CoreFX/runtest/CoreFXTestHarness/Test.csproj b/external/corert/tests/CoreFX/runtest/CoreFXTestHarness/Test.csproj new file mode 100644 index 0000000000..8d83f8eedf --- /dev/null +++ b/external/corert/tests/CoreFX/runtest/CoreFXTestHarness/Test.csproj @@ -0,0 +1,74 @@ + + + + + + + + $(ExecutableName) + .exe + Exe + + + + $(FrameworkLibPath)\..\tools\ + netcoreapp2.1 + + $(NoWarn);NU1603 + + + + + + + + + $(XunitAbstractionsVersion) + + + $(XunitPackageVersion) + + + $(XunitPackageVersion) + + + $(XunitPackageVersion) + + + $(XunitRunnerUtilityVersion) + + + $(XunitPackageVersion) + + + $(XunitNetcoreExtensionsVersion) + + + $(CoreFxTestUtilitiesVersion) + + + + + + + + + + + $(MSBuildProjectDirectory)\ + $(MSBuildProjectDirectory)\ + + + + + win-x64 + linux-x64 + osx-x64 + + + + + + + + diff --git a/external/corert/tests/CoreFX/runtest/CoreFXTestHarness/default.rd.xml b/external/corert/tests/CoreFX/runtest/CoreFXTestHarness/default.rd.xml new file mode 100644 index 0000000000..81d5bc9e0a --- /dev/null +++ b/external/corert/tests/CoreFX/runtest/CoreFXTestHarness/default.rd.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/external/corert/tests/CoreFX/runtest/dir.props b/external/corert/tests/CoreFX/runtest/dir.props new file mode 100644 index 0000000000..e947c5a996 --- /dev/null +++ b/external/corert/tests/CoreFX/runtest/dir.props @@ -0,0 +1,33 @@ + + + + + + + $(OS) + + + + + false + $(MSBuildThisFileDirectory)\ + $(ProjectDir)src\ + $(ProjectDir)..\..\..\packages\ + $(ProjectDir)..\Tools\ + $(ToolsDir)dotnetcli/ + true + + + + + + + + + + + + + diff --git a/external/corert/tests/CoreFX/runtest/runtest.cmd b/external/corert/tests/CoreFX/runtest/runtest.cmd new file mode 100644 index 0000000000..76b81430e1 --- /dev/null +++ b/external/corert/tests/CoreFX/runtest/runtest.cmd @@ -0,0 +1,107 @@ +@if not defined __echo @echo off +setlocal EnableDelayedExpansion + +:: Set the default arguments +set __BuildArch=x64 +set __BuildType=Debug +set __BuildOS=Windows_NT + +:: Default to highest Visual Studio version available +set __VSVersion=vs2017 +set __VSProductVersion=150 + +:: Define a prefix for most output progress messages that come from this script. That makes +:: it easier to see where these are coming from. Note that there is a trailing space here. +set __MsgPrefix=RUNTEST: + +set __ProjectDir=%~dp0 +:: remove trailing slash +if %__ProjectDir:~-1%==\ set "__ProjectDir=%__ProjectDir:~0,-1%" +set "__ProjectFilesDir=%__ProjectDir%" +set "__RootBinDir=%__ProjectDir%\..\bin" +set "__LogsDir=%__RootBinDir%\Logs" + +:Arg_Loop +if "%1" == "" goto ArgsDone + +if /i "%1" == "/?" goto Usage +if /i "%1" == "-?" goto Usage +if /i "%1" == "/h" goto Usage +if /i "%1" == "-h" goto Usage +if /i "%1" == "/help" goto Usage +if /i "%1" == "-help" goto Usage + +if /i "%1" == "x64" (set __BuildArch=x64&set __MSBuildBuildArch=x64&shift&goto Arg_Loop) +if /i "%1" == "x86" (set __BuildArch=x86&set __MSBuildBuildArch=x86&shift&goto Arg_Loop) + +if /i "%1" == "debug" (set __BuildType=Debug&shift&goto Arg_Loop) +if /i "%1" == "release" (set __BuildType=Release&shift&goto Arg_Loop) + +if /i "%1" == "LogsDir" (set __LogsDir=%2&shift&shift&goto Arg_Loop) + +if /i not "%1" == "msbuildargs" goto SkipMsbuildArgs + +set CORE_ROOT=%1 +echo %__MsgPrefix%CORE_ROOT is initially set to: "%CORE_ROOT%" +shift +:ArgsDone + +set "__TestWorkingDir=%CoreRT_TestRoot\CoreFX%" + +if not defined XunitTestBinBase set XunitTestBinBase=%__TestWorkingDir% + +if not exist %__LogsDir% md %__LogsDir% + +:: Check presence of VS +if not defined VS%__VSProductVersion%COMNTOOLS goto NoVS + +set __VSToolsRoot=!VS%__VSProductVersion%COMNTOOLS! +if %__VSToolsRoot:~-1%==\ set "__VSToolsRoot=%__VSToolsRoot:~0,-1%" + +:: Set the environment for the build- VS cmd prompt +echo %__MsgPrefix%Using environment: "%__VSToolsRoot%\VsDevCmd.bat" +call "%__VSToolsRoot%\VsDevCmd.bat" + +if not defined VSINSTALLDIR ( + echo %__MsgPrefix%Error: runtest.cmd should be run from a Visual Studio Command Prompt. Please see https://github.com/dotnet/coreclr/blob/master/Documentation/project-docs/developer-guide.md for build instructions. + exit /b 1 +) + +if not defined FXCustomTestLauncher ( + echo The CoreFX test launcher is not defined + exit /b 1 +) + +set SAVED_ERROR_LEVEL=0 +:: Iterate through unzipped CoreFX tests +for /D %%i in ("%XunitTestBinBase%\*" ) do ( + set TestFolderName=%%i + set TestFileName=%%~nxi + + echo %FXCustomTestLauncher% !TestFolderName! !TestFileName! + call %FXCustomTestLauncher% !TestFolderName! !TestFileName! + set TestExitCode=!errorlevel! + if !TestExitCode! neq 0 ( + echo Test !TestFileName! failed with !TestExitCode! + set SAVED_ERROR_LEVEL=!TestExitCode! + ) + +) + +exit /b !SAVED_ERROR_LEVEL! + +:Usage +echo. +echo Usage: +echo %0 BuildArch BuildType +echo where: +echo. +echo./? -? /h -h /help -help: view this message. +echo BuildArch- Optional parameter - x64 or x86 ^(default: x64^). +echo BuildType- Optional parameter - Debug, Release, or Checked ^(default: Debug^). +exit /b 1 + +:NoVS +echo Visual Studio 2017 ^(Community is free^) is a prerequisite to build this repository. +echo See: https://github.com/dotnet/coreclr/blob/master/Documentation/project-docs/developer-guide.md#prerequisites +exit /b 1 diff --git a/external/corert/tests/CoreFX/runtest/runtest.sh b/external/corert/tests/CoreFX/runtest/runtest.sh new file mode 100755 index 0000000000..f67a48f00e --- /dev/null +++ b/external/corert/tests/CoreFX/runtest/runtest.sh @@ -0,0 +1,80 @@ +# Exit code constants +readonly EXIT_CODE_SUCCESS=0 # Script ran normally. +readonly EXIT_CODE_EXCEPTION=1 # Script exited because something exceptional happened (e.g. bad arguments, Ctrl-C interrupt). +readonly EXIT_CODE_TEST_FAILURE=2 # Script completed successfully, but one or more tests failed. + +function print_usage { + echo '' + echo 'CoreFX test runner script.' + echo '' + echo 'Typical command line:' + echo '' + echo 'corefx/tests/runtest.sh' + echo ' --testRootDir="tests_downloaded/CoreFX"' + echo ' --testLauncher="tests/CoreFX/corerun"' + echo '' + echo 'Required arguments:' + echo ' --testRootDir= : Root directory of the CoreFX test build ' + echo ' --testLauncher= : Path to the test launcher script' +} + +function run_tests_in_directory { + local savedErroLevel=$EXIT_CODE_SUCCESS + local testDir=$1 + for testSubDir in ${testDir}/* ; do + # Build and run each test + echo Building ${testSubDir} + ${FXCustomTestLauncher} ${testSubDir} ${__LogDir} + if [ $? != 0 ]; + then + savedErroLevel=$EXIT_CODE_TEST_FAILURE + fi + done + return $savedErroLevel + +} + + + +# Argument variables +testRootDir= +__LogDir= +FXCustomTestLauncher= + +for i in "$@" +do + case $i in + --testRootDir=*) + testRootDir=${i#*=} + ;; + --logdir=*) + __LogDir=${i#*=} + ;; + --testLauncher=*) + FXCustomTestLauncher=${i#*=} + ;; + *) + echo "Unknown switch: $i" + print_usage + exit $EXIT_CODE_SUCCESS + ;; + esac +done + +if [ -z "$testRootDir" ]; then + echo "--testRootDir is required." + print_usage + exit $EXIT_CODE_EXCEPTION +fi +if [ ! -d "$testRootDir" ]; then + echo "Directory specified by --testRootDir does not exist: $testRootDir" + exit $EXIT_CODE_EXCEPTION +fi + +if [ -z "$__LogDir" ]; then + __LogDir=$testRootDir +fi + +run_tests_in_directory ${testRootDir} + +exit diff --git a/external/corert/tests/CoreFX/runtest/src/TestUtils/TestFileSetup/CoreFX.TestUtils.TestFileSetup.csproj b/external/corert/tests/CoreFX/runtest/src/TestUtils/TestFileSetup/CoreFX.TestUtils.TestFileSetup.csproj new file mode 100644 index 0000000000..eb7413ef30 --- /dev/null +++ b/external/corert/tests/CoreFX/runtest/src/TestUtils/TestFileSetup/CoreFX.TestUtils.TestFileSetup.csproj @@ -0,0 +1,18 @@ + + + + netcoreapp2.1 + Exe + + + + $(NewtonsoftJsonVersion) + + + $(NewtonsoftJsonSchemaVersion) + + + $(SystemCommandLineVersion) + + + diff --git a/external/corert/tests/CoreFX/runtest/src/TestUtils/TestFileSetup/RSPGenerator.cs b/external/corert/tests/CoreFX/runtest/src/TestUtils/TestFileSetup/RSPGenerator.cs new file mode 100644 index 0000000000..f67dd42418 --- /dev/null +++ b/external/corert/tests/CoreFX/runtest/src/TestUtils/TestFileSetup/RSPGenerator.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace CoreFX.TestUtils.TestFileSetup +{ + public class RSPGenerator + { + public void GenerateRSPFile(XUnitTestAssembly testDefinition, string outputPath) + { + if (!Directory.Exists(outputPath)) + { + Directory.CreateDirectory(outputPath); + } + string rspFilePath = Path.Combine(outputPath, testDefinition.Name + ".rsp"); + + if (File.Exists(rspFilePath)) + File.Delete(rspFilePath); + + + using (StreamWriter sr = File.CreateText(rspFilePath)) + { + if (testDefinition.Exclusions == null) + return; + + // Method exclusions + if (testDefinition.Exclusions.Methods != null) + { + foreach (Exclusion exclusion in testDefinition.Exclusions.Methods) + { + if (String.IsNullOrWhiteSpace(exclusion.Name)) + continue; + sr.Write("-skipmethod "); + sr.Write(exclusion.Name); + sr.WriteLine(); + } + } + + // Class exclusions + if (testDefinition.Exclusions.Classes != null) + { + foreach (Exclusion exclusion in testDefinition.Exclusions.Classes) + { + if (String.IsNullOrWhiteSpace(exclusion.Name)) + continue; + sr.Write("-skipclass "); + sr.Write(exclusion.Name); + sr.WriteLine(); + } + + } + + // Namespace exclusions + if (testDefinition.Exclusions.Namespaces != null) + { + foreach (Exclusion exclusion in testDefinition.Exclusions.Namespaces) + { + if (String.IsNullOrWhiteSpace(exclusion.Name)) + continue; + sr.Write("-skipnamespace "); + sr.Write(exclusion.Name); + sr.WriteLine(); + } + } + } + } + } +} diff --git a/external/corert/tests/CoreFX/runtest/src/TestUtils/TestFileSetup/TestFileSetup.cs b/external/corert/tests/CoreFX/runtest/src/TestUtils/TestFileSetup/TestFileSetup.cs new file mode 100644 index 0000000000..50e89c5ad7 --- /dev/null +++ b/external/corert/tests/CoreFX/runtest/src/TestUtils/TestFileSetup/TestFileSetup.cs @@ -0,0 +1,329 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.CommandLine; +using System.Diagnostics; +using System.IO; +using System.IO.Compression; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Schema; +using Newtonsoft.Json.Schema.Generation; + +namespace CoreFX.TestUtils.TestFileSetup +{ + /// + /// Defines the set of flags that represent exit codes + /// + [Flags] + public enum ExitCode : int + { + Success = 0, + HttpError = 1, + IOError = 2, + JsonSchemaValidationError = 3, + UnknownError = 10 + + } + + /// + /// This helper class is used to fetch CoreFX tests from a specified URL, unarchive them and create a flat directory structure + /// through which to iterate. + /// + public static class TestFileSetup + { + private static HttpClient httpClient; + private static bool cleanTestBuild = false; + + private static string outputDir; + private static string testUrl; + private static string testListPath; + + public static void Main(string[] args) + { + ExitCode exitCode = ExitCode.UnknownError; + ArgumentSyntax argSyntax = ParseCommandLine(args); + + try + { + if (!Directory.Exists(outputDir)) + Directory.CreateDirectory(outputDir); + + if (cleanTestBuild) + { + CleanBuild(outputDir); + } + + // Map test names to their definitions + Dictionary testAssemblyDefinitions = DeserializeTestJson(testListPath); + + SetupTests(testUrl, outputDir, testAssemblyDefinitions).Wait(); + exitCode = ExitCode.Success; + } + + catch (AggregateException e) + { + e.Handle(innerExc => + { + + if (innerExc is HttpRequestException) + { + exitCode = ExitCode.HttpError; + Console.WriteLine("Error downloading tests from: " + testUrl); + Console.WriteLine(innerExc.Message); + return true; + } + else if (innerExc is IOException) + { + exitCode = ExitCode.IOError; + Console.WriteLine(innerExc.Message); + return true; + } + else if (innerExc is JSchemaValidationException || innerExc is JsonSerializationException) + { + exitCode = ExitCode.JsonSchemaValidationError; + Console.WriteLine("Error validating test list: "); + Console.WriteLine(innerExc.Message); + return true; + } + return false; + }); + } + + Environment.Exit((int)exitCode); + } + + private static ArgumentSyntax ParseCommandLine(string[] args) + { + ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => + { + syntax.DefineOption("out|outDir|outputDirectory", ref outputDir, "Directory where tests are downloaded"); + syntax.DefineOption("testUrl", ref testUrl, "URL, pointing to the list of tests"); + syntax.DefineOption("testListJsonPath", ref testListPath, "JSON-formatted list of test assembly names to download"); + syntax.DefineOption("clean|cleanOutputDir", ref cleanTestBuild, "Clean test assembly output directory"); + }); + + return argSyntax; + } + + private static Dictionary DeserializeTestJson(string testDefinitionFilePath) + { + JSchemaGenerator jsonGenerator = new JSchemaGenerator(); + + JSchema testDefinitionSchema = jsonGenerator.Generate(typeof(IList)); + IList testAssemblies = new List(); + + IList validationMessages = new List(); + + using (var sr = new StreamReader(testDefinitionFilePath)) + using (var jsonReader = new JsonTextReader(sr)) + using (var jsonValidationReader = new JSchemaValidatingReader(jsonReader)) + { + // Create schema validator + jsonValidationReader.Schema = testDefinitionSchema; + jsonValidationReader.ValidationEventHandler += (o, a) => validationMessages.Add(a.Message); + + // Deserialize json test assembly definitions + JsonSerializer serializer = new JsonSerializer(); + try + { + testAssemblies = serializer.Deserialize>(jsonValidationReader); + } + catch (JsonSerializationException ex) + { + throw new AggregateException(ex); + } + } + + // TODO - ABORT AND WARN + if (validationMessages.Count != 0) + { + StringBuilder aggregateExceptionMessage = new StringBuilder(); + foreach (string validationMessage in validationMessages) + { + aggregateExceptionMessage.Append("JSON Validation Error: "); + aggregateExceptionMessage.Append(validationMessage); + aggregateExceptionMessage.AppendLine(); + } + + throw new AggregateException(new JSchemaValidationException(aggregateExceptionMessage.ToString())); + + } + + var nameToTestAssemblyDef = new Dictionary(); + + // Map test names to their definitions + foreach (XUnitTestAssembly assembly in testAssemblies) + { + nameToTestAssemblyDef.Add(assembly.Name, assembly); + } + + return nameToTestAssemblyDef; + } + + private static async Task SetupTests(string jsonUrl, string destinationDirectory, Dictionary testDefinitions = null, bool runAllTests = false) + { + Debug.Assert(Directory.Exists(destinationDirectory)); + Debug.Assert(runAllTests || testDefinitions != null); + + string tempDirPath = Path.Combine(destinationDirectory, "temp"); + if (!Directory.Exists(tempDirPath)) + { + Directory.CreateDirectory(tempDirPath); + } + Dictionary testPayloads = await GetTestUrls(jsonUrl, testDefinitions, runAllTests); + + if (testPayloads == null) + { + return; + } + + await GetTestArchives(testPayloads, tempDirPath); + ExpandArchivesInDirectory(tempDirPath, destinationDirectory); + + RSPGenerator rspGenerator = new RSPGenerator(); + foreach (XUnitTestAssembly assembly in testDefinitions.Values) + { + rspGenerator.GenerateRSPFile(assembly, Path.Combine(destinationDirectory, assembly.Name)); + } + + Directory.Delete(tempDirPath); + } + + private static async Task> GetTestUrls(string jsonUrl, Dictionary testDefinitions = null, bool runAllTests = false) + { + if (httpClient is null) + { + httpClient = new HttpClient(); + } + + Debug.Assert(runAllTests || testDefinitions != null); + // Set up the json stream reader + using (var responseStream = await httpClient.GetStreamAsync(jsonUrl)) + using (var streamReader = new StreamReader(responseStream)) + using (var jsonReader = new JsonTextReader(streamReader)) + { + // Manual parsing - we only need to key-value pairs from each object and this avoids deserializing all of the work items into objects + string markedTestName = string.Empty; + string currentPropertyName = string.Empty; + + while (jsonReader.Read()) + { + if (jsonReader.Value != null) + { + switch (jsonReader.TokenType) + { + case JsonToken.PropertyName: + currentPropertyName = jsonReader.Value.ToString(); + break; + case JsonToken.String: + if (currentPropertyName.Equals("WorkItemId")) + { + string currentTestName = jsonReader.Value.ToString(); + + if (runAllTests || testDefinitions.ContainsKey(currentTestName)) + { + markedTestName = currentTestName; + } + } + else if (currentPropertyName.Equals("PayloadUri") && markedTestName != string.Empty) + { + if (!testDefinitions.ContainsKey(markedTestName)) + { + testDefinitions[markedTestName] = new XUnitTestAssembly() { Name = markedTestName }; + } + testDefinitions[markedTestName].Url = jsonReader.Value.ToString(); + markedTestName = string.Empty; + } + break; + } + } + } + + } + return testDefinitions; + } + + private static async Task GetTestArchives(Dictionary testPayloads, string downloadDir) + { + if (httpClient is null) + { + httpClient = new HttpClient(); + } + + foreach (string testName in testPayloads.Keys) + { + string payloadUri = testPayloads[testName].Url; + + if (!Uri.IsWellFormedUriString(payloadUri, UriKind.Absolute)) + continue; + + using (var response = await httpClient.GetStreamAsync(payloadUri)) + { + if (response.CanRead) + { + // Create the test setup directory if it doesn't exist + if (!Directory.Exists(downloadDir)) + { + Directory.CreateDirectory(downloadDir); + } + + // CoreFX test archives are output as .zip regardless of platform + string archivePath = Path.Combine(downloadDir, testName + ".zip"); + + // Copy to a temp folder + using (FileStream file = new FileStream(archivePath, FileMode.Create)) + { + await response.CopyToAsync(file); + } + + } + } + } + } + + private static void ExpandArchivesInDirectory(string archiveDirectory, string destinationDirectory, bool cleanup = true) + { + Debug.Assert(Directory.Exists(archiveDirectory)); + Debug.Assert(Directory.Exists(destinationDirectory)); + + string[] archives = Directory.GetFiles(archiveDirectory, "*.zip", SearchOption.TopDirectoryOnly); + + foreach (string archivePath in archives) + { + string destinationDirName = Path.Combine(destinationDirectory, Path.GetFileNameWithoutExtension(archivePath)); + + ZipFile.ExtractToDirectory(archivePath, destinationDirName); + + + // Delete archives + if (cleanup) + { + File.Delete(archivePath); + } + } + } + + private static void CleanBuild(string directoryToClean) + { + Debug.Assert(Directory.Exists(directoryToClean)); + DirectoryInfo dirInfo = new DirectoryInfo(directoryToClean); + + foreach (FileInfo file in dirInfo.EnumerateFiles()) + { + file.Delete(); + } + + foreach (DirectoryInfo dir in dirInfo.EnumerateDirectories()) + { + dir.Delete(true); + } + } + + } +} diff --git a/external/corert/tests/CoreFX/runtest/src/TestUtils/TestFileSetup/XUnitTestAssembly.cs b/external/corert/tests/CoreFX/runtest/src/TestUtils/TestFileSetup/XUnitTestAssembly.cs new file mode 100644 index 0000000000..6570b0af87 --- /dev/null +++ b/external/corert/tests/CoreFX/runtest/src/TestUtils/TestFileSetup/XUnitTestAssembly.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Newtonsoft.Json; + +namespace CoreFX.TestUtils.TestFileSetup +{ + public class XUnitTestAssembly + { + [JsonRequired] + [JsonProperty("name")] + public string Name; + + [JsonRequired] + [JsonProperty("exclusions")] + public Exclusions Exclusions; + + // Used to assign a test url or to override it via the json file definition + [JsonIgnore] + [JsonProperty(Required = Required.Default)] + public string Url; + + } + + public class Exclusions + { + [JsonProperty("namespaces")] + public Exclusion[] Namespaces; + + [JsonProperty("classes")] + public Exclusion[] Classes; + + [JsonProperty("methods")] + public Exclusion[] Methods; + } + + public class Exclusion + { + [JsonRequired] + [JsonProperty("name", Required = Required.DisallowNull)] + public string Name; + + [JsonRequired] + [JsonProperty("reason", Required = Required.DisallowNull)] + public string Reason; + } +} diff --git a/external/corert/tests/CoreFX/runtest/src/TestUtils/XUnit/CoreFX.TestUtils.XUnit.csproj b/external/corert/tests/CoreFX/runtest/src/TestUtils/XUnit/CoreFX.TestUtils.XUnit.csproj new file mode 100644 index 0000000000..9b33127691 --- /dev/null +++ b/external/corert/tests/CoreFX/runtest/src/TestUtils/XUnit/CoreFX.TestUtils.XUnit.csproj @@ -0,0 +1,15 @@ + + + + netcoreapp2.1 + Exe + + + + $(NewtonsoftJsonVersion) + + + $(SystemCommandLineVersion) + + + diff --git a/external/corert/tests/CoreFX/runtest/src/TestUtils/XUnit/ResultFormatter.cs b/external/corert/tests/CoreFX/runtest/src/TestUtils/XUnit/ResultFormatter.cs new file mode 100644 index 0000000000..6a1b10ee13 --- /dev/null +++ b/external/corert/tests/CoreFX/runtest/src/TestUtils/XUnit/ResultFormatter.cs @@ -0,0 +1,132 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/// +/// This helper class reads xunit xml log files and prints the tallied test results to the console +/// +using System; +using System.Collections.Generic; +using System.CommandLine; +using System.Diagnostics; +using System.IO; +using System.IO.Compression; +using System.Net.Http; +using System.Reflection; +using System.Threading.Tasks; +using System.Xml; +using Newtonsoft.Json; + +namespace CoreFX.TestUtils.XUnit +{ + public static class ResultFormatter + { + private static string logDir; + private static string logPattern; + + public static void Main(string[] args) + { + ArgumentSyntax syntax = ParseCommandLine(args); + IEnumerable logFiles = DiscoverLogs(logDir, logPattern); + PrintTotals(logFiles); + } + + private static void PrintTotals(IEnumerable logFiles) + { + int total = 0; + int passed = 0; + int failed = 0; + int skipped = 0; + ulong timeElapsed = 0; + bool printTotals = false; + + foreach (string logFile in logFiles) + { + try + { + + // XMLReader escapes the character sequence \\.. as just a single backslash \ - Is this intended behavior? + using (XmlReader reader = XmlReader.Create(logFile.Replace(@"\\..", @"\.."))) + { + reader.MoveToContent(); + reader.ReadToDescendant("collection"); + do + { + // Get total tests in current element + string totalAttr = reader.GetAttribute("total"); + int currentTotal; + Int32.TryParse(totalAttr, out currentTotal); + + // Get passed tests + string passedAttr = reader.GetAttribute("passed"); + int currentPassed; + Int32.TryParse(passedAttr, out currentPassed); + + // Get failed tests + string failedAttr = reader.GetAttribute("failed"); + int currentFailed; + Int32.TryParse(failedAttr, out currentFailed); + + // Get skipped tests + string skippedAttr = reader.GetAttribute("skipped"); + int currentSkipped; + Int32.TryParse(skippedAttr, out currentSkipped); + + // Get time elapsed + string timeAttr = reader.GetAttribute("time"); + ulong currentTime; + UInt64.TryParse(timeAttr, out currentTime); + + // Update running total only once current element has been parsed + total += currentTotal; + passed += currentPassed; + failed += currentFailed; + skipped += currentSkipped; + timeElapsed += currentTime; + + } while (reader.ReadToNextSibling("collection")); + + // If we've fully parsed a log, print totals + printTotals = true; + } + } + catch (XmlException exc) + { + Console.WriteLine("Malformed Log: {0} ", logFile); + Console.WriteLine("Reason: {0} ", exc.Message); + continue; + } + } + + if (printTotals) + { + Console.WriteLine("=== CoreFX TEST EXECUTION SUMMARY ===: "); + Console.WriteLine(String.Format("Total: {0}, Passed: {1}, Failed: {2}, Skipped: {3}", total, passed, failed, timeElapsed)); + Console.WriteLine("Detailed logs written to: " + logDir); + } + } + + private static ArgumentSyntax ParseCommandLine(string[] args) + { + + ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => + { + syntax.DefineOption("log|logDirectory|logDir", ref logDir, "Path to directory of xml test results"); + syntax.DefineOption("pattern|p", ref logPattern, "Pattern of XUnit log filenames for which to search"); + }); + + return argSyntax; + } + + public static IEnumerable DiscoverLogs(string logDirectory, string logPattern) + { + Debug.Assert(Directory.Exists(logDirectory)); + Console.WriteLine(logDirectory); + var logFiles = Directory.EnumerateFiles(logDirectory, logPattern, SearchOption.AllDirectories); + + return logFiles; + } + + + } +} diff --git a/external/corert/tests/CoreFXTestListURL.txt b/external/corert/tests/CoreFXTestListURL.txt new file mode 100644 index 0000000000..f19d23b12a --- /dev/null +++ b/external/corert/tests/CoreFXTestListURL.txt @@ -0,0 +1 @@ +https://cloudcijobs.blob.core.windows.net/corertci/CoreFXArchives/TestList.json \ No newline at end of file diff --git a/external/corert/tests/CoreFXTestListURL_Linux.txt b/external/corert/tests/CoreFXTestListURL_Linux.txt new file mode 100644 index 0000000000..e7b7c744e7 --- /dev/null +++ b/external/corert/tests/CoreFXTestListURL_Linux.txt @@ -0,0 +1 @@ +https://cloudcijobs.blob.core.windows.net/corertci/TestList_Linux.json \ No newline at end of file diff --git a/external/corert/tests/CoreFXTestListURL_OSX.txt b/external/corert/tests/CoreFXTestListURL_OSX.txt new file mode 100644 index 0000000000..e201a86154 --- /dev/null +++ b/external/corert/tests/CoreFXTestListURL_OSX.txt @@ -0,0 +1 @@ +https://cloudcijobs.blob.core.windows.net/corertci/TestList_OSX.json \ No newline at end of file diff --git a/external/corert/tests/TopN.CoreFX.Unix.issues.json b/external/corert/tests/TopN.CoreFX.Unix.issues.json new file mode 100644 index 0000000000..ce20df44b7 --- /dev/null +++ b/external/corert/tests/TopN.CoreFX.Unix.issues.json @@ -0,0 +1,556 @@ +[ + { + "name": "System.Collections.Tests", + "exclusions": { + "namespaces": null, + "classes": null, + "methods": [ + { + "name": "System.Collections.Tests.SortedList_Generic_Tests_string_string.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedList_Generic_Tests_string_string.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedList_Generic_Tests_string_string.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Queue_ICollection_NonGeneric_Tests.ICollection_NonGeneric_CopyTo_ArrayOfEnumType", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.Queue_ICollection_NonGeneric_Tests.IGenericSharedAPI_SerializeDeserialize", + "reason": "System.Runtime.Serialization.SerializationException" + }, + { + "name": "System.Collections.Tests.List_Generic_Tests_int.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.List_Generic_Tests_int.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.List_Generic_Tests_int.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_NullComparer.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_NullComparer.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_NullComparer.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedDictionary_Generic_Tests_Values_AsICollection.ICollection_NonGeneric_CopyTo_ArrayOfEnumType", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.SortedDictionary_IDictionary_NonGeneric_Tests.IDictionary_NonGeneric_IDictionaryEnumerator_Current_ReturnsSameValueOnRepeatedCalls", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.SortedDictionary_IDictionary_NonGeneric_Tests.IDictionary_NonGeneric_IDictionaryEnumerator_Current_FromStartToFinish", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.SortedDictionary_IDictionary_NonGeneric_Tests.ICollection_NonGeneric_CopyTo_ArrayOfEnumType", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.SortedDictionary_IDictionary_NonGeneric_Tests.IGenericSharedAPI_SerializeDeserialize", + "reason": "System.Runtime.Serialization.SerializationException" + }, + { + "name": "System.Collections.Tests.Stack_Generic_Tests_int.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_TreeSubset_Int_Tests.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_TreeSubset_Int_Tests.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_TreeSubset_Int_Tests.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_Comparer_AbsOfInt.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_Comparer_AbsOfInt.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_Comparer_AbsOfInt.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_int_int.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_int_int.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_int_int.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedList_Generic_Tests_Keys_AsICollection.ICollection_NonGeneric_CopyTo_ArrayOfEnumType", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_Comparer_HashCodeAlwaysReturnsZero.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_Comparer_HashCodeAlwaysReturnsZero.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_Comparer_HashCodeAlwaysReturnsZero.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_Keys_AsICollection.ICollection_NonGeneric_CopyTo_ArrayOfEnumType", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_ModOfInt.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_ModOfInt.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_ModOfInt.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_Comparer_SameAsDefaultComparer.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_Comparer_SameAsDefaultComparer.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_Comparer_SameAsDefaultComparer.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Dictionary_IDictionary_NonGeneric_Tests.IDictionary_NonGeneric_IDictionaryEnumerator_Current_ReturnsSameValueOnRepeatedCalls", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.Dictionary_IDictionary_NonGeneric_Tests.IGenericSharedAPI_SerializeDeserialize", + "reason": "System.TypeInitializationException" + }, + { + "name": "System.Collections.Tests.Dictionary_IDictionary_NonGeneric_Tests.IDictionary_NonGeneric_IDictionaryEnumerator_Current_FromStartToFinish", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.Dictionary_IDictionary_NonGeneric_Tests.ICollection_NonGeneric_CopyTo_ArrayOfEnumType", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_BadIntEqualityComparer.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_BadIntEqualityComparer.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_BadIntEqualityComparer.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedList_IDictionary_NonGeneric_Tests.IGenericSharedAPI_SerializeDeserialize", + "reason": "System.Runtime.Serialization.SerializationException" + }, + { + "name": "System.Collections.Tests.SortedList_IDictionary_NonGeneric_Tests.IDictionary_NonGeneric_IDictionaryEnumerator_Current_ReturnsSameValueOnRepeatedCalls", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.SortedList_IDictionary_NonGeneric_Tests.ICollection_NonGeneric_CopyTo_ArrayOfEnumType", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.SortedList_IDictionary_NonGeneric_Tests.IDictionary_NonGeneric_IDictionaryEnumerator_Current_FromStartToFinish", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.SortedDictionary_Generic_Tests_EquatableBackwardsOrder_int.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedDictionary_Generic_Tests_EquatableBackwardsOrder_int.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedDictionary_Generic_Tests_EquatableBackwardsOrder_int.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.List_Generic_Tests_int_ReadOnly.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.List_Generic_Tests_int_ReadOnly.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.List_Generic_Tests_int_ReadOnly.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_WrapStructural_Int.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_WrapStructural_Int.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_WrapStructural_Int.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_ICollection_NonGeneric_Tests.IGenericSharedAPI_SerializeDeserialize", + "reason": "System.Runtime.Serialization.SerializationException" + }, + { + "name": "System.Collections.Tests.SortedSet_ICollection_NonGeneric_Tests.ICollection_NonGeneric_CopyTo_ArrayOfEnumType", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.SortedList_Generic_Tests_Values_AsICollection.ICollection_NonGeneric_CopyTo_ArrayOfEnumType", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_AbsOfInt.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_AbsOfInt.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_AbsOfInt.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedDictionary_Generic_Tests_string_string.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedDictionary_Generic_Tests_string_string.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedDictionary_Generic_Tests_string_string.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedDictionary_Generic_Tests_Keys_AsICollection.ICollection_NonGeneric_CopyTo_ArrayOfEnumType", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.LinkedList_ICollection_NonGeneric_Tests.IGenericSharedAPI_SerializeDeserialize", + "reason": "System.Runtime.Serialization.SerializationException" + }, + { + "name": "System.Collections.Tests.LinkedList_ICollection_NonGeneric_Tests.ICollection_NonGeneric_CopyTo_ArrayOfEnumType", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_HashCodeAlwaysReturnsZero.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_HashCodeAlwaysReturnsZero.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_HashCodeAlwaysReturnsZero.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_IEnumerable_NonGeneric_Tests.IGenericSharedAPI_SerializeDeserialize", + "reason": "System.Runtime.Serialization.SerializationException" + }, + { + "name": "System.Collections.Tests.SortedList_Generic_Tests_EquatableBackwardsOrder_int.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedList_Generic_Tests_EquatableBackwardsOrder_int.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedList_Generic_Tests_EquatableBackwardsOrder_int.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.LinkedList_Generic_Tests_int.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.LinkedList_Generic_Tests_int.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.LinkedList_Generic_Tests_int.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Queue_Generic_Tests_int.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_SimpleInt_int_With_Comparer_WrapStructural_SimpleInt.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_SimpleInt_int_With_Comparer_WrapStructural_SimpleInt.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_SimpleInt_int_With_Comparer_WrapStructural_SimpleInt.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_WrapStructural_SimpleInt.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_WrapStructural_SimpleInt.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_WrapStructural_SimpleInt.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.DebugView_Tests.TestDebuggerAttributes_Null", + "reason": "System.InvalidOperationException" + }, + { + "name": "System.Collections.Tests.DebugView_Tests.TestDebuggerAttributes", + "reason": "System.InvalidOperationException" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_string_string.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_string_string.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_string_string.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_Comparer_ModOfInt.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_Comparer_ModOfInt.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedSet_Generic_Tests_int_With_Comparer_ModOfInt.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Stack_ICollection_NonGeneric_Tests.IGenericSharedAPI_SerializeDeserialize", + "reason": "System.Runtime.Serialization.SerializationException" + }, + { + "name": "System.Collections.Tests.Stack_ICollection_NonGeneric_Tests.ICollection_NonGeneric_CopyTo_ArrayOfEnumType", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_SameAsDefaultComparer.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_SameAsDefaultComparer.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.HashSet_Generic_Tests_int_With_Comparer_SameAsDefaultComparer.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_Values_AsICollection.ICollection_NonGeneric_CopyTo_ArrayOfEnumType", + "reason": "System.Reflection.MissingMetadataException" + }, + { + "name": "System.Collections.Tests.SortedDictionary_Generic_Tests_int_int.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedDictionary_Generic_Tests_int_int.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedDictionary_Generic_Tests_int_int.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedList_Generic_Tests_int_int.ICollection_Generic_Remove_DefaultValueContainedInCollection", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedList_Generic_Tests_int_int.Enumerator_MoveNext_AfterDisposal", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.SortedList_Generic_Tests_int_int.ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue", + "reason": "$BlockedFromReflection_0_5b449e4c" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_string_string.IEnumerable_Generic_Enumerator_Reset_ModifiedBeforeEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_string_string.IEnumerable_Generic_Enumerator_Reset_ModifiedAfterEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_string_string.IEnumerable_Generic_Enumerator_MoveNext_ModifiedAfterEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_string_string.IEnumerable_Generic_Enumerator_MoveNext_ModifiedBeforeEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_string_string.IEnumerable_Generic_Enumerator_Reset_ModifiedDuringEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_string_string.IEnumerable_Generic_Enumerator_MoveNext_ModifiedDuringEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_SimpleInt_int_With_Comparer_WrapStructural_SimpleInt.IEnumerable_Generic_Enumerator_Reset_ModifiedBeforeEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_SimpleInt_int_With_Comparer_WrapStructural_SimpleInt.IEnumerable_Generic_Enumerator_MoveNext_ModifiedDuringEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_SimpleInt_int_With_Comparer_WrapStructural_SimpleInt.IEnumerable_Generic_Enumerator_MoveNext_ModifiedBeforeEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_SimpleInt_int_With_Comparer_WrapStructural_SimpleInt.IEnumerable_Generic_Enumerator_Reset_ModifiedDuringEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_SimpleInt_int_With_Comparer_WrapStructural_SimpleInt.IEnumerable_Generic_Enumerator_Reset_ModifiedAfterEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_SimpleInt_int_With_Comparer_WrapStructural_SimpleInt.IEnumerable_Generic_Enumerator_MoveNext_ModifiedAfterEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_int_int.IEnumerable_Generic_Enumerator_Reset_ModifiedDuringEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_int_int.IEnumerable_Generic_Enumerator_MoveNext_ModifiedAfterEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_int_int.IEnumerable_Generic_Enumerator_MoveNext_ModifiedBeforeEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_int_int.IEnumerable_Generic_Enumerator_Reset_ModifiedBeforeEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_int_int.IEnumerable_Generic_Enumerator_Reset_ModifiedAfterEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_Generic_Tests_int_int.IEnumerable_Generic_Enumerator_MoveNext_ModifiedDuringEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_IDictionary_NonGeneric_Tests.IEnumerable_NonGeneric_Enumerator_MoveNext_ModifiedBeforeEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_IDictionary_NonGeneric_Tests.IEnumerable_NonGeneric_Enumerator_Reset_ModifiedBeforeEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_IDictionary_NonGeneric_Tests.IEnumerable_NonGeneric_Enumerator_Reset_ModifiedDuringEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_IDictionary_NonGeneric_Tests.IEnumerable_NonGeneric_Enumerator_MoveNext_ModifiedDuringEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_IDictionary_NonGeneric_Tests.IEnumerable_NonGeneric_Enumerator_Reset_ModifiedAfterEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + }, + { + "name": "System.Collections.Tests.Dictionary_IDictionary_NonGeneric_Tests.IEnumerable_NonGeneric_Enumerator_MoveNext_ModifiedAfterEnumeration_ThrowsInvalidOperationException", + "reason": "Assert.All() Failure: 1 out of 4 items in the collection did not pass.\r\n" + } + ] + } + } +] diff --git a/external/corert/tests/TopN.CoreFX.Windows.issues.json.REMOVED.git-id b/external/corert/tests/TopN.CoreFX.Windows.issues.json.REMOVED.git-id new file mode 100644 index 0000000000..e9ee1a6876 --- /dev/null +++ b/external/corert/tests/TopN.CoreFX.Windows.issues.json.REMOVED.git-id @@ -0,0 +1 @@ +4848b78f48058af458159bc785d8d2bbdff2f148 \ No newline at end of file diff --git a/external/corert/tests/runtest.cmd b/external/corert/tests/runtest.cmd index 0c23b18a74..b54c08ab03 100644 --- a/external/corert/tests/runtest.cmd +++ b/external/corert/tests/runtest.cmd @@ -10,8 +10,9 @@ set CoreRT_BuildOS=Windows_NT set CoreRT_TestRun=true set CoreRT_TestCompileMode= set CoreRT_RunCoreCLRTests= +set CoreRT_RunCoreFXTests= set CoreRT_CoreCLRTargetsFile= -set CoreRT_TestLogFileName=testresults.xml +set CoreRT_TestLogFileName=testResults.xml set CoreRT_TestName=* :ArgLoop @@ -48,6 +49,7 @@ if /i "%1" == "/coreclr" ( :ExtRepoTestsOk goto ArgLoop ) +if /i "%1" == "/corefx" (set CoreRT_RunCoreFXTests=true&shift&goto ArgLoop) if /i "%1" == "/coreclrsingletest" (set CoreRT_RunCoreCLRTests=true&set CoreRT_CoreCLRTest=%2&shift&shift&goto ArgLoop) if /i "%1" == "/mode" (set CoreRT_TestCompileMode=%2&shift&shift&goto ArgLoop) if /i "%1" == "/test" (set CoreRT_TestName=%2&shift&shift&goto ArgLoop) @@ -67,6 +69,7 @@ echo /mode : Optionally restrict to a single code generator. Specify echo /test : Run a single test by folder name (ie, BasicThreading) echo /runtest : Should just compile or run compiled binary? Specify: true/false. Default: true. echo /coreclr : Download and run the CoreCLR repo tests +echo /corefx : Download and run the CoreFX repo tests echo /coreclrsingletest ^ echo : Run a single CoreCLR repo test echo /multimodule : Compile the framework as a .lib and link tests against it (only supports ryujit) @@ -121,7 +124,8 @@ call "%_VSCOMNTOOLS%\VsDevCmd.bat" :RunVCVars call "!VS150COMNTOOLS!\..\..\VC\Auxiliary\Build\vcvarsall.bat" %CoreRT_HostArch% -if "%CoreRT_RunCoreCLRTests%"=="true" goto :TestExtRepo +if "%CoreRT_RunCoreCLRTests%"=="true" goto :TestExtRepoCoreCLR +if "%CoreRT_RunCoreFXTests%"=="true" goto :TestExtRepoCoreFX if /i "%__BuildType%"=="Debug" ( set __LinkLibs=msvcrtd.lib @@ -301,12 +305,19 @@ goto :eof set __SavedErrorLevel=!ErrorLevel! if "%CoreRT_TestRun%"=="false" (goto :SkipTestRun) - if "%__Mode%" == "wasm" (goto :SkipTestRun) + + set __Extension=exe - if "%__SavedErrorLevel%"=="0" ( + if "%__Mode%"=="wasm" ( + REM Skip running if this is WASM build-only testing running in a different architecture's build + if /i not "%CoreRT_BuildArch%"=="wasm" (goto :SkipTestRun) + set __Extension=html + ) + + if "!__SavedErrorLevel!"=="0" ( echo. echo Running test !__SourceFileName! - call !__SourceFile!.cmd !__SourceFolder!\bin\%CoreRT_BuildType%\%CoreRT_BuildArch%\native !__SourceFileName!.exe + call !__SourceFile!.cmd !__SourceFolder!\bin\%CoreRT_BuildType%\%CoreRT_BuildArch%\native !__SourceFileName!.!__Extension! set __SavedErrorLevel=!ErrorLevel! ) ) @@ -333,9 +344,54 @@ goto :eof powershell -Command Write-Host %1 -foreground "red" exit /b -1 +:RestoreCoreFXTests + + :: Explicitly restore the test helper project + "%CoreRT_CliDir%\dotnet.exe" msbuild /t:Restore "%CoreRT_TestFileHelperProjectPath%" + if errorlevel 1 ( + exit /b 1 + ) + "%CoreRT_CliDir%\dotnet.exe" msbuild /t:Restore "%CoreRT_XunitHelperProjectPath%" + if errorlevel 1 ( + exit /b 1 + ) + + :: Build the test helper projects + "%CoreRT_CliDir%\dotnet.exe" msbuild /m /ConsoleLoggerParameters:ForceNoAlign "/p:IlcPath=%CoreRT_ToolchainDir%" "/p:Configuration=%CoreRT_BuildType%" "/p:OSGroup=%CoreRT_BuildOS%" "/p:Platform=%CoreRT_BuildArch%" "/p:RepoLocalBuild=true" "/p:FrameworkLibPath=%CoreRT_TestRoot%..\bin\%CoreRT_BuildOS%.%CoreRT_BuildArch%.%CoreRT_BuildType%\lib" "/p:FrameworkObjPath=%~dp0..\bin\obj\%CoreRT_BuildOS%.%CoreRT_BuildArch%.%CoreRT_BuildType%\Framework" "/p:OutputPath=%CoreRT_TestingUtilitiesOutputDir%" /p:RepoLocalBuild=true "%CoreRT_TestFileHelperProjectPath%" + if errorlevel 1 ( + exit /b 1 + ) + + "%CoreRT_CliDir%\dotnet.exe" msbuild /m /ConsoleLoggerParameters:ForceNoAlign "/p:IlcPath=%CoreRT_ToolchainDir%" "/p:Configuration=%CoreRT_BuildType%" "/p:OSGroup=%CoreRT_BuildOS%" "/p:Platform=%CoreRT_BuildArch%" "/p:RepoLocalBuild=true" "/p:FrameworkLibPath=%CoreRT_TestRoot%..\bin\%CoreRT_BuildOS%.%CoreRT_BuildArch%.%CoreRT_BuildType%\lib" "/p:FrameworkObjPath=%~dp0..\bin\obj\%CoreRT_BuildOS%.%CoreRT_BuildArch%.%CoreRT_BuildType%\Framework" "/p:OutputPath=%CoreRT_TestingUtilitiesOutputDir%" /p:RepoLocalBuild=true "%CoreRT_XunitHelperProjectPath%" + if errorlevel 1 ( + exit /b 1 + ) + + set TESTS_SEMAPHORE=%CoreRT_TestExtRepo_CoreFX%\init-tests.completed + :: If sempahore exists do nothing + if exist "%TESTS_SEMAPHORE%" ( + echo Tests are already initialized. + goto :EOF + ) + + set /p TESTS_REMOTE_URL=< "%~dp0/CoreFXTestListURL.txt" + set TEST_LIST="%~dp0/TopN.CoreFX.Windows.issues.json" + + if not exist !CoreRT_TestingUtilitiesOutputDir!\%CoreRT_TestFileHelperName%.dll ( + echo File !CoreRT_TestingUtilitiesOutputDir!\%CoreRT_TestFileHelperName%.dll not found. + exit /b 1 + ) + + "%CoreRT_CliDir%\dotnet.exe" !CoreRT_TestingUtilitiesOutputDir!\%CoreRT_TestFileHelperName%.dll --clean --outputDirectory !CoreRT_TestExtRepo_CoreFX! --testListJsonPath "%TEST_LIST%" --testUrl "%TESTS_REMOTE_URL%" + if errorlevel 1 ( + exit /b 1 + ) + + exit /b 0 + :RestoreCoreCLRTests - set TESTS_SEMAPHORE=%CoreRT_TestExtRepo%\init-tests.completed + set TESTS_SEMAPHORE=%CoreRT_TestExtRepo_CoreCLR%\init-tests.completed :: If sempahore exists do nothing if exist "%TESTS_SEMAPHORE%" ( @@ -343,15 +399,15 @@ goto :eof goto :EOF ) - if exist "%CoreRT_TestExtRepo%" rmdir /S /Q "%CoreRT_TestExtRepo%" - mkdir "%CoreRT_TestExtRepo%" + if exist "%CoreRT_TestExtRepo_CoreCLR%" rmdir /S /Q "%CoreRT_TestExtRepo_CoreCLR%" + mkdir "%CoreRT_TestExtRepo_CoreCLR%" set /p TESTS_REMOTE_URL=< "%~dp0\CoreCLRTestsURL.txt" - set TESTS_LOCAL_ZIP=%CoreRT_TestExtRepo%\tests.zip + set TESTS_LOCAL_ZIP=%CoreRT_TestExtRepo_CoreCLR%\tests.zip set INIT_TESTS_LOG=%~dp0..\init-tests.log echo Restoring tests (this may take a few minutes).. echo Installing '%TESTS_REMOTE_URL%' to '%TESTS_LOCAL_ZIP%' >> "%INIT_TESTS_LOG%" - powershell -NoProfile -ExecutionPolicy unrestricted -Command "$retryCount = 0; $success = $false; do { try { [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; (New-Object Net.WebClient).DownloadFile('%TESTS_REMOTE_URL%', '%TESTS_LOCAL_ZIP%'); $success = $true; } catch { if ($retryCount -ge 6) { throw; } else { $retryCount++; Start-Sleep -Seconds (5 * $retryCount); } } } while ($success -eq $false); Add-Type -Assembly 'System.IO.Compression.FileSystem' -ErrorVariable AddTypeErrors; if ($AddTypeErrors.Count -eq 0) { [System.IO.Compression.ZipFile]::ExtractToDirectory('%TESTS_LOCAL_ZIP%', '%CoreRT_TestExtRepo%') } else { (New-Object -com shell.application).namespace('%CoreRT_TestExtRepo%').CopyHere((new-object -com shell.application).namespace('%TESTS_LOCAL_ZIP%').Items(),16) }" >> "%INIT_TESTS_LOG%" + powershell -NoProfile -ExecutionPolicy unrestricted -Command "$retryCount = 0; $success = $false; do { try { [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; (New-Object Net.WebClient).DownloadFile('%TESTS_REMOTE_URL%', '%TESTS_LOCAL_ZIP%'); $success = $true; } catch { if ($retryCount -ge 6) { throw; } else { $retryCount++; Start-Sleep -Seconds (5 * $retryCount); } } } while ($success -eq $false); Add-Type -Assembly 'System.IO.Compression.FileSystem' -ErrorVariable AddTypeErrors; if ($AddTypeErrors.Count -eq 0) { [System.IO.Compression.ZipFile]::ExtractToDirectory('%TESTS_LOCAL_ZIP%', '%CoreRT_TestExtRepo_CoreCLR%') } else { (New-Object -com shell.application).namespace('%CoreRT_TestExtRepo_CoreCLR%').CopyHere((new-object -com shell.application).namespace('%TESTS_LOCAL_ZIP%').Items(),16) }" >> "%INIT_TESTS_LOG%" if errorlevel 1 ( echo ERROR: Could not download CoreCLR tests correctly. See '%INIT_TESTS_LOG%' for more details. 1>&2 exit /b 1 @@ -361,7 +417,7 @@ goto :eof echo CoreCLR tests restored from %TESTS_REMOTE_URL% > %TESTS_SEMAPHORE% exit /b 0 -:TestExtRepo +:TestExtRepoCoreCLR :: Omit the exclude parameter to CoreCLR's test harness if we're running all tests set CoreCLRExcludeText=exclude if "%CoreRT_CoreCLRTargetsFile%" == "" ( @@ -369,15 +425,15 @@ goto :eof ) echo Running external tests - if "%CoreRT_TestExtRepo%" == "" ( - set CoreRT_TestExtRepo=%CoreRT_TestRoot%\..\tests_downloaded\CoreCLR + if "%CoreRT_TestExtRepo_CoreCLR%" == "" ( + set CoreRT_TestExtRepo_CoreCLR=%CoreRT_TestRoot%\..\tests_downloaded\CoreCLR call :RestoreCoreCLRTests if errorlevel 1 ( exit /b 1 ) ) - if not exist "%CoreRT_TestExtRepo%" ((call :Fail "%CoreRT_TestExtRepo% does not exist") & exit /b 1) + if not exist "%CoreRT_TestExtRepo_CoreCLR%" ((call :Fail "%CoreRT_TestExtRepo_CoreCLR% does not exist") & exit /b 1) if "%CoreRT_MultiFileConfiguration%" == "MultiModule" ( set IlcMultiModule=true @@ -389,7 +445,7 @@ goto :eof echo. set CLRCustomTestLauncher=%CoreRT_TestRoot%\CoreCLR\build-and-run-test.cmd - set XunitTestBinBase=!CoreRT_TestExtRepo! + set XunitTestBinBase=!CoreRT_TestExtRepo_CoreCLR! pushd %CoreRT_TestRoot%\CoreCLR\runtest "%CoreRT_CliDir%\dotnet.exe" msbuild /t:Restore /p:RepoLocalBuild=true src\TestWrappersConfig\XUnitTooling.depproj @@ -416,3 +472,43 @@ goto :eof set __SavedErrorLevel=%ErrorLevel% popd exit /b %__SavedErrorLevel% + +:TestExtRepoCoreFX + + set CoreRT_TestExtRepo_CoreFX=%CoreRT_TestRoot%\..\tests_downloaded\CoreFX + set CoreRT_TestingUtilitiesOutputDir=%CoreRT_TestExtRepo_CoreFX%\..\CoreFXUtilities + + :: Set paths to helpers + set CoreRT_TestFileHelperName=CoreFX.TestUtils.TestFileSetup + set CoreRT_TestFileHelperProjectPath="%CoreRT_TestRoot%\CoreFX\runtest\src\TestUtils\TestFileSetup\%CoreRT_TestFileHelperName%.csproj" + + set CoreRT_XunitHelperName=CoreFX.TestUtils.XUnit + set CoreRT_XunitHelperProjectPath="%CoreRT_TestRoot%\CoreFX\runtest\src\TestUtils\XUnit\%CoreRT_XunitHelperName%.csproj" + + :: TODO Check if each requested test has already been restored + call :RestoreCoreFXTests + if errorlevel 1 ( + exit /b 1 + ) + + set FXCustomTestLauncher=%CoreRT_TestRoot%\CoreFX\build-and-run-test.cmd + set XunitTestBinBase=%CoreRT_TestExtRepo_CoreFX% + + :: Place test logs so they can be found by CI + set XunitLogDir= %__CoreRTTestBinDir%\CoreFX + + :: Clean up existing logs + if exist "%XunitLogDir%" rmdir /S /Q "%XunitLogDir%" + mkdir "%XunitLogDir%" + pushd %CoreRT_TestRoot%\CoreFX\runtest + + :: TODO Add single test/target test support; add exclude tests argument + + echo runtest.cmd %CoreRT_BuildArch% %CoreRT_BuildType% LogsDir %XunitLogDir% + call runtest.cmd %CoreRT_BuildArch% %CoreRT_BuildType% LogsDir %XunitLogDir% + + set __SavedErrorLevel=%ErrorLevel% + popd + + exit /b %__SavedErrorLevel% + diff --git a/external/corert/tests/runtest.sh b/external/corert/tests/runtest.sh index 51104cf812..9da8a524a3 100755 --- a/external/corert/tests/runtest.sh +++ b/external/corert/tests/runtest.sh @@ -6,6 +6,7 @@ usage() echo " -mode : Compilation mode. Specify cpp/ryujit. Default: ryujit" echo " -test : Run a single test by folder name (ie, BasicThreading)" echo " -runtest : Should just compile or run compiled binary? Specify: true/false. Default: true." + echo " -corefx : Download and run the CoreFX repo tests" echo " -coreclr : Download and run the CoreCLR repo tests" echo " -multimodule : Compile the framework as a .so and link tests against it (ryujit only)" echo " -coredumps : [For CI use] Enables core dump generation, and analyzes and possibly stores/uploads" @@ -38,6 +39,7 @@ run_test_dir() local __dir_path=`dirname ${__test_dir}` local __filename=`basename ${__dir_path}` local __extra_args="" + local __extra_flags=() if [ "${__mode}" = "Cpp" ]; then __extra_args="${__extra_args} /p:NativeCodeGen=cpp" fi @@ -46,9 +48,11 @@ run_test_dir() fi if [ -n "${__extra_cxxflags}" ]; then __extra_cxxflags="/p:AdditionalCppCompilerFlags=\"${__extra_cxxflags}\"" + __extra_flags+=("${__extra_cxxflags}") fi - if [ -n "${__extra_cxxflags}" ]; then + if [ -n "${__extra_linkflags}" ]; then __extra_linkflags="/p:AdditionalLinkerFlags=\"${__extra_linkflags}\"" + __extra_flags+=("${__extra_linkflags}") fi if [ "${CoreRT_MultiFileConfiguration}" = "MultiModule" ]; then __extra_args="${__extra_args} /p:IlcMultiModule=true" @@ -58,8 +62,8 @@ run_test_dir() local __msbuild_dir=${CoreRT_TestRoot}/../Tools - echo ${__msbuild_dir}/msbuild.sh /ds /m /p:IlcPath=${CoreRT_ToolchainDir} /p:Configuration=${CoreRT_BuildType} /p:Platform=${CoreRT_BuildArch} /p:RepoLocalBuild=true "/p:FrameworkLibPath=${CoreRT_TestRoot}/../bin/${CoreRT_BuildOS}.${CoreRT_BuildArch}.${CoreRT_BuildType}/lib" "/p:FrameworkObjPath=${CoreRT_TestRoot}/../bin/obj/${CoreRT_BuildOS}.${CoreRT_BuildArch}.${CoreRT_BuildType}/Framework" ${__extra_args} ${__extra_cxxflags} ${__extra_linkflags} ${__dir_path}/${__filename}.csproj - ${__msbuild_dir}/msbuild.sh /ds /m /p:IlcPath=${CoreRT_ToolchainDir} /p:Configuration=${CoreRT_BuildType} /p:Platform=${CoreRT_BuildArch} /p:OSGroup=${CoreRT_BuildOS} /p:RepoLocalBuild=true "/p:FrameworkLibPath=${CoreRT_TestRoot}/../bin/${CoreRT_BuildOS}.${CoreRT_BuildArch}.${CoreRT_BuildType}/lib" "/p:FrameworkObjPath=${CoreRT_TestRoot}/../bin/obj/${CoreRT_BuildOS}.${CoreRT_BuildArch}.${CoreRT_BuildType}/Framework" ${__extra_args} ${__extra_cxxflags} ${__extra_linkflags} ${__dir_path}/${__filename}.csproj + echo ${__msbuild_dir}/msbuild.sh /ds /m /p:IlcPath=${CoreRT_ToolchainDir} /p:Configuration=${CoreRT_BuildType} /p:Platform=${CoreRT_BuildArch} /p:OSGroup=${CoreRT_BuildOS} /p:RepoLocalBuild=true "/p:FrameworkLibPath=${CoreRT_TestRoot}/../bin/${CoreRT_BuildOS}.${CoreRT_BuildArch}.${CoreRT_BuildType}/lib" "/p:FrameworkObjPath=${CoreRT_TestRoot}/../bin/obj/${CoreRT_BuildOS}.${CoreRT_BuildArch}.${CoreRT_BuildType}/Framework" ${__extra_args} "${__extra_flags[@]}" ${__dir_path}/${__filename}.csproj + ${__msbuild_dir}/msbuild.sh /ds /m /p:IlcPath=${CoreRT_ToolchainDir} /p:Configuration=${CoreRT_BuildType} /p:Platform=${CoreRT_BuildArch} /p:OSGroup=${CoreRT_BuildOS} /p:RepoLocalBuild=true "/p:FrameworkLibPath=${CoreRT_TestRoot}/../bin/${CoreRT_BuildOS}.${CoreRT_BuildArch}.${CoreRT_BuildType}/lib" "/p:FrameworkObjPath=${CoreRT_TestRoot}/../bin/obj/${CoreRT_BuildOS}.${CoreRT_BuildArch}.${CoreRT_BuildType}/Framework" ${__extra_args} "${__extra_flags[@]}" ${__dir_path}/${__filename}.csproj local __exitcode=$? @@ -84,7 +88,7 @@ run_test_dir() return $? } -download_and_unzip_tests_artifacts() +download_and_unzip_coreclr_tests_artifacts() { url=$1 location=$2 @@ -104,6 +108,49 @@ download_and_unzip_tests_artifacts() fi } +download_and_unzip_corefx_tests_artifacts() +{ + url=$1 + test_list=$2 + #semaphore=${CoreRT_TestExtRepo_CoreFX}/init-tests.completed + + local __msbuild_dir=${CoreRT_CliBinDir}/.. + + # Build and restore test helper projects + ${CoreRT_CliBinDir}/dotnet restore "${CoreRT_TestFileHelperProjectPath}" + local __exitcode=$? + if [ ${__exitcode} != 0 ]; then + exit ${__exitcode} + fi + + ${CoreRT_CliBinDir}/dotnet restore "${CoreRT_XunitHelperProjectPath}" + __exitcode=$? + if [ ${__exitcode} != 0 ]; then + exit ${__exitcode} + fi + + # Build the test helper projects + ${CoreRT_CliBinDir}/dotnet build /m /ConsoleLoggerParameters:ForceNoAlign /p:IlcPath=${CoreRT_ToolchainDir} /p:Configuration=${CoreRT_BuildType} /p:Platform=${CoreRT_BuildArch} /p:OSGroup=${CoreRT_BuildOS} /p:RepoLocalBuild=true "/p:FrameworkLibPath=${CoreRT_TestRoot}/../bin/${CoreRT_BuildOS}.${CoreRT_BuildArch}.${CoreRT_BuildType}/lib" "/p:FrameworkObjPath=${CoreRT_TestRoot}/../bin/obj/${CoreRT_BuildOS}.${CoreRT_BuildArch}.${CoreRT_BuildType}/Framework" "/p:OutputPath=${CoreRT_TestingUtilitiesOutputDir}" "${CoreRT_TestFileHelperProjectPath}" + + __exitcode=$? + if [ ${__exitcode} != 0 ]; then + exit ${__exitcode} + fi + + ${CoreRT_CliBinDir}/dotnet build /m /ConsoleLoggerParameters:ForceNoAlign /p:IlcPath=${CoreRT_ToolchainDir} /p:Configuration=${CoreRT_BuildType} /p:Platform=${CoreRT_BuildArch} /p:OSGroup=${CoreRT_BuildOS} /p:RepoLocalBuild=true "/p:FrameworkLibPath=${CoreRT_TestRoot}/../bin/${CoreRT_BuildOS}.${CoreRT_BuildArch}.${CoreRT_BuildType}/lib" "/p:FrameworkObjPath=${CoreRT_TestRoot}/../bin/obj/${CoreRT_BuildOS}.${CoreRT_BuildArch}.${CoreRT_BuildType}/Framework" "/p:OutputPath=${CoreRT_TestingUtilitiesOutputDir}" "${CoreRT_XunitHelperProjectPath}" + __exitcode=$? + if [ ${__exitcode} != 0 ]; then + exit ${__exitcode} + fi + + ${CoreRT_CliBinDir}/dotnet ${CoreRT_TestingUtilitiesOutputDir}/${CoreRT_TestFileHelperName}.dll --clean --outputDirectory ${CoreRT_TestExtRepo_CoreFX} --testListJsonPath ${test_list} --testUrl ${url} + __exitcode=$? + if [ ${__exitcode} != 0 ]; then + exit ${__exitcode} + fi +} + + restore_coreclr_tests() { CoreRT_Test_Download_Semaphore=${CoreRT_TestExtRepo}/init-tests.completed @@ -118,10 +165,10 @@ restore_coreclr_tests() CoreRT_NativeArtifactRepo=${CoreRT_TestExtRepo}/native echo "Restoring tests (this may take a few minutes).." - download_and_unzip_tests_artifacts ${TESTS_REMOTE_URL} ${CoreRT_TestExtRepo} ${CoreRT_Test_Download_Semaphore} + download_and_unzip_coreclr_tests_artifacts ${TESTS_REMOTE_URL} ${CoreRT_TestExtRepo} ${CoreRT_Test_Download_Semaphore} echo "Restoring native test artifacts..." - download_and_unzip_tests_artifacts ${NATIVE_REMOTE_URL} ${CoreRT_NativeArtifactRepo} ${CoreRT_NativeArtifact_Download_Semaphore} + download_and_unzip_coreclr_tests_artifacts ${NATIVE_REMOTE_URL} ${CoreRT_NativeArtifactRepo} ${CoreRT_NativeArtifact_Download_Semaphore} } run_coreclr_tests() @@ -159,6 +206,79 @@ run_coreclr_tests() ./runtest.sh --testRootDir=${CoreRT_TestExtRepo} --coreOverlayDir=${CoreRT_TestRoot}/CoreCLR ${CoreRT_TestSelectionArg} --logdir=$__LogDir --disableEventLogging } +run_corefx_tests() +{ + CoreRT_TestExtRepo_CoreFX=${CoreRT_TestRoot}/../tests_downloaded/CoreFX + CoreRT_TestingUtilitiesOutputDir=${CoreRT_TestExtRepo_CoreFX}/../CoreFXUtilities + + export CoreRT_TestRoot + export CoreRT_EnableCoreDumps + + export CoreRT_TestExtRepo_CoreFX + export CoreRT_TestingUtilitiesOutputDir + export CoreRT_CliBinDir + + if [ ! -d "${CoreRT_TestExtRepo_CoreFX}" ]; then + mkdir -p ${CoreRT_TestExtRepo_CoreFX} + fi + + # Set paths to helpers + CoreRT_TestFileHelperName=CoreFX.TestUtils.TestFileSetup + CoreRT_TestFileHelperProjectPath="${CoreRT_TestRoot}/CoreFX/runtest/src/TestUtils/TestFileSetup/${CoreRT_TestFileHelperName}.csproj" + + CoreRT_XunitHelperName=CoreFX.TestUtils.XUnit + CoreRT_XunitHelperProjectPath="${CoreRT_TestRoot}/CoreFX/runtest/src/TestUtils/XUnit/${CoreRT_XunitHelperName}.csproj" + + TEST_LIST_JSON=${CoreRT_TestRoot}/TopN.CoreFX.Unix.issues.json + case "$(uname -s)" in + # Check if we're running under Linux + Linux) + TESTS_REMOTE_URL=$(<${CoreRT_TestRoot}/CoreFXTestListURL_Linux.txt) + ;; + # Check if we're running under OSX + Darwin) + TESTS_REMOTE_URL=$(<${CoreRT_TestRoot}/CoreFXTestListURL_OSX.txt) + ;; + # Default to Linux if we don't recognize the OS + *) + TESTS_REMOTE_URL=$(<${CoreRT_TestRoot}/CoreFXTestListURL_Linux.txt) + ;; + esac + + + download_and_unzip_corefx_tests_artifacts ${TESTS_REMOTE_URL} ${TEST_LIST_JSON} + __exitcode=$? + if [ ${__exitcode} != 0 ]; + then + exit ${__exitcode} + fi + + FXCustomTestLauncher=${CoreRT_TestRoot}/CoreFX/corerun + XunitTestBinBase=${CoreRT_TestExtRepo_CoreFX} + XunitLogDir=${CoreRT_TestRoot}/../bin/tests/CoreFX + + # Clean up existing logs + if [ -d "${XunitLogDir}" ]; then + rm -rf "${XunitLogDir}" + fi + mkdir ${XunitLogDir} + + pushd ${CoreRT_TestRoot}/CoreFX/runtest + + # TODO Add single test/target test support; add exclude tests argument + ./runtest.sh --testRootDir=${XunitTestBinBase} --logdir=${XunitLogDir} --testLauncher=${FXCustomTestLauncher} + __exitcode=$? + if [ ${__exitcode} != 0 ]; + then + exit ${__exitcode} + fi + + echo ${CoreRT_CliBinDir}/dotnet ${CoreRT_TestingUtilitiesOutputDir}/${CoreRT_XunitHelperName}.dll --logDir ${XunitLogDir} --pattern "*.xml" + + ${CoreRT_CliBinDir}/dotnet ${CoreRT_TestingUtilitiesOutputDir}/${CoreRT_XunitHelperName}.dll --logDir ${XunitLogDir} --pattern "*.xml" + +} + CoreRT_TestRoot="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" CoreRT_CliBinDir=${CoreRT_TestRoot}/../Tools/dotnetcli CoreRT_BuildArch=x64 @@ -238,6 +358,10 @@ while [ "$1" != "" ]; do exit -1 fi ;; + -corefx) + CoreRT_RunCoreFXTests=true; + shift + ;; -multimodule) CoreRT_MultiFileConfiguration=MultiModule; ;; @@ -324,6 +448,11 @@ if [ ${CoreRT_RunCoreCLRTests} ]; then exit $? fi +if [ ${CoreRT_RunCoreFXTests} ]; then + run_corefx_tests + exit $? +fi + __CppTotalTests=0 __CppPassedTests=0 __JitTotalTests=0 diff --git a/external/corert/tests/src/Simple/BasicThreading/BasicThreading.cmd b/external/corert/tests/src/Simple/BasicThreading/BasicThreading.cmd index 8712cf5757..bf2e377397 100644 --- a/external/corert/tests/src/Simple/BasicThreading/BasicThreading.cmd +++ b/external/corert/tests/src/Simple/BasicThreading/BasicThreading.cmd @@ -1,8 +1,6 @@ @echo off setlocal -rem Enable Server GC for this test -set RH_UseServerGC=1 "%1\%2" set ErrorCode=%ERRORLEVEL% IF "%ErrorCode%"=="100" ( diff --git a/external/corert/tests/src/Simple/BasicThreading/BasicThreading.cs b/external/corert/tests/src/Simple/BasicThreading/BasicThreading.cs index 23360a8927..7f77687a42 100644 --- a/external/corert/tests/src/Simple/BasicThreading/BasicThreading.cs +++ b/external/corert/tests/src/Simple/BasicThreading/BasicThreading.cs @@ -17,10 +17,6 @@ class Program { SimpleReadWriteThreadStaticTest.Run(42, "SimpleReadWriteThreadStatic"); - // TODO: After issue https://github.com/dotnet/corert/issues/2695 is fixed, move FinalizeTest to run at the end - if (FinalizeTest.Run() != Pass) - return Fail; - ThreadStaticsTestWithTasks.Run(); if (ThreadTest.Run() != Pass) @@ -28,6 +24,9 @@ class Program if (TimerTest.Run() != Pass) return Fail; + + if (FinalizeTest.Run() != Pass) + return Fail; return Pass; } diff --git a/external/corert/tests/src/Simple/BasicThreading/BasicThreading.csproj b/external/corert/tests/src/Simple/BasicThreading/BasicThreading.csproj index 45ebce05d6..3570f12a68 100644 --- a/external/corert/tests/src/Simple/BasicThreading/BasicThreading.csproj +++ b/external/corert/tests/src/Simple/BasicThreading/BasicThreading.csproj @@ -1,4 +1,7 @@ + + true + diff --git a/external/corert/tests/src/Simple/BasicThreading/BasicThreading.sh b/external/corert/tests/src/Simple/BasicThreading/BasicThreading.sh index 91ec7c7507..ca45ba4e4b 100755 --- a/external/corert/tests/src/Simple/BasicThreading/BasicThreading.sh +++ b/external/corert/tests/src/Simple/BasicThreading/BasicThreading.sh @@ -1,7 +1,5 @@ #!/usr/bin/env bash -# Enable Server GC for this test -export RH_UseServerGC=1 $1/$2 if [ $? == 100 ]; then echo pass diff --git a/external/corert/tests/src/Simple/Delegates/Delegates.cs b/external/corert/tests/src/Simple/Delegates/Delegates.cs index 1271eb9b33..d17133dfe6 100644 --- a/external/corert/tests/src/Simple/Delegates/Delegates.cs +++ b/external/corert/tests/src/Simple/Delegates/Delegates.cs @@ -4,6 +4,8 @@ using System; +using Pointer = System.Reflection.Pointer; + public class BringUpTests { const int Pass = 100; @@ -105,6 +107,14 @@ public class BringUpTests return false; } + { + // This will end up being a delegate to a sealed virtual method. + ClassWithIFoo t = new ClassWithIFoo("Class"); + Func d = t.DoFoo; + if (d(987) != "Class987") + return false; + } + Console.WriteLine("OK"); return true; } @@ -247,7 +257,10 @@ public class BringUpTests unsafe { GetAndReturnPointerDelegate d = ClassWithPointers.GetAndReturnPointer; - if ((IntPtr)d.DynamicInvoke(new object[] { (IntPtr)8 }) != (IntPtr)50) + if (Pointer.Unbox(d.DynamicInvoke(new object[] { (IntPtr)8 })) != (void*)50) + return false; + + if (Pointer.Unbox(d.DynamicInvoke(new object[] { Pointer.Box((void*)9, typeof(void*)) })) != (void*)51) return false; } @@ -390,14 +403,14 @@ static class ExtensionClass } } -unsafe delegate IntPtr GetAndReturnPointerDelegate(void* ptr); +unsafe delegate byte* GetAndReturnPointerDelegate(void* ptr); unsafe delegate void PassPointerByRefDelegate(ref void* ptr); unsafe static class ClassWithPointers { - public static IntPtr GetAndReturnPointer(void* ptr) + public static byte* GetAndReturnPointer(void* ptr) { - return (IntPtr)((byte*)ptr + 42); + return (byte*)ptr + 42; } public static void PassPointerByRef(ref void* ptr) diff --git a/external/corert/tests/src/Simple/Generics/Generics.cs b/external/corert/tests/src/Simple/Generics/Generics.cs index 3b5386b343..fe16f5b71f 100644 --- a/external/corert/tests/src/Simple/Generics/Generics.cs +++ b/external/corert/tests/src/Simple/Generics/Generics.cs @@ -31,6 +31,8 @@ class Program TestGvmDependencies.Run(); TestFieldAccess.Run(); TestNativeLayoutGeneration.Run(); + TestInterfaceVTableTracking.Run(); + TestClassVTableTracking.Run(); return 100; } @@ -2088,4 +2090,60 @@ class Program throw new Exception(); } } + + class TestInterfaceVTableTracking + { + class Gen { } + + interface IFoo + { + Array Frob(); + } + + class GenericBase : IFoo + { + public Array Frob() + { + return new Gen[1,1]; + } + } + + class Derived : GenericBase> + { + } + + static volatile IFoo> s_foo; + + public static void Run() + { + // This only really tests whether we can compile this. + s_foo = new Derived(); + Array arr = s_foo.Frob(); + arr.SetValue(new Gen>(), new int[] { 0, 0 }); + } + } + + class TestClassVTableTracking + { + class Unit { } + + class Gen + { + public virtual int Test() + { + return 42; + } + } + + static int Call() + { + return new Gen().Test(); + } + + public static void Run() + { + // This only really tests whether we can compile this. + Call(); + } + } } diff --git a/external/corert/tests/src/Simple/HelloWasm/HelloWasm.cmd b/external/corert/tests/src/Simple/HelloWasm/HelloWasm.cmd index 286a11ffc3..2852ea3701 100644 --- a/external/corert/tests/src/Simple/HelloWasm/HelloWasm.cmd +++ b/external/corert/tests/src/Simple/HelloWasm/HelloWasm.cmd @@ -1,14 +1,13 @@ @echo off setlocal -set ErrorCode=100 -for /f "usebackq delims=;" %%F in (`"%1\%2" world`) do ( - if "%%F"=="Hello world" set ErrorCode=0 -) -IF "%ErrorCode%"=="0" ( - echo %~n0: pass + +call emrun --browser=firefox --browser_args=-headless --safe_firefox_profile --silence_timeout 10 "%1\%2" + +IF "%errorlevel%"=="100" ( + echo %~n0: Pass EXIT /b 0 ) ELSE ( - echo %~n0: fail - %ErrorCode% + echo %~n0: fail - %ErrorLevel% EXIT /b 1 ) endlocal diff --git a/external/corert/tests/src/Simple/HelloWasm/HelloWasm.csproj b/external/corert/tests/src/Simple/HelloWasm/HelloWasm.csproj index f070f287a0..0684df90e4 100644 --- a/external/corert/tests/src/Simple/HelloWasm/HelloWasm.csproj +++ b/external/corert/tests/src/Simple/HelloWasm/HelloWasm.csproj @@ -4,6 +4,9 @@ + + + diff --git a/external/corert/tests/src/Simple/HelloWasm/ILHelpers.il b/external/corert/tests/src/Simple/HelloWasm/ILHelpers.il new file mode 100644 index 0000000000..8d763d7c32 --- /dev/null +++ b/external/corert/tests/src/Simple/HelloWasm/ILHelpers.il @@ -0,0 +1,111 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +.assembly extern mscorlib +{ + .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) + .ver 4:0:0:0 +} + +.assembly extern System.Private.CoreLib +{ + .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) + .ver 4:0:0:0 +} + +.assembly ILHelpers { } + +.class public ILHelpers.ILHelpersTest +{ + .method public static void EatArgs(string, object) + { + ret + } + + .method public static void EatArg(object) + { + ret + } + //this is copied from the test case for https://github.com/dotnet/coreclr/issues/14784 + //its been adapted to remove the requirement for Console.WriteLine because thats not supported in WASM + //it can be removed once we have support for Console.WriteLine and can run the CoreCLR tests + .method public static int32 InlineAssignByte() + { + .locals init ( + int8 local, + object b + ) + ldstr "InlineAssignByte" + ldc.i4 300 + dup + stloc.0 + box int32 + stloc.1 + ldloc.1 + call void ILHelpers.ILHelpersTest::EatArgs(string, object) + ldstr "InlineAssignByte" + ldloc.0 + box int32 + call void ILHelpers.ILHelpersTest::EatArgs(string, object) + ldloc.1 + //after the unboxing and truncation on the way in ensure that we can subtract 200 and end up with the expected 100 return value + unbox.any int32 + ldc.i4 200 + sub + ret + } + .method public static int32 DupTest(int32&) + { + .locals init ( + int32 local, + int32 local2 + ) + ldarg.0 + //push a bunch of entries onto the stack using dup, we will consume them through the rest of this method + dup + dup + dup + dup + dup + //first off lets ensure the passed parameter was pointing to an int of less than 10 (it should be 9) + ldind.i4 + ldc.i4 10 + clt + brtrue target + //this is just trying to mess with the stack accross basic block boundries + //it should actually leave the evaluation stack unchanged in the end + pop + dup + //make sure we can deref one of our duplicate int refs and box it without any trouble + target: ldind.i4 + box int32 + call void ILHelpers.ILHelpersTest::EatArg(object) + //deref one of our duplicates and add 1 to it, this should not write back to the parameter it should only be stored in the local + ldind.i4 + ldc.i4 1 + add + stloc.0 + //load one of our duplicates and add 200 to it, we're eventually going to return this value and test for it in the caller + ldind.i4 + ldc.i4 200 + add + //this should write back into the parameter + stind.i4 + ldloc.0 + dup + add + dup + stloc.1 + ldloc.0 + ceq + //if the added value equals the source value we've got something writing to its original StackEntry instead of a dup + brtrue failure + ldind.i4 + ret + failure: + pop + ldc.i4 0 + ret + } +} \ No newline at end of file diff --git a/external/corert/tests/src/Simple/HelloWasm/ILHelpers.ilproj b/external/corert/tests/src/Simple/HelloWasm/ILHelpers.ilproj new file mode 100644 index 0000000000..01625f5e0b --- /dev/null +++ b/external/corert/tests/src/Simple/HelloWasm/ILHelpers.ilproj @@ -0,0 +1,20 @@ + + + netstandard2.0 + Library + portable + $(MSBuildProjectDirectory)\bin\$(Configuration)\$(Platform)\ + $(MSBuildProjectDirectory)\obj\$(Configuration)\$(Platform)\ + + + + + + + + $(MicrosoftNETCoreAppPackageVersion) + + + + + diff --git a/external/corert/tests/src/Simple/HelloWasm/Program.cs b/external/corert/tests/src/Simple/HelloWasm/Program.cs index 75864c2e03..98ccb4eb1f 100644 --- a/external/corert/tests/src/Simple/HelloWasm/Program.cs +++ b/external/corert/tests/src/Simple/HelloWasm/Program.cs @@ -13,16 +13,46 @@ internal static class Program private static int staticInt; [ThreadStatic] private static int threadStaticInt; - private static unsafe void Main(string[] args) + private static unsafe int Main(string[] args) { + PrintLine("Starting"); + Add(1, 2); int tempInt = 0; + int tempInt2 = 0; (*(&tempInt)) = 9; if(tempInt == 9) { PrintLine("Hello from C#!"); } + int* targetAddr = (tempInt > 0) ? (&tempInt2) : (&tempInt); + + (*targetAddr) = 1; + if(tempInt2 == 1 && tempInt == 9) + { + PrintLine("basic block stack entry Test: Ok."); + } + + if(ILHelpers.ILHelpersTest.InlineAssignByte() == 100) + { + PrintLine("Inline assign byte Test: Ok."); + } + else + { + PrintLine("Inline assign byte Test: Failed."); + } + + int dupTestInt = 9; + if(ILHelpers.ILHelpersTest.DupTest(ref dupTestInt) == 209 && dupTestInt == 209) + { + PrintLine("dup test: Ok."); + } + else + { + PrintLine("dup test: Failed."); + } + TestClass tempObj = new TestDerivedClass(1337); tempObj.TestMethod("Hello"); tempObj.TestVirtualMethod("Hello"); @@ -55,12 +85,19 @@ internal static class Program PrintLine("thread static int field test: Ok."); } + StaticCtorTest(); + var boxedInt = (object)tempInt; if(((int)boxedInt) == 9) { PrintLine("box test: Ok."); } - + else + { + PrintLine("box test: Failed. Value:"); + PrintLine(boxedInt.ToString()); + } + var boxedStruct = (object)new BoxStubTest { Value = "Boxed Stub Test: Ok." }; PrintLine(boxedStruct.ToString()); @@ -157,6 +194,10 @@ internal static class Program arrayTest[1].Value = "Array load/store test: Ok."; PrintLine(arrayTest[1].Value); + int ii = 0; + arrayTest[ii++].Value = "dup ref test: Ok."; + PrintLine(arrayTest[0].Value); + var largeArrayTest = new long[] { Int64.MaxValue, 0, Int64.MinValue, 0 }; if(largeArrayTest[0] == Int64.MaxValue && largeArrayTest[1] == 0 && @@ -186,6 +227,9 @@ internal static class Program IntToStringTest(); CastingTestClass castingTest = new DerivedCastingTestClass1(); + + PrintLine("interface call test: Ok " + (castingTest as ICastingTest1).GetValue().ToString()); + if (((DerivedCastingTestClass1)castingTest).GetValue() == 1 && !(castingTest is DerivedCastingTestClass2)) { PrintLine("Type casting with isinst & castclass to class test: Ok."); @@ -208,17 +252,74 @@ internal static class Program ldindTest(); - System.Diagnostics.Debugger.Break(); + InterfaceDispatchTest(); - var testRuntimeHelpersInitArray = new long[] {1, 2, 3}; - if(testRuntimeHelpersInitArray[0] == 1 && + var testRuntimeHelpersInitArray = new long[] { 1, 2, 3 }; + if (testRuntimeHelpersInitArray[0] == 1 && testRuntimeHelpersInitArray[1] == 2 && testRuntimeHelpersInitArray[2] == 3) { PrintLine("Runtime.Helpers array initialization test: Ok."); } + var testMdArrayInstantiation = new int[2, 2]; + if (testMdArrayInstantiation != null && testMdArrayInstantiation.GetLength(0) == 2 && testMdArrayInstantiation.GetLength(1) == 2) + PrintLine("Multi-dimension array instantiation test: Ok."); + + int intToCast = 1; + double castedDouble = (double)intToCast; + if (castedDouble == 1d) + { + PrintLine("(double) cast test: Ok."); + } + else + { + var toInt = (int)castedDouble; +// PrintLine("expected 1m, but was " + castedDouble.ToString()); // double.ToString is not compiling at the time of writing, but this would be better output + PrintLine($"(double) cast test : Failed. Back to int on next line"); + PrintLine(toInt.ToString()); + } + + if (1f < 2d && 1d < 2f && 1f == 1d) + { + PrintLine("different width float comparisons: Ok."); + } + + // floats are 7 digits precision, so check some double more precise to make sure there is no loss occurring through some inadvertent cast to float + if (10.23456789d != 10.234567891d) + { + PrintLine("double precision comparison: Ok."); + } + + if (12.34567f == 12.34567f && 12.34567f != 12.34568f) + { + PrintLine("float comparison: Ok."); + } + + // Create a ByReference through the ReadOnlySpan ctor and call the ByReference.Value via the indexer. + var span = "123".AsSpan(); + if (span[0] != '1' + || span[1] != '2' + || span[2] != '3') + { + PrintLine("ByReference intrinsics exercise via ReadOnlySpan failed"); + PrintLine(span[0].ToString()); + PrintLine(span[1].ToString()); + PrintLine(span[2].ToString()); + } + else + { + PrintLine("ByReference intrinsics exercise via ReadOnlySpan OK."); + } + + TestConstrainedClassCalls(); + + // This test should remain last to get other results before stopping the debugger + PrintLine("Debugger.Break() test: Ok if debugger is open and breaks."); + System.Diagnostics.Debugger.Break(); + PrintLine("Done"); + return 100; } private static int StaticDelegateTarget() @@ -346,6 +447,160 @@ internal static class Program } } + private static void InterfaceDispatchTest() + { + ItfStruct itfStruct = new ItfStruct(); + if (ItfCaller(itfStruct) == 4) + { + PrintLine("Struct interface test: Ok."); + } + } + + // Calls the ITestItf interface via a generic to ensure the concrete type is known and + // an interface call is generated instead of a virtual or direct call + private static int ItfCaller(T obj) where T : ITestItf + { + return obj.GetValue(); + } + + private static void StaticCtorTest() + { + BeforeFieldInitTest.Nop(); + if (StaticsInited.BeforeFieldInitInited) + { + PrintLine("BeforeFieldInitType inited too early"); + } + else + { + int x = BeforeFieldInitTest.TestField; + if (StaticsInited.BeforeFieldInitInited) + { + PrintLine("BeforeFieldInit test: Ok."); + } + else + { + PrintLine("BeforeFieldInit cctor not run"); + } + } + + NonBeforeFieldInitTest.Nop(); + if (StaticsInited.NonBeforeFieldInitInited) + { + PrintLine("NonBeforeFieldInit test: Ok."); + } + else + { + PrintLine("NonBeforeFieldInitType cctor not run"); + } + } + + private static void TestConstrainedClassCalls() + { + string s = "utf-8"; + + PrintString("Direct ToString test: "); + string stringDirectToString = s.ToString(); + if (s.Equals(stringDirectToString)) + { + PrintLine("Ok."); + } + else + { + PrintString("Failed. Returned string:\""); + PrintString(stringDirectToString); + PrintLine("\""); + } + + // Generic calls on methods not defined on object + uint dataFromBase = GenericGetData(new MyBase(11)); + PrintString("Generic call to base class test: "); + if (dataFromBase == 11) + { + PrintLine("Ok."); + } + else + { + PrintLine("Failed."); + } + + uint dataFromUnsealed = GenericGetData(new UnsealedDerived(13)); + PrintString("Generic call to unsealed derived class test: "); + if (dataFromUnsealed == 26) + { + PrintLine("Ok."); + } + else + { + PrintLine("Failed."); + } + + uint dataFromSealed = GenericGetData(new SealedDerived(15)); + PrintString("Generic call to sealed derived class test: "); + if (dataFromSealed == 45) + { + PrintLine("Ok."); + } + else + { + PrintLine("Failed."); + } + + uint dataFromUnsealedAsBase = GenericGetData(new UnsealedDerived(17)); + PrintString("Generic call to unsealed derived class as base test: "); + if (dataFromUnsealedAsBase == 34) + { + PrintLine("Ok."); + } + else + { + PrintLine("Failed."); + } + + uint dataFromSealedAsBase = GenericGetData(new SealedDerived(19)); + PrintString("Generic call to sealed derived class as base test: "); + if (dataFromSealedAsBase == 57) + { + PrintLine("Ok."); + } + else + { + PrintLine("Failed."); + } + + // Generic calls to methods defined on object + uint hashCodeOfSealedViaGeneric = (uint)GenericGetHashCode(new MySealedClass(37)); + PrintString("Generic GetHashCode for sealed class test: "); + if (hashCodeOfSealedViaGeneric == 74) + { + PrintLine("Ok."); + } + else + { + PrintLine("Failed."); + } + + uint hashCodeOfUnsealedViaGeneric = (uint)GenericGetHashCode(new MyUnsealedClass(41)); + PrintString("Generic GetHashCode for unsealed class test: "); + if (hashCodeOfUnsealedViaGeneric == 82) + { + PrintLine("Ok."); + } + else + { + PrintLine("Failed."); + } + } + + static uint GenericGetData(T obj) where T : MyBase + { + return obj.GetData(); + } + + static int GenericGetHashCode(T obj) + { + return obj.GetHashCode(); + } + [DllImport("*")] private static unsafe extern int printf(byte* str, byte* unused); } @@ -433,6 +688,38 @@ public class TestDerivedClass : TestClass } } +public class StaticsInited +{ + public static bool BeforeFieldInitInited; + public static bool NonBeforeFieldInitInited; +} + +public class BeforeFieldInitTest +{ + public static int TestField = BeforeFieldInit(); + + public static void Nop() { } + + static int BeforeFieldInit() + { + StaticsInited.BeforeFieldInitInited = true; + return 3; + } +} + +public class NonBeforeFieldInitTest +{ + public static int TestField; + + public static void Nop() { } + + static NonBeforeFieldInitTest() + { + TestField = 4; + StaticsInited.NonBeforeFieldInitInited = true; + } +} + public interface ICastingTest1 { int GetValue(); @@ -457,3 +744,110 @@ public class DerivedCastingTestClass2 : CastingTestClass, ICastingTest2 { public override int GetValue() => 2; } + +public interface ITestItf +{ + int GetValue(); +} + +public struct ItfStruct : ITestItf +{ + public int GetValue() + { + return 4; + } +} + +public sealed class MySealedClass +{ + uint _data; + + public MySealedClass() + { + _data = 104; + } + + public MySealedClass(uint data) + { + _data = data; + } + + public uint GetData() + { + return _data; + } + + public override int GetHashCode() + { + return (int)_data * 2; + } + + public override string ToString() + { + Program.PrintLine("MySealedClass.ToString called. Data:"); + Program.PrintLine(_data.ToString()); + return _data.ToString(); + } +} + +public class MyUnsealedClass +{ + uint _data; + + public MyUnsealedClass() + { + _data = 24; + } + + public MyUnsealedClass(uint data) + { + _data = data; + } + + public uint GetData() + { + return _data; + } + + public override int GetHashCode() + { + return (int)_data * 2; + } + + public override string ToString() + { + return _data.ToString(); + } +} + +public class MyBase +{ + protected uint _data; + public MyBase(uint data) + { + _data = data; + } + + public virtual uint GetData() + { + return _data; + } +} + +public class UnsealedDerived : MyBase +{ + public UnsealedDerived(uint data) : base(data) { } + public override uint GetData() + { + return _data * 2; + } +} + +public sealed class SealedDerived : MyBase +{ + public SealedDerived(uint data) : base(data) { } + public override uint GetData() + { + return _data * 3; + } +} diff --git a/external/corert/tests/src/Simple/PInvoke/PInvoke.cs b/external/corert/tests/src/Simple/PInvoke/PInvoke.cs index 3024b84eb6..29e2def920 100644 --- a/external/corert/tests/src/Simple/PInvoke/PInvoke.cs +++ b/external/corert/tests/src/Simple/PInvoke/PInvoke.cs @@ -3,9 +3,17 @@ // See the LICENSE file in the project root for more information. using System; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; +// Make sure the interop data are present even without reflection +namespace System.Runtime.CompilerServices +{ + [AttributeUsage(AttributeTargets.All)] + internal class __BlockAllReflectionAttribute : Attribute { } +} + // Name of namespace matches the name of the assembly on purpose to // ensure that we can handle this (mostly an issue for C++ code generation). namespace PInvokeTests @@ -97,6 +105,9 @@ namespace PInvokeTests [DllImport("*", CallingConvention = CallingConvention.StdCall)] public static extern int SafeHandleOutTest(out SafeMemoryHandle sh1); + [DllImport("*", CallingConvention = CallingConvention.StdCall)] + public static extern int SafeHandleRefTest(ref SafeMemoryHandle sh1, bool change); + [DllImport("*", CallingConvention = CallingConvention.StdCall, SetLastError = true)] public static extern bool LastErrorTest(); @@ -104,6 +115,11 @@ namespace PInvokeTests [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern bool ReversePInvoke_Int(Delegate_Int del); + delegate int Delegate_Int_AggressiveInlining(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j); + [DllImport("*", CallingConvention = CallingConvention.StdCall, EntryPoint = "ReversePInvoke_Int")] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static extern bool ReversePInvoke_Int_AggressiveInlining(Delegate_Int_AggressiveInlining del); + [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet=CharSet.Ansi)] delegate bool Delegate_String(string s); [DllImport("*", CallingConvention = CallingConvention.StdCall)] @@ -233,8 +249,9 @@ namespace PInvokeTests TestSizeParamIndex(); #if !CODEGEN_CPP TestDelegate(); -#endif TestStruct(); + TestMarshalStructAPIs(); +#endif return 100; } @@ -435,6 +452,18 @@ namespace PInvokeTests int actual = SafeHandleOutTest(out hnd2); int expected = unchecked((int)hnd2.DangerousGetHandle().ToInt64()); ThrowIfNotEquals(actual, expected, "SafeHandle out marshalling failed"); + + Console.WriteLine("Testing marshalling ref SafeHandle"); + SafeMemoryHandle hndOriginal = hnd2; + SafeHandleRefTest(ref hnd2, false); + ThrowIfNotEquals(hndOriginal, hnd2, "SafeHandle no-op ref marshalling failed"); + + int actual3 = SafeHandleRefTest(ref hnd2, true); + int expected3 = unchecked((int)hnd2.DangerousGetHandle().ToInt64()); + ThrowIfNotEquals(actual3, expected3, "SafeHandle ref marshalling failed"); + + hndOriginal.Dispose(); + hnd2.Dispose(); } private static void TestSizeParamIndex() @@ -473,8 +502,13 @@ namespace PInvokeTests private static void TestDelegate() { Console.WriteLine("Testing Delegate"); + Delegate_Int del = new Delegate_Int(Sum); ThrowIfNotEquals(true, ReversePInvoke_Int(del), "Delegate marshalling failed."); + + Delegate_Int_AggressiveInlining del_aggressive = new Delegate_Int_AggressiveInlining(Sum); + ThrowIfNotEquals(true, ReversePInvoke_Int_AggressiveInlining(del_aggressive), "Delegate marshalling with aggressive inlining failed."); + unsafe { // @@ -562,20 +596,35 @@ namespace PInvokeTests public ExplicitStruct f2; } - - [StructLayout(LayoutKind.Explicit)] - public struct TestStruct2 - { - [FieldOffset(0)] - public int f1; - [FieldOffset(8)] + [StructLayout(LayoutKind.Sequential)] + public struct NonBlittableStruct + { + public int f1; public bool f2; + public bool f3; + public bool f4; + } + + [StructLayout(LayoutKind.Sequential)] + public class BlittableClass + { + public long f1; + public int f2; + public int f3; + public long f4; + } + + [StructLayout(LayoutKind.Sequential)] + public class NonBlittableClass + { + public bool f1; + public bool f2; + public int f3; } private static void TestStruct() { -#if !CODEGEN_CPP Console.WriteLine("Testing Structs"); SequentialStruct ss = new SequentialStruct(); ss.f0 = 100; @@ -639,24 +688,6 @@ namespace PInvokeTests InlineUnicodeStruct ius = new InlineUnicodeStruct(); ius.inlineString = "Hello World"; - - TestStruct2 ts = new TestStruct2() { f1 = 100, f2 = true}; - int size = Marshal.SizeOf(ts); - IntPtr memory = Marshal.AllocHGlobal(size); - try - { - Marshal.StructureToPtr(ts, memory, false); - TestStruct2 ts2 = Marshal.PtrToStructure(memory); - ThrowIfNotEquals(true, ts2.f1 == 100 && ts2.f2 == true, "Struct marshalling Marshal API failed"); - - IntPtr offset = Marshal.OffsetOf("f2"); - ThrowIfNotEquals(new IntPtr(8), offset, "Struct marshalling OffsetOf failed."); - } - finally - { - Marshal.FreeHGlobal(memory); - } - ThrowIfNotEquals(true, InlineArrayTest(ref ias, ref ius), "inline array marshalling failed"); bool pass = true; for (short i = 0; i < 128; i++) @@ -672,7 +703,6 @@ namespace PInvokeTests ThrowIfNotEquals("Hello World", ius.inlineString, "Inline ByValTStr Unicode marshalling failed"); - // RhpThrowEx is not implemented in CPPCodeGen pass = false; AutoStruct autoStruct = new AutoStruct(); try @@ -691,7 +721,59 @@ namespace PInvokeTests callbacks.callback1 = new Callback1(callbackFunc1); callbacks.callback2 = new Callback2(callbackFunc2); ThrowIfNotEquals(true, RegisterCallbacks(ref callbacks), "Scenario 7: Struct with delegate marshalling failed"); -#endif + } + + private static void TestMarshalStructAPIs() + { + Console.WriteLine("Testing Marshal APIs for structs"); + + NonBlittableStruct ts = new NonBlittableStruct() { f1 = 100, f2 = true, f3 = false, f4 = true }; + int size = Marshal.SizeOf(ts); + ThrowIfNotEquals(16, size, "Marshal.SizeOf failed"); + IntPtr memory = Marshal.AllocHGlobal(size); + try + { + Marshal.StructureToPtr(ts, memory, false); + NonBlittableStruct ts2 = Marshal.PtrToStructure(memory); + ThrowIfNotEquals(true, ts2.f1 == 100 && ts2.f2 == true && ts2.f3 == false && ts2.f4 == true, "NonBlittableStruct marshalling Marshal API failed"); + + IntPtr offset = Marshal.OffsetOf("f2"); + ThrowIfNotEquals(new IntPtr(4), offset, "Struct marshalling OffsetOf failed."); + } + finally + { + Marshal.FreeHGlobal(memory); + } + + BlittableClass bc = new BlittableClass() { f1 = 100, f2 = 12345678, f3 = 999, f4 = -4 }; + int bc_size = Marshal.SizeOf(bc); + ThrowIfNotEquals(24, bc_size, "Marshal.SizeOf failed"); + IntPtr bc_memory = Marshal.AllocHGlobal(bc_size); + try + { + Marshal.StructureToPtr(bc, bc_memory, false); + BlittableClass bc2 = Marshal.PtrToStructure(bc_memory); + ThrowIfNotEquals(true, bc2.f1 == 100 && bc2.f2 == 12345678 && bc2.f3 == 999 && bc2.f4 == -4, "BlittableClass marshalling Marshal API failed"); + } + finally + { + Marshal.FreeHGlobal(bc_memory); + } + + NonBlittableClass nbc = new NonBlittableClass() { f1 = false, f2 = true, f3 = 42 }; + int nbc_size = Marshal.SizeOf(nbc); + ThrowIfNotEquals(12, nbc_size, "Marshal.SizeOf failed"); + IntPtr nbc_memory = Marshal.AllocHGlobal(nbc_size); + try + { + Marshal.StructureToPtr(nbc, nbc_memory, false); + NonBlittableClass nbc2 = Marshal.PtrToStructure(nbc_memory); + ThrowIfNotEquals(true, nbc2.f1 == false && nbc2.f2 == true && nbc2.f3 == 42, "NonBlittableClass marshalling Marshal API failed"); + } + finally + { + Marshal.FreeHGlobal(nbc_memory); + } } } diff --git a/external/corert/tests/src/Simple/PInvoke/PInvokeNative.cpp b/external/corert/tests/src/Simple/PInvoke/PInvokeNative.cpp index 90ea1dbff8..713fb4435a 100644 --- a/external/corert/tests/src/Simple/PInvoke/PInvokeNative.cpp +++ b/external/corert/tests/src/Simple/PInvoke/PInvokeNative.cpp @@ -313,13 +313,17 @@ DLL_EXPORT bool __stdcall SafeHandleTest(HANDLE sh, long shValue) DLL_EXPORT long __stdcall SafeHandleOutTest(HANDLE **sh) { - if (sh == NULL) - return -1; - *sh = (HANDLE *)malloc(100); return (long)((size_t)(*sh)); } +DLL_EXPORT long __stdcall SafeHandleRefTest(HANDLE **sh, bool alloc) +{ + if (alloc) + *sh = (HANDLE *)malloc(100); + return (long)((size_t)(*sh)); +} + DLL_EXPORT bool __stdcall ReversePInvoke_Int(int(__stdcall *fnPtr) (int, int, int, int, int, int, int, int, int, int)) { return fnPtr(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) == 55; diff --git a/external/corert/tests/src/Simple/Reflection/Reflection.cs b/external/corert/tests/src/Simple/Reflection/Reflection.cs index 322650a2c1..86e47c39d2 100644 --- a/external/corert/tests/src/Simple/Reflection/Reflection.cs +++ b/external/corert/tests/src/Simple/Reflection/Reflection.cs @@ -10,6 +10,7 @@ using System; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using System.Reflection; [assembly: TestAssembly] @@ -43,6 +44,7 @@ internal class ReflectionTest TestCreateDelegate.Run(); TestInstanceFields.Run(); TestReflectionInvoke.Run(); + TestByRefReturnInvoke.Run(); return 100; } @@ -89,9 +91,34 @@ internal class ReflectionTest { return "Hello " + _world; } + +#if OPTIMIZED_MODE_WITHOUT_SCANNER + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] +#endif + public static unsafe string GetHelloPointer(char* ptr) + { + return "Hello " + unchecked((int)ptr); + } + +#if OPTIMIZED_MODE_WITHOUT_SCANNER + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] +#endif + public static unsafe string GetHelloPointerToo(char** ptr) + { + return "Hello " + unchecked((int)ptr); + } + +#if OPTIMIZED_MODE_WITHOUT_SCANNER + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] +#endif + public static unsafe bool* GetPointer(void* ptr, object dummyJustToMakeThisUseSharedThunk) + { + return (bool*)ptr; + } + } - public static void Run() + public static unsafe void Run() { Console.WriteLine(nameof(TestReflectionInvoke)); @@ -102,6 +129,9 @@ internal class ReflectionTest InvokeTests.GetHello(null); InvokeTests.GetHelloGeneric(0); InvokeTests.GetHelloGeneric(0); + InvokeTests.GetHelloPointer(null); + InvokeTests.GetHelloPointerToo(null); + InvokeTests.GetPointer(null, null); string unused; InvokeTests.GetHelloByRef(null, out unused); unused.ToString(); @@ -128,6 +158,31 @@ internal class ReflectionTest if ((string)args[1] != "Hello world") throw new Exception(); } + + { + MethodInfo helloPointerMethod = typeof(InvokeTests).GetTypeInfo().GetDeclaredMethod("GetHelloPointer"); + string resultNull = (string)helloPointerMethod.Invoke(null, new object[] { null }); + if (resultNull != "Hello 0") + throw new Exception(); + + string resultVal = (string)helloPointerMethod.Invoke(null, new object[] { Pointer.Box((void*)42, typeof(char*)) }); + if (resultVal != "Hello 42") + throw new Exception(); + } + + { + MethodInfo helloPointerTooMethod = typeof(InvokeTests).GetTypeInfo().GetDeclaredMethod("GetHelloPointerToo"); + string result = (string)helloPointerTooMethod.Invoke(null, new object[] { Pointer.Box((void*)85, typeof(char**)) }); + if (result != "Hello 85") + throw new Exception(); + } + + { + MethodInfo getPointerMethod = typeof(InvokeTests).GetTypeInfo().GetDeclaredMethod("GetPointer"); + object result = getPointerMethod.Invoke(null, new object[] { Pointer.Box((void*)2018, typeof(void*)), null }); + if (Pointer.Unbox(result) != (void*)2018) + throw new Exception(); + } } } @@ -384,7 +439,23 @@ internal class ReflectionTest } } + ref struct ByRefLike + { + public readonly T Value; + + public ByRefLike(T value) + { + Value = value; + } + + public override string ToString() + { + return Value.ToString() + " " + typeof(T).ToString(); + } + } + delegate string ToStringDelegate(ref ByRefLike thisObj); + delegate string ToStringDelegate(ref ByRefLike thisObj); public static void Run() { @@ -396,15 +467,40 @@ internal class ReflectionTest default(ByRefLike).ToString(); ToStringDelegate s = null; s = s.Invoke; + default(ByRefLike).ToString(); + ToStringDelegate s2 = null; + s2 = s2.Invoke; } - Type byRefLikeType = GetTestType(nameof(TestByRefLikeTypeMethod), nameof(ByRefLike)); - MethodInfo toStringMethod = byRefLikeType.GetMethod("ToString"); - var toString = (ToStringDelegate)toStringMethod.CreateDelegate(typeof(ToStringDelegate)); + { + Type byRefLikeType = GetTestType(nameof(TestByRefLikeTypeMethod), nameof(ByRefLike)); + MethodInfo toStringMethod = byRefLikeType.GetMethod("ToString"); + var toString = (ToStringDelegate)toStringMethod.CreateDelegate(typeof(ToStringDelegate)); - ByRefLike foo = new ByRefLike(123); - if (toString(ref foo) != "123") - throw new Exception(); + ByRefLike foo = new ByRefLike(123); + if (toString(ref foo) != "123") + throw new Exception(); + } + + { + Type byRefLikeGenericType = typeof(ByRefLike); + MethodInfo toStringGenericMethod = byRefLikeGenericType.GetMethod("ToString"); + var toStringGeneric = (ToStringDelegate)toStringGenericMethod.CreateDelegate(typeof(ToStringDelegate)); + + ByRefLike fooGeneric = new ByRefLike("Hello"); + if (toStringGeneric(ref fooGeneric) != "Hello System.String") + throw new Exception(); + } + + { + Type byRefLikeGenericType = typeof(ByRefLike); + MethodInfo toStringGenericMethod = byRefLikeGenericType.GetMethod("ToString"); + var toStringGeneric = (ToStringDelegate)toStringGenericMethod.CreateDelegate(typeof(ToStringDelegate)); + + ByRefLike fooGeneric = new ByRefLike("Hello"); + if (toStringGeneric(ref fooGeneric) != "Hello System.Object") + throw new Exception(); + } } } @@ -501,6 +597,203 @@ internal class ReflectionTest } } + class TestByRefReturnInvoke + { + enum Mine { One = 2018 } + + [StructLayout(LayoutKind.Sequential)] + struct BigStruct { public ulong X, Y, Z, W, A, B, C, D; } + + public ref struct ByRefLike { } + + private sealed class TestClass + { + private T _value; + + public TestClass(T value) { _value = value; } + public ref T RefReturningProp + { +#if OPTIMIZED_MODE_WITHOUT_SCANNER + [MethodImpl(MethodImplOptions.NoInlining)] +#endif + get => ref _value; + } +#if OPTIMIZED_MODE_WITHOUT_SCANNER + [MethodImpl(MethodImplOptions.NoInlining)] +#endif + public static unsafe ref ByRefLike ByRefLikeRefReturningMethod(ByRefLike* a) => ref *a; + } + + private sealed unsafe class TestClassIntPointer + { + private int* _value; + + public TestClassIntPointer(int* value) { _value = value; } + public ref int* RefReturningProp + { +#if OPTIMIZED_MODE_WITHOUT_SCANNER + [MethodImpl(MethodImplOptions.NoInlining)] +#endif + get => ref _value; + } + public unsafe ref int* NullRefReturningProp + { +#if OPTIMIZED_MODE_WITHOUT_SCANNER + [MethodImpl(MethodImplOptions.NoInlining)] +#endif + get => ref *(int**)null; + } + } + + public static void TestRefReturnPropertyGetValue() + { + TestRefReturnInvoke('a', (p, t) => p.GetValue(t)); + TestRefReturnInvoke(Mine.One, (p, t) => p.GetValue(t)); + TestRefReturnInvoke("Hello", (p, t) => p.GetValue(t)); + TestRefReturnInvoke(new BigStruct { X = 123, D = 456 }, (p, t) => p.GetValue(t)); + TestRefReturnInvoke(new object(), (p, t) => p.GetValue(t)); + TestRefReturnInvoke((object)null, (p, t) => p.GetValue(t)); + } + + public static void TestRefReturnMethodInvoke() + { + TestRefReturnInvoke(Mine.One, (p, t) => p.GetGetMethod().Invoke(t, Array.Empty())); + TestRefReturnInvoke("Hello", (p, t) => p.GetGetMethod().Invoke(t, Array.Empty())); + TestRefReturnInvoke(new BigStruct { X = 123, D = 456 }, (p, t) => p.GetGetMethod().Invoke(t, Array.Empty())); + TestRefReturnInvoke(new object(), (p, t) => p.GetGetMethod().Invoke(t, Array.Empty())); + TestRefReturnInvoke((object)null, (p, t) => p.GetGetMethod().Invoke(t, Array.Empty())); + } + + public static void TestRefReturnNullable() + { + TestRefReturnInvokeNullable(42); + TestRefReturnInvokeNullable(Mine.One); + TestRefReturnInvokeNullable(new BigStruct { X = 987, D = 543 }); + } + + public static void TestRefReturnNullableNoValue() + { + TestRefReturnInvokeNullable(default(int?)); + TestRefReturnInvokeNullable(default(Mine?)); + TestRefReturnInvokeNullable(default(BigStruct?)); + } + + public static unsafe void TestRefReturnOfPointer() + { + int* expected = (int*)0x1122334455667788; + TestClassIntPointer tc = new TestClassIntPointer(expected); + + if (string.Empty.Length > 0) + { + ((IntPtr)tc.RefReturningProp).ToString(); + } + + PropertyInfo p = typeof(TestClassIntPointer).GetProperty(nameof(TestClassIntPointer.RefReturningProp)); + object rv = p.GetValue(tc); + Assert.True(rv is Pointer); + int* actual = (int*)(Pointer.Unbox(rv)); + Assert.Equal((IntPtr)expected, (IntPtr)actual); + } + + public static unsafe void TestNullRefReturnOfPointer() + { + TestClassIntPointer tc = new TestClassIntPointer(null); + + if (string.Empty.Length > 0) + { + ((IntPtr)tc.NullRefReturningProp).ToString(); + } + + PropertyInfo p = typeof(TestClassIntPointer).GetProperty(nameof(TestClassIntPointer.NullRefReturningProp)); + Assert.NotNull(p); + Assert.Throws(() => p.GetValue(tc)); + } + + public static unsafe void TestByRefLikeRefReturn() + { + if (string.Empty.Length > 0) + { + TestClass.ByRefLikeRefReturningMethod(null); + } + + ByRefLike brl = new ByRefLike(); + ByRefLike* pBrl = &brl; + MethodInfo mi = typeof(TestClass).GetMethod(nameof(TestClass.ByRefLikeRefReturningMethod)); + try + { + // Don't use Assert.Throws because that will make a lambda and invalidate the pointer + object o = mi.Invoke(null, new object[] { Pointer.Box(pBrl, typeof(ByRefLike*)) }); + Assert.Fail(); + } + catch (NotSupportedException) + { + } + } + + private static void TestRefReturnInvoke(T value, Func, object> invoker) + { + TestClass tc = new TestClass(value); + + if (String.Empty.Length > 0) + { + tc.RefReturningProp.ToString(); + } + + PropertyInfo p = typeof(TestClass).GetProperty(nameof(TestClass.RefReturningProp)); + object rv = invoker(p, tc); + if (rv != null) + { + Assert.Equal(typeof(T), rv.GetType()); + } + + if (typeof(T).IsValueType) + { + Assert.Equal(value, rv); + } + else + { + Assert.Same(value, rv); + } + } + + private static void TestRefReturnInvokeNullable(T? nullable) where T : struct + { + TestClass tc = new TestClass(nullable); + + if (string.Empty.Length > 0) + { + tc.RefReturningProp.ToString(); + } + + PropertyInfo p = typeof(TestClass).GetProperty(nameof(TestClass.RefReturningProp)); + object rv = p.GetValue(tc); + if (rv != null) + { + Assert.Equal(typeof(T), rv.GetType()); + } + if (nullable.HasValue) + { + Assert.Equal(nullable.Value, rv); + } + else + { + Assert.Null(rv); + } + } + + public static void Run() + { + Console.WriteLine(nameof(TestByRefReturnInvoke)); + TestRefReturnPropertyGetValue(); + TestRefReturnMethodInvoke(); + TestRefReturnNullable(); + TestRefReturnNullableNoValue(); + TestRefReturnOfPointer(); + TestNullRefReturnOfPointer(); + TestByRefLikeRefReturn(); + } + } + #region Helpers private static Type GetTestType(string testName, string typeName) @@ -534,6 +827,66 @@ internal class ReflectionTest return true; } + class Assert + { + public static void Equal(T expected, T actual) + { + if (object.ReferenceEquals(expected, actual)) + return; + + if ((object)expected == null || (object)actual == null) + throw new Exception(); + + if (!expected.Equals(actual)) + throw new Exception(); + } + + public static void Same(T expected, T actual) + { + if (!object.ReferenceEquals(expected, actual)) + throw new Exception(); + } + + public static void Null(object x) + { + if (x != null) + throw new Exception(); + } + + public static void NotNull(object x) + { + if (x == null) + throw new Exception(); + } + + public static void True(bool x) + { + if (!x) + throw new Exception(); + } + + public static void Fail() + { + throw new Exception(); + } + + public static void Throws(Action a) + { + try + { + a(); + } + catch (Exception ex) + { + if (ex.GetType() != typeof(T)) + throw new Exception(); + return; + } + + throw new Exception(); + } + } + #endregion } diff --git a/external/corert/tests/src/Simple/SharedLibrary/NativeCallable.cs b/external/corert/tests/src/Simple/SharedLibrary/NativeCallable.cs new file mode 100644 index 0000000000..4a080bfcfd --- /dev/null +++ b/external/corert/tests/src/Simple/SharedLibrary/NativeCallable.cs @@ -0,0 +1,14 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Runtime.InteropServices +{ + [AttributeUsage(AttributeTargets.Method)] + public sealed class NativeCallableAttribute : Attribute + { + public string EntryPoint; + public CallingConvention CallingConvention; + public NativeCallableAttribute() { } + } +} \ No newline at end of file diff --git a/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.cmd b/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.cmd new file mode 100644 index 0000000000..2167b8ecfe --- /dev/null +++ b/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.cmd @@ -0,0 +1,12 @@ +@echo off +setlocal +"%1\%2" +set ErrorCode=%ERRORLEVEL% +IF "%ErrorCode%"=="100" ( + echo %~n0: pass + EXIT /b 0 +) ELSE ( + echo %~n0: fail - %ErrorCode% + EXIT /b 1 +) +endlocal diff --git a/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.cpp b/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.cpp new file mode 100644 index 0000000000..f61053689e --- /dev/null +++ b/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.cpp @@ -0,0 +1,66 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +#ifdef _WIN32 +#include "windows.h" +#else +#include "dlfcn.h" +#endif +#include "stdio.h" +#include "string.h" + +#ifndef _WIN32 +#define __stdcall +#endif + +// typedef for shared lib exported methods +typedef int(__stdcall *f_ReturnsPrimitiveInt)(); +typedef bool(__stdcall *f_ReturnsPrimitiveBool)(); +typedef char(__stdcall *f_ReturnsPrimitiveChar)(); +typedef void(__stdcall *f_EnsureManagedClassLoaders)(); + +#ifdef _WIN32 +int main() +#else +int main(int argc, char* argv[]) +#endif +{ +#ifdef _WIN32 + HINSTANCE handle = LoadLibrary("SharedLibrary.dll"); +#elif __APPLE__ + void *handle = dlopen(strcat(argv[0], ".dylib"), RTLD_LAZY); +#else + void *handle = dlopen(strcat(argv[0], ".so"), RTLD_LAZY); +#endif + + if (!handle) + return 1; + +#ifdef _WIN32 + f_ReturnsPrimitiveInt returnsPrimitiveInt = (f_ReturnsPrimitiveInt)GetProcAddress(handle, "ReturnsPrimitiveInt"); + f_ReturnsPrimitiveBool returnsPrimitiveBool = (f_ReturnsPrimitiveBool)GetProcAddress(handle, "ReturnsPrimitiveBool"); + f_ReturnsPrimitiveChar returnsPrimitiveChar = (f_ReturnsPrimitiveChar)GetProcAddress(handle, "ReturnsPrimitiveChar"); + f_EnsureManagedClassLoaders ensureManagedClassLoaders = (f_EnsureManagedClassLoaders)GetProcAddress(handle, "EnsureManagedClassLoaders"); +#else + f_ReturnsPrimitiveInt returnsPrimitiveInt = (f_ReturnsPrimitiveInt)dlsym(handle, "ReturnsPrimitiveInt"); + f_ReturnsPrimitiveBool returnsPrimitiveBool = (f_ReturnsPrimitiveBool)dlsym(handle, "ReturnsPrimitiveBool"); + f_ReturnsPrimitiveChar returnsPrimitiveChar = (f_ReturnsPrimitiveChar)dlsym(handle, "ReturnsPrimitiveChar"); + f_EnsureManagedClassLoaders ensureManagedClassLoaders = (f_EnsureManagedClassLoaders)dlsym(handle, "EnsureManagedClassLoaders"); +#endif + + if (returnsPrimitiveInt() != 10) + return 1; + + if (!returnsPrimitiveBool()) + return 1; + + if (returnsPrimitiveChar() != 'a') + return 1; + + // As long as no unmanaged exception is thrown + // managed class loaders were initialized successfully + ensureManagedClassLoaders(); + + return 100; +} diff --git a/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.cs b/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.cs new file mode 100644 index 0000000000..78fd2c9a1a --- /dev/null +++ b/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.cs @@ -0,0 +1,37 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.InteropServices; + +namespace SharedLibrary +{ + public class ClassLibrary + { + [NativeCallable(EntryPoint = "ReturnsPrimitiveInt", CallingConvention = CallingConvention.StdCall)] + public static int ReturnsPrimitiveInt() + { + return 10; + } + + [NativeCallable(EntryPoint = "ReturnsPrimitiveBool", CallingConvention = CallingConvention.StdCall)] + public static bool ReturnsPrimitiveBool() + { + return true; + } + + [NativeCallable(EntryPoint = "ReturnsPrimitiveChar", CallingConvention = CallingConvention.StdCall)] + public static char ReturnsPrimitiveChar() + { + return 'a'; + } + + [NativeCallable(EntryPoint = "EnsureManagedClassLoaders", CallingConvention = CallingConvention.StdCall)] + public static void EnsureManagedClassLoaders() + { + Random random = new Random(); + random.Next(); + } + } +} diff --git a/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.csproj b/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.csproj new file mode 100644 index 0000000000..5bfa784b93 --- /dev/null +++ b/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.csproj @@ -0,0 +1,35 @@ + + + + Library + Shared + + + + + + + + + $(NativeOutputPath)SharedLibrary + + + + + + + + + + + + + + + + + + + + + diff --git a/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.sh b/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.sh new file mode 100755 index 0000000000..6640f629fc --- /dev/null +++ b/external/corert/tests/src/Simple/SharedLibrary/SharedLibrary.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +$1/$2 +if [ $? == 100 ]; then + echo pass + exit 0 +else + echo fail + exit 1 +fi diff --git a/external/corert/tests/src/Simple/Interfaces/no_cpp b/external/corert/tests/src/Simple/SharedLibrary/no_cpp similarity index 100% rename from external/corert/tests/src/Simple/Interfaces/no_cpp rename to external/corert/tests/src/Simple/SharedLibrary/no_cpp diff --git a/external/corert/tests/src/Simple/SharedLibrary/no_linux b/external/corert/tests/src/Simple/SharedLibrary/no_linux new file mode 100644 index 0000000000..872fb9d56f --- /dev/null +++ b/external/corert/tests/src/Simple/SharedLibrary/no_linux @@ -0,0 +1 @@ +Skip this test for linux diff --git a/external/corert/tests/src/Simple/SimpleTest.targets b/external/corert/tests/src/Simple/SimpleTest.targets index aae9489711..9a018e7eb5 100644 --- a/external/corert/tests/src/Simple/SimpleTest.targets +++ b/external/corert/tests/src/Simple/SimpleTest.targets @@ -13,7 +13,7 @@ false true .NETCoreApp - netcoreapp2.0 + netcoreapp2.1 diff --git a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs b/external/corert/tests/src/Simple/StaticLibrary/NativeCallable.cs similarity index 59% rename from external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs rename to external/corert/tests/src/Simple/StaticLibrary/NativeCallable.cs index 32fc295932..a96a6c793a 100644 --- a/external/corert/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs +++ b/external/corert/tests/src/Simple/StaticLibrary/NativeCallable.cs @@ -2,23 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Runtime.CompilerServices; - namespace System.Runtime.InteropServices { - //BARTOK expects [AttributeUsage(AttributeTargets.Method)] public sealed class NativeCallableAttribute : Attribute { - // Optional. If omitted, then the method is native callable, but no EAT is emitted. public string EntryPoint; - - // Optional. If omitted a default will be chosen by the compiler. public CallingConvention CallingConvention; - - public NativeCallableAttribute() - { - } + public NativeCallableAttribute() { } } } diff --git a/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.cmd b/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.cmd new file mode 100644 index 0000000000..2167b8ecfe --- /dev/null +++ b/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.cmd @@ -0,0 +1,12 @@ +@echo off +setlocal +"%1\%2" +set ErrorCode=%ERRORLEVEL% +IF "%ErrorCode%"=="100" ( + echo %~n0: pass + EXIT /b 0 +) ELSE ( + echo %~n0: fail - %ErrorCode% + EXIT /b 1 +) +endlocal diff --git a/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.cpp b/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.cpp new file mode 100644 index 0000000000..25674cf25d --- /dev/null +++ b/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.cpp @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +#include "stdio.h" + +extern "C" int Add(int a, int b); +extern "C" int Subtract(int a, int b); +extern "C" bool Not(bool b); + +int main() +{ + if (Add(2, 3) != 5) + return 1; + + if (Subtract(3, 1) != 2) + return 1; + + if (!Not(false)) + return 1; + + return 100; +} diff --git a/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.cs b/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.cs new file mode 100644 index 0000000000..3e7f6e78c2 --- /dev/null +++ b/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.cs @@ -0,0 +1,30 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.InteropServices; + +namespace StaticLibrary +{ + public class ClassLibrary + { + [NativeCallable(EntryPoint = "Add", CallingConvention = CallingConvention.StdCall)] + public static int Add(int a, int b) + { + return a + b; + } + + [NativeCallable(EntryPoint = "Subtract", CallingConvention = CallingConvention.StdCall)] + public static int Subtract(int a, int b) + { + return a - b; + } + + [NativeCallable(EntryPoint = "Not", CallingConvention = CallingConvention.StdCall)] + public static bool Not(bool b) + { + return !b; + } + } +} diff --git a/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.csproj b/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.csproj new file mode 100644 index 0000000000..591b8644b3 --- /dev/null +++ b/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.csproj @@ -0,0 +1,53 @@ + + + + Library + Static + + + + + + + + + $(NativeOutputPath)StaticLibrary + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.sh b/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.sh new file mode 100755 index 0000000000..6640f629fc --- /dev/null +++ b/external/corert/tests/src/Simple/StaticLibrary/StaticLibrary.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +$1/$2 +if [ $? == 100 ]; then + echo pass + exit 0 +else + echo fail + exit 1 +fi diff --git a/external/corert/tests/src/Simple/StaticLibrary/no_cpp b/external/corert/tests/src/Simple/StaticLibrary/no_cpp new file mode 100644 index 0000000000..639bcaf8ba --- /dev/null +++ b/external/corert/tests/src/Simple/StaticLibrary/no_cpp @@ -0,0 +1 @@ +Skip this test for cpp codegen mode diff --git a/external/linker/README.md b/external/linker/README.md index d7c34548c7..3e45109822 100644 --- a/external/linker/README.md +++ b/external/linker/README.md @@ -21,3 +21,95 @@ TODO ## Build & Test Status [![Build Status](https://jenkins.mono-project.com/buildStatus/icon?job=test-linker-mainline)](https://jenkins.mono-project.com/job/test-linker-mainline/) + +## Link xml file examples + +A link xml file can be used to explicitly preserve assemblies, types, and members. Below is a sample file containing examples of various usages. + +```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` diff --git a/external/linker/linker/Linker.Steps/LoadReferencesStep.cs b/external/linker/linker/Linker.Steps/LoadReferencesStep.cs index 6d6cada511..5cd56d3795 100644 --- a/external/linker/linker/Linker.Steps/LoadReferencesStep.cs +++ b/external/linker/linker/Linker.Steps/LoadReferencesStep.cs @@ -34,21 +34,19 @@ using Mono.Cecil; namespace Mono.Linker.Steps { public class LoadReferencesStep : BaseStep { - - readonly Dictionary _references = new Dictionary (); + + readonly HashSet references = new HashSet (); protected override void ProcessAssembly (AssemblyDefinition assembly) { ProcessReferences (assembly); } - void ProcessReferences (AssemblyDefinition assembly) + protected void ProcessReferences (AssemblyDefinition assembly) { - if (_references.ContainsKey (assembly.Name)) + if (!references.Add (assembly.Name)) return; - _references.Add (assembly.Name, assembly); - Context.RegisterAssembly (assembly); foreach (AssemblyDefinition referenceDefinition in Context.ResolveReferences (assembly)) { diff --git a/external/linker/linker/Linker.Steps/MarkStep.cs b/external/linker/linker/Linker.Steps/MarkStep.cs index f93c75bf18..fb7958c2db 100644 --- a/external/linker/linker/Linker.Steps/MarkStep.cs +++ b/external/linker/linker/Linker.Steps/MarkStep.cs @@ -253,8 +253,8 @@ namespace Mono.Linker.Steps { Tracer.Push (provider); try { foreach (CustomAttribute ca in provider.CustomAttributes) { - if (IsUserDependencyMarker (ca.AttributeType)) { - MarkUserDependency (provider as MethodReference, ca); + if (IsUserDependencyMarker (ca.AttributeType) && provider is MemberReference mr) { + MarkUserDependency (mr, ca); continue; } @@ -274,14 +274,13 @@ namespace Mono.Linker.Steps { protected virtual bool IsUserDependencyMarker (TypeReference type) { - return type.Name == "PreserveDependencyAttribute" && - type.Namespace == "System.Runtime.CompilerServices"; + return PreserveDependencyLookupStep.IsPreserveDependencyAttribute (type); } - protected virtual void MarkUserDependency (MethodReference context, CustomAttribute ca) + protected virtual void MarkUserDependency (MemberReference context, CustomAttribute ca) { - var args = ca.ConstructorArguments; - if (args.Count == 2 && args[1].Value is string condition) { + if (ca.HasProperties && ca.Properties [0].Name == "Condition") { + var condition = ca.Properties [0].Argument.Value as string; switch (condition) { case "": case null: @@ -297,57 +296,51 @@ namespace Mono.Linker.Steps { } } - if (args.Count >= 1 && args[0].Value is string dependency) { - string member = null; - string type = null; - string[] signature = null; - TypeDefinition td = null; - - var sign_start = dependency.IndexOf ('('); - var sign_end = dependency.LastIndexOf (')'); - if (sign_start > 0 && sign_end > sign_start) { - var parameters = dependency.Substring (sign_start + 1, sign_end - sign_start - 1).Replace (" ", ""); - signature = string.IsNullOrEmpty (parameters) ? Array.Empty () : parameters.Split (','); - var idx = dependency.LastIndexOf ('.', sign_start); - if (idx > 0) { - member = dependency.Substring (idx + 1, sign_start - idx - 1).TrimEnd (); - type = dependency.Substring (0, idx); - } else { - member = dependency.Substring (0, sign_start - 1); - td = context.DeclaringType.Resolve (); - } - } else if (sign_start < 0) { - var idx = dependency.LastIndexOf ('.'); - if (idx > 0) { - member = dependency.Substring (idx + 1); - type = dependency.Substring (0, idx); - } else { - member = dependency; - td = context.DeclaringType.Resolve (); - } + AssemblyDefinition assembly; + var args = ca.ConstructorArguments; + if (args.Count >= 3 && args [2].Value is string assemblyName) { + if (!_context.Resolver.AssemblyCache.TryGetValue (assemblyName, out assembly)) { + _context.Logger.LogMessage (MessageImportance.Low, $"Could not resolve '{assemblyName}' assembly dependency"); + return; } + } else { + assembly = null; + } + + TypeDefinition td = null; + if (args.Count >= 2 && args [1].Value is string typeName) { + td = FindType (assembly ?? context.Module.Assembly, typeName); if (td == null) { - if (type == null) { - _context.Logger.LogMessage (MessageImportance.Low, $"Could not resolve '{dependency}' dependency"); - return; - } - - td = FindType (context.Module.Assembly, type); - if (td == null) { - _context.Logger.LogMessage (MessageImportance.Low, $"Could not find '{dependency}' dependency"); - return; - } + _context.Logger.LogMessage (MessageImportance.Low, $"Could not resolve '{typeName}' type dependency"); + return; } - - if (MarkDependencyMethod (td, member, signature)) - return; - - if (MarkDependencyField (td, member)) - return; - - _context.Logger.LogMessage (MessageImportance.High, $"Could not resolve dependency member '{member}' declared in type '{dependency}'"); + } else { + td = context.DeclaringType.Resolve (); } + + string member = null; + string[] signature = null; + if (args.Count >= 1 && args [0].Value is string memberSignature) { + memberSignature = memberSignature.Replace (" ", ""); + var sign_start = memberSignature.IndexOf ('('); + var sign_end = memberSignature.LastIndexOf (')'); + if (sign_start > 0 && sign_end > sign_start) { + var parameters = memberSignature.Substring (sign_start + 1, sign_end - sign_start - 1); + signature = string.IsNullOrEmpty (parameters) ? Array.Empty () : parameters.Split (','); + member = memberSignature.Substring (0, sign_start); + } else { + member = memberSignature; + } + } + + if (MarkDependencyMethod (td, member, signature)) + return; + + if (MarkDependencyField (td, member)) + return; + + _context.Logger.LogMessage (MessageImportance.High, $"Could not resolve dependency member '{member}' declared in type '{td.FullName}'"); } static TypeDefinition FindType (AssemblyDefinition assembly, string fullName) @@ -460,6 +453,9 @@ namespace Mono.Linker.Steps { case "System.ThreadStaticAttribute": case "System.ContextStaticAttribute": return true; + case "System.Runtime.InteropServices.InterfaceTypeAttribute": + case "System.Runtime.InteropServices.GuidAttribute": + return !_context.IsFeatureExcluded ("com"); } if (!Annotations.IsMarked (attr_type.Resolve ())) @@ -480,7 +476,7 @@ namespace Mono.Linker.Steps { // then surely nothing is using this attribute and there is no need to mark it if (!Annotations.IsMarked (resolvedConstructor.Module) && !Annotations.IsMarked (ca.AttributeType)) return false; - + if (ca.Constructor.DeclaringType.Namespace == "System.Diagnostics") { string attributeName = ca.Constructor.DeclaringType.Name; if (attributeName == "DebuggerDisplayAttribute" || attributeName == "DebuggerTypeProxyAttribute") { @@ -815,6 +811,7 @@ namespace Mono.Linker.Steps { MarkType (field.FieldType); MarkCustomAttributes (field); MarkMarshalSpec (field); + DoAdditionalFieldProcessing (field); Annotations.Mark (field); } @@ -930,8 +927,23 @@ namespace Mono.Linker.Steps { { } - // Allow subclassers to mark additional things when marking a method - protected virtual void DoAdditionalTypeProcessing (TypeDefinition method) + // Allow subclassers to mark additional things + protected virtual void DoAdditionalTypeProcessing (TypeDefinition type) + { + } + + // Allow subclassers to mark additional things + protected virtual void DoAdditionalFieldProcessing (FieldDefinition field) + { + } + + // Allow subclassers to mark additional things + protected virtual void DoAdditionalPropertyProcessing (PropertyDefinition property) + { + } + + // Allow subclassers to mark additional things + protected virtual void DoAdditionalEventProcessing (EventDefinition evt) { } @@ -1744,6 +1756,7 @@ namespace Mono.Linker.Steps { protected void MarkProperty (PropertyDefinition prop) { MarkCustomAttributes (prop); + DoAdditionalPropertyProcessing (prop); } protected virtual void MarkEvent (EventDefinition evt) @@ -1752,6 +1765,7 @@ namespace Mono.Linker.Steps { MarkMethodIfNotNull (evt.AddMethod); MarkMethodIfNotNull (evt.InvokeMethod); MarkMethodIfNotNull (evt.RemoveMethod); + DoAdditionalEventProcessing (evt); } void MarkMethodIfNotNull (MethodReference method) @@ -1856,7 +1870,6 @@ namespace Mono.Linker.Steps { if (!CheckReflectionMethod (instruction, reflectionMethod)) continue; - _context.Tracer.Push ($"Reflection-{instruction.Operand as MethodReference}"); var nameOfThingUsedViaReflection = OperandOfNearestInstructionBefore (i, OpCodes.Ldstr, instructions); var bindingFlags = (BindingFlags) OperandOfNearestInstructionBefore (i, OpCodes.Ldc_I4_S, instructions); @@ -1868,7 +1881,6 @@ namespace Mono.Linker.Steps { if (typeDefinition != null) markMethod (instructions, nameOfThingUsedViaReflection, typeDefinition, bindingFlags); } - _context.Tracer.Pop (); } } @@ -1880,32 +1892,44 @@ namespace Mono.Linker.Steps { if (!CheckReflectionMethod (instruction, "GetType")) continue; - _context.Tracer.Push ($"Reflection-{instruction.Operand as MethodReference}"); var typeAssemblyQualifiedName = OperandOfNearestInstructionBefore (i, OpCodes.Ldstr, instructions); if (!TypeNameParser.TryParseTypeAssemblyQualifiedName (typeAssemblyQualifiedName, out string typeName, out string assemblyName)) continue; + TypeDefinition foundType = null; foreach (var assemblyDefinition in _context.GetAssemblies ()) { if (assemblyName != null && assemblyDefinition.Name.Name != assemblyName) continue; - var type = assemblyDefinition.MainModule.GetType (typeName); - if (type != null) - { - MarkType(type); + foundType = assemblyDefinition.MainModule.GetType (typeName); + if (foundType != null) break; - } } - _context.Tracer.Pop (); + + if (foundType == null) + continue; + + _context.Tracer.Push ($"Reflection-{foundType}"); + try { + MarkType (foundType); + } finally { + _context.Tracer.Pop (); + } } } void MarkConstructorsUsedViaReflection (Collection instructions, string unused, TypeDefinition declaringType, BindingFlags bindingFlags) { foreach (var method in declaringType.Methods) { - if ((bindingFlags == BindingFlags.Default || bindingFlags.IsSet(BindingFlags.Public) == method.IsPublic) && method.Name == ".ctor") - MarkMethod (method); + if ((bindingFlags == BindingFlags.Default || bindingFlags.IsSet(BindingFlags.Public) == method.IsPublic) && method.Name == ".ctor") { + Tracer.Push ($"Reflection-{method}"); + try { + MarkMethod (method); + } finally { + Tracer.Pop (); + } + } } } @@ -1916,8 +1940,14 @@ namespace Mono.Linker.Steps { foreach (var method in declaringType.Methods) { if ((bindingFlags == BindingFlags.Default || bindingFlags.IsSet(BindingFlags.Public) == method.IsPublic && bindingFlags.IsSet(BindingFlags.Static) == method.IsStatic) - && method.Name == name) - MarkMethod (method); + && method.Name == name) { + Tracer.Push ($"Reflection-{method}"); + try { + MarkMethod (method); + } finally { + Tracer.Pop (); + } + } } } @@ -1928,11 +1958,16 @@ namespace Mono.Linker.Steps { foreach (var property in declaringType.Properties) { if (property.Name == name) { - // It is not easy to reliably detect in the IL code whether the getter or setter (or both) are used. - // Be conservative and mark everything for the property. - MarkProperty (property); - MarkMethodIfNotNull (property.GetMethod); - MarkMethodIfNotNull (property.SetMethod); + Tracer.Push ($"Reflection-{property}"); + try { + // It is not easy to reliably detect in the IL code whether the getter or setter (or both) are used. + // Be conservative and mark everything for the property. + MarkProperty (property); + MarkMethodIfNotNull (property.GetMethod); + MarkMethodIfNotNull (property.SetMethod); + } finally { + Tracer.Pop (); + } } } } @@ -1943,8 +1978,14 @@ namespace Mono.Linker.Steps { return; foreach (var field in declaringType.Fields) { - if (field.Name == name) - MarkField (field); + if (field.Name == name) { + Tracer.Push ($"Reflection-{field}"); + try { + MarkField (field); + } finally { + Tracer.Pop (); + } + } } } @@ -1954,8 +1995,14 @@ namespace Mono.Linker.Steps { return; foreach (var eventInfo in declaringType.Events) { - if (eventInfo.Name == name) - MarkEvent (eventInfo); + if (eventInfo.Name == name) { + Tracer.Push ($"Reflection-{eventInfo}"); + try { + MarkEvent (eventInfo); + } finally { + Tracer.Pop (); + } + } } } diff --git a/external/linker/linker/Linker.Steps/PreserveDependencyLookupStep.cs b/external/linker/linker/Linker.Steps/PreserveDependencyLookupStep.cs new file mode 100644 index 0000000000..d68ec51c73 --- /dev/null +++ b/external/linker/linker/Linker.Steps/PreserveDependencyLookupStep.cs @@ -0,0 +1,86 @@ +// +// PreserveDependencyLookupStep.cs +// +// Author: +// Marek Safar (marek.safar@gmail.com) +// +// Copyright (C) 2018 Microsoft Corporation +// +// 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 System; +using Mono.Cecil; +using Mono.Collections.Generic; + +namespace Mono.Linker.Steps { + public class PreserveDependencyLookupStep : LoadReferencesStep { + protected override void ProcessAssembly (AssemblyDefinition assembly) + { + var module = assembly.MainModule; + + foreach (var type in module.Types) { + if (type.HasMethods) { + foreach (var method in type.GetMethods ()) { + var md = method.Resolve (); + if (md?.HasCustomAttributes != true) + continue; + + ProcessPreserveDependencyAttribute (md.CustomAttributes); + } + } + + if (type.HasFields) { + foreach (var field in type.Fields) { + var md = field.Resolve (); + if (md?.HasCustomAttributes != true) + continue; + + ProcessPreserveDependencyAttribute (md.CustomAttributes); + } + } + } + } + + public static bool IsPreserveDependencyAttribute (TypeReference tr) + { + return tr.Name == "PreserveDependencyAttribute" && tr.Namespace == "System.Runtime.CompilerServices"; + } + + void ProcessPreserveDependencyAttribute (Collection attributes) + { + foreach (var ca in attributes) { + if (!IsPreserveDependencyAttribute (ca.AttributeType)) + continue; + + if (ca.ConstructorArguments.Count != 3) + continue; + + var assemblyName = ca.ConstructorArguments [2].Value as string; + if (assemblyName == null) + continue; + + var newDependency = Context.Resolve (new AssemblyNameReference (assemblyName, new Version ())); + if (newDependency != null) + ProcessReferences (newDependency); + } + } + } +} diff --git a/external/linker/linker/Linker.Steps/SweepStep.cs b/external/linker/linker/Linker.Steps/SweepStep.cs index 695e2c220b..3ed73c196e 100644 --- a/external/linker/linker/Linker.Steps/SweepStep.cs +++ b/external/linker/linker/Linker.Steps/SweepStep.cs @@ -50,7 +50,7 @@ namespace Mono.Linker.Steps { { assemblies = Context.Annotations.GetAssemblies ().ToArray (); foreach (var assembly in assemblies) { - SweepAssembly (assembly); + ProcessAssemblyAction (assembly); if ((Annotations.GetAction (assembly) == AssemblyAction.Copy) && !Context.KeepTypeForwarderOnlyAssemblies) { // Copy assemblies can still contain Type references with @@ -73,36 +73,41 @@ namespace Mono.Linker.Steps { } } - protected virtual void SweepAssembly (AssemblyDefinition assembly) + protected void ProcessAssemblyAction (AssemblyDefinition assembly) { switch (Annotations.GetAction (assembly)) { - case AssemblyAction.Link: - if (!IsMarkedAssembly (assembly)) { - RemoveAssembly (assembly); + case AssemblyAction.Link: + if (!IsMarkedAssembly (assembly)) { + RemoveAssembly (assembly); + return; + } + break; + + case AssemblyAction.AddBypassNGenUsed: + if (!IsMarkedAssembly (assembly)) { + RemoveAssembly (assembly); + } else { + Annotations.SetAction (assembly, AssemblyAction.AddBypassNGen); + } return; - } - break; - case AssemblyAction.AddBypassNGenUsed: - if (!IsMarkedAssembly (assembly)) { - RemoveAssembly (assembly); - } else { - Annotations.SetAction (assembly, AssemblyAction.AddBypassNGen); - } - return; + case AssemblyAction.CopyUsed: + if (!IsMarkedAssembly (assembly)) { + RemoveAssembly (assembly); + } else { + Annotations.SetAction (assembly, AssemblyAction.Copy); + } + return; - case AssemblyAction.CopyUsed: - if (!IsMarkedAssembly (assembly)) { - RemoveAssembly (assembly); - } else { - Annotations.SetAction (assembly, AssemblyAction.Copy); - } - return; - - default: - return; + default: + return; } + + SweepAssembly (assembly); + } + protected virtual void SweepAssembly (AssemblyDefinition assembly) + { var types = new List (); foreach (TypeDefinition type in assembly.MainModule.Types) { @@ -134,7 +139,7 @@ namespace Mono.Linker.Steps { return Annotations.IsMarked (assembly.MainModule); } - void RemoveAssembly (AssemblyDefinition assembly) + protected virtual void RemoveAssembly (AssemblyDefinition assembly) { Annotations.SetAction (assembly, AssemblyAction.Delete); @@ -394,6 +399,8 @@ namespace Mono.Linker.Steps { foreach (var parameter in method.Parameters) SweepCustomAttributes (parameter); + + SweepCustomAttributes (method.MethodReturnType); } } diff --git a/external/linker/linker/Linker/Driver.cs b/external/linker/linker/Linker/Driver.cs index 6c49e2537c..8a380db365 100644 --- a/external/linker/linker/Linker/Driver.cs +++ b/external/linker/linker/Linker/Driver.cs @@ -434,6 +434,7 @@ namespace Mono.Linker { Pipeline p = new Pipeline (); p.AppendStep (new LoadReferencesStep ()); p.AppendStep (new BlacklistStep ()); + p.AppendStep (new PreserveDependencyLookupStep ()); p.AppendStep (new TypeMapStep ()); p.AppendStep (new MarkStep ()); p.AppendStep (new SweepStep ()); diff --git a/external/linker/linker/Linker/Pipeline.cs b/external/linker/linker/Linker/Pipeline.cs index bf4ca82385..a28de3ba1b 100644 --- a/external/linker/linker/Linker/Pipeline.cs +++ b/external/linker/linker/Linker/Pipeline.cs @@ -123,12 +123,17 @@ namespace Mono.Linker { { while (_steps.Count > 0) { IStep step = _steps [0]; - context.Tracer.Push (step); - step.Process (context); - context.Tracer.Pop (); + ProcessStep (context, step); _steps.Remove (step); } } + + protected virtual void ProcessStep (LinkContext context, IStep step) + { + context.Tracer.Push (step); + step.Process (context); + context.Tracer.Pop (); + } public IStep [] GetSteps () { diff --git a/external/linker/linker/Mono.Linker.csproj b/external/linker/linker/Mono.Linker.csproj index ca391a4b4a..d3284919df 100644 --- a/external/linker/linker/Mono.Linker.csproj +++ b/external/linker/linker/Mono.Linker.csproj @@ -99,6 +99,7 @@ + diff --git a/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Helpers/TempRoot.cs b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Helpers/TempRoot.cs index 7cda580b2d..004171bb1b 100644 --- a/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Helpers/TempRoot.cs +++ b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Helpers/TempRoot.cs @@ -54,9 +54,9 @@ namespace Microsoft.NuGet.Build.Tasks.Tests.Helpers return dir; } - public TempFile CreateFile(TempRoot root, string prefix = null, string extension = null, string directory = null, [CallerFilePath]string callerSourcePath = null, [CallerLineNumber]int callerLineNumber = 0) + public TempFile CreateFile(string prefix = null, string extension = null, string directory = null, [CallerFilePath]string callerSourcePath = null, [CallerLineNumber]int callerLineNumber = 0) { - return AddFile(new DisposableFile(root, prefix, extension, directory, callerSourcePath, callerLineNumber)); + return AddFile(new DisposableFile(this, prefix, extension, directory, callerSourcePath, callerLineNumber)); } public DisposableFile AddFile(DisposableFile file) diff --git a/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Json/Json.Designer.cs b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Json/Json.Designer.cs index e75ea945e1..9137dec9ca 100644 --- a/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Json/Json.Designer.cs +++ b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Json/Json.Designer.cs @@ -358,5 +358,25 @@ namespace Microsoft.NuGet.Build.Tasks.Tests.Json { return ResourceManager.GetString("Win10_xunit", resourceCulture); } } + + /// + /// Looks up a localized resource of type System.Byte[]. + /// + internal static byte[] WithoutTargets_assets { + get { + object obj = ResourceManager.GetObject("WithoutTargets_assets", resourceCulture); + return ((byte[])(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Byte[]. + /// + internal static byte[] WithTargets_assets { + get { + object obj = ResourceManager.GetObject("WithTargets_assets", resourceCulture); + return ((byte[])(obj)); + } + } } } diff --git a/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Json/Json.resx b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Json/Json.resx index 993a1fef5b..0286e1b9fe 100644 --- a/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Json/Json.resx +++ b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Json/Json.resx @@ -151,4 +151,10 @@ multipleprojectfiledependencygroups_casemismatch.json;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + WithoutTargets.assets.json;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + WithTargets.assets.json;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + \ No newline at end of file diff --git a/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Json/WithTargets.assets.json b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Json/WithTargets.assets.json new file mode 100644 index 0000000000..bef673f774 --- /dev/null +++ b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Json/WithTargets.assets.json @@ -0,0 +1,51 @@ +{ + "version": 2, + "targets": { + ".NETFramework,Version=v4.5": { + "System.Text/4.5.0": { + "type": "package", + "dependencies": { + "System": "4.5.0" + }, + "compile": { + "ref/net45/System.Text.dll": {} + } + } + } + }, + "libraries": { + "System.Text/4.5.0": { + "type": "package", + "path": "system.text/4.5.0" + } + }, + "projectFileDependencyGroups": {}, + "project": { + "version": "1.0.0", + "restore": { + "projectUniqueName": "X:\\ProjectPath\\ProjectPath.csproj", + "projectName": "ProjectPath", + "projectPath": "X:\\ProjectPath\\ProjectPath.csproj", + "outputPath": "X:\\ProjectPath\\obj\\", + "projectStyle": "PackageReference", + "originalTargetFrameworks": [ + "net45" + ], + "frameworks": { + "net45": { + "projectReferences": {} + } + } + }, + "frameworks": { + "net45": { + "dependencies": { + "System.Text": { + "target": "Package", + "version": "[4.5.0, )" + } + } + } + } + } +} \ No newline at end of file diff --git a/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Json/WithoutTargets.assets.json b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Json/WithoutTargets.assets.json new file mode 100644 index 0000000000..4eae5df02c --- /dev/null +++ b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Json/WithoutTargets.assets.json @@ -0,0 +1,39 @@ +{ + "version": 2, + "targets": {}, + "libraries": { + "System.Text/4.5.0": { + "type": "package", + "path": "system.text/4.5.0" + } + }, + "projectFileDependencyGroups": {}, + "project": { + "version": "1.0.0", + "restore": { + "projectUniqueName": "X:\\ProjectPath\\ProjectPath.csproj", + "projectName": "ProjectPath", + "projectPath": "X:\\ProjectPath\\ProjectPath.csproj", + "outputPath": "X:\\ProjectPath\\obj\\", + "projectStyle": "PackageReference", + "originalTargetFrameworks": [ + "net45" + ], + "frameworks": { + "net45": { + "projectReferences": {} + } + } + }, + "frameworks": { + "net45": { + "dependencies": { + "System.Text": { + "target": "Package", + "version": "[4.5.0, )" + } + } + } + } + } +} \ No newline at end of file diff --git a/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Microsoft.NuGet.Build.Tasks.Tests.csproj b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Microsoft.NuGet.Build.Tasks.Tests.csproj index 342af76599..83774b45ff 100644 --- a/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Microsoft.NuGet.Build.Tasks.Tests.csproj +++ b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks.Tests/Microsoft.NuGet.Build.Tasks.Tests.csproj @@ -9,7 +9,7 @@ Properties Microsoft.NuGet.Build.Tasks.Tests Microsoft.NuGet.Build.Tasks.Tests - v4.5 + v4.6.2 512 true @@ -72,7 +72,9 @@ - + + Designer + @@ -83,8 +85,9 @@ - + + @@ -92,6 +95,7 @@ ResXFileCodeGenerator Json.Designer.cs + Designer ResXFileCodeGenerator @@ -101,6 +105,16 @@ + + + 2.3.1 + + + 2.3.1 + runtime; build; native; contentfiles; analyzers + all + + + + + <_HandlePackageFileConflictsAfter>$(_HandlePackageFileConflictsAfter);ResolveNuGetPackageAssetsNonAOT + + + - - + + + + + + - - %(NonAheadOfTimeRuntimeImplementations.FullPath) - %(NonAheadOfTimeRuntimeImplementations.FullPath) + + + + + <_ReferencesFromNuGetPackages Remove="%(ReferencePath.FileName)" Condition="'%(ReferencePath.ResolvedFrom)' == 'ImplicitlyExpandTargetFramework'" /> + + + + <_ResolvedProjectReferencePaths Include="@(_ReferencesFromNuGetPackages)" Condition="'%(_ReferencesFromNuGetPackages.NuGetSourceType)' == 'Project'" /> + + + + + + + + true + + + + + + + + + + + + + %(ReferenceCopyLocalPaths.FullPath) + %(ReferenceCopyLocalPaths.FullPath) @@ -264,7 +329,7 @@ Copyright (c) .NET Foundation. All rights reserved. --> .NETCore,Version=v5.0 - UAP,Version=v10.0.15138 + UAP,Version=v10.0.15138 .NETCore,Version=v5.0 <_ComputeNetCoreFrameworkInjectionParametersBeforeTargets Condition="'$(AppxPackage)' == 'true' and '$(TargetPlatformIdentifier)' == 'UAP'">BeforeGenerateProjectPriFile @@ -298,14 +363,14 @@ Copyright (c) .NET Foundation. All rights reserved. @(_NuGetInjectionSourceDirectories->'%(Identity)\RS2.project.lock.json') - @(_NuGetInjectionSourceDirectories->'%(Identity)\RS3.project.lock.json') + @(_NuGetInjectionSourceDirectories->'%(Identity)\RS3.project.lock.json') @(_NuGetInjectionSourceDirectories->'%(Identity)\project.lock.json') .NETCore,Version=v5.0 @(_NuGetInjectionSourceDirectories->'%(Identity)\project.lock.json') - $([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\NuGet\Repository', 'NETCoreSDK', null, RegistryView.Registry32, RegistryView.Default)) + $([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\NuGet\Repository', 'UWPNugetPackages', null, RegistryView.Registry32, RegistryView.Default)) _analyzers = new List(); private readonly List _copyLocalItems = new List(); private readonly List _references = new List(); @@ -215,7 +217,11 @@ namespace Microsoft.NuGet.Build.Tasks { if (!_fileExists(ProjectLockFile)) { - throw new ExceptionFromResource(nameof(Strings.LockFileNotFound), ProjectLockFile); + var errorMessage = IsLockFileProjectJsonBased(ProjectLockFile) ? + nameof(Strings.LockFileNotFoundForProjectJson) : + nameof(Strings.LockFileNotFoundForProjectFile); + + throw new ExceptionFromResource(errorMessage, ProjectLockFile); } JObject lockFile; @@ -688,7 +694,7 @@ namespace Microsoft.NuGet.Build.Tasks } else { - ThrowExceptionIfNotAllowingFallback(nameof(Strings.MissingFramework), TargetMonikers.First().ItemSpec); + GiveErrorForMissingFramework(); } // If we're still here, that means we're allowing fallback, so let's try @@ -707,23 +713,47 @@ namespace Microsoft.NuGet.Build.Tasks var firstTarget = (JObject)enumerableTargets.FirstOrDefault().Value; if (firstTarget == null) { - throw new ExceptionFromResource(nameof(Strings.NoTargetsInLockFile)); + GiveErrorForNoTargets(); } return firstTarget; } + private void GiveErrorForNoTargets() + { + var noTargetsInLockFileErrorString = IsLockFileProjectJsonBased(ProjectLockFile) ? + nameof(Strings.NoTargetsInLockFileForProjectJson) : + nameof(Strings.NoTargetsInLockFileForProjectFile); + + throw new ExceptionFromResource(noTargetsInLockFileErrorString); + } + private void GiveErrorForMissingRuntimeIdentifier() { - string runtimePiece = '"' + RuntimeIdentifier + "\": { }"; + var runtimePiece = RuntimeIdentifier; + var runtimesSection = $"<{RuntimeIdentifiersProperty}>{RuntimeIdentifier}"; + var missingRuntimeInRuntimesErrorString = nameof(Strings.MissingRuntimeIdentifierInProjectFile); + var missingRuntimesErrorString = nameof(Strings.MissingRuntimeIdentifierPropertyInProjectFile); - bool hasRuntimesSection; + if (IsLockFileProjectJsonBased(ProjectLockFile)) + { + runtimePiece = '"' + RuntimeIdentifier + "\": { }"; + runtimesSection = "\"runtimes\": { " + runtimePiece + " }"; + missingRuntimeInRuntimesErrorString = nameof(Strings.MissingRuntimeInProjectJson); + missingRuntimesErrorString = nameof(Strings.MissingRuntimesSectionInProjectJson); + } + + bool hasRuntimesSection = true; try { - using (var streamReader = new StreamReader(ProjectLockFile.Replace(".lock.json", ".json"))) + // try reading the project.json file only of the project is project.json based + if (IsLockFileProjectJsonBased(ProjectLockFile)) { - var jsonFile = JObject.Load(new JsonTextReader(streamReader)); - hasRuntimesSection = jsonFile["runtimes"] != null; + using (var streamReader = new StreamReader(ProjectLockFile.Replace(".lock.json", ".json"))) + { + var jsonFile = JObject.Load(new JsonTextReader(streamReader)); + hasRuntimesSection = jsonFile["runtimes"] != null; + } } } catch @@ -734,15 +764,23 @@ namespace Microsoft.NuGet.Build.Tasks if (hasRuntimesSection) { - ThrowExceptionIfNotAllowingFallback(nameof(Strings.MissingRuntimeInRuntimesSection), RuntimeIdentifier, runtimePiece); + ThrowExceptionIfNotAllowingFallback(missingRuntimeInRuntimesErrorString, RuntimeIdentifier, runtimePiece); } else { - var runtimesSection = "\"runtimes\": { " + runtimePiece + " }"; - ThrowExceptionIfNotAllowingFallback(nameof(Strings.MissingRuntimesSection), runtimesSection); + ThrowExceptionIfNotAllowingFallback(missingRuntimesErrorString, runtimesSection); } } + private void GiveErrorForMissingFramework() + { + var missingFrameworkErrorString = IsLockFileProjectJsonBased(ProjectLockFile) ? + nameof(Strings.MissingFrameworkInProjectJson) : + nameof(Strings.MissingFrameworkInProjectFile); + + ThrowExceptionIfNotAllowingFallback(missingFrameworkErrorString, TargetMonikers.First().ItemSpec); + } + private void ThrowExceptionIfNotAllowingFallback(string resourceName, params string[] messageArgs) { if (!AllowFallbackOnTargetSelection) @@ -968,7 +1006,11 @@ namespace Microsoft.NuGet.Build.Tasks if (libraryObject == null) { - throw new ExceptionFromResource(nameof(Strings.MissingPackageInTargetsSection), package.Key); + var errorMessage = IsLockFileProjectJsonBased(ProjectLockFile) ? + nameof(Strings.MissingPackageInTargetsForProjectJson) : + nameof(Strings.MissingPackageInTargetsSectionForProjectFile); + + throw new ExceptionFromResource(errorMessage, package.Key); } // If this is a project then we need to figure out it's relative output path @@ -1042,5 +1084,10 @@ namespace Microsoft.NuGet.Build.Tasks return String.Empty; } } + + private static bool IsLockFileProjectJsonBased(string lockFilePath) + { + return lockFilePath.EndsWith("lock.json", StringComparison.OrdinalIgnoreCase); + } } } diff --git a/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks/Strings.Designer.cs b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks/Strings.Designer.cs index 9b3de63177..0056db5363 100644 --- a/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks/Strings.Designer.cs +++ b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks/Strings.Designer.cs @@ -19,7 +19,7 @@ namespace Microsoft.NuGet.Build.Tasks { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Strings { @@ -69,75 +69,111 @@ namespace Microsoft.NuGet.Build.Tasks { } } + /// + /// Looks up a localized string similar to Assets file {0} couldn't be found. Run a NuGet package restore to generate this file.. + /// + internal static string LockFileNotFoundForProjectFile { + get { + return ResourceManager.GetString("LockFileNotFoundForProjectFile", resourceCulture); + } + } + /// /// Looks up a localized string similar to Lock file {0} couldn't be found. Run a NuGet package restore to generate this file.. /// - internal static string LockFileNotFound { + internal static string LockFileNotFoundForProjectJson { get { - return ResourceManager.GetString("LockFileNotFound", resourceCulture); + return ResourceManager.GetString("LockFileNotFoundForProjectJson", resourceCulture); } } /// - /// Looks up a localized string similar to Your project is not referencing the "{0}" framework. Add a reference to "{0}" in the "frameworks" section of your project.json, and then re-run NuGet restore.. + /// Looks up a localized string similar to Your project does not reference "{0}" framework. Add a reference to "{0}" in the "TargetFrameworks" property of your project file and then re-run NuGet restore.. /// - internal static string MissingFramework { + internal static string MissingFrameworkInProjectFile { get { - return ResourceManager.GetString("MissingFramework", resourceCulture); + return ResourceManager.GetString("MissingFrameworkInProjectFile", resourceCulture); } } /// - /// Looks up a localized string similar to Your project is consuming assets from the project '{0}' but no MSBuild project is found in the project.lock.json. Check the project references in your project file, and re-run NuGet restore.. + /// Looks up a localized string similar to Your project does not reference "{0}" framework. Add a reference to "{0}" in the "frameworks" section of your project.json and then re-run NuGet restore.. /// - internal static string MissingMSBuildPathInProjectPackage { + internal static string MissingFrameworkInProjectJson { get { - return ResourceManager.GetString("MissingMSBuildPathInProjectPackage", resourceCulture); + return ResourceManager.GetString("MissingFrameworkInProjectJson", resourceCulture); } } /// /// Looks up a localized string similar to The package '{0}' could not be found in the libraries section of the lock file. This may indicate your lock file is corrupted.. /// - internal static string MissingPackageInTargetsSection { + internal static string MissingPackageInTargetsForProjectJson { get { - return ResourceManager.GetString("MissingPackageInTargetsSection", resourceCulture); + return ResourceManager.GetString("MissingPackageInTargetsForProjectJson", resourceCulture); } } /// - /// Looks up a localized string similar to The project.json is referencing the project '{0}', but an output path was not specified on an item in the {1} property.. + /// Looks up a localized string similar to The package '{0}' could not be found in the libraries section of the assets file. This may indicate your assets file is corrupted.. /// - internal static string MissingProjectReference { + internal static string MissingPackageInTargetsSectionForProjectFile { get { - return ResourceManager.GetString("MissingProjectReference", resourceCulture); + return ResourceManager.GetString("MissingPackageInTargetsSectionForProjectFile", resourceCulture); } } /// - /// Looks up a localized string similar to Your project.json doesn't list '{0}' as a targeted runtime. You should add '{1}' inside your "runtimes" section in your project.json, and then re-run NuGet restore.. + /// Looks up a localized string similar to Your project file doesn't list '{0}' as a "RuntimeIdentifier". You should add '{1}' to the "RuntimeIdentifiers" property in your project file and then re-run NuGet restore.. /// - internal static string MissingRuntimeInRuntimesSection { + internal static string MissingRuntimeIdentifierInProjectFile { get { - return ResourceManager.GetString("MissingRuntimeInRuntimesSection", resourceCulture); + return ResourceManager.GetString("MissingRuntimeIdentifierInProjectFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your project file doesn't have the "RuntimeIdentifiers" property. You should add '{0}' to your project file and then re-run NuGet restore.. + /// + internal static string MissingRuntimeIdentifierPropertyInProjectFile { + get { + return ResourceManager.GetString("MissingRuntimeIdentifierPropertyInProjectFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your project.json doesn't list '{0}' as a "RuntimeIdentifier". You should add '{1}' inside your "runtimes" section in your project.json and then re-run NuGet restore.. + /// + internal static string MissingRuntimeInProjectJson { + get { + return ResourceManager.GetString("MissingRuntimeInProjectJson", resourceCulture); } } /// /// Looks up a localized string similar to Your project.json doesn't have a runtimes section. You should add '{0}' to your project.json and then re-run NuGet restore.. /// - internal static string MissingRuntimesSection { + internal static string MissingRuntimesSectionInProjectJson { get { - return ResourceManager.GetString("MissingRuntimesSection", resourceCulture); + return ResourceManager.GetString("MissingRuntimesSectionInProjectJson", resourceCulture); } } /// - /// Looks up a localized string similar to No targets could be found in the lock file. Make sure you have a supports or runtimes section i your project.json file.. + /// Looks up a localized string similar to No targets could be found in the assets file. Make sure you have "RuntimeIdentifiers" property in your project file.. /// - internal static string NoTargetsInLockFile { + internal static string NoTargetsInLockFileForProjectFile { get { - return ResourceManager.GetString("NoTargetsInLockFile", resourceCulture); + return ResourceManager.GetString("NoTargetsInLockFileForProjectFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No targets could be found in the lock file. Make sure you have a supports or runtimes section in your project.json file.. + /// + internal static string NoTargetsInLockFileForProjectJson { + get { + return ResourceManager.GetString("NoTargetsInLockFileForProjectJson", resourceCulture); } } diff --git a/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks/Strings.resx b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks/Strings.resx index 16d5d646af..0e26628ac6 100644 --- a/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks/Strings.resx +++ b/external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks/Strings.resx @@ -119,38 +119,67 @@ The preprocessor token '{0}' has been given more than one value. Choosing '{1}' as the value. + 0 token +1 - chosen value - + + Assets file {0} couldn't be found. Run a NuGet package restore to generate this file. + 0 - assets file path + + Lock file {0} couldn't be found. Run a NuGet package restore to generate this file. + 0 - lock file path - - Your project is not referencing the "{0}" framework. Add a reference to "{0}" in the "frameworks" section of your project.json, and then re-run NuGet restore. + + Your project does not reference "{0}" framework. Add a reference to "{0}" in the "TargetFrameworks" property of your project file and then re-run NuGet restore. + 0 - target framework - - Your project is consuming assets from the project '{0}' but no MSBuild project is found in the project.lock.json. Check the project references in your project file, and re-run NuGet restore. + + Your project does not reference "{0}" framework. Add a reference to "{0}" in the "frameworks" section of your project.json and then re-run NuGet restore. + 0 - target framework - + The package '{0}' could not be found in the libraries section of the lock file. This may indicate your lock file is corrupted. + 0 package id - - The project.json is referencing the project '{0}', but an output path was not specified on an item in the {1} property. + + The package '{0}' could not be found in the libraries section of the assets file. This may indicate your assets file is corrupted. + 0 package id - - Your project.json doesn't list '{0}' as a targeted runtime. You should add '{1}' inside your "runtimes" section in your project.json, and then re-run NuGet restore. + + Your project file doesn't list '{0}' as a "RuntimeIdentifier". You should add '{1}' to the "RuntimeIdentifiers" property in your project file and then re-run NuGet restore. + 0 &1 - Runtime Identifier - + + Your project file doesn't have the "RuntimeIdentifiers" property. You should add '{0}' to your project file and then re-run NuGet restore. + 0 - Runtime Identifier + + + Your project.json doesn't list '{0}' as a "RuntimeIdentifier". You should add '{1}' inside your "runtimes" section in your project.json and then re-run NuGet restore. + 0 - Runtime Identifier + + Your project.json doesn't have a runtimes section. You should add '{0}' to your project.json and then re-run NuGet restore. + 0 - Runtime Identifier - - No targets could be found in the lock file. Make sure you have a supports or runtimes section i your project.json file. + + No targets could be found in the assets file. Make sure you have "RuntimeIdentifiers" property in your project file. + + + No targets could be found in the lock file. Make sure you have a supports or runtimes section in your project.json file. The package {0} with version {1} could not be found in {2}. Run a NuGet package restore to download the package. + 0 - package id +1 - package version +2 - package folder path The {0} property must be set in order to consume preprocessed content. + 0 - directory path The token '{0}' is unrecognized. + 0 - token \ No newline at end of file diff --git a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Api/ITestResult.cs b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Api/ITestResult.cs index b0735af696..f3488adf7e 100644 --- a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Api/ITestResult.cs +++ b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Api/ITestResult.cs @@ -82,6 +82,17 @@ namespace NUnit.Framework.Api get; } +#if MONO + /// + /// Gets any exception associated with an + /// error or failure. + /// + string ExceptionType + { + get; + } +#endif + /// /// Gets the number of asserts executed /// when running the test and all its children. diff --git a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Commands/ApplyChangesToContextCommand.cs b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Commands/ApplyChangesToContextCommand.cs index c7ee4ca75b..844f351ff3 100644 --- a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Commands/ApplyChangesToContextCommand.cs +++ b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Commands/ApplyChangesToContextCommand.cs @@ -52,7 +52,7 @@ namespace NUnit.Framework.Internal.Commands } catch (Exception ex) { -#if !NETCF && !SILVERLIGHT && !__TVOS__ && !__WATCHOS__ +#if !NETCF && !SILVERLIGHT && !__TVOS__ && !__WATCHOS__ && !MONOTOUCH_TV && !MONOTOUCH_WATCH if (ex is ThreadAbortException) Thread.ResetAbort(); #endif diff --git a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Commands/ExpectedExceptionCommand.cs b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Commands/ExpectedExceptionCommand.cs index 566540ed2b..93ac4d3435 100644 --- a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Commands/ExpectedExceptionCommand.cs +++ b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Commands/ExpectedExceptionCommand.cs @@ -64,7 +64,7 @@ namespace NUnit.Framework.Internal.Commands } catch (Exception ex) { -#if !NETCF && !SILVERLIGHT && !__TVOS__ && !__WATCHOS__ +#if !NETCF && !SILVERLIGHT && !__TVOS__ && !__WATCHOS__ && !MONOTOUCH_TV && !MONOTOUCH_WATCH if (ex is ThreadAbortException) Thread.ResetAbort(); #endif diff --git a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Commands/SetUpTearDownCommand.cs b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Commands/SetUpTearDownCommand.cs index 069e83b9d6..bc7e2aa954 100644 --- a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Commands/SetUpTearDownCommand.cs +++ b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Commands/SetUpTearDownCommand.cs @@ -85,7 +85,7 @@ namespace NUnit.Framework.Internal.Commands } catch (Exception ex) { -#if !NETCF && !SILVERLIGHT && !__TVOS__ && !__WATCHOS__ +#if !NETCF && !SILVERLIGHT && !__TVOS__ && !__WATCHOS__ && !MONOTOUCH_TV && !MONOTOUCH_WATCH if (ex is ThreadAbortException) Thread.ResetAbort(); #endif diff --git a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Results/TestResult.cs b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Results/TestResult.cs index cdb2913151..4958f01b17 100755 --- a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Results/TestResult.cs +++ b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Results/TestResult.cs @@ -23,6 +23,7 @@ using System; using NUnit.Framework.Api; +using System.Reflection; namespace NUnit.Framework.Internal { @@ -55,6 +56,13 @@ namespace NUnit.Framework.Internal /// private string stackTrace; +#if MONO + /// + /// The exceptionType at the point of failure + /// + private string exceptionType; +#endif + /// /// Message giving the reason for failure, error or skipping the test /// @@ -162,6 +170,17 @@ namespace NUnit.Framework.Internal get { return stackTrace; } } +#if MONO + /// + /// Gets any exception associated with an + /// error or failure. + /// + public virtual string ExceptionType + { + get { return exceptionType; } + } +#endif + /// /// Gets or sets the count of asserts executed /// when running the test. @@ -412,6 +431,10 @@ namespace NUnit.Framework.Internal if (ex is NUnitException) ex = ex.InnerException; +#if MONO + exceptionType = ex?.GetType().ToString(); +#endif + if (ex is System.Threading.ThreadAbortException) SetResult(ResultState.Cancelled, "Test cancelled by user", ex.StackTrace); else if (ex is AssertionException) @@ -422,10 +445,17 @@ namespace NUnit.Framework.Internal SetResult(ResultState.Inconclusive, ex.Message, StackFilter.Filter(ex.StackTrace)); else if (ex is SuccessException) SetResult(ResultState.Success, ex.Message, StackFilter.Filter(ex.StackTrace)); - else - SetResult(ResultState.Error, + else { + MethodInfo write = null; + if (Environment.GetEnvironmentVariable ("MONO_TEST_TELEMETRY") != null) + write = Type.GetType ("Mono.Runtime", false).GetMethod ("WriteStateToDisk", BindingFlags.NonPublic | BindingFlags.Static); + if (write != null) + write.Invoke (null, new object [] { ex }); + + SetResult(ResultState.Error, ExceptionHelper.BuildMessage(ex), ExceptionHelper.BuildStackTrace(ex)); + } } #endregion diff --git a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Tests/Test.cs b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Tests/Test.cs index 473c9458ea..7009c4f1ab 100644 --- a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Tests/Test.cs +++ b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/Tests/Test.cs @@ -306,7 +306,7 @@ namespace NUnit.Framework.Internal if (other == null) return -1; - return this.FullName.CompareTo(other.FullName); + return String.CompareOrdinal (this.FullName, other.FullName); } #endregion diff --git a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/ThreadUtility.cs b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/ThreadUtility.cs index 1ce37f8775..d0f58d470b 100644 --- a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/ThreadUtility.cs +++ b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/ThreadUtility.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if (CLR_2_0 || CLR_4_0) && !NETCF && !SILVERLIGHT && !__TVOS__ && !__WATCHOS__ +#if (CLR_2_0 || CLR_4_0) && !NETCF && !SILVERLIGHT && !__TVOS__ && !__WATCHOS__ && !MONOTOUCH_TV && !MONOTOUCH_WATCH using System; using System.Threading; diff --git a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/WorkItems/WorkItem.cs b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/WorkItems/WorkItem.cs index 69980b82bc..db7d208ad7 100644 --- a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/WorkItems/WorkItem.cs +++ b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Internal/WorkItems/WorkItem.cs @@ -122,7 +122,7 @@ namespace NUnit.Framework.Internal.WorkItems { _context = new TestExecutionContext(context); -#if (CLR_2_0 || CLR_4_0) && !SILVERLIGHT && !__TVOS__ && !__WATCHOS__ +#if (CLR_2_0 || CLR_4_0) && !SILVERLIGHT && !__TVOS__ && !__WATCHOS__ && !MONOTOUCH_TV && !MONOTOUCH_WATCH // Timeout set at a higher level int timeout = _context.TestCaseTimeout; @@ -139,7 +139,7 @@ namespace NUnit.Framework.Internal.WorkItems #endif } -#if (CLR_2_0 || CLR_4_0) && !SILVERLIGHT && !__TVOS__ && !__WATCHOS__ +#if (CLR_2_0 || CLR_4_0) && !SILVERLIGHT && !__TVOS__ && !__WATCHOS__ && !MONOTOUCH_TV && !MONOTOUCH_WATCH private void RunTestWithTimeout(int timeout) { Thread thread = new Thread(new ThreadStart(RunTest)); diff --git a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Runner/CommandLineOptions.cs b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Runner/CommandLineOptions.cs index 7a7fa5524b..edf1445b91 100644 --- a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Runner/CommandLineOptions.cs +++ b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Runner/CommandLineOptions.cs @@ -313,7 +313,11 @@ namespace NUnitLite.Runner break; case "format": resultFormat = val; - if (resultFormat != "nunit3" && resultFormat != "nunit2") + if (resultFormat != "nunit3" && resultFormat != "nunit2" +#if MONO + && resultFormat != "xunit" +#endif + ) InvalidOption(option); break; case "out": diff --git a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Runner/OutputWriters/XunitXmlOutputWriter.cs b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Runner/OutputWriters/XunitXmlOutputWriter.cs new file mode 100644 index 0000000000..7fbbbdb0f4 --- /dev/null +++ b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Runner/OutputWriters/XunitXmlOutputWriter.cs @@ -0,0 +1,226 @@ +#if MONO +using System; +using System.Globalization; +using System.Reflection; +using System.Xml; +using System.IO; +using NUnit.Framework.Api; +using NUnit.Framework.Internal; +using System.Collections.Generic; + +namespace NUnitLite.Runner +{ + /// + /// XunitXmlOutputWriter is able to create an xml file representing + /// the result of a test run in xUnit.net v2 format. + /// + public class XunitXmlOutputWriter : OutputWriter + { + private XmlWriter xmlWriter; + private DateTime startTime; + private static Dictionary resultStates = new Dictionary(); + + static XunitXmlOutputWriter() + { + resultStates["Passed"] = "Pass"; + resultStates["Failed"] = "Fail"; + resultStates["Failed:Error"] = "Fail"; + resultStates["Failed:Cancelled"] = "Fail"; + resultStates["Inconclusive"] = "Skip"; + resultStates["Skipped"] = "Skip"; + resultStates["Skipped:Ignored"] = "Skip"; + resultStates["Skipped:Invalid"] = "Skip"; + } + + public XunitXmlOutputWriter(DateTime startTime) + { + this.startTime = startTime; + } + + public override void WriteResultFile(ITestResult result, TextWriter writer) + { + XmlTextWriter xmlWriter = new XmlTextWriter(writer); + xmlWriter.Formatting = Formatting.Indented; + + try + { + WriteXmlOutput(result, xmlWriter); + } + finally + { + writer.Close(); + } + } + + private void WriteXmlOutput(ITestResult result, XmlWriter xmlWriter) + { + this.xmlWriter = xmlWriter; + + InitializeXmlFile(result); + WriteResultElement(result); + TerminateXmlFile(); + } + + private void InitializeXmlFile(ITestResult result) + { + ResultSummary summaryResults = new ResultSummary(result); + + xmlWriter.WriteStartDocument(); + + xmlWriter.WriteStartElement("assemblies"); + + xmlWriter.WriteStartElement("assembly"); + + xmlWriter.WriteAttributeString("name", result.FullName); + AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(Assembly.GetExecutingAssembly()); + xmlWriter.WriteAttributeString("environment", $"nunit-version: {assemblyName.Version}, clr-version: {Environment.Version}, os-version: {Environment.OSVersion}, platform: {Environment.OSVersion.Platform}, cwd: {Environment.CurrentDirectory}, machine-name: {Environment.MachineName}, user: {Environment.UserName}, user-domain: {Environment.UserDomainName}"); + xmlWriter.WriteAttributeString("test-framework", "nunitlite"); + xmlWriter.WriteAttributeString("run-date", XmlConvert.ToString(startTime, "yyyy-MM-dd")); + xmlWriter.WriteAttributeString("run-time", XmlConvert.ToString(startTime, "HH:mm:ss")); + + xmlWriter.WriteAttributeString("total", summaryResults.TestCount.ToString()); + xmlWriter.WriteAttributeString("errors", summaryResults.ErrorCount.ToString()); + xmlWriter.WriteAttributeString("failed", summaryResults.FailureCount.ToString()); + xmlWriter.WriteAttributeString("skipped", summaryResults.SkipCount.ToString()); + + // TODO: inconclusive? invalid? + var passedCount = summaryResults.TestCount - summaryResults.FailureCount - summaryResults.SkipCount - summaryResults.NotRunCount; + xmlWriter.WriteAttributeString("passed", passedCount.ToString()); + } + + private void WriteResultElement(ITestResult result) + { + if (result.Test is TestSuite) { + if ((result.Test as TestSuite).TestType == "Assembly") { + WriteChildResults(result); + return; + } + StartTestElement(result); + WriteChildResults(result); + xmlWriter.WriteEndElement(); // test element + } + else { + StartTestElement(result); + WritePropertiesAndCategories(result); + + switch (result.ResultState.Status) + { + case TestStatus.Skipped: + case TestStatus.Inconclusive: + WriteReasonElement(result.Message); + break; + case TestStatus.Failed: + WriteFailureElement(result.Message, result.StackTrace, result.ExceptionType ?? "UnknownException"); + break; + } + + xmlWriter.WriteEndElement(); // test element + } + } + + private void TerminateXmlFile() + { + xmlWriter.WriteEndElement(); // assembly + xmlWriter.WriteEndElement(); // assemblies + xmlWriter.WriteEndDocument(); + xmlWriter.Flush(); + xmlWriter.Close(); + } + + private void StartTestElement(ITestResult result) + { + ITest test = result.Test; + TestSuite suite = test as TestSuite; + + if (suite != null) + { + xmlWriter.WriteStartElement("collection"); + xmlWriter.WriteAttributeString("name", result.Test.FullName); + } + else + { + xmlWriter.WriteStartElement("test"); + xmlWriter.WriteAttributeString("name", result.FullName); + xmlWriter.WriteAttributeString("type", result.Test.FixtureType.ToString()); + xmlWriter.WriteAttributeString("method", result.Name); + } + + TestStatus status = result.ResultState.Status; + string translatedResult = resultStates[result.ResultState.ToString()]; + + xmlWriter.WriteAttributeString("result", translatedResult); + xmlWriter.WriteAttributeString("time", result.Duration.TotalSeconds.ToString()); + } + + private void WritePropertiesAndCategories(ITestResult result) + { + IPropertyBag properties = result.Test.Properties; + int nprops = 0; + + foreach (string key in properties.Keys) + { + foreach (object prop in properties[key]) + { + if (nprops++ == 0) + xmlWriter.WriteStartElement("traits"); + + xmlWriter.WriteStartElement("trait"); + xmlWriter.WriteAttributeString("name", key); + xmlWriter.WriteAttributeString("value", prop.ToString()); + xmlWriter.WriteEndElement(); + } + } + + if (nprops > 0) + xmlWriter.WriteEndElement(); + } + + private void WriteReasonElement(string message) + { + xmlWriter.WriteStartElement("reason"); + xmlWriter.WriteCData(message); + xmlWriter.WriteEndElement(); + } + + private void WriteFailureElement(string message, string stackTrace, string exceptionType) + { + xmlWriter.WriteStartElement("failure"); + xmlWriter.WriteAttributeString("exception-type", exceptionType); + xmlWriter.WriteStartElement("message"); + WriteCData(message); + xmlWriter.WriteEndElement(); + xmlWriter.WriteStartElement("stack-trace"); + if (stackTrace != null) + WriteCData(stackTrace); + xmlWriter.WriteEndElement(); + xmlWriter.WriteEndElement(); + } + + private void WriteChildResults(ITestResult result) + { + foreach (ITestResult childResult in result.Children) + WriteResultElement(childResult); + } + + private void WriteCData(string text) + { + int start = 0; + while (true) + { + int illegal = text.IndexOf("]]>", start); + if (illegal < 0) + break; + xmlWriter.WriteCData(text.Substring(start, illegal - start + 2)); + start = illegal + 2; + if (start >= text.Length) + return; + } + + if (start > 0) + xmlWriter.WriteCData(text.Substring(start)); + else + xmlWriter.WriteCData(text); + } + } +} +#endif diff --git a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Runner/TextUI.cs b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Runner/TextUI.cs index 6d85a86faf..8709c0945b 100644 --- a/external/nunit-lite/NUnitLite-1.0.0/src/framework/Runner/TextUI.cs +++ b/external/nunit-lite/NUnitLite-1.0.0/src/framework/Runner/TextUI.cs @@ -109,10 +109,6 @@ namespace NUnitLite.Runner /// An array of arguments public void Execute(string[] args) { - // NOTE: Execute must be directly called from the - // test assembly in order for the mechanism to work. - Assembly callingAssembly = Assembly.GetCallingAssembly(); - this.commandLineOptions = new CommandLineOptions(); commandLineOptions.Parse(args); @@ -163,8 +159,12 @@ namespace NUnitLite.Runner } } - if (assemblies.Count == 0) + if (assemblies.Count == 0) { + // NOTE: Execute must be directly called from the + // test assembly in order for the mechanism to work. + Assembly callingAssembly = Assembly.GetCallingAssembly(); assemblies.Add(callingAssembly); + } // TODO: For now, ignore all but first assembly Assembly assembly = assemblies[0] as Assembly; @@ -321,8 +321,14 @@ namespace NUnitLite.Runner if (resultFormat == "nunit2") new NUnit2XmlOutputWriter(startTime).WriteResultFile(result, resultFile); - else + else if (resultFormat == "nunit3") new NUnit3XmlOutputWriter(startTime).WriteResultFile(result, resultFile); +#if MONO + else if (resultFormat == "xunit") + new XunitXmlOutputWriter(startTime).WriteResultFile(result, resultFile); +#endif + else + throw new Exception("Unknown resultFormat."); Console.WriteLine(); Console.WriteLine("Results saved as {0}.", resultFile); diff --git a/ikvm-native/Makefile.in b/ikvm-native/Makefile.in index 6981e9f38b..6eb6b21be7 100644 --- a/ikvm-native/Makefile.in +++ b/ikvm-native/Makefile.in @@ -83,7 +83,8 @@ subdir = ikvm-native DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs $(top_srcdir)/depcomp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -228,6 +229,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -301,6 +303,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/libgc/include/gc.h b/libgc/include/gc.h index c9c20e65a6..960481db87 100644 --- a/libgc/include/gc.h +++ b/libgc/include/gc.h @@ -42,11 +42,6 @@ # define GC_CONST # endif -# ifdef __cplusplus - extern "C" { -# endif - - /* Define word and signed_word to be unsigned and signed types of the */ /* size as char * or void *. There seems to be no way to do this */ /* even semi-portably. The following is probably no better/worse */ @@ -66,6 +61,10 @@ typedef __int64 GC_signed_word; #endif +#ifdef __cplusplus +extern "C" { +#endif + /* Public read-only variables */ GC_API GC_word GC_gc_no;/* Counter incremented per collection. */ @@ -501,7 +500,17 @@ GC_API GC_PTR GC_malloc_atomic_ignore_off_page GC_PROTO((size_t lb)); #endif #if defined(__linux__) || defined(__GLIBC__) + +#ifdef __cplusplus +} // extern "C" +#endif + # include + +#ifdef __cplusplus +extern "C" { +#endif + # if (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1 || __GLIBC__ > 2) \ && !defined(__ia64__) # ifndef GC_HAVE_BUILTIN_BACKTRACE @@ -965,7 +974,17 @@ GC_API void (*GC_is_visible_print_proc) #if !defined(GC_USE_LD_WRAP) && \ (defined(GC_PTHREADS) || defined(GC_SOLARIS_THREADS) || defined(GC_DARWIN_THREADS) || defined(GC_MACOSX_THREADS)) + +#ifdef __cplusplus +} // extern "C" +#endif + # include "gc_pthread_redirects.h" + +#ifdef __cplusplus +extern "C" { +#endif + #endif # if defined(PCR) || defined(GC_SOLARIS_THREADS) || \ @@ -985,8 +1004,17 @@ extern void GC_thr_init(void); /* Needed for Solaris/X86 */ #endif /* THREADS && !SRC_M3 */ #if defined(GC_WIN32_THREADS) && !defined(__CYGWIN32__) && !defined(__CYGWIN__) + +#ifdef __cplusplus +} // extern "C" +#endif + # include +#ifdef __cplusplus +extern "C" { +#endif + # ifdef GC_INSIDE_DLL BOOL WINAPI GC_DllMain(HINSTANCE inst, ULONG reason, LPVOID reserved); # endif @@ -1081,6 +1109,10 @@ extern void GC_thr_init(void); /* Needed for Solaris/X86 */ GC_API void GC_win32_free_heap (); #endif +#ifdef __cplusplus +} // extern "C" +#endif + #if ( defined(_AMIGA) && !defined(GC_AMIGA_MAKINGLIB) ) /* Allocation really goes through GC_amiga_allocwrapper_do */ # include "gc_amiga_redirects.h" @@ -1090,8 +1122,4 @@ extern void GC_thr_init(void); /* Needed for Solaris/X86 */ # include "gc_local_alloc.h" #endif -#ifdef __cplusplus - } /* end of extern "C" */ -#endif - #endif /* _GC_H */ diff --git a/libgc/include/gc_gcj.h b/libgc/include/gc_gcj.h index 5e79e27b82..660d9d337a 100644 --- a/libgc/include/gc_gcj.h +++ b/libgc/include/gc_gcj.h @@ -44,6 +44,10 @@ # include "gc.h" #endif +#ifdef __cplusplus +extern "C" { +#endif + /* The following allocators signal an out of memory condition with */ /* return GC_oom_fn(bytes); */ @@ -110,4 +114,8 @@ extern int GC_gcj_debug_kind; GC_gcj_malloc_ignore_off_page(s,d) # endif +#ifdef __cplusplus +} // extern "C" +#endif + #endif /* GC_GCJ_H */ diff --git a/libgc/include/gc_local_alloc.h b/libgc/include/gc_local_alloc.h index 16f51c1e12..fcbb942c9a 100644 --- a/libgc/include/gc_local_alloc.h +++ b/libgc/include/gc_local_alloc.h @@ -49,6 +49,10 @@ #ifndef GC_LOCAL_ALLOC_H #define GC_LOCAL_ALLOC_H +#ifdef __cplusplus +extern "C" { +#endif + /* We assume ANSI C for this interface. */ GC_PTR GC_local_malloc(size_t bytes); @@ -62,6 +66,10 @@ GC_PTR GC_local_malloc_atomic(size_t bytes); void * ptr_to_struct_containing_descr); #endif +#ifdef __cplusplus +} // extern "C" +#endif + # ifdef GC_DEBUG /* We don't really use local allocation in this case. */ # define GC_LOCAL_MALLOC(s) GC_debug_malloc(s,GC_EXTRAS) diff --git a/libgc/include/gc_pthread_redirects.h b/libgc/include/gc_pthread_redirects.h index 520a36bf66..982d93403e 100644 --- a/libgc/include/gc_pthread_redirects.h +++ b/libgc/include/gc_pthread_redirects.h @@ -15,6 +15,11 @@ /* facility in thr_keycreate. Alternatively, keep a redundant pointer */ /* to thread specific data on the thread stack. */ # include + +#ifdef __cplusplus +extern "C" { +#endif + int GC_thr_create(void *stack_base, size_t stack_size, void *(*start_routine)(void *), void *arg, long flags, thread_t *new_thread); @@ -26,11 +31,22 @@ # define thr_join GC_thr_join # define thr_suspend GC_thr_suspend # define thr_continue GC_thr_continue + +#ifdef __cplusplus +} // extern "C" +#endif + #endif /* GC_SOLARIS_THREADS */ #if defined(GC_SOLARIS_PTHREADS) + # include # include + +#ifdef __cplusplus +extern "C" { +#endif + extern int GC_pthread_create(pthread_t *new_thread, const pthread_attr_t *attr, void * (*thread_execp)(void *), void *arg); @@ -39,6 +55,11 @@ # define pthread_join GC_pthread_join # define pthread_create GC_pthread_create # define pthread_detach GC_pthread_detach + +#ifdef __cplusplus +} // extern "C" +#endif + #endif #if defined(GC_SOLARIS_PTHREADS) || defined(GC_SOLARIS_THREADS) @@ -51,6 +72,10 @@ # include # include +#ifdef __cplusplus +extern "C" { +#endif + int GC_pthread_create(pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg); @@ -87,6 +112,10 @@ # define dlopen GC_dlopen #endif +#ifdef __cplusplus +} // extern "C" +#endif + #endif /* GC_xxxxx_THREADS */ #endif /* GC_PTHREAD_REDIRECTS_H */ diff --git a/libgc/include/private/gc_locks.h b/libgc/include/private/gc_locks.h index ba4fd185b9..d93e9eb8ba 100644 --- a/libgc/include/private/gc_locks.h +++ b/libgc/include/private/gc_locks.h @@ -43,7 +43,17 @@ * */ # ifdef THREADS + +#ifdef __cplusplus +extern "C" { +#endif + void GC_noop1 GC_PROTO((word)); + +#ifdef __cplusplus +} // extern "C" +#endif + # ifdef PCR_OBSOLETE /* Faster, but broken with multiple lwp's */ # include "th/PCR_Th.h" # include "th/PCR_ThCrSec.h" diff --git a/libgc/include/private/gc_priv.h b/libgc/include/private/gc_priv.h index 53afd7828d..431cb58803 100644 --- a/libgc/include/private/gc_priv.h +++ b/libgc/include/private/gc_priv.h @@ -366,6 +366,10 @@ void GC_print_callers GC_PROTO((struct callinfo info[NFRAMES])); # define BZERO(x,n) bzero((char *)(x),(int)(n)) # endif +#ifdef __cplusplus +extern "C" { +#endif + #if defined(DARWIN) # if defined(POWERPC) # define GC_MACH_THREAD_STATE_FLAVOR PPC_THREAD_STATE @@ -413,7 +417,18 @@ void GC_print_callers GC_PROTO((struct callinfo info[NFRAMES])); * Stop and restart mutator threads. */ # ifdef PCR + +#ifdef __cplusplus +} // extern "C" +#endif + # include "th/PCR_ThCtl.h" + +#ifdef __cplusplus +extern "C" { +#endif + + # define STOP_WORLD() \ PCR_ThCtl_SetExclusiveMode(PCR_ThCtl_ExclusiveMode_stopNormal, \ PCR_allSigsBlocked, \ @@ -1315,7 +1330,7 @@ void GC_initiate_gc GC_PROTO((void)); /* If the mark state is invalid, this */ /* becomes full colleection. Otherwise */ /* it's partial. */ -void GC_push_all GC_PROTO((ptr_t bottom, ptr_t top)); +void GC_push_all (void* bottom, void* top); /* Push everything in a range */ /* onto mark stack. */ void GC_push_selected GC_PROTO(( \ @@ -1960,6 +1975,10 @@ void GC_err_puts GC_PROTO((GC_CONST char *s)); /* some other reason. */ # endif /* PARALLEL_MARK */ +#ifdef __cplusplus +} // extern "C" +#endif + # if defined(GC_PTHREADS) && !defined(GC_SOLARIS_THREADS) /* We define the thread suspension signal here, so that we can refer */ /* to it in the dirty bit implementation, if necessary. Ideally we */ diff --git a/libgc/mark.c b/libgc/mark.c index e870342e41..03fd59ec70 100644 --- a/libgc/mark.c +++ b/libgc/mark.c @@ -1191,11 +1191,13 @@ void GC_mark_init() * Should only be used if there is no possibility of mark stack * overflow. */ -void GC_push_all(bottom, top) -ptr_t bottom; -ptr_t top; +void GC_push_all(void_bottom, void_top) +void* void_bottom; +void* void_top; { - register word length; + ptr_t bottom = (ptr_t)void_bottom; + ptr_t top = (ptr_t)void_top; + word length; bottom = (ptr_t)(((word) bottom + ALIGNMENT-1) & ~(ALIGNMENT-1)); top = (ptr_t)(((word) top) & ~(ALIGNMENT-1)); diff --git a/llvm/Makefile.am b/llvm/Makefile.am index a17422ff60..09c0c4bec0 100644 --- a/llvm/Makefile.am +++ b/llvm/Makefile.am @@ -47,4 +47,10 @@ endif # Override this so we don't try to re-copy llvm when we install mono install: +if TARGET_WASM +LLVM_TARGET=wasm32 +else +LLVM_TARGET= +endif + include build.mk diff --git a/llvm/Makefile.in b/llvm/Makefile.in index 59d3562b7a..180e6e6755 100644 --- a/llvm/Makefile.in +++ b/llvm/Makefile.in @@ -20,6 +20,9 @@ # make reset-llvm will checkout a version of llvm which is suitable for this version of mono # into $top_srcdir/llvm/llvm. # +# Input variables +# - LLVM_TARGET: if set to wasm32 will trigger a 32bits build that enable the experimental WebAssembly backend +# # # This is a python script and a set of make targets to implement support for conditional submodules @@ -96,7 +99,8 @@ DIST_COMMON = $(srcdir)/build.mk \ $(top_srcdir)/mkinstalldirs subdir = llvm ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -165,6 +169,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -238,6 +243,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ @@ -365,12 +386,15 @@ EXTRA_DIST = SUBMODULES.json build.mk build_llvm_config.sh @ENABLE_LLVM_TRUE@@HOST_WIN32_TRUE@llvm_config = llvm-config.exe @ENABLE_LLVM_TRUE@@HAVE_ZLIB_FALSE@llvm_extra_libs = @ENABLE_LLVM_TRUE@@HAVE_ZLIB_TRUE@llvm_extra_libs = -lz +@TARGET_WASM_FALSE@LLVM_TARGET = +@TARGET_WASM_TRUE@LLVM_TARGET = wasm32 # FIXME: URL should be http://xamjenkinsartifact.blob.core.windows.net/build-package-osx-llvm-$(NEEDED_LLVM_BRANCH)/llvm-osx64-$(NEEDED_LLVM_VERSION).tar.gz LLVM_DOWNLOAD_LOCATION = "http://xamjenkinsartifact.blob.core.windows.net/build-package-osx-llvm-release60/llvm-osx64-$(NEEDED_LLVM_VERSION).tar.gz" NINJA := $(shell which ninja) SUBMODULES_CONFIG_FILE = $(top_srcdir)/llvm/SUBMODULES.json SCRIPT = $(top_srcdir)/scripts/submodules/versions.py +EXTRA_LLVM_ARGS = $(if $(filter $(LLVM_TARGET),wasm32), -DLLVM_BUILD_32_BITS=On -DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD="WebAssembly",) all: all-am .SUFFIXES: @@ -745,6 +769,7 @@ $(LLVM_BUILD)/$(if $(NINJA),build.ninja,Makefile): $(LLVM_PATH)/CMakeLists.txt | -DLLVM_INCLUDE_EXAMPLES=Off \ -DLLVM_TOOLS_TO_BUILD="opt;llc;llvm-config;llvm-dis" \ -DLLVM_TARGETS_TO_BUILD="X86;ARM;AArch64" \ + $(EXTRA_LLVM_ARGS) \ -DLLVM_ENABLE_ASSERTIONS=$(if $(INTERNAL_LLVM_ASSERTS),On,Off) \ -DLLVM_ENABLE_LIBXML2=Off \ -DHAVE_FUTIMENS=0 \ diff --git a/llvm/build.mk b/llvm/build.mk index 83efa7964b..84fa91ca52 100644 --- a/llvm/build.mk +++ b/llvm/build.mk @@ -4,6 +4,9 @@ # make reset-llvm will checkout a version of llvm which is suitable for this version of mono # into $top_srcdir/llvm/llvm. # +# Input variables +# - LLVM_TARGET: if set to wasm32 will trigger a 32bits build that enable the experimental WebAssembly backend +# top_srcdir ?= $(abspath $(CURDIR)/..) @@ -42,6 +45,8 @@ $(LLVM_PATH): $(LLVM_PATH)/CMakeLists.txt: | $(LLVM_PATH) +EXTRA_LLVM_ARGS = $(if $(filter $(LLVM_TARGET),wasm32), -DLLVM_BUILD_32_BITS=On -DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD="WebAssembly",) + # -DLLVM_ENABLE_LIBXML2=Off is needed because xml2 is not used and it breaks 32-bit builds on 64-bit Linux hosts $(LLVM_BUILD)/$(if $(NINJA),build.ninja,Makefile): $(LLVM_PATH)/CMakeLists.txt | $(LLVM_BUILD) cd $(LLVM_BUILD) && $(CMAKE) \ @@ -54,6 +59,7 @@ $(LLVM_BUILD)/$(if $(NINJA),build.ninja,Makefile): $(LLVM_PATH)/CMakeLists.txt | -DLLVM_INCLUDE_EXAMPLES=Off \ -DLLVM_TOOLS_TO_BUILD="opt;llc;llvm-config;llvm-dis" \ -DLLVM_TARGETS_TO_BUILD="X86;ARM;AArch64" \ + $(EXTRA_LLVM_ARGS) \ -DLLVM_ENABLE_ASSERTIONS=$(if $(INTERNAL_LLVM_ASSERTS),On,Off) \ -DLLVM_ENABLE_LIBXML2=Off \ -DHAVE_FUTIMENS=0 \ diff --git a/m4/Makefile.in b/m4/Makefile.in index 0e9df17453..8a78e94372 100644 --- a/m4/Makefile.in +++ b/m4/Makefile.in @@ -82,7 +82,8 @@ subdir = m4 DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -151,6 +152,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -224,6 +226,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/m4/apple-target.m4 b/m4/apple-target.m4 new file mode 100644 index 0000000000..3e5844e1fa --- /dev/null +++ b/m4/apple-target.m4 @@ -0,0 +1,40 @@ +# Usage: +# AC_MONO_APPLE_TARGET(target-name, action-if-found, action-if-not-found) +# +# Checks whether `target-name` is defined in "TargetConditionals.h" +# +AC_DEFUN([AC_MONO_APPLE_TARGET], [ + AC_MONO_APPLE_AVAILABLE([$1], [for $1], [$1 == 1], $2, $3) +]) + + +# Usage: +# AC_MONO_APPLE_AVAILABLE(name, message, conditional, action-if-found, action-if-not-found) +# +# Checks for `conditional` using "TargetConditionals.h" and "AvailabilityMacros.h" +# +AC_DEFUN([AC_MONO_APPLE_AVAILABLE], [ + # cache the compilation check + AC_CACHE_CHECK([$2], [ac_cv_apple_available_[]$1], [ + AC_TRY_COMPILE([ + #include "TargetConditionals.h" + #include "AvailabilityMacros.h" + ],[ + #if !($3) + #error failed + #endif + ], [ + ac_cv_apple_available_[]$1=yes + ], [ + ac_cv_apple_available_[]$1=no + ]) + ]) + # keep the actions out of the cache check because they need to be always executed. + if test x$ac_cv_apple_available_[]$1 = xyes; then + $1=yes + [$4] + else + $1=no + [$5] + fi +]) diff --git a/man/Makefile.in b/man/Makefile.in index 767a8d18d0..49a6e59d74 100644 --- a/man/Makefile.in +++ b/man/Makefile.in @@ -82,7 +82,8 @@ subdir = man DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -183,6 +184,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -256,6 +258,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/man/mono-cil-strip.1 b/man/mono-cil-strip.1 index 2a4ab8f1fd..61885b26fb 100644 --- a/man/mono-cil-strip.1 +++ b/man/mono-cil-strip.1 @@ -2,12 +2,17 @@ .SH NAME Mono CIL strip .SH SYNOPSIS -.B mono-cil-strip assembly [output-assembly] +.B mono-cil-strip [options] assembly [output-assembly] .SH DESCRIPTION mono-cil-strip is a tool which takes an assembly, and empty its method bodies. This is useful to reduce an assembly size when an assembly has already been compiled using Mono's Ahead Of Time compiler (AOT), where the CIL code is no longer necessary, but the metadata still is. +.SH OPTIONS +The following options are available: +.TP +.I "-q" +Only output errors. .SH COPYRIGHT Copyright (C) 2008 Novell, Inc (http://www.novell.com) .SH MAILING LISTS diff --git a/man/mono.1 b/man/mono.1 index 7b9ae4eddf..c0bd98c98b 100644 --- a/man/mono.1 +++ b/man/mono.1 @@ -221,6 +221,13 @@ obtained by calling the bundled .I opt program that comes with Mono. .TP +.I llvmllc=[options] +Use this option to override the built-in set of flags passed to the +LLVM static compiler (llc). The list of possible flags that can be passed can be +obtained by calling the bundled +.I llc +program that comes with Mono. +.TP .I llvm-outfile=[filename] Gives the path for the temporary LLVM bitcode file created during AOT. .I dedup @@ -374,6 +381,9 @@ Prints additional information about type loading failures. .TP .I write-symbols,no-write-symbols Instructs the AOT compiler to emit (or not emit) debug symbol information. +.TP +.I no-opt +Instructs the AOT compiler tot no call opt when compiling with LLVM. .PP For more information about AOT, see: http://www.mono-project.com/docs/advanced/aot/ .RE @@ -1628,6 +1638,32 @@ home directories that might be shared over the network. If set, extra checks are made during IO operations. Currently, this includes only advisory locks around file writes. .TP +\fBMONO_TLS_PROVIDER\fR +This environment variable controls which TLS/SSL provider Mono will +use. The options are usually determined by the operating system where +Mono was compiled and the configuration options that were used for +it. +.RS +.ne 8 +.TP +.I default +Uses the default TLS stack that the Mono runtime was configured with. +Usually this is configured to use Apple's SSL stack on Apple +platforms, and Boring SSL on other platforms. +.TP +.I apple +Forces the use of the Apple SSL stack, only works on Apple platforms. +.TP +.I btls +Forces the use of the BoringSSL stack. See +https://opensource.google.com/projects/boringssl for more information +about this stack. +.TP +.I legacy +This is the old Mono stack, which only supports SSL and TLS up to +version 1.0. It is deprecated and will be removed in the future. +.RE +.TP \fBMONO_TLS_SESSION_CACHE_TIMEOUT\fR The time, in seconds, that the SSL/TLS session cache will keep it's entry to avoid a new negotiation between the client and a server. Negotiation are very diff --git a/mcs/build/common/Consts.cs b/mcs/build/common/Consts.cs index 3f8b053964..c7128128cd 100644 --- a/mcs/build/common/Consts.cs +++ b/mcs/build/common/Consts.cs @@ -34,11 +34,11 @@ static class Consts // Use these assembly version constants to make code more maintainable. // - public const string MonoVersion = "5.18.0.252"; + public const string MonoVersion = "5.20.0.180"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; - public const string MonoCorlibVersion = "179F7FD7-9CE8-424E-84AF-0DF5B0B8B469"; + public const string MonoCorlibVersion = "B886E13F-6276-4BE5-85F8-C6BF5EDBD200"; #if MOBILE // Versions of .NET Framework for Silverlight 4.0 diff --git a/mcs/build/common/basic-profile-check.cs b/mcs/build/common/basic-profile-check.cs index 2eba396f20..6fe2fe7ccf 100644 --- a/mcs/build/common/basic-profile-check.cs +++ b/mcs/build/common/basic-profile-check.cs @@ -41,7 +41,7 @@ class X Version min_mono_version; #if __MonoCS__ - min_mono_version = new Version (5, 18); + min_mono_version = new Version (5, 19); #else min_mono_version = new Version (5, 10); #endif diff --git a/mcs/build/gensources.cs b/mcs/build/gensources.cs index 25386755c0..b41e15e2cd 100644 --- a/mcs/build/gensources.cs +++ b/mcs/build/gensources.cs @@ -68,7 +68,7 @@ public static class Program { Console.Error.WriteLine ("--stdout"); Console.Error.WriteLine (" Writes results to standard output (omit outputFileName if you use this)"); Console.Error.WriteLine ("--strict"); - Console.Error.WriteLine (" Produces an error exit code if files or directories are invalid/missing"); + Console.Error.WriteLine (" Produces an error exit code if files or directories are invalid/missing or other warnings occur"); Console.Error.WriteLine ("--basedir:"); Console.Error.WriteLine (" Sets the base directory when reading a single sources/exclusions pair (default is the directory containing the sources file)"); return 1; @@ -449,7 +449,7 @@ public class SourcesParser { return state.Result; } - testPath = Path.Combine (libraryDirectory, $"{hostPlatform}_{libraryName}"); + testPath = Path.Combine (libraryDirectory, $"{hostPlatform}_defaultprofile_{libraryName}"); ok = TryParseTargetInto (state, testPath); if (ok) { @@ -517,18 +517,37 @@ public class SourcesParser { var platformFallbackTargets = new List (); + var ambiguousSourcesNames = new List (); + foreach (var hostPlatform in AllHostPlatformNames) { state.ProfileName = null; state.HostPlatform = hostPlatform; - var testPath = Path.Combine (libraryDirectory, $"{hostPlatform}_{libraryName}"); + var testPath = Path.Combine (libraryDirectory, $"{hostPlatform}_defaultprofile_{libraryName}"); var target = ParseTarget (state, testPath, defaultTarget); if ((target != null) && target.IsFallback) platformFallbackTargets.Add (target); + + if ((target == null) || target.IsFallback) { + var oldTestPath = Path.Combine (libraryDirectory, $"{hostPlatform}_{libraryName}.sources"); + if (File.Exists (oldTestPath)) + ambiguousSourcesNames.Add (oldTestPath); + + oldTestPath = Path.Combine (libraryDirectory, $"{hostPlatform}_{libraryName}.exclude.sources"); + if (File.Exists (oldTestPath)) + ambiguousSourcesNames.Add (oldTestPath); + } } StripFallbackTargetsOrDefaultTarget (state, defaultTarget, platformFallbackTargets, AllHostPlatformNames.Length); + foreach (var path in ambiguousSourcesNames) { + if (!state.Result.SourcesFiles.ContainsKey (path) && !state.Result.ExclusionFiles.ContainsKey (path)) { + Console.Error.WriteLine ($"// The file '{path}' was found but not used by sources parsing. Did you mean hostPlatform_defaultprofile_{libraryName}?"); + state.Result.ErrorCount += 1; + } + } + PrintSummary (state, originalTestPath); return state.Result; diff --git a/mcs/build/library.make b/mcs/build/library.make index d7cabd9c68..b17c32043d 100644 --- a/mcs/build/library.make +++ b/mcs/build/library.make @@ -14,13 +14,12 @@ # command line. # -# All dependent libs become dependent dirs for parallel builds -# Have to rename to handle differences between assembly/directory names -DEP_LIBS=$(patsubst System.Xml,System.XML,$(LIB_REFS)) - LIB_REFS_FULL = $(call _FILTER_OUT,=, $(LIB_REFS)) $(DEFAULT_REFERENCES) LIB_REFS_ALIAS = $(filter-out $(LIB_REFS_FULL),$(LIB_REFS)) +# All dependent libs become dependent dirs for parallel builds +DEP_LIBS = $(filter-out %=, $(subst =,= ,$(LIB_REFS))) + ifdef TARGET_NET_REFERENCE # System*, mscorlib references come from the TARGET_NET_REFERENCE dir, others from the profile dir LIB_REFS_MONO_FULL = $(call _FILTER_OUT,System,$(call _FILTER_OUT,mscorlib,$(LIB_REFS_FULL))) @@ -75,17 +74,6 @@ endif endif endif -# -# The bare directory contains the plain versions of System and System.Xml -# -bare_libdir = $(the_libdir_base)bare - -# -# The secxml directory contains the System version that depends on -# System.Xml and Mono.Security -# -secxml_libdir = $(the_libdir_base)secxml - the_libdir = $(the_libdir_base)$(intermediate) ifdef LIBRARY_USE_INTERMEDIATE_FILE diff --git a/mcs/build/profiles/basic.make b/mcs/build/profiles/basic.make index eb2264efd4..7dd7770fc5 100644 --- a/mcs/build/profiles/basic.make +++ b/mcs/build/profiles/basic.make @@ -122,7 +122,7 @@ $(PROFILE_EXE): $(topdir)/build/common/basic-profile-check.cs $(GENSOURCES_CS) $(BOOTSTRAP_MCS) /noconfig /langversion:latest /r:mscorlib.dll /r:System.dll /r:System.Core.dll /out:$(GENSOURCES_EXE).tmp $(GENSOURCES_CS) - rm $(GENSOURCES_EXE) mv $(GENSOURCES_EXE).tmp $(GENSOURCES_EXE) - - rm $@ + - rm -f $@ mv $@.tmp $@ $(PROFILE_OUT): $(PROFILE_EXE) diff --git a/mcs/build/profiles/net_4_x.make b/mcs/build/profiles/net_4_x.make index 6c63573645..16f8eb528d 100644 --- a/mcs/build/profiles/net_4_x.make +++ b/mcs/build/profiles/net_4_x.make @@ -23,4 +23,5 @@ ENFORCE_LIBRARY_WARN_AS_ERROR = yes ifdef PLATFORM_MACOS MONO_FEATURE_APPLETLS=1 +ENABLE_GSS=1 endif diff --git a/mcs/build/rules.make b/mcs/build/rules.make index 831f149a61..6a84ac73dd 100644 --- a/mcs/build/rules.make +++ b/mcs/build/rules.make @@ -54,7 +54,7 @@ INTERNAL_CSC_LOCATION = $(CSC_LOCATION) INTERNAL_CSC = CSC_SDK_PATH_DISABLED= $(RUNTIME) $(RUNTIME_FLAGS) $(CSC_RUNTIME_FLAGS) $(INTERNAL_CSC_LOCATION) RESGEN = MONO_PATH="$(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(RUNTIME) $(RUNTIME_FLAGS) $(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)/resgen.exe -STRING_REPLACER = MONO_PATH="$(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(RUNTIME) $(RUNTIME_FLAGS) $(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)/cil-stringreplacer.exe +STRING_REPLACER = MONO_PATH="$(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(RUNTIME) $(RUNTIME_FLAGS) $(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)/tmp/cil-stringreplacer.exe ILASM = MONO_PATH="$(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(RUNTIME) $(RUNTIME_FLAGS) $(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)/ilasm.exe GENSOURCES_LIBDIR = $(topdir)/class/lib/$(BUILD_TOOLS_PROFILE) GENSOURCES_CS = $(topdir)/build/gensources.cs @@ -243,6 +243,9 @@ endif $(if $(filter $*,all), \ $(MAKE) $(PROFILE_PARALLEL_SUBDIRS) ENABLE_PARALLEL_SUBDIR_BUILD=1 || { final_exit="exit 1"; $$dk; };, \ $(foreach subdir,$(PROFILE_PARALLEL_SUBDIRS),$(MAKE) -C $(subdir) $* || { final_exit="exit 1"; $$dk; };))) \ + $(if $(FACADES_FOLDER), \ + $(MAKE) -C $(FACADES_FOLDER) $* || { final_exit="exit 1"; $$dk; }; \ + ) \ $$final_exit ifdef ENABLE_PARALLEL_SUBDIR_BUILD @@ -264,15 +267,24 @@ endif # directories it depends on. # ifneq ($(PROFILE_PARALLEL_SUBDIRS),) + dep_dirs = .dep_dirs-$(PROFILE) -$(dep_dirs): - @echo "Creating $@..." + +# +# This should track dependencies better but the variable can be defined in any +# Makefile dependency. On top of that we should also regenerate when any of the +# PROFILE_PARALLEL_SUBDIRS Makefile's are changed +# +$(dep_dirs): Makefile + $(if $(V),@echo "Creating $(abspath $@)...",) list='$(PROFILE_PARALLEL_SUBDIRS)'; \ echo > $@; \ for d in $$list; do \ $(MAKE) -C $$d gen-deps DEPS_TARGET_DIR=$$d DEPS_FILE=$(abspath $@); \ done + -include $(dep_dirs) + endif .PHONY: gen-deps diff --git a/mcs/build/tests.make b/mcs/build/tests.make index 216b3731de..a59a3b6a9e 100644 --- a/mcs/build/tests.make +++ b/mcs/build/tests.make @@ -44,8 +44,15 @@ $(topdir)/../external/corefx/src/Common/src/System/PasteArguments.Unix.cs ifeq ($(PROFILE),monodroid) xunit_src += $(topdir)/../mcs/class/test-helpers/RemoteExecutorTestBase.Mobile.cs else -xunit_src += $(topdir)/../mcs/class/test-helpers/RemoteExecutorTestBase.Mono.cs \ -$(topdir)/../external/corefx/src/CoreFx.Private.TestUtilities/src/System/Diagnostics/RemoteExecutorTestBase.Process.cs +ifeq ($(PROFILE),monotouch_tv) +xunit_src += $(topdir)/../mcs/class/test-helpers/RemoteExecutorTestBase.Mobile.cs +else +ifeq ($(PROFILE),monotouch_watch) +xunit_src += $(topdir)/../mcs/class/test-helpers/RemoteExecutorTestBase.Mobile.cs +else +xunit_src += $(topdir)/../mcs/class/test-helpers/RemoteExecutorTestBase.Mono.cs $(topdir)/../external/corefx/src/CoreFx.Private.TestUtilities/src/System/Diagnostics/RemoteExecutorTestBase.Process.cs +endif +endif endif endif @@ -85,7 +92,7 @@ test_assembly_dep = $(the_assembly) endif tests_CLEAN_FILES += $(test_lib_output) $(test_lib_output:$(ASSEMBLY_EXT)=.pdb) $(test_response) $(test_makefrag) -xtest_sourcefile = $(PROFILE)_$(ASSEMBLY:$(ASSEMBLY_EXT)=_xtest.dll.sources) +xtest_sourcefile = $(PROFILE_PLATFORM)_$(PROFILE)_$(ASSEMBLY:$(ASSEMBLY_EXT)=_xtest.dll.sources) xtest_sourcefile_excludes = $(PROFILE)_$(ASSEMBLY:$(ASSEMBLY_EXT)=_xtest.dll.exclude.sources) xunit_test_lib = $(PROFILE)_$(ASSEMBLY:$(ASSEMBLY_EXT)=_xunit-test.dll) @@ -169,14 +176,20 @@ endif NUNITLITE_CONFIG_FILE=$(topdir)/class/lib/$(PROFILE)/$(PARENT_PROFILE)nunit-lite-console.exe.config -patch-nunitlite-appconfig: - cp -f $(topdir)/tools/nunit-lite/nunit-lite-console/nunit-lite-console.exe.config.tmpl $(NUNITLITE_CONFIG_FILE) +$(test_lib_output).nunitlite.config: $(topdir)/tools/nunit-lite/nunit-lite-console/nunit-lite-console.exe.config.tmpl $(TEST_NUNITLITE_APP_CONFIG_GLOBAL) $(TEST_NUNITLITE_APP_CONFIG_RUNTIME) $(TEST_NUNITLITE_APP_CONFIG_SUPPLEMENTAL) | $(test_lib_dir) + cp -f $(topdir)/tools/nunit-lite/nunit-lite-console/nunit-lite-console.exe.config.tmpl $(test_lib_output).nunitlite.config ifdef TEST_NUNITLITE_APP_CONFIG_GLOBAL - sed -i -e "/__INSERT_CUSTOM_APP_CONFIG_GLOBAL__/r $(TEST_NUNITLITE_APP_CONFIG_GLOBAL)" $(NUNITLITE_CONFIG_FILE) + sed -i -e "/__INSERT_CUSTOM_APP_CONFIG_GLOBAL__/r $(TEST_NUNITLITE_APP_CONFIG_GLOBAL)" $(test_lib_output).nunitlite.config endif ifdef TEST_NUNITLITE_APP_CONFIG_RUNTIME - sed -i -e "/__INSERT_CUSTOM_APP_CONFIG_RUNTIME__/r $(TEST_NUNITLITE_APP_CONFIG_RUNTIME)" $(NUNITLITE_CONFIG_FILE) + sed -i -e "/__INSERT_CUSTOM_APP_CONFIG_RUNTIME__/r $(TEST_NUNITLITE_APP_CONFIG_RUNTIME)" $(test_lib_output).nunitlite.config endif +ifdef TEST_NUNITLITE_APP_CONFIG_SUPPLEMENTAL + cp -f $(TEST_NUNITLITE_APP_CONFIG_SUPPLEMENTAL) $(test_lib_output).nunitlite.config.$(TEST_NUNITLITE_APP_CONFIG_SUPPLEMENTAL) +endif + +copy-nunitlite-appconfig: $(test_lib_output).nunitlite.config + cp -f $(test_lib_output).nunitlite.config $(NUNITLITE_CONFIG_FILE) ifdef PLATFORM_AOT_SUFFIX @@ -222,7 +235,7 @@ TEST_HARNESS_EXEC=$(TEST_RUNTIME) $(TEST_RUNTIME_FLAGS) $(TEST_COVERAGE_FLAGS) $ endif ## FIXME: i18n problem in the 'sed' command below -run-test-lib: test-local test-local-aot-compile patch-nunitlite-appconfig +run-test-lib: test-local test-local-aot-compile copy-nunitlite-appconfig ok=:; \ PATH="$(TEST_RUNTIME_WRAPPERS_PATH):$(PATH)" MONO_REGISTRY_PATH="$(HOME)/.mono/registry" MONO_TESTS_IN_PROGRESS="yes" DBG_RUNTIME_ARGS="$(TEST_RUNTIME_FLAGS)" $(TEST_HARNESS_EXEC) $(test_assemblies) $(NOSHADOW_FLAG) $(TEST_HARNESS_FLAGS) $(LOCAL_TEST_HARNESS_FLAGS) $(TEST_HARNESS_EXCLUDES) $(LABELS_ARG) -format:nunit2 -result:TestResult-$(PROFILE).xml $(FIXTURE_ARG) $(TESTNAME_ARG)|| ok=false; \ if [ ! -f "TestResult-$(PROFILE).xml" ]; then echo "The test runner didn't produce a test result XML, probably due to a crash of the runtime. Check the log for more details." > TestResult-$(PROFILE).xml; fi; \ @@ -249,7 +262,7 @@ ifdef HAVE_CS_TESTS $(test_lib_dir): mkdir -p $@ -$(test_lib_output): $(test_assembly_dep) $(test_response) $(test_nunit_dep) | $(test_lib_dir) +$(test_lib_output): $(test_assembly_dep) $(test_response) $(test_nunit_dep) $(test_lib_output).nunitlite.config | $(test_lib_dir) $(TEST_COMPILE) $(LIBRARY_FLAGS) -target:library -out:$@ $(test_flags) $(LOCAL_TEST_COMPILER_ONDOTNET_FLAGS) @$(test_response) test_response_preprocessed = $(test_response)_preprocessed @@ -335,7 +348,7 @@ xtest_response_preprocessed = $(xtest_response)_preprocessed # This handles .excludes/.sources pairs, as well as resolving the # includes that occur in .sources files -$(xtest_response): $(xtest_sourcefile) $(wildcard $(xtest_sourcefile_excludes)) $(GENSOURCES_CS) +$(xtest_response): $(xtest_sourcefile) $(wildcard *xtest.dll.sources) $(wildcard $(xtest_sourcefile_excludes)) $(GENSOURCES_CS) $(GENSOURCES_RUNTIME) --debug $(GENSOURCES_EXE) --strict "$@" "$(xtest_sourcefile)" "$(xtest_sourcefile_excludes)" $(xtest_makefrag): $(xtest_response) diff --git a/mcs/class/Commons.Xml.Relaxng/Commons.Xml.Relaxng_test.dll.sources b/mcs/class/Commons.Xml.Relaxng/Commons.Xml.Relaxng_test.dll.sources index a50fa519e4..fcf2278feb 100644 --- a/mcs/class/Commons.Xml.Relaxng/Commons.Xml.Relaxng_test.dll.sources +++ b/mcs/class/Commons.Xml.Relaxng/Commons.Xml.Relaxng_test.dll.sources @@ -1,3 +1,4 @@ +../../test-helpers/TestResourceHelper.cs RdpPatternTests.cs RelaxngDatatypeProviderTests.cs RelaxngReaderTests.cs diff --git a/mcs/class/Commons.Xml.Relaxng/Makefile b/mcs/class/Commons.Xml.Relaxng/Makefile index f9b57fea26..c508f063be 100644 --- a/mcs/class/Commons.Xml.Relaxng/Makefile +++ b/mcs/class/Commons.Xml.Relaxng/Makefile @@ -11,15 +11,20 @@ LIB_REFS = System System.Xml KEYFILE = ../mono.pub LIB_MCS_FLAGS = \ $(foreach r, $(OTHER_RES), /resource:$(r),$(notdir $(r))) -TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -nowarn:0618 -nowarn:219 -nowarn:169 -EXTRA_DISTFILES = \ - Commons.Xml.Relaxng.Rnc/RncParser.jay \ + +TEST_RESOURCE_FILES = \ $(wildcard Test/XmlFiles/*.rng) \ $(wildcard Test/XmlFiles/*.rnc) \ $(wildcard Test/XmlFiles/*.nvdl) \ - $(wildcard Test/XmlFiles/*.xml) \ + $(wildcard Test/XmlFiles/*.xml) + +TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -nowarn:0618 -nowarn:219 -nowarn:169 $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) + +EXTRA_DISTFILES = \ + Commons.Xml.Relaxng.Rnc/RncParser.jay \ $(wildcard Test/standalone_tests/*.cs) \ - $(RESOURCE_FILES) + $(RESOURCE_FILES) \ + $(TEST_RESOURCE_FILES) Commons.Xml.Relaxng.Rnc/RncParser.cs: Commons.Xml.Relaxng.Rnc/RncParser.jay $(topdir)/jay/skeleton.cs $(topdir)/jay/jay -ctv -o Commons.Xml.Relaxng.Rnc/RncParser.cs $< < $(topdir)/jay/skeleton.cs diff --git a/mcs/class/Commons.Xml.Relaxng/Test/NvdlValidatingReaderTests.cs b/mcs/class/Commons.Xml.Relaxng/Test/NvdlValidatingReaderTests.cs index 8f0ae73cf6..bb0f740dc4 100644 --- a/mcs/class/Commons.Xml.Relaxng/Test/NvdlValidatingReaderTests.cs +++ b/mcs/class/Commons.Xml.Relaxng/Test/NvdlValidatingReaderTests.cs @@ -13,6 +13,8 @@ using System.Xml; using Commons.Xml.Nvdl; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Commons.Xml.Relaxng { [TestFixture] @@ -21,7 +23,7 @@ namespace MonoTests.Commons.Xml.Relaxng [Test] public void ReadNvdlNvdl () { - using (TextReader r = File.OpenText ("Test/XmlFiles/nvdl.nvdl")) { + using (TextReader r = File.OpenText (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/nvdl.nvdl"))) { NvdlRules rules = NvdlReader.Read ( new XmlTextReader (r)); } @@ -31,7 +33,7 @@ namespace MonoTests.Commons.Xml.Relaxng public void ValidateNvdlNvdl () { NvdlRules rules = null; - string path = "Test/XmlFiles/nvdl.nvdl"; + string path = TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/nvdl.nvdl"); using (TextReader r = File.OpenText (path)) { rules = NvdlReader.Read ( new XmlTextReader (path, r)); diff --git a/mcs/class/Commons.Xml.Relaxng/Test/RelaxngDatatypeProviderTests.cs b/mcs/class/Commons.Xml.Relaxng/Test/RelaxngDatatypeProviderTests.cs index ccf4e5d191..70e2c2f6b4 100644 --- a/mcs/class/Commons.Xml.Relaxng/Test/RelaxngDatatypeProviderTests.cs +++ b/mcs/class/Commons.Xml.Relaxng/Test/RelaxngDatatypeProviderTests.cs @@ -12,6 +12,8 @@ using Commons.Xml.Relaxng; using Commons.Xml.Relaxng.XmlSchema; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Commons.Xml.Relaxng { [TestFixture] @@ -23,7 +25,7 @@ namespace MonoTests.Commons.Xml.Relaxng var datatypeLibrary = SetupMyDataProvider (); XmlDocument xml = new XmlDocument (); xml.LoadXml (" mytype 1 "); - XmlDocument schemaXml = ReadDoc ("Test/XmlFiles/463264.rng"); + XmlDocument schemaXml = ReadDoc (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/463264.rng")); XmlReader reader = new RelaxngValidatingReader (new XmlNodeReader (xml), new XmlNodeReader (schemaXml), datatypeLibrary); while (reader.Read ()) ; @@ -35,7 +37,7 @@ namespace MonoTests.Commons.Xml.Relaxng var datatypeLibrary = SetupMyDataProvider (); XmlDocument xml = new XmlDocument (); xml.LoadXml (" 1 mytype "); - XmlDocument schemaXml = ReadDoc ("Test/XmlFiles/463267.rng"); + XmlDocument schemaXml = ReadDoc (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/463267.rng")); XmlReader reader = new RelaxngValidatingReader (new XmlNodeReader (xml), new XmlNodeReader (schemaXml), datatypeLibrary); while (reader.Read ()) ; diff --git a/mcs/class/Commons.Xml.Relaxng/Test/RelaxngReaderTests.cs b/mcs/class/Commons.Xml.Relaxng/Test/RelaxngReaderTests.cs index 802da2d175..ca1df825b0 100644 --- a/mcs/class/Commons.Xml.Relaxng/Test/RelaxngReaderTests.cs +++ b/mcs/class/Commons.Xml.Relaxng/Test/RelaxngReaderTests.cs @@ -13,6 +13,8 @@ using System.Xml; using Commons.Xml.Relaxng; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Commons.Xml.Relaxng { [TestFixture] @@ -33,7 +35,7 @@ namespace MonoTests.Commons.Xml.Relaxng [Test] public void SimpleRead () { - loadGrammarFromUrl ("Test/XmlFiles/SimpleElementPattern1.rng"); + loadGrammarFromUrl (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/SimpleElementPattern1.rng")); RelaxngPattern p = reader.ReadPattern (); Assert.AreEqual (RelaxngPatternType.Element, p.PatternType); @@ -42,7 +44,7 @@ namespace MonoTests.Commons.Xml.Relaxng [Test] public void CompileRelaxngGrammar () { - loadGrammarFromUrl ("Test/XmlFiles/relaxng.rng"); + loadGrammarFromUrl (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/relaxng.rng")); RelaxngPattern p = reader.ReadPattern (); Assert.AreEqual (RelaxngPatternType.Grammar, p.PatternType); diff --git a/mcs/class/Commons.Xml.Relaxng/Test/RelaxngValidatingReaderTests.cs b/mcs/class/Commons.Xml.Relaxng/Test/RelaxngValidatingReaderTests.cs index 62e4924d88..bdf92baf98 100644 --- a/mcs/class/Commons.Xml.Relaxng/Test/RelaxngValidatingReaderTests.cs +++ b/mcs/class/Commons.Xml.Relaxng/Test/RelaxngValidatingReaderTests.cs @@ -14,6 +14,7 @@ using Commons.Xml.Relaxng; using NUnit.Framework; using RVR = Commons.Xml.Relaxng.RelaxngValidatingReader; +using MonoTests.Helpers; namespace MonoTests.Commons.Xml.Relaxng { @@ -45,8 +46,8 @@ namespace MonoTests.Commons.Xml.Relaxng [Test] public void SimpleElementPattern1 () { - SetupReaderFromUrl ("Test/XmlFiles/SimpleElementPattern1.xml", - "Test/XmlFiles/SimpleElementPattern1.rng"); + SetupReaderFromUrl (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/SimpleElementPattern1.xml"), + TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/SimpleElementPattern1.rng")); while (!reader.EOF) reader.Read (); @@ -55,8 +56,8 @@ namespace MonoTests.Commons.Xml.Relaxng [Test] public void SimpleElementPattern2 () { - SetupReaderFromUrl ("Test/XmlFiles/SimpleElementPattern2.xml", - "Test/XmlFiles/SimpleElementPattern2.rng"); + SetupReaderFromUrl (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/SimpleElementPattern2.xml"), + TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/SimpleElementPattern2.rng")); while (!reader.EOF) reader.Read (); @@ -65,7 +66,7 @@ namespace MonoTests.Commons.Xml.Relaxng [Test] public void ReadPracticalSample1 () { - SetupReaderFromUrl ("Test/XmlFiles/team.xml", "Test/XmlFiles/team.rng"); + SetupReaderFromUrl (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/team.xml"), TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/team.rng")); while (!reader.EOF) reader.Read (); } @@ -75,8 +76,8 @@ namespace MonoTests.Commons.Xml.Relaxng { // validate relaxng.rng with relaxng.rng RVR r = new RVR ( - new XmlTextReader ("Test/XmlFiles/relaxng.rng"), - new XmlTextReader ("Test/XmlFiles/relaxng.rng")); + new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/relaxng.rng")), + new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/relaxng.rng"))); while (!r.EOF) r.Read (); } diff --git a/mcs/class/Commons.Xml.Relaxng/Test/RncTests.cs b/mcs/class/Commons.Xml.Relaxng/Test/RncTests.cs index fb7ac65e9c..9703b4cb65 100644 --- a/mcs/class/Commons.Xml.Relaxng/Test/RncTests.cs +++ b/mcs/class/Commons.Xml.Relaxng/Test/RncTests.cs @@ -15,6 +15,8 @@ using Commons.Xml.Relaxng; using Commons.Xml.Relaxng.Rnc; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Commons.Xml.Relaxng { [TestFixture] @@ -43,19 +45,19 @@ namespace MonoTests.Commons.Xml.Relaxng [Test] public void TestRelaxngRnc () { - Compile ("Test/XmlFiles/relaxng.rnc"); + Compile (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/relaxng.rnc")); } [Test] public void TestAtomRnc () { - Compile ("Test/XmlFiles/atom.rnc"); + Compile (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/atom.rnc")); } [Test] public void TestInfocardRnc () { - Compile ("Test/XmlFiles/schemas-xmlsoap-or-ws-2005-05-identity.rnc"); + Compile (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/schemas-xmlsoap-or-ws-2005-05-identity.rnc")); } [Test] @@ -85,8 +87,8 @@ start = mine"; [Test] public void InheritDefaultNamespace () { - RelaxngPattern g = Compile ("Test/XmlFiles/include-default-namespace.rnc"); - XmlReader xtr = new XmlTextReader ("Test/XmlFiles/include-default-namespace.xml"); + RelaxngPattern g = Compile (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/include-default-namespace.rnc")); + XmlReader xtr = new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/include-default-namespace.xml")); RelaxngValidatingReader r = new RelaxngValidatingReader (xtr, g); try { while (!r.EOF) diff --git a/mcs/class/Facades/Makefile b/mcs/class/Facades/Makefile index 4de8b1f6b7..1df413517d 100644 --- a/mcs/class/Facades/Makefile +++ b/mcs/class/Facades/Makefile @@ -37,9 +37,9 @@ doc-update-local: doc-update-recursive: @echo "do not recurse the Facades folder" -System System.Core System.ComponentModel.DataAnnotations System.Numerics System.Numerics.Vectors System.Runtime.Serialization System.Transactions System.XML \ +System System.Core System.ComponentModel.DataAnnotations System.Numerics System.Numerics.Vectors System.Runtime.Serialization System.Transactions System.Xml \ System.ComponentModel.Composition System.ServiceModel System.Xml.Linq System.Data System.IO.Compression.FileSystem System.Runtime.InteropServices.RuntimeInformation \ -System.ServiceProcess System.Security System.Net.Http.WebRequest System.Net.Http System.ServiceProcess System.IO.Compression \ +System.ServiceProcess System.Security System.Net.Http.WebRequest System.Net.Http System.ServiceProcess System.IO.Compression System.IdentityModel \ System.Web.Services: all-local-aot: diff --git a/mcs/class/Facades/System.Drawing.Common/Makefile b/mcs/class/Facades/System.Drawing.Common/Makefile index c29765ca0a..5935eb802b 100644 --- a/mcs/class/Facades/System.Drawing.Common/Makefile +++ b/mcs/class/Facades/System.Drawing.Common/Makefile @@ -12,7 +12,7 @@ LIBRARY = System.Drawing.Common.dll KEYFILE = ../../Open.snk LIBRARY_SNK = $(KEYFILE) SIGN_FLAGS = /delaysign /nowarn:1616,1699 -LIB_REFS = +LIB_REFS = System LIB_MCS_FLAGS = $(SIGN_FLAGS) $(EXTRA_LIB_MCS_FLAGS) ifdef false # we'll enable this at a later point diff --git a/mcs/class/Facades/System.Drawing.Common/TypeForwarders.cs b/mcs/class/Facades/System.Drawing.Common/TypeForwarders.cs deleted file mode 100644 index 9376fd7c62..0000000000 --- a/mcs/class/Facades/System.Drawing.Common/TypeForwarders.cs +++ /dev/null @@ -1,174 +0,0 @@ -// -// Copyright (c) 2018 Microsoft -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -#if false // we'll enable these at a later point - -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Bitmap))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.BitmapSuffixInSameAssemblyAttribute))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.BitmapSuffixInSatelliteAssemblyAttribute))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Brush))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Brushes))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.BufferedGraphics))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.BufferedGraphicsContext))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.BufferedGraphicsManager))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.CharacterRange))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.ColorTranslator))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.ContentAlignment))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.CopyPixelOperation))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Design.CategoryNameCollection))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.AdjustableArrowCap))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.Blend))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.ColorBlend))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.CombineMode))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.CompositingMode))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.CompositingQuality))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.CoordinateSpace))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.CustomLineCap))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.DashCap))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.DashStyle))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.FillMode))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.FlushIntention))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.GraphicsContainer))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.GraphicsPath))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.GraphicsPathIterator))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.GraphicsState))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.HatchBrush))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.HatchStyle))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.InterpolationMode))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.LinearGradientBrush))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.LinearGradientMode))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.LineCap))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.LineJoin))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.Matrix))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.MatrixOrder))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.PathData))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.PathGradientBrush))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.PathPointType))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.PenAlignment))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.PenType))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.PixelOffsetMode))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.QualityMode))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.RegionData))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.SmoothingMode))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.WarpMode))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Drawing2D.WrapMode))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Font))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.FontFamily))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.FontStyle))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Graphics))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Graphics.DrawImageAbort))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Graphics.EnumerateMetafileProc))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.GraphicsUnit))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Icon))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.IDeviceContext))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Image))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Image.GetThumbnailImageAbort))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.ImageAnimator))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.BitmapData))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.ColorAdjustType))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.ColorChannelFlag))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.ColorMap))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.ColorMapType))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.ColorMatrix))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.ColorMatrixFlag))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.ColorMode))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.ColorPalette))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.EmfPlusRecordType))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.EmfType))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.Encoder))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.EncoderParameter))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.EncoderParameters))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.EncoderParameterValueType))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.EncoderValue))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.FrameDimension))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.ImageAttributes))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.ImageCodecFlags))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.ImageCodecInfo))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.ImageFlags))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.ImageFormat))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.ImageLockMode))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.Metafile))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.MetafileFrameUnit))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.MetafileHeader))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.MetafileType))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.MetaHeader))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.PaletteFlags))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.PixelFormat))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.PlayRecordCallback))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.PropertyItem))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Imaging.WmfPlaceableFileHeader))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Pen))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Pens))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.Duplex))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.InvalidPrinterException))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.Margins))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PageSettings))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PaperKind))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PaperSize))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PaperSource))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PaperSourceKind))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PreviewPageInfo))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PreviewPrintController))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrintAction))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrintController))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrintDocument))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrinterResolution))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrinterResolutionKind))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrinterSettings))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrinterSettings.PaperSizeCollection))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrinterSettings.PaperSourceCollection))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrinterSettings.PrinterResolutionCollection))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrinterSettings.StringCollection))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrinterUnit))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrinterUnitConvert))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrintEventArgs))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrintEventHandler))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrintPageEventArgs))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrintPageEventHandler))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.PrintRange))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.QueryPageSettingsEventArgs))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.QueryPageSettingsEventHandler))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Printing.StandardPrintController))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Region))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.RotateFlipType))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.SolidBrush))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.StringAlignment))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.StringDigitSubstitute))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.StringFormat))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.StringFormatFlags))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.StringTrimming))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.StringUnit))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.SystemBrushes))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.SystemColors))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.SystemFonts))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.SystemIcons))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.SystemPens))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Text.FontCollection))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Text.GenericFontFamilies))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Text.HotkeyPrefix))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Text.InstalledFontCollection))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Text.PrivateFontCollection))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.Text.TextRenderingHint))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.TextureBrush))] -[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Drawing.ToolboxBitmapAttribute))] - -#endif diff --git a/mcs/class/Facades/System.Drawing.Common/TypeForwarders.cs.REMOVED.git-id b/mcs/class/Facades/System.Drawing.Common/TypeForwarders.cs.REMOVED.git-id new file mode 100644 index 0000000000..108d8b746b --- /dev/null +++ b/mcs/class/Facades/System.Drawing.Common/TypeForwarders.cs.REMOVED.git-id @@ -0,0 +1 @@ +8515153f31ef28434d2bfcc153059733675c124f \ No newline at end of file diff --git a/mcs/class/Facades/System.Runtime.Serialization.Xml/Makefile b/mcs/class/Facades/System.Runtime.Serialization.Xml/Makefile index 33067e02f9..92ad2df241 100644 --- a/mcs/class/Facades/System.Runtime.Serialization.Xml/Makefile +++ b/mcs/class/Facades/System.Runtime.Serialization.Xml/Makefile @@ -11,7 +11,7 @@ LIBRARY = System.Runtime.Serialization.Xml.dll KEYFILE = ../../msfinal.pub SIGN_FLAGS = /delaysign /nowarn:1616,1699 -LIB_REFS = System System.Runtime.Serialization System.Xml Facades/System.Runtime.Serialization.Primitives +LIB_REFS = System System.Runtime.Serialization System.Xml LIB_MCS_FLAGS = $(SIGN_FLAGS) PLATFORM_DEBUG_FLAGS = diff --git a/mcs/class/Facades/System.Security.Cryptography.OpenSsl/AssemblyInfo.cs b/mcs/class/Facades/System.Security.Cryptography.OpenSsl/AssemblyInfo.cs new file mode 100644 index 0000000000..4367a56b53 --- /dev/null +++ b/mcs/class/Facades/System.Security.Cryptography.OpenSsl/AssemblyInfo.cs @@ -0,0 +1,35 @@ +// +// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.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 System; +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyTitle ("System.Security.Cryptography.OpenSsl")] +[assembly: AssemblyDescription ("System.Security.Cryptography.OpenSsl")] +[assembly: AssemblyDefaultAlias ("System.Security.Cryptography.OpenSsl")] +[assembly: AssemblyCompany ("Mono development team")] +[assembly: AssemblyProduct ("Mono Common Language Infrastructure")] +[assembly: AssemblyCopyright ("(c) Various Mono authors")] +[assembly: AssemblyVersion ("4.0.0.0")] +[assembly: AssemblyInformationalVersion ("4.0.0.0")] +[assembly: AssemblyFileVersion ("4.0.0.0")] diff --git a/mcs/class/corlib/System.Security.AccessControl/PrivilegeNotHeldException.cs b/mcs/class/Facades/System.Security.Cryptography.OpenSsl/ECDsaOpenSsl.cs similarity index 57% rename from mcs/class/corlib/System.Security.AccessControl/PrivilegeNotHeldException.cs rename to mcs/class/Facades/System.Security.Cryptography.OpenSsl/ECDsaOpenSsl.cs index e0f0b3d37a..a96ed9ff97 100644 --- a/mcs/class/corlib/System.Security.AccessControl/PrivilegeNotHeldException.cs +++ b/mcs/class/Facades/System.Security.Cryptography.OpenSsl/ECDsaOpenSsl.cs @@ -1,10 +1,10 @@ // -// System.Security.AccessControl.PrivilegeNotHeldException class +// ECDsaOpenSsl.cs // -// Author: -// Dick Porter +// Authors: +// Marek Safar // -// Copyright (C) 2006 Novell, Inc (http://www.novell.com) +// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the @@ -13,10 +13,10 @@ // 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 @@ -26,43 +26,48 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // -using System.Runtime.InteropServices; -using System.Runtime.Serialization; -using System.Security.Permissions; - -namespace System.Security.AccessControl { - - [Serializable] - public sealed class PrivilegeNotHeldException : UnauthorizedAccessException, ISerializable +namespace System.Security.Cryptography +{ + public sealed class ECDsaOpenSsl : ECDsa { - public PrivilegeNotHeldException () + public ECDsaOpenSsl () { + throw new NotImplementedException (); } - public PrivilegeNotHeldException (string privilege) - : base (privilege) + public ECDsaOpenSsl (int keySize) { + throw new NotImplementedException (); } - public PrivilegeNotHeldException (string privilege, - Exception inner) - : base (privilege, inner) + public ECDsaOpenSsl(IntPtr handle) { + throw new NotImplementedException (); } - public string PrivilegeName + public ECDsaOpenSsl (ECCurve curve) { - get { - throw new NotImplementedException (); - } + throw new NotImplementedException (); } - - [MonoTODO] - public override void GetObjectData (SerializationInfo info, - StreamingContext context) + + public ECDsaOpenSsl (SafeEvpPKeyHandle pkeyHandle) + { + throw new NotImplementedException (); + } + + public override byte[] SignHash (byte[] hash) + { + throw new NotImplementedException (); + } + + public override bool VerifyHash (byte[] hash, byte[] signature) + { + throw new NotImplementedException (); + } + + public SafeEvpPKeyHandle DuplicateKeyHandle () { throw new NotImplementedException (); } } -} - +} \ No newline at end of file diff --git a/mcs/class/Facades/System.Security.Cryptography.OpenSsl/Makefile b/mcs/class/Facades/System.Security.Cryptography.OpenSsl/Makefile new file mode 100644 index 0000000000..e76512f5c6 --- /dev/null +++ b/mcs/class/Facades/System.Security.Cryptography.OpenSsl/Makefile @@ -0,0 +1,21 @@ +MCS_BUILD_DIR = ../../../build + +thisdir = class/Facades/System.Security.Cryptography.OpenSsl +SUBDIRS = +include $(MCS_BUILD_DIR)/rules.make + +LIBRARY_SUBDIR = Facades +LIBRARY_INSTALL_DIR = $(mono_libdir)/mono/$(FRAMEWORK_VERSION)/Facades + +LIBRARY = System.Security.Cryptography.OpenSsl.dll + +KEYFILE = ../../msfinal.pub +SIGN_FLAGS = /delaysign /nowarn:1616,1699 +LIB_REFS = System.Core +LIB_MCS_FLAGS = $(SIGN_FLAGS) + +NO_TEST = yes + +include $(MCS_BUILD_DIR)/library.make + + diff --git a/mcs/class/Facades/System.Security.Cryptography.OpenSsl/RSAOpenSsl.cs b/mcs/class/Facades/System.Security.Cryptography.OpenSsl/RSAOpenSsl.cs new file mode 100644 index 0000000000..d00e2b8b1e --- /dev/null +++ b/mcs/class/Facades/System.Security.Cryptography.OpenSsl/RSAOpenSsl.cs @@ -0,0 +1,88 @@ +// +// RSAOpenSsl.cs +// +// Authors: +// Marek Safar +// +// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.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. +// + +namespace System.Security.Cryptography +{ + public sealed class RSAOpenSsl : RSA + { + public RSAOpenSsl () + { + throw new NotImplementedException (); + } + + public RSAOpenSsl (int keySize) + { + throw new NotImplementedException (); + } + + public RSAOpenSsl(IntPtr handle) + { + throw new NotImplementedException (); + } + + public RSAOpenSsl (ECCurve curve) + { + throw new NotImplementedException (); + } + + public RSAOpenSsl (RSAParameters parameters) + { + throw new NotImplementedException (); + } + + public RSAOpenSsl (SafeEvpPKeyHandle pkeyHandle) + { + throw new NotImplementedException (); + } + + public override RSAParameters ExportParameters (bool includePrivateParameters) + { + throw new NotImplementedException (); + } + + public override void ImportParameters (RSAParameters parameters) + { + throw new NotImplementedException (); + } + + public override byte[] SignHash (byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) + { + throw new NotImplementedException (); + } + + public override bool VerifyHash (byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) + { + throw new NotImplementedException (); + } + + public SafeEvpPKeyHandle DuplicateKeyHandle () + { + throw new NotImplementedException (); + } + } +} \ No newline at end of file diff --git a/mcs/class/corlib/System.Runtime.InteropServices/CustomQueryInterfaceMode.cs b/mcs/class/Facades/System.Security.Cryptography.OpenSsl/SafeEvpPKeyHandle.cs similarity index 68% rename from mcs/class/corlib/System.Runtime.InteropServices/CustomQueryInterfaceMode.cs rename to mcs/class/Facades/System.Security.Cryptography.OpenSsl/SafeEvpPKeyHandle.cs index 1cbf55c08e..85fd74539b 100644 --- a/mcs/class/corlib/System.Runtime.InteropServices/CustomQueryInterfaceMode.cs +++ b/mcs/class/Facades/System.Security.Cryptography.OpenSsl/SafeEvpPKeyHandle.cs @@ -1,8 +1,8 @@ // -// CustomQueryInterfaceMode.cs +// SafeEvpPKeyHandle.cs // // Authors: -// Alexander Köplinger +// Marek Safar // // Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com) // @@ -26,13 +26,25 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // -using System; - -namespace System.Runtime.InteropServices +namespace System.Security.Cryptography { - public enum CustomQueryInterfaceMode + public sealed class SafeEvpPKeyHandle : System.Runtime.InteropServices.SafeHandle { - Allow = 1, - Ignore = 0 + public SafeEvpPKeyHandle (IntPtr handle, bool ownsHandle) + : base (handle, ownsHandle) + { + } + + public override bool IsInvalid { get { throw new NotImplementedException (); } } + + public SafeEvpPKeyHandle DuplicateHandle () + { + throw new NotImplementedException (); + } + + protected override bool ReleaseHandle () + { + return true; + } } -} +} \ No newline at end of file diff --git a/mcs/class/Facades/System.Security.Cryptography.OpenSsl/System.Security.Cryptography.OpenSsl.dll.sources b/mcs/class/Facades/System.Security.Cryptography.OpenSsl/System.Security.Cryptography.OpenSsl.dll.sources new file mode 100644 index 0000000000..9e2bb4b66f --- /dev/null +++ b/mcs/class/Facades/System.Security.Cryptography.OpenSsl/System.Security.Cryptography.OpenSsl.dll.sources @@ -0,0 +1,4 @@ +AssemblyInfo.cs +ECDsaOpenSsl.cs +RSAOpenSsl.cs +SafeEvpPKeyHandle.cs diff --git a/mcs/class/Facades/System.ServiceModel.Primitives/Makefile b/mcs/class/Facades/System.ServiceModel.Primitives/Makefile index 14d3275d71..dc15771f8d 100644 --- a/mcs/class/Facades/System.ServiceModel.Primitives/Makefile +++ b/mcs/class/Facades/System.ServiceModel.Primitives/Makefile @@ -11,7 +11,7 @@ LIBRARY = System.ServiceModel.Primitives.dll KEYFILE = ../../msfinal.pub SIGN_FLAGS = /delaysign /nowarn:1616,1699 -LIB_REFS = System System.ServiceModel System.Xml System.IdentityModel Facades/System.Security.Cryptography.X509Certificates +LIB_REFS = System System.ServiceModel System.Xml System.IdentityModel LIB_MCS_FLAGS = $(SIGN_FLAGS) diff --git a/mcs/class/Facades/netstandard/Makefile b/mcs/class/Facades/netstandard/Makefile index c1e93987f1..08bc8d849b 100644 --- a/mcs/class/Facades/netstandard/Makefile +++ b/mcs/class/Facades/netstandard/Makefile @@ -13,10 +13,7 @@ KEYFILE = ../../Open.snk LIBRARY_SNK = $(KEYFILE) SIGN_FLAGS = /delaysign /nowarn:1616,1699 /nowarn:618 LIB_REFS = System System.Xml System.Xml.Linq System.Runtime.Serialization System.Core System.Numerics System.Numerics.Vectors System.Net.Http System.Transactions \ -System.IO.Compression System.Data System.ComponentModel.Composition System.IO.Compression.FileSystem Facades/System.Runtime.InteropServices.RuntimeInformation \ -Facades/System.Security.Cryptography.Algorithms Facades/System.Globalization.Extensions Facades/System.Data.Common \ -Facades/System.Diagnostics.StackTrace Facades/System.Runtime.Serialization.Xml Facades/System.Runtime.Serialization.Primitives \ -Facades/System.Security.SecureString Facades/System.Threading.Overlapped Facades/System.Xml.XPath.XDocument +System.IO.Compression System.Data System.ComponentModel.Composition System.IO.Compression.FileSystem LIB_MCS_FLAGS = $(SIGN_FLAGS) $(EXTRA_LIB_MCS_FLAGS) diff --git a/mcs/class/Facades/subdirs.make b/mcs/class/Facades/subdirs.make index b941efca3f..6a4ac016e1 100644 --- a/mcs/class/Facades/subdirs.make +++ b/mcs/class/Facades/subdirs.make @@ -28,12 +28,13 @@ System.IO.FileSystem.AccessControl System.Reflection.TypeExtensions System.Refle System.Threading.AccessControl System.ValueTuple \ System.Security.Cryptography.Primitives System.Text.Encoding.CodePages System.IO.FileSystem.Watcher \ System.Security.Cryptography.ProtectedData System.ServiceProcess.ServiceController System.IO.Pipes \ -System.Net.Ping System.Resources.Reader System.Resources.Writer System.Runtime.Serialization.Formatters System.Security.Cryptography.Csp +System.Net.Ping System.Resources.Reader System.Resources.Writer System.Runtime.Serialization.Formatters System.Security.Cryptography.Csp \ +System.Runtime.InteropServices.RuntimeInformation System.Xml.XPath.XDocument System.Threading.Overlapped System.Security.SecureString \ +System.Diagnostics.StackTrace System.Data.Common System.Globalization.Extensions System.Runtime.Serialization.Xml System.ServiceModel.Primitives \ +System.Security.Cryptography.X509Certificates System.Runtime.Serialization.Primitives System.Security.Cryptography.Algorithms # common_SUBDIRS dependencies -common_DEPS_SUBDIRS = System.Security.Cryptography.X509Certificates System.ServiceModel.Primitives System.Runtime.Serialization.Primitives \ -System.Runtime.Serialization.Xml System.Security.Cryptography.Algorithms System.Globalization.Extensions System.Data.Common \ -System.Diagnostics.StackTrace System.Security.SecureString System.Threading.Overlapped System.Xml.XPath.XDocument System.Runtime.InteropServices.RuntimeInformation +common_DEPS_SUBDIRS := netstandard_drawing_SUBDIRS = System.Drawing.Primitives netstandard @@ -78,21 +79,20 @@ monotouch_watch_PARALLEL_SUBDIRS = $(monotouch_PARALLEL_SUBDIRS) monotouch_tv_SUBDIRS = $(monotouch_SUBDIRS) monotouch_tv_PARALLEL_SUBDIRS = $(monotouch_PARALLEL_SUBDIRS) -winaot_SUBDIRS = $(common_DEPS_SUBDIRS) $(netstandard_drawing_SUBDIRS) $(mobile_only_DEPS_SUBDIRS) +winaot_SUBDIRS = $(common_DEPS_SUBDIRS) $(netstandard_drawing_SUBDIRS) winaot_PARALLEL_SUBDIRS = $(common_SUBDIRS) $(mobile_only_SUBDIRS) -orbis_SUBDIRS = $(common_DEPS_SUBDIRS) $(netstandard_drawing_SUBDIRS) $(mobile_only_DEPS_SUBDIRS) +orbis_SUBDIRS = $(common_DEPS_SUBDIRS) $(netstandard_drawing_SUBDIRS) orbis_PARALLEL_SUBDIRS = $(common_SUBDIRS) $(mobile_only_SUBDIRS) -unreal_SUBDIRS = $(common_DEPS_SUBDIRS) $(netstandard_drawing_SUBDIRS) $(mobile_only_DEPS_SUBDIRS) +unreal_SUBDIRS = $(common_DEPS_SUBDIRS) $(netstandard_drawing_SUBDIRS) unreal_PARALLEL_SUBDIRS = $(common_SUBDIRS) $(mobile_only_SUBDIRS) -wasm_SUBDIRS = $(common_DEPS_SUBDIRS) $(netstandard_drawing_SUBDIRS) $(mobile_only_DEPS_SUBDIRS) +wasm_SUBDIRS = $(common_DEPS_SUBDIRS) $(netstandard_drawing_SUBDIRS) wasm_PARALLEL_SUBDIRS = $(common_SUBDIRS) $(mobile_only_SUBDIRS) -mobile_only_SUBDIRS = System.Security.Cryptography.Pkcs System.Threading.Tasks.Extensions System.Memory System.Buffers \ -System.Security.Cryptography.Cng System.Runtime.Loader System.Xml.XPath.XmlDocument System.Reflection.DispatchProxy System.Drawing.Common - -mobile_only_DEPS_SUBDIRS = System.Security.Cryptography.OpenSsl +mobile_only_SUBDIRS = System.Security.Cryptography.Pkcs System.Security.Cryptography.OpenSsl System.Threading.Tasks.Extensions \ +System.Security.Cryptography.Cng System.Runtime.Loader System.Xml.XPath.XmlDocument System.Reflection.DispatchProxy System.Memory \ +System.Drawing.Common System.Buffers PROFILE_PARALLEL_SUBDIRS = $(net_4_x_PARALLEL_SUBDIRS) diff --git a/mcs/class/I18N/CJK/I18N.CJK_test.dll.sources b/mcs/class/I18N/CJK/I18N.CJK_test.dll.sources index 2a1c4fdc4c..c1bb9ecd41 100644 --- a/mcs/class/I18N/CJK/I18N.CJK_test.dll.sources +++ b/mcs/class/I18N/CJK/I18N.CJK_test.dll.sources @@ -1,3 +1,4 @@ +../../../test-helpers/TestResourceHelper.cs ../../EncodingTestBase.cs I18N.CJK.EncodingTest.cs I18N.CJK.Test.cs diff --git a/mcs/class/I18N/CJK/Makefile b/mcs/class/I18N/CJK/Makefile index f4edf52eea..1ea7140353 100644 --- a/mcs/class/I18N/CJK/Makefile +++ b/mcs/class/I18N/CJK/Makefile @@ -8,8 +8,11 @@ KEYFILE = ../../mono.pub LOCAL_MCS_FLAGS = /unsafe /resource:big5.table /resource:gb2312.table /resource:jis.table /resource:ks.table /resource:gb18030.table /define:DISABLE_UNSAFE TEST_LIB_REFS = I18N +TEST_RESOURCE_FILES = $(wildcard Test/texts/*.txt) +TEST_MCS_FLAGS = $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) + EXTRA_DISTFILES = big5.table jis.table gb2312.table ks.table gb18030.table \ README.gb18030 \ - $(wildcard Test/texts/*.txt) + $(TEST_RESOURCE_FILES) include ../../../build/library.make diff --git a/mcs/class/I18N/CJK/Test/I18N.CJK.Test.cs b/mcs/class/I18N/CJK/Test/I18N.CJK.Test.cs index 2c045c450a..e2a2547851 100644 --- a/mcs/class/I18N/CJK/Test/I18N.CJK.Test.cs +++ b/mcs/class/I18N/CJK/Test/I18N.CJK.Test.cs @@ -12,6 +12,8 @@ using System.IO; using System.Text; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.I18N.CJK { [TestFixture] @@ -81,19 +83,19 @@ namespace MonoTests.I18N.CJK [Test] public void CP936_Encode () { - AssertEncode ("Test/texts/chinese-utf8.txt", "Test/texts/chinese-936.txt", 936); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese-936.txt"), 936); } [Test] public void CP936_Encode3 () { - AssertEncode("Test/texts/chinese3-utf8.txt", "Test/texts/chinese3-936.txt", 936); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese3-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese3-936.txt"), 936); } [Test] public void CP936_Decode () { - AssertDecode ("Test/texts/chinese-utf8.txt", "Test/texts/chinese-936.txt", 936); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese-936.txt"), 936); } [Test] @@ -114,19 +116,19 @@ namespace MonoTests.I18N.CJK [Test] public void CP950_Encode () { - AssertEncode ("Test/texts/chinese2-utf8.txt", "Test/texts/chinese2-950.txt", 950); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese2-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese2-950.txt"), 950); } [Test] public void CP950_Encode4 () { - AssertEncode("Test/texts/chinese4-utf8.txt", "Test/texts/chinese4-950.txt", 950); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese4-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese4-950.txt"), 950); } [Test] public void CP950_Decode () { - AssertDecode ("Test/texts/chinese2-utf8.txt", "Test/texts/chinese2-950.txt", 950); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese2-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese2-950.txt"), 950); } // GB18030 @@ -134,13 +136,13 @@ namespace MonoTests.I18N.CJK [Test] public void CP54936_Encode () { - AssertEncode ("Test/texts/chinese-utf8.txt", "Test/texts/chinese-54936.txt", 54936); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese-54936.txt"), 54936); } [Test] public void CP54936_Decode () { - AssertDecode ("Test/texts/chinese-utf8.txt", "Test/texts/chinese-54936.txt", 54936); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/chinese-54936.txt"), 54936); } #endregion @@ -152,13 +154,13 @@ namespace MonoTests.I18N.CJK [Test] public void CP932_Encode () { - AssertEncode ("Test/texts/japanese-utf8.txt", "Test/texts/japanese-932.txt", 932); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-932.txt"), 932); } [Test] public void CP932_Decode () { - AssertDecode ("Test/texts/japanese-utf8.txt", "Test/texts/japanese-932.txt", 932); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-932.txt"), 932); } [Test] @@ -175,13 +177,13 @@ namespace MonoTests.I18N.CJK [Test] public void CP51932_Encode () { - AssertEncode ("Test/texts/japanese-utf8.txt", "Test/texts/japanese-51932.txt", 51932); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-51932.txt"), 51932); } [Test] public void CP51932_Decode () { - AssertDecode ("Test/texts/japanese-utf8.txt", "Test/texts/japanese-51932.txt", 51932); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-51932.txt"), 51932); } // ISO-2022-JP @@ -189,49 +191,49 @@ namespace MonoTests.I18N.CJK [Test] public void CP50220_Encode () { - AssertEncode ("Test/texts/japanese2-utf8.txt", "Test/texts/japanese2-50220.txt", 50220); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese2-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese2-50220.txt"), 50220); } [Test] public void CP50220_Encode_3 () { - AssertEncode("Test/texts/japanese3-utf8.txt", "Test/texts/japanese3-50220.txt", 50220); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese3-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese3-50220.txt"), 50220); } [Test] public void CP50220_Decode () { - AssertDecode ("Test/texts/japanese2-utf8.txt", "Test/texts/japanese2-50220.txt", 50220); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese2-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese2-50220.txt"), 50220); } [Test] public void CP50221_Encode () { - AssertEncode ("Test/texts/japanese-utf8.txt", "Test/texts/japanese-50221.txt", 50221); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-50221.txt"), 50221); } [Test] public void CP50221_Encode_3() { - AssertEncode("Test/texts/japanese3-utf8.txt", "Test/texts/japanese3-50221.txt", 50221); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese3-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese3-50221.txt"), 50221); } [Test] public void CP50221_Decode () { - AssertDecode ("Test/texts/japanese-utf8.txt", "Test/texts/japanese-50221.txt", 50221); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-50221.txt"), 50221); } [Test] public void CP50222_Encode () { - AssertEncode ("Test/texts/japanese-utf8.txt", "Test/texts/japanese-50222.txt", 50222); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-50222.txt"), 50222); } [Test] public void CP50222_Decode () { - AssertDecode ("Test/texts/japanese-utf8.txt", "Test/texts/japanese-50222.txt", 50222); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/japanese-50222.txt"), 50222); } [Test] @@ -585,13 +587,13 @@ namespace MonoTests.I18N.CJK [Test] public void CP949_Encode () { - AssertEncode ("Test/texts/korean-utf8.txt", "Test/texts/korean-949.txt", 949); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/korean-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/korean-949.txt"), 949); } [Test] public void CP949_Decode () { - AssertDecode ("Test/texts/korean-utf8.txt", "Test/texts/korean-949.txt", 949); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/korean-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/korean-949.txt"), 949); } #endregion diff --git a/mcs/class/I18N/MidEast/I18N.MidEast_test.dll.sources b/mcs/class/I18N/MidEast/I18N.MidEast_test.dll.sources index 3dc561486e..3048bdd42f 100644 --- a/mcs/class/I18N/MidEast/I18N.MidEast_test.dll.sources +++ b/mcs/class/I18N/MidEast/I18N.MidEast_test.dll.sources @@ -1,3 +1,4 @@ +../../../test-helpers/TestResourceHelper.cs ../../EncodingTestBase.cs I18N.MidEast.EncodingTest.cs I18N.MidEast.Test.cs diff --git a/mcs/class/I18N/MidEast/Makefile b/mcs/class/I18N/MidEast/Makefile index 1fa7d0533d..9b9cba1514 100644 --- a/mcs/class/I18N/MidEast/Makefile +++ b/mcs/class/I18N/MidEast/Makefile @@ -8,7 +8,10 @@ KEYFILE = ../../mono.pub LOCAL_MCS_FLAGS = /unsafe TEST_LIB_REFS = I18N +TEST_RESOURCE_FILES = $(wildcard Test/texts/*.txt) +TEST_MCS_FLAGS = $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) + EXTRA_DISTFILES = $(wildcard *.ucm) \ - $(wildcard Test/texts/*.txt) + $(TEST_RESOURCE_FILES) include ../../../build/library.make diff --git a/mcs/class/I18N/MidEast/Test/I18N.MidEast.Test.cs b/mcs/class/I18N/MidEast/Test/I18N.MidEast.Test.cs index 85b03b3be3..72dd0bdee2 100644 --- a/mcs/class/I18N/MidEast/Test/I18N.MidEast.Test.cs +++ b/mcs/class/I18N/MidEast/Test/I18N.MidEast.Test.cs @@ -14,6 +14,8 @@ using System.IO; using System.Text; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.I18N.MidEast { [TestFixture] @@ -96,7 +98,7 @@ namespace MonoTests.I18N.MidEast public void HandleFallback_Encode_Generic(int cp) { - AssertEncode ("Test/texts/encoder-handlefallback-generic-utf8.txt", "Test/texts/encoder-handlefallback-generic-output.txt", cp, "error_foobar"); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/encoder-handlefallback-generic-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/encoder-handlefallback-generic-output.txt"), cp, "error_foobar"); } [Test] @@ -109,13 +111,13 @@ namespace MonoTests.I18N.MidEast public void Ascii_Test_All() { foreach (int cp in cps) - AssertEncode("Test/texts/ascii-test.txt", "Test/texts/ascii-test.txt", cp); + AssertEncode(TestResourceHelper.GetFullPathOfResource ("Test/texts/ascii-test.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/ascii-test.txt"), cp); } [Test] public void CP1254_Encode () { - AssertEncode ("Test/texts/turkish-utf8.txt", "Test/texts/turkish-1254.txt", 1254); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/turkish-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/turkish-1254.txt"), 1254); } } } diff --git a/mcs/class/I18N/Rare/I18N.Rare_test.dll.sources b/mcs/class/I18N/Rare/I18N.Rare_test.dll.sources index e787b1805c..4d72bd3613 100644 --- a/mcs/class/I18N/Rare/I18N.Rare_test.dll.sources +++ b/mcs/class/I18N/Rare/I18N.Rare_test.dll.sources @@ -1,3 +1,4 @@ +../../../test-helpers/TestResourceHelper.cs ../../EncodingTestBase.cs I18N.Rare.EncodingTest.cs I18N.Rare.Test.cs diff --git a/mcs/class/I18N/Rare/Makefile b/mcs/class/I18N/Rare/Makefile index 0eb6f79717..aa6d282d9b 100644 --- a/mcs/class/I18N/Rare/Makefile +++ b/mcs/class/I18N/Rare/Makefile @@ -8,7 +8,10 @@ KEYFILE = ../../mono.pub LOCAL_MCS_FLAGS = /unsafe TEST_LIB_REFS = I18N +TEST_RESOURCE_FILES = $(wildcard Test/texts/*.txt) +TEST_MCS_FLAGS = $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) + EXTRA_DISTFILES = $(wildcard *.ucm) \ - $(wildcard Test/texts/*.txt) + $(TEST_RESOURCE_FILES) include ../../../build/library.make diff --git a/mcs/class/I18N/Rare/Test/I18N.Rare.Test.cs b/mcs/class/I18N/Rare/Test/I18N.Rare.Test.cs index efdc5f7ad5..026e31c790 100644 --- a/mcs/class/I18N/Rare/Test/I18N.Rare.Test.cs +++ b/mcs/class/I18N/Rare/Test/I18N.Rare.Test.cs @@ -31,6 +31,8 @@ using System.IO; using System.Text; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.I18N.Rare { [TestFixture] @@ -68,7 +70,7 @@ namespace MonoTests.I18N.Rare [TestCaseSource (nameof (cps))] public void Ascii_Test_All(int cp) { - AssertDecode("Test/texts/ascii-test.txt", "Test/texts/ascii-test.txt", cp); + AssertDecode(TestResourceHelper.GetFullPathOfResource ("Test/texts/ascii-test.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/ascii-test.txt"), cp); } } } diff --git a/mcs/class/I18N/West/I18N.West_test.dll.sources b/mcs/class/I18N/West/I18N.West_test.dll.sources index bf39542632..cc16b0fbf4 100644 --- a/mcs/class/I18N/West/I18N.West_test.dll.sources +++ b/mcs/class/I18N/West/I18N.West_test.dll.sources @@ -1,3 +1,4 @@ +../../../test-helpers/TestResourceHelper.cs ../../EncodingTestBase.cs I18N.West.EncodingTest.cs I18N.West.Test.cs diff --git a/mcs/class/I18N/West/Makefile b/mcs/class/I18N/West/Makefile index 1a2e72ea21..7c2786b0b8 100644 --- a/mcs/class/I18N/West/Makefile +++ b/mcs/class/I18N/West/Makefile @@ -6,9 +6,11 @@ LIBRARY = I18N.West.dll LIB_REFS = I18N KEYFILE = ../../mono.pub LOCAL_MCS_FLAGS = /unsafe -#NO_TEST = yes + +TEST_RESOURCE_FILES = $(wildcard Test/texts/*.txt) +TEST_MCS_FLAGS = $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) EXTRA_DISTFILES = $(wildcard *.ucm) \ - $(wildcard Test/texts/*.txt) + $(TEST_RESOURCE_FILES) include ../../../build/library.make diff --git a/mcs/class/I18N/West/Test/I18N.West.Test.cs b/mcs/class/I18N/West/Test/I18N.West.Test.cs index 4b735c50f9..1bcd26378d 100644 --- a/mcs/class/I18N/West/Test/I18N.West.Test.cs +++ b/mcs/class/I18N/West/Test/I18N.West.Test.cs @@ -12,6 +12,8 @@ using System.IO; using System.Text; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.I18N.West { [TestFixture] @@ -66,145 +68,145 @@ namespace MonoTests.I18N.West [Test] public void CP437_Encode () { - AssertEncode ("Test/texts/box-utf8.txt", "Test/texts/box-437.txt", 437); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/box-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/box-437.txt"), 437); } [Test] public void CP437_Decode () { - AssertDecode ("Test/texts/box-utf8.txt", "Test/texts/box-437.txt", 437); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/box-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/box-437.txt"), 437); } [Test] public void CP850_Encode () { - AssertEncode ("Test/texts/latin-utf8.txt", "Test/texts/latin-850.txt", 850); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/latin-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/latin-850.txt"), 850); } [Test] public void CP850_Decode () { - AssertDecode ("Test/texts/latin-utf8.txt", "Test/texts/latin-850.txt", 850); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/latin-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/latin-850.txt"), 850); } [Test] public void CP860_Encode () { - AssertEncode ("Test/texts/portguese-utf8.txt", "Test/texts/portguese-860.txt", 860); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/portguese-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/portguese-860.txt"), 860); } [Test] public void CP860_Decode () { - AssertDecode ("Test/texts/portguese-utf8.txt", "Test/texts/portguese-860.txt", 860); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/portguese-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/portguese-860.txt"), 860); } [Test] public void CP861_Encode () { - AssertEncode ("Test/texts/icelandic2-utf8.txt", "Test/texts/icelandic2-861.txt", 861); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/icelandic2-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/icelandic2-861.txt"), 861); } [Test] public void CP861_Decode () { - AssertDecode ("Test/texts/icelandic2-utf8.txt", "Test/texts/icelandic2-861.txt", 861); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/icelandic2-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/icelandic2-861.txt"), 861); } [Test] public void CP863_Encode () { - AssertEncode ("Test/texts/french2-utf8.txt", "Test/texts/french2-863.txt", 863); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/french2-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/french2-863.txt"), 863); } [Test] public void CP863_Decode () { - AssertDecode ("Test/texts/french2-utf8.txt", "Test/texts/french2-863.txt", 863); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/french2-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/french2-863.txt"), 863); } [Test] public void CP865_Encode () { - AssertEncode ("Test/texts/nordic-utf8.txt", "Test/texts/nordic-865.txt", 865); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/nordic-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/nordic-865.txt"), 865); } [Test] public void CP865_Decode () { - AssertDecode ("Test/texts/nordic-utf8.txt", "Test/texts/nordic-865.txt", 865); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/nordic-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/nordic-865.txt"), 865); } [Test] public void CP1250_Encode () { - AssertEncode ("Test/texts/polish-utf8.txt", "Test/texts/polish-1250.txt", 1250); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/polish-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/polish-1250.txt"), 1250); } [Test] public void CP1250_Decode () { - AssertDecode ("Test/texts/polish-utf8.txt", "Test/texts/polish-1250.txt", 1250); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/polish-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/polish-1250.txt"), 1250); } [Test] public void CP1252_Encode () { - AssertEncode ("Test/texts/norwegian-utf8.txt", "Test/texts/norwegian-1252.txt", 1252); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/norwegian-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/norwegian-1252.txt"), 1252); } [Test] public void CP1252_Decode () { - AssertDecode ("Test/texts/norwegian-utf8.txt", "Test/texts/norwegian-1252.txt", 1252); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/norwegian-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/norwegian-1252.txt"), 1252); } [Test] public void CP1253_Encode () { - AssertEncode ("Test/texts/greek-utf8.txt", "Test/texts/greek-1253.txt", 1253); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/greek-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/greek-1253.txt"), 1253); } [Test] public void CP1253_Decode () { - AssertDecode ("Test/texts/greek-utf8.txt", "Test/texts/greek-1253.txt", 1253); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/greek-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/greek-1253.txt"), 1253); } [Test] public void CP10000_Encode () { - AssertEncode ("Test/texts/french-utf8.txt", "Test/texts/french-10000.txt", 10000); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/french-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/french-10000.txt"), 10000); } [Test] public void CP10000_Decode () { - AssertDecode ("Test/texts/french-utf8.txt", "Test/texts/french-10000.txt", 10000); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/french-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/french-10000.txt"), 10000); } [Test] public void CP10079_Encode () { - AssertEncode ("Test/texts/icelandic-utf8.txt", "Test/texts/icelandic-10079.txt", 10079); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/icelandic-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/icelandic-10079.txt"), 10079); } [Test] public void CP10079_Decode () { - AssertDecode ("Test/texts/icelandic-utf8.txt", "Test/texts/icelandic-10079.txt", 10079); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/icelandic-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/icelandic-10079.txt"), 10079); } [Test] public void CP28592_Encode () { - AssertEncode ("Test/texts/hungarian-utf8.txt", "Test/texts/hungarian-28592.txt", 28592); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/hungarian-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/hungarian-28592.txt"), 28592); } [Test] public void CP28592_Decode () { - AssertDecode ("Test/texts/hungarian-utf8.txt", "Test/texts/hungarian-28592.txt", 28592); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/hungarian-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/hungarian-28592.txt"), 28592); } // FIXME: Which language is good enough to test 28593 ??? @@ -212,26 +214,26 @@ namespace MonoTests.I18N.West [Test] public void CP28597_Encode () { - AssertEncode ("Test/texts/greek-utf8.txt", "Test/texts/greek-28597.txt", 28597); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/greek-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/greek-28597.txt"), 28597); } [Test] public void CP28597_Decode () { - AssertDecode ("Test/texts/greek-utf8.txt", "Test/texts/greek-28597.txt", 28597); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/greek-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/greek-28597.txt"), 28597); } // FIXME: Which language is good enough to test 28605 ??? [Test] public void CP28605_Encode () { - AssertEncode ("Test/texts/latin-utf8.txt", "Test/texts/latin-28605.txt", 28605); + AssertEncode (TestResourceHelper.GetFullPathOfResource ("Test/texts/latin-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/latin-28605.txt"), 28605); } [Test] public void CP28605_Decode () { - AssertDecode ("Test/texts/latin-utf8.txt", "Test/texts/latin-28605.txt", 28605); + AssertDecode (TestResourceHelper.GetFullPathOfResource ("Test/texts/latin-utf8.txt"), TestResourceHelper.GetFullPathOfResource ("Test/texts/latin-28605.txt"), 28605); } [Test] diff --git a/mcs/class/Makefile b/mcs/class/Makefile index 680bd0e05e..b725f9be52 100644 --- a/mcs/class/Makefile +++ b/mcs/class/Makefile @@ -1,6 +1,10 @@ thisdir = class -pcl_facade_dirs := Facades +NO_FACADES_PROFILE := $(filter monodroid_tools binary_reference_assemblies xbuild_12 xbuild_14, $(PROFILE)) + +ifndef NO_FACADES_PROFILE +FACADES_FOLDER := Facades +endif -include ../build/config.make @@ -27,11 +31,16 @@ basic_SUBDIRS := \ ../ilasm \ corlib/il -build_SUBDIRS := \ +# Tooling dependencies of mscorlib, we build them to /tmp folder for MONO_PATH to work +# reliably for clean and update builds. All deps are built against stable API to run with +# range of boostrap versions and .NET at the same time +build_SUBDIRS = \ Mono.Cecil \ $(MCS_MODE_dirs) \ ../tools/cil-stringreplacer \ - corlib \ + corlib + +build_PARALLEL_SUBDIRS = \ Mono.Security \ System \ System.XML \ @@ -48,15 +57,23 @@ build_SUBDIRS := \ PEAPI ifdef MCS_MODE -basic_PARALLEL_SUBDIRS := ../mcs $(pcl_facade_dirs) -build_PARALLEL_SUBDIRS := ../mcs $(pcl_facade_dirs) -else -basic_PARALLEL_SUBDIRS := $(pcl_facade_dirs) -build_PARALLEL_SUBDIRS := $(pcl_facade_dirs) +basic_PARALLEL_SUBDIRS := ../mcs + +build_SUBDIRS += \ + Mono.Security \ + System \ + System.XML \ + System.Security \ + Mono.Posix \ + System.Core + +build_PARALLEL_SUBDIRS += ../mcs endif mobile_common_dirs := \ - corlib \ + corlib + +mobile_common_dirs_parallel := \ Mono.Security \ System \ System.Core \ @@ -86,75 +103,81 @@ mobile_common_dirs := \ System.Net.Http \ System.Windows \ System.Xml.Serialization \ - Mono.CSharp \ Microsoft.CSharp \ System.Reflection.Context \ System.Net.Http.WinHttpHandler \ System.Runtime.CompilerServices.Unsafe -testing_aot_full_dirs := \ - $(mobile_common_dirs) \ - Mono.Simd \ - $(pcl_facade_dirs) +testing_aot_full_dirs_parallel := \ + $(mobile_common_dirs_parallel) \ + Mono.Simd \ + Mono.CSharp -testing_aot_hybrid_dirs := \ - $(mobile_common_dirs) \ - Mono.Simd \ - $(pcl_facade_dirs) +testing_aot_hybrid_dirs_parallel := $(testing_aot_full_dirs_parallel) -xammac_dirs := \ - $(mobile_common_dirs) \ +xammac_dirs_parallel := \ + $(mobile_common_dirs_parallel) \ Mono.CompilerServices.SymbolWriter \ - $(pcl_facade_dirs) + Mono.CSharp -monodroid_dirs := \ - $(mobile_common_dirs) \ +monodroid_dirs_parallel := \ + $(mobile_common_dirs_parallel) \ Mono.CompilerServices.SymbolWriter \ Mono.Btls.Interface \ - Mono.Posix \ - $(pcl_facade_dirs) + Mono.Posix \ + Mono.CSharp -monodroid_tools_dirs := \ +monodroid_tools_dirs_parallel := \ Mono.Cecil \ ICSharpCode.SharpZipLib \ monodoc -monotouch_dirs := \ - $(mobile_common_dirs) \ - Mono.Simd \ - $(pcl_facade_dirs) +monotouch_dirs_parallel := \ + $(mobile_common_dirs_parallel) \ + Mono.Simd \ + Mono.CSharp \ + Mono.Runtime.Tests -monotouch_watch_dirs := $(filter-out Mono.Security Mono.Data.Tds,$(monotouch_dirs)) -monotouch_tv_dirs := $(monotouch_dirs) +monotouch_watch_dirs_parallel := $(filter-out Mono.Security Mono.Data.Tds,$(monotouch_dirs_parallel)) -monotouch_runtime_dirs := \ - corlib \ +monotouch_runtime_dirs_parallel := \ Mono.Security \ System \ System.Core \ System.XML \ Mono.CSharp -monotouch_watch_runtime_dirs := $(filter-out Mono.Security Mono.Data.Tds,$(monotouch_runtime_dirs)) -monotouch_tv_runtime_dirs := $(monotouch_runtime_dirs) +monotouch_tv_dirs_parallel := $(monotouch_dirs_parallel) -winaot_dirs := \ - $(mobile_common_dirs) \ - System.Drawing \ - $(pcl_facade_dirs) +monotouch_tv_runtime_dirs_parallel := $(monotouch_runtime_dirs_parallel) -unreal_dirs := \ - $(mobile_common_dirs) \ - System.Drawing \ - $(pcl_facade_dirs) +monotouch_watch_runtime_dirs_parallel := \ + System \ + System.Core \ + System.XML \ + Mono.CSharp -wasm_dirs := \ - $(mobile_common_dirs) \ - System.Drawing \ - $(pcl_facade_dirs) +monotouch_tv_runtime_dirs := \ + Mono.Security \ + $(monotouch_watch_runtime_dirs_parallel) -xammac_4_5_dirs := \ - corlib \ +winaot_dirs_parallel := \ + $(mobile_common_dirs_parallel) \ + System.Drawing + +unreal_dirs_parallel := \ + $(mobile_common_dirs_parallel) \ + System.Drawing + +wasm_dirs_parallel := \ + $(mobile_common_dirs_parallel) \ + System.Drawing + +orbis_dirs_parallel := \ + $(filter-out Microsoft.CSharp Mono.Data.Sqlite,$(mobile_common_dirs_parallel)) \ + System.Drawing + +xammac_4_5_dirs_parallel := \ Mono.Security \ System \ System.XML \ @@ -200,16 +223,17 @@ xammac_4_5_dirs := \ System.Net.Http.WebRequest \ System.Reflection.Context \ System.Net.Http.WinHttpHandler \ - System.Runtime.CompilerServices.Unsafe \ - $(pcl_facade_dirs) + System.Runtime.CompilerServices.Unsafe +# Could be just mscorlib but we have unhandled dependency from RabbitMQ.Client.Apigen.exe net_4_x_dirs := \ - corlib \ + corlib \ Mono.Security \ - System \ - System.XML \ + System \ + System.XML + +net_4_x_parallel_dirs = \ System.Security \ - Mono.CompilerServices.SymbolWriter \ Mono.Posix \ System.Core \ System.Configuration \ @@ -218,10 +242,9 @@ net_4_x_dirs := \ System.IO.Compression.FileSystem \ System.Transactions \ System.EnterpriseServices \ - Mono.Data.Tds \ System.Numerics \ System.Numerics.Vectors \ - System.Data \ + System.Data \ System.ComponentModel.DataAnnotations \ Accessibility \ Mono.WebBrowser \ @@ -238,16 +261,13 @@ net_4_x_dirs := \ System.Configuration.Install \ System.Management \ System.Data.OracleClient \ - Cscompmgd \ Commons.Xml.Relaxng \ Mono.Messaging \ System.Messaging \ System.ServiceProcess \ System.Drawing.Design \ ICSharpCode.SharpZipLib \ - IBM.Data.DB2 \ - CustomMarshalers \ - SystemWebTestShim \ + Microsoft.CSharp \ System.ServiceModel.Internals \ SMDiagnostics \ System.Runtime.Serialization \ @@ -262,10 +282,7 @@ net_4_x_dirs := \ System.Web.Extensions \ System.Web.Extensions.Design \ System.Web.DynamicData \ - Mono.CSharp \ System.Net \ - System.Json \ - Microsoft.CSharp \ System.Xaml \ WindowsBase \ System.ServiceModel.Activation \ @@ -284,18 +301,19 @@ net_4_x_dirs := \ System.Net.Http.Formatting \ System.Web.Http \ System.Web.Http.SelfHost \ - System.Web.Http.WebHost - -# These are the subdirs which depends on libs in net_4_x_dirs -# or have proper dependencies between each other -net_4_x_parallel_dirs := \ + System.Web.Http.WebHost \ + CustomMarshalers \ + IBM.Data.DB2 \ PEAPI \ I18N \ + Cscompmgd \ + Mono.CompilerServices.SymbolWriter \ Mono.Btls.Interface \ Mono.Http \ Mono.Cairo \ Mono.Cecil \ Mono.Cecil.Mdb \ + Mono.CSharp \ Mono.Debugger.Soft \ Mono.C5 \ Mono.Management \ @@ -306,6 +324,7 @@ net_4_x_parallel_dirs := \ Mono.Parallel \ Mono.Security.Win32 \ Mono.Messaging.RabbitMQ \ + Mono.Data.Tds \ System.Dynamic \ System.Windows.Forms.DataVisualization \ System.Reactive.Interfaces \ @@ -323,6 +342,7 @@ net_4_x_parallel_dirs := \ System.Data.Services \ System.Data.Entity \ System.Data.DataSetExtensions \ + System.Json \ System.Json.Microsoft \ System.Threading.Tasks.Dataflow \ System.ComponentModel.Composition.4.5 \ @@ -344,51 +364,69 @@ net_4_x_parallel_dirs := \ Mono.Runtime.Tests \ System.Runtime.CompilerServices.Unsafe \ legacy/Mono.Cecil \ - $(pcl_facade_dirs) + SystemWebTestShim \ + $(xbuild_4_0_dirs) -xbuild_2_0_dirs := \ +xbuild_4_0_dirs := \ Microsoft.Build.Framework \ Microsoft.Build.Utilities \ Microsoft.Build.Engine \ Mono.XBuild.Tasks \ - Microsoft.Build.Tasks - -xbuild_4_0_dirs := \ - $(xbuild_2_0_dirs) \ + Microsoft.Build.Tasks \ Microsoft.Build -orbis_dirs := \ - $(filter-out Microsoft.CSharp Mono.CSharp Mono.Data.Sqlite,$(mobile_common_dirs)) \ - System.Drawing \ - $(pcl_facade_dirs) +monodroid_SUBDIRS := $(mobile_common_dirs) +monodroid_PARALLEL_SUBDIRS := $(monodroid_dirs_parallel) +monodroid_tools_SUBDIRS := +monodroid_tools_PARALLEL_SUBDIRS := $(monodroid_tools_dirs_parallel) + +monotouch_SUBDIRS := $(mobile_common_dirs) +monotouch_PARALLEL_SUBDIRS := $(monotouch_dirs_parallel) +monotouch_watch_SUBDIRS := $(mobile_common_dirs) +monotouch_watch_PARALLEL_SUBDIRS := $(monotouch_watch_dirs_parallel) +monotouch_tv_SUBDIRS := $(mobile_common_dirs) +monotouch_tv_PARALLEL_SUBDIRS := $(monotouch_tv_dirs_parallel) +monotouch_runtime_SUBDIRS := $(mobile_common_dirs) +monotouch_runtime_PARALLEL_SUBDIRS := $(monotouch_runtime_dirs_parallel) +monotouch_watch_runtime_SUBDIRS := $(mobile_common_dirs) +monotouch_watch_runtime_PARALLEL_SUBDIRS := $(monotouch_watch_runtime_dirs_parallel) +monotouch_tv_runtime_SUBDIRS := $(mobile_common_dirs) +monotouch_tv_runtime_PARALLEL_SUBDIRS := $(monotouch_tv_runtime_dirs_parallel) + +testing_aot_full_SUBDIRS := $(mobile_common_dirs) +testing_aot_full_PARALLEL_SUBDIRS := $(testing_aot_full_dirs_parallel) +testing_aot_hybrid_SUBDIRS := $(mobile_common_dirs) +testing_aot_hybrid_PARALLEL_SUBDIRS := $(testing_aot_hybrid_dirs_parallel) + +xammac_SUBDIRS := $(mobile_common_dirs) +xammac_PARALLEL_SUBDIRS := $(xammac_dirs_parallel) +xammac_net_4_5_SUBDIRS := $(mobile_common_dirs) +xammac_net_4_5_PARALLEL_SUBDIRS := $(xammac_4_5_dirs_parallel) -monodroid_SUBDIRS := $(monodroid_dirs) -monodroid_tools_SUBDIRS := $(monodroid_tools_dirs) -monotouch_SUBDIRS := $(monotouch_dirs) -monotouch_watch_SUBDIRS := $(monotouch_watch_dirs) -monotouch_tv_SUBDIRS := $(monotouch_tv_dirs) -monotouch_runtime_SUBDIRS := $(monotouch_runtime_dirs) -monotouch_watch_runtime_SUBDIRS := $(monotouch_watch_runtime_dirs) -monotouch_tv_runtime_SUBDIRS := $(monotouch_tv_runtime_dirs) -testing_aot_full_SUBDIRS := $(testing_aot_full_dirs) -testing_aot_hybrid_SUBDIRS := $(testing_aot_hybrid_dirs) -xammac_SUBDIRS := $(xammac_dirs) -xammac_net_4_5_SUBDIRS := $(xammac_4_5_dirs) binary_reference_assemblies_SUBDIRS := reference-assemblies -net_4_x_SUBDIRS := $(net_4_x_dirs) $(xbuild_4_0_dirs) +net_4_x_SUBDIRS := $(net_4_x_dirs) net_4_x_PARALLEL_SUBDIRS := $(net_4_x_parallel_dirs) xbuild_12_SUBDIRS := $(xbuild_4_0_dirs) xbuild_14_SUBDIRS := $(xbuild_4_0_dirs) Microsoft.NuGet.Build.Tasks -winaot_SUBDIRS := $(winaot_dirs) -orbis_SUBDIRS := $(orbis_dirs) -unreal_SUBDIRS := $(unreal_dirs) -wasm_SUBDIRS := $(wasm_dirs) + +winaot_SUBDIRS := $(mobile_common_dirs) +winaot_PARALLEL_SUBDIRS := $(winaot_dirs_parallel) + +orbis_SUBDIRS := $(mobile_common_dirs) +orbis_PARALLEL_SUBDIRS := $(orbis_dirs_parallel) + +unreal_SUBDIRS := $(mobile_common_dirs) +unreal_PARALLEL_SUBDIRS := $(unreal_dirs_parallel) + +wasm_SUBDIRS := $(mobile_common_dirs) +wasm_PARALLEL_SUBDIRS := $(wasm_dirs_parallel) include ../build/rules.make -SUBDIRS = $(testing_aot_full_dirs) $(testing_aot_hybrid_dirs) $(monotouch_dirs) $(monodroid_dirs) $(monodroid_tools_dirs) $(xammac_dirs) $(net_4_x_dirs) $(net_4_x_parallel_dirs) $(xammac_net_4_5_SUBDIRS) $(unreal_dirs) - -DIST_ONLY_SUBDIRS = dlr aot-compiler reference-assemblies $(xbuild_4_0_dirs) Microsoft.NuGet.Build.Tasks +DIST_SUBDIRS = $(testing_aot_full_dirs_parallel) $(testing_aot_hybrid_dirs_parallel) $(monotouch_dirs_parallel) \ +$(monodroid_dirs_parallel) $(monodroid_tools_dirs_parallel) $(xammac_dirs_parallel) $(net_4_x_dirs) $(net_4_x_parallel_dirs) \ +$(xammac_4_5_dirs_parallel) $(unreal_dirs_parallel) $(wasm_dirs_parallel) $(xbuild_14_SUBDIRS) \ +dlr aot-compiler reference-assemblies Facades # No new makefiles for: System.Messaging, System.Web.Mobile, # System.ServiceProcess @@ -418,6 +456,7 @@ DISTFILES = \ test-helpers/RemoteExecutorTestBase.Mobile.cs \ test-helpers/RemoteExecutorTestBase.Mono.cs \ test-helpers/SocketResponder.cs \ + test-helpers/TestResourceHelper.cs \ $(foreach HOST_PLATFORM,macos linux win32 unix,lib/$(monolite_dir)/mcs.exe $(monolite_files)) .PHONY: all-local $(STD_TARGETS:=-local) @@ -495,3 +534,9 @@ csproj-local: do-clean: $(RM) -rf $(topdir)/class/lib/$(PROFILE) + +## Aliases for .dep_dirs-* tracker +.PHONY: Microsoft.Build.Utilities.v4.0 System.ComponentModel.Composition System.Xml +Microsoft.Build.Utilities.v4.0: Microsoft.Build.Utilities +System.ComponentModel.Composition: System.ComponentModel.Composition.4.5 +System.Xml: System.XML diff --git a/mcs/class/Microsoft.Build.Engine/Makefile b/mcs/class/Microsoft.Build.Engine/Makefile index 30fdb0fd1e..a79619f955 100644 --- a/mcs/class/Microsoft.Build.Engine/Makefile +++ b/mcs/class/Microsoft.Build.Engine/Makefile @@ -11,13 +11,15 @@ LIB_REFS = $(PARENT_PROFILE)System $(PARENT_PROFILE)System.Core $(PARENT_PROFILE KEYFILE = ../msfinal.pub LIB_MCS_FLAGS = -TEST_MCS_FLAGS = +TEST_RESOURCE_FILES = \ + $(wildcard Test/resources/*.csproj) + +TEST_MCS_FLAGS = $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) TEST_LIB_REFS = $(XBUILD_FRAMEWORK) $(XBUILD_UTILITIES) $(PARENT_PROFILE)System.Xml TEST_NUNITLITE_APP_CONFIG_RUNTIME=Test/test-config-file-$(PROFILE) EXTRA_DISTFILES = \ Test/resources/TestTasks.cs \ - Test/resources/*.*proj \ Test/resources/*.csproj CLEAN_FILES = Test/resources/TestTasks-$(PROFILE).dll Test/resources/TestTasks-$(PROFILE).dll.mdb Test/resources/TestTasks-$(PROFILE).pdb @@ -25,13 +27,13 @@ CLEAN_FILES = Test/resources/TestTasks-$(PROFILE).dll Test/resources/TestTasks-$ Test/resources/TestTasks-$(PROFILE).dll: Test/resources/TestTasks.cs $(CSCOMPILE) /out:$@ Test/resources/TestTasks.cs /r:$(topdir)/class/lib/$(PROFILE)/$(PARENT_PROFILE)/mscorlib.dll /r:$(topdir)/class/lib/$(PROFILE)/$(XBUILD_FRAMEWORK).dll /r:$(topdir)/class/lib/$(PROFILE)/$(XBUILD_UTILITIES).dll /target:library -test-local: compile-resources +TEST_MCS_FLAGS += -resource:Test/resources/TestTasks-$(PROFILE).dll,Test/resources/TestTasks.dll -compile-resources: Test/resources/TestTasks-$(PROFILE).dll - cp Test/resources/TestTasks-$(PROFILE).dll Test/resources/TestTasks.dll ifndef MCS_MODE - cp Test/resources/TestTasks-$(PROFILE).pdb Test/resources/TestTasks.pdb +TEST_MCS_FLAGS += -resource:Test/resources/TestTasks-$(PROFILE).pdb,Test/resources/TestTasks.pdb endif +test-local: Test/resources/TestTasks-$(PROFILE).dll + include $(XBUILD_DIR)/xbuild_test.make include ../../build/library.make diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.Engine_test.dll.sources b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.Engine_test.dll.sources index 7ffded4450..6b4309e98f 100644 --- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.Engine_test.dll.sources +++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.Engine_test.dll.sources @@ -1,3 +1,4 @@ +../../test-helpers/TestResourceHelper.cs Microsoft.Build.BuildEngine/BuildChooseTest.cs Microsoft.Build.BuildEngine/BuildItemGroupCollectionTest.cs Microsoft.Build.BuildEngine/BuildItemGroupTest.cs diff --git a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/BuildItemTest.cs b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/BuildItemTest.cs index 918c3ff8ae..0bff449649 100644 --- a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/BuildItemTest.cs +++ b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/BuildItemTest.cs @@ -31,6 +31,8 @@ using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.BuildEngine { [TestFixture] public class BuildItemTest { @@ -919,7 +921,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { public void TestBuildItemTransform () { string projectText = @" - + diff --git a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/BuildPropertyTest.cs b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/BuildPropertyTest.cs index f5f0472292..5df2d75e49 100644 --- a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/BuildPropertyTest.cs +++ b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/BuildPropertyTest.cs @@ -33,6 +33,8 @@ using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.BuildEngine { [TestFixture] public class BuildPropertyTest { diff --git a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/BuildTaskTest.cs b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/BuildTaskTest.cs index 1d3da0f4ef..d10f37167a 100644 --- a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/BuildTaskTest.cs +++ b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/BuildTaskTest.cs @@ -33,6 +33,8 @@ using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.BuildEngine { [TestFixture] public class BuildTaskTest { @@ -321,7 +323,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -356,7 +358,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -416,7 +418,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -449,7 +451,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" diff --git a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/EngineTest.cs b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/EngineTest.cs index 0a9edff4e5..2c0f75353b 100755 --- a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/EngineTest.cs +++ b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/EngineTest.cs @@ -996,6 +996,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { // helper methods for TestGlobalProperties* void WriteGlobalPropertiesProjects (string mainProject, string firstProject, string secondProject) { + Directory.CreateDirectory (Path.Combine ("Test", "resources")); using (StreamWriter sw = new StreamWriter (Path.Combine ("Test", Path.Combine ("resources", "main.proj")))) { sw.Write (mainProject); } diff --git a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/ImportCollectionTest.cs b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/ImportCollectionTest.cs index 2f9160bded..7efc7d080a 100644 --- a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/ImportCollectionTest.cs +++ b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/ImportCollectionTest.cs @@ -32,6 +32,8 @@ using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.BuildEngine { [TestFixture] public class ImportCollectionTest { @@ -60,8 +62,8 @@ namespace MonoTests.Microsoft.Build.BuildEngine { { string documentString = @" - - + + "; @@ -81,7 +83,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { { string documentString = @" - + "; @@ -99,7 +101,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { { string documentString = @" - + "; @@ -117,7 +119,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { { string documentString = @" - + "; @@ -135,7 +137,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { { string documentString = @" - + "; @@ -153,7 +155,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { { string documentString = @" - + "; diff --git a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/ImportTest.cs b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/ImportTest.cs index 6edebb8461..9c773a41c4 100644 --- a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/ImportTest.cs +++ b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/ImportTest.cs @@ -33,6 +33,8 @@ using Microsoft.Build.Utilities; using NUnit.Framework; using System.IO; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.BuildEngine { [TestFixture] public class ImportTest { @@ -63,7 +65,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" - + "; @@ -111,7 +113,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { { string documentString = @" - + "; @@ -128,7 +130,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { { string documentString = @" - + "; @@ -145,7 +147,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { { string documentString = @" - + "; @@ -167,7 +169,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { { string documentString = @" - + "; engine = new Engine (Consts.BinPath); @@ -181,7 +183,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { { string documentString = @" - + "; @@ -199,7 +201,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { { string documentString = @" - + "; diff --git a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/ProjectTest.cs b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/ProjectTest.cs index 594c085877..f4357de4c9 100644 --- a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/ProjectTest.cs +++ b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/ProjectTest.cs @@ -40,6 +40,8 @@ using System.Text; using MBT = MonoTests.Microsoft.Build.Tasks; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.BuildEngine { class TestLogger : Logger { @@ -155,7 +157,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { - + "; @@ -1055,7 +1057,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" - + @@ -1306,7 +1308,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { { //test for multiple items with same metadata also string projectString = @" - + Abc Def @@ -1346,7 +1348,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { public void TestBatchedMetadataRef2 () { string projectString = @" - + Abc Def @@ -1400,7 +1402,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { public void TestBatchedMetadataRef3 () { string projectString = @" - + Abc Def @@ -1436,7 +1438,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { public void TestBatchedMetadataRef4 () { string projectString = @" - + Abc Def @@ -1465,7 +1467,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { public void TestBatchedMetadataRef5 () { string projectString = @" - + Abc Def @@ -1500,7 +1502,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { [Category ("NotDotNet")] public void TestBatchedMetadataRefInOutput () { string projectString = @" - + Abc Def @@ -2265,7 +2267,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string expected_output_msg) { string projectString = String.Format (@" - + <{0} Property=""{1}""> diff --git a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/TargetTest.cs b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/TargetTest.cs index d36ae15870..e73a05d12f 100644 --- a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/TargetTest.cs +++ b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/TargetTest.cs @@ -36,6 +36,8 @@ using NUnit.Framework; using System.IO; using System.Xml; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.BuildEngine { [TestFixture] public class TargetTest { @@ -1038,7 +1040,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { { engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); - project.Load (Path.Combine ("Test", Path.Combine ("resources", "TestReturns.csproj"))); + project.Load (TestResourceHelper.GetFullPathOfResource ("Test/resources/TestReturns.csproj")); var logger = new TestMessageLogger (); engine.RegisterLogger (logger); diff --git a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/UsingTaskCollectionTest.cs b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/UsingTaskCollectionTest.cs index fd1df4b3d2..c8939a318d 100644 --- a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/UsingTaskCollectionTest.cs +++ b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/UsingTaskCollectionTest.cs @@ -32,6 +32,8 @@ using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.BuildEngine { [TestFixture] public class UsingTaskCollectionTest { @@ -45,7 +47,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -67,11 +69,11 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -84,12 +86,12 @@ namespace MonoTests.Microsoft.Build.BuildEngine { IEnumerator en = project.UsingTasks.GetEnumerator (); en.MoveNext (); - Assert.AreEqual ("Test/resources/TestTasks.dll", ((UsingTask) en.Current).AssemblyFile, "A1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/TestTasks.dll"), ((UsingTask) en.Current).AssemblyFile, "A1"); Assert.AreEqual ("TrueTestTask", ((UsingTask) en.Current).TaskName, "A2"); en.MoveNext (); - Assert.AreEqual ("Test/resources/TestTasks.dll", ((UsingTask) en.Current).AssemblyFile, "A3"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/TestTasks.dll"), ((UsingTask) en.Current).AssemblyFile, "A3"); Assert.AreEqual ("FalseTestTask", ((UsingTask) en.Current).TaskName, "A4"); Assert.IsFalse (en.MoveNext ()); @@ -102,7 +104,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -123,7 +125,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -145,7 +147,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -167,7 +169,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -187,7 +189,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -207,7 +209,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -230,7 +232,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" diff --git a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/UsingTaskTest.cs b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/UsingTaskTest.cs index 82d5e30091..6c0c39f5d1 100644 --- a/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/UsingTaskTest.cs +++ b/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/UsingTaskTest.cs @@ -32,6 +32,8 @@ using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.BuildEngine { [TestFixture] public class UsingTaskTest { @@ -45,7 +47,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -61,7 +63,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { UsingTask ut = (UsingTask) en.Current; - Assert.AreEqual ("Test/resources/TestTasks.dll", ut.AssemblyFile, "A1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/TestTasks.dll"), ut.AssemblyFile, "A1"); Assert.IsNull (ut.AssemblyName, "A2"); Assert.AreEqual ("true", ut.Condition, "A3"); Assert.AreEqual (false, ut.IsImported, "A4"); @@ -74,7 +76,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -89,7 +91,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { UsingTask ut = (UsingTask) en.Current; - Assert.AreEqual ("Test/resources/TestTasks.dll", ut.AssemblyFile, "A1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/TestTasks.dll"), ut.AssemblyFile, "A1"); Assert.IsNull (ut.AssemblyName, "A2"); Assert.AreEqual (null, ut.Condition, "A3"); Assert.AreEqual (false, ut.IsImported, "A4"); @@ -133,7 +135,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" "; @@ -208,11 +210,11 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -238,7 +240,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { Assert.AreEqual (2, project.UsingTasks.Count, "A0"); foreach (UsingTask ut in project.UsingTasks) { - Assert.AreEqual ("Test/resources/TestTasks.dll", ut.AssemblyFile, "A1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/TestTasks.dll"), ut.AssemblyFile, "A1"); Assert.IsNull (ut.AssemblyName, "A2"); Assert.AreEqual (null, ut.Condition, "A3"); Assert.AreEqual (false, ut.IsImported, "A4"); @@ -301,11 +303,11 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -343,7 +345,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { string documentString = @" @@ -367,7 +369,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine { UsingTask ut = (UsingTask) en.Current; - Assert.AreEqual ("Test/resources/TestTasks.dll", ut.AssemblyFile, "A1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/TestTasks.dll"), ut.AssemblyFile, "A1"); Assert.IsNull (ut.AssemblyName, "A2"); Assert.AreEqual ("false", ut.Condition, "A3"); Assert.AreEqual (false, ut.IsImported, "A4"); diff --git a/mcs/class/Microsoft.Build.Engine/Test/various/Conditions.cs b/mcs/class/Microsoft.Build.Engine/Test/various/Conditions.cs index c3c8dacabc..f8a3ebd97d 100644 --- a/mcs/class/Microsoft.Build.Engine/Test/various/Conditions.cs +++ b/mcs/class/Microsoft.Build.Engine/Test/various/Conditions.cs @@ -31,6 +31,8 @@ using System.Xml; using Microsoft.Build.BuildEngine; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.BuildEngine.Various { [TestFixture] public class Conditions { @@ -297,7 +299,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { - + "; diff --git a/mcs/class/Microsoft.Build.Engine/Test/various/EvaluationOrder.cs b/mcs/class/Microsoft.Build.Engine/Test/various/EvaluationOrder.cs index 77b45eb5bc..da2ef12ebb 100644 --- a/mcs/class/Microsoft.Build.Engine/Test/various/EvaluationOrder.cs +++ b/mcs/class/Microsoft.Build.Engine/Test/various/EvaluationOrder.cs @@ -30,6 +30,8 @@ using System.Xml; using Microsoft.Build.BuildEngine; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.BuildEngine.Various { [TestFixture] public class EvaluationOrder { @@ -242,7 +244,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - Test/resources/Import.csproj + " + TestResourceHelper.GetFullPathOfResource ("Test/resources/Import.csproj") + @" @@ -268,7 +270,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { - Test/resources/Import.csproj + " + TestResourceHelper.GetFullPathOfResource ("Test/resources/Import.csproj") + @" "; @@ -290,7 +292,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - + @@ -316,7 +318,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { - + "; @@ -340,7 +342,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { AnotherValue - + "; @@ -359,7 +361,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - + AnotherValue @@ -382,7 +384,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - + Another$(ImportedProperty) @@ -405,7 +407,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - Test\resources\TestTasks.dll + " + TestResourceHelper.GetFullPathOfResource ("Test/resources/TestTasks.dll") + @" diff --git a/mcs/class/Microsoft.Build.Engine/Test/various/Items.cs b/mcs/class/Microsoft.Build.Engine/Test/various/Items.cs index 3a07eb289f..7b9da9dcf5 100755 --- a/mcs/class/Microsoft.Build.Engine/Test/various/Items.cs +++ b/mcs/class/Microsoft.Build.Engine/Test/various/Items.cs @@ -35,6 +35,8 @@ using NUnit.Framework; using System.IO; using Microsoft.Build.Framework; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.BuildEngine.Various { [TestFixture] public class Items { @@ -722,9 +724,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { public void TestEmptyItemsWithBatching () { string project_xml = @" - - - + + + @@ -808,7 +810,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - + A @(A)g @@ -875,7 +877,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - + @@ -901,7 +903,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - + A A;B @@ -946,7 +948,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - + A A;B @@ -995,7 +997,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - + A A;B @@ -1041,7 +1043,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - + A A;B @@ -1192,7 +1194,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { { return @" - + A A;B @@ -1236,7 +1238,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - + @@ -1260,7 +1262,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - + @@ -1284,7 +1286,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - + @@ -1311,7 +1313,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { string documentString = @" - + diff --git a/mcs/class/Microsoft.Build.Engine/Test/various/Properties.cs b/mcs/class/Microsoft.Build.Engine/Test/various/Properties.cs index 144a6d72ea..0f8301539e 100644 --- a/mcs/class/Microsoft.Build.Engine/Test/various/Properties.cs +++ b/mcs/class/Microsoft.Build.Engine/Test/various/Properties.cs @@ -31,6 +31,8 @@ using System.Xml; using Microsoft.Build.BuildEngine; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.BuildEngine.Various { [TestFixture] public class Properties { @@ -72,7 +74,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various { { string documentString = @" - + A B diff --git a/mcs/class/Microsoft.Build.Tasks/Makefile b/mcs/class/Microsoft.Build.Tasks/Makefile index 09aeca3b10..a2f6f7c7b5 100644 --- a/mcs/class/Microsoft.Build.Tasks/Makefile +++ b/mcs/class/Microsoft.Build.Tasks/Makefile @@ -13,7 +13,23 @@ LIB_REFS = $(PARENT_PROFILE)System $(PARENT_PROFILE)System.Core $(PARENT_PROFILE $(XBUILD_UTILITIES) $(XBUILD_FRAMEWORK) $(XBUILD_ENGINE) $(XBUILD_TASKS) KEYFILE = ../msfinal.pub -TEST_MCS_FLAGS = +TEST_RESOURCE_FILES = \ + Test/resources/test.cs \ + Test/resources/test.dll \ + Test/resources/Sample.cs \ + Test/resources/Sample.vb \ + Test/resources/junk.txt \ + Test/resources/binary/FancyStuff.dll \ + Test/resources/binary/FancyStuff.dll.mdb \ + Test/resources/binary/SimpleWrite.dll \ + Test/resources/binary/SimpleWrite.dll.mdb \ + Test/resources/binary/Testing.dll \ + Test/resources/binary/Testing.dll.mdb \ + Test/resources/binary/XbuildReferenceBugTest.exe \ + Test/resources/binary/XbuildReferenceBugTest.exe.mdb \ + Test/resources/binary/XbuildReferenceBugTest2.exe + +TEST_MCS_FLAGS = $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) TEST_LIB_REFS = $(PARENT_PROFILE)System.Xml $(XBUILD_ENGINE) $(XBUILD_FRAMEWORK) $(XBUILD_TASKS) $(XBUILD_UTILITIES) $(PARENT_PROFILE)System.Core TEST_NUNITLITE_APP_CONFIG_RUNTIME=Test/test-config-file-$(PROFILE) @@ -22,11 +38,7 @@ ifeq (4, $(FRAMEWORK_VERSION_MAJOR)) TEST_LIB_REFS += Microsoft.Build endif -EXTRA_DISTFILES = \ - Test/resources/test.cs \ - Test/resources/Sample.cs \ - Test/resources/Sample.vb \ - Test/resources/junk.txt +EXTRA_DISTFILES = $(filter-out Test/resources/test.dll, $(TEST_RESOURCE_FILES)) Test/resources/test.dll: Test/resources/test.cs $(CSCOMPILE) -r:$(topdir)/class/lib/$(PROFILE)/mscorlib.dll -target:library /out:$@ $< diff --git a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks_test.dll.sources b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks_test.dll.sources index 4be774955d..a720834a41 100644 --- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks_test.dll.sources +++ b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks_test.dll.sources @@ -1,3 +1,4 @@ +../../test-helpers/TestResourceHelper.cs Microsoft.Build.Tasks/ALTest.cs Microsoft.Build.Tasks/AssignCultureTest.cs Microsoft.Build.Tasks/AssignProjectConfigurationTest.cs diff --git a/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/CreateCSharpManifestResourceNameTest.cs b/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/CreateCSharpManifestResourceNameTest.cs index 47f2b75e14..a5451695fb 100755 --- a/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/CreateCSharpManifestResourceNameTest.cs +++ b/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/CreateCSharpManifestResourceNameTest.cs @@ -6,6 +6,8 @@ using System.Text; using NUnit.Framework; using Microsoft.Build.BuildEngine; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.Tasks { [TestFixture] @@ -17,9 +19,8 @@ namespace MonoTests.Microsoft.Build.Tasks public CreateCSharpManifestResourceNameTest () { - string sample_cs_path = Path.Combine ("Test", Path.Combine ("resources", "Sample.cs")); - string junk_file = Path.Combine ("Test", Path.Combine ("resources", "junk.txt")); - string curdir = Path.GetDirectoryName (Environment.CurrentDirectory); + string sample_cs_path = TestResourceHelper.GetFullPathOfResource ("Test/resources/Sample.cs"); + string junk_file = TestResourceHelper.GetFullPathOfResource ("Test/resources/junk.txt"); /* {Include, LogicalName, DependentUpon, TargetPath} */ resx_no_culture_files = new string [,] { @@ -31,9 +32,9 @@ namespace MonoTests.Microsoft.Build.Tasks // can't find a C# class in the .vb file { "foo with space.resx", "RandomName", junk_file, "bar with space.resx" }, - { "Test/resources/foo with space.resx", null, "Sample.cs", null }, - { "Test/resources/foo with space.resx", "RandomName", "Sample.cs", null }, - { "Test/resources/foo with space.resx", "RandomName", "Sample.cs", "bar with space.resx"}, + { TestResourceHelper.GetFullPathOfResource ("Test/resources/foo with space.resx"), null, "Sample.cs", null }, + { TestResourceHelper.GetFullPathOfResource ("Test/resources/foo with space.resx"), "RandomName", "Sample.cs", null }, + { TestResourceHelper.GetFullPathOfResource ("Test/resources/foo with space.resx"), "RandomName", "Sample.cs", "bar with space.resx"}, // W/o dependent file { "foo with space.resx", null, null, null }, @@ -52,8 +53,8 @@ namespace MonoTests.Microsoft.Build.Tasks // can't find a C# class in the .vb file { "foo with space.de.resx", "RandomName", junk_file, "bar with space.fr.resx" }, - { "Test/resources/foo with space.de.resx", null, "Sample.cs", null }, - { "Test/resources/foo with space.de.resx", "RandomName", "Sample.cs", null}, + { TestResourceHelper.GetFullPathOfResource ("Test/resources/foo with space.de.resx"), null, "Sample.cs", null }, + { TestResourceHelper.GetFullPathOfResource ("Test/resources/foo with space.de.resx"), "RandomName", "Sample.cs", null}, // W/o dependent file { "foo with space.de.resx", null, null, null }, diff --git a/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/CreateVisualBasicManifestResourceNameTest.cs b/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/CreateVisualBasicManifestResourceNameTest.cs index b5b4b18b87..d329e2a872 100755 --- a/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/CreateVisualBasicManifestResourceNameTest.cs +++ b/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/CreateVisualBasicManifestResourceNameTest.cs @@ -7,6 +7,8 @@ using System.Text; using NUnit.Framework; using Microsoft.Build.BuildEngine; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.Tasks { [TestFixture] @@ -17,9 +19,8 @@ namespace MonoTests.Microsoft.Build.Tasks string [,] non_resx_no_culture_files, non_resx_with_culture_files; public CreateVisualBasicManifestResourceNameTest () { - string junk_file = Path.Combine ("Test", Path.Combine ("resources", "junk.txt")); - string sample_vb_path = Path.Combine ("Test", Path.Combine ("resources", "Sample.vb")); - string curdir = Path.GetDirectoryName (Environment.CurrentDirectory); + string junk_file = TestResourceHelper.GetFullPathOfResource ("Test/resources/junk.txt"); + string sample_vb_path = TestResourceHelper.GetFullPathOfResource ("Test/resources/Sample.vb"); /* {Include, LogicalName, DependentUpon, TargetPath} */ resx_no_culture_files = new string [,] { @@ -31,9 +32,9 @@ namespace MonoTests.Microsoft.Build.Tasks // can't find a C# class in the .vb file { "foo with space.resx", "RandomName", junk_file, "bar with space.resx" }, - { "Test/resources/foo with space.resx", null, "Sample.vb", null }, - { "Test/resources/foo with space.resx", "RandomName", "Sample.vb", null }, - { "Test/resources/foo with space.resx", "RandomName", "Sample.vb", "bar with space.resx"}, + { TestResourceHelper.GetFullPathOfResource ("Test/resources/foo with space.resx"), null, "Sample.vb", null }, + { TestResourceHelper.GetFullPathOfResource ("Test/resources/foo with space.resx"), "RandomName", "Sample.vb", null }, + { TestResourceHelper.GetFullPathOfResource ("Test/resources/foo with space.resx"), "RandomName", "Sample.vb", "bar with space.resx"}, // W/o dependent file { "foo with space.resx", null, null, null }, @@ -52,8 +53,8 @@ namespace MonoTests.Microsoft.Build.Tasks // can't find a C# class in the .vb file { "foo with space.de.resx", "RandomName", junk_file, "bar with space.fr.resx" }, - { "Test/resources/foo with space.de.resx", null, "Sample.vb", null }, - { "Test/resources/foo with space.de.resx", "RandomName", "Sample.vb", null}, + { TestResourceHelper.GetFullPathOfResource ("Test/resources/foo with space.de.resx"), null, "Sample.vb", null }, + { TestResourceHelper.GetFullPathOfResource ("Test/resources/foo with space.de.resx"), "RandomName", "Sample.vb", null}, // W/o dependent file { "foo with space.de.resx", null, null, null }, diff --git a/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/ManagedCompilerTest.cs b/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/ManagedCompilerTest.cs index 1134ecac40..f72b8b3c47 100644 --- a/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/ManagedCompilerTest.cs +++ b/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/ManagedCompilerTest.cs @@ -34,6 +34,8 @@ using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.Tasks { class MCExtended : ManagedCompiler { @@ -683,7 +685,7 @@ namespace MonoTests.Microsoft.Build.Tasks { mc.References = null; Assert.IsTrue (mc.CheckAllReferencesExistOnDisk (), "A2"); - string path = Path.Combine (Path.Combine ("Test", "resources"), "test.cs"); + string path = TestResourceHelper.GetFullPathOfResource ("Test/resources/test.cs"); mc.References = new ITaskItem [1] { new TaskItem (path) }; Assert.IsTrue (mc.CheckAllReferencesExistOnDisk (), "A3"); diff --git a/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/ResolveAssemblyReferenceTest.cs b/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/ResolveAssemblyReferenceTest.cs index 5d802a32fa..4e3bf07941 100644 --- a/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/ResolveAssemblyReferenceTest.cs +++ b/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/ResolveAssemblyReferenceTest.cs @@ -35,6 +35,8 @@ using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build.Tasks { [TestFixture] @@ -67,7 +69,7 @@ namespace MonoTests.Microsoft.Build.Tasks { { engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); - project.LoadXml (ResolveAssembly (null, @"Test\resources\test.dll")); + project.LoadXml (ResolveAssembly (null, TestResourceHelper.GetFullPathOfResource ("Test/resources/test.dll"))); Assert.IsTrue (project.Build ("A"), "A1"); big = project.GetEvaluatedItemsByName ("ResolvedFiles"); @@ -80,7 +82,7 @@ namespace MonoTests.Microsoft.Build.Tasks { { engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); - project.LoadXml (ResolveAssembly (null, @"Test\resources\binary\FancyStuff.dll")); + project.LoadXml (ResolveAssembly (null, TestResourceHelper.GetFullPathOfResource ("Test/resources/binary/FancyStuff.dll"))); Assert.IsTrue (project.Build ("A"), "A1"); big = project.GetEvaluatedItemsByName ("ResolvedFiles"); @@ -97,7 +99,7 @@ namespace MonoTests.Microsoft.Build.Tasks { { engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); - project.LoadXml (ResolveAssembly (null, @"Test\resources\binary\SimpleWrite.dll")); + project.LoadXml (ResolveAssembly (null, TestResourceHelper.GetFullPathOfResource ("Test/resources/binary/SimpleWrite.dll"))); Assert.IsTrue (project.Build ("A"), "A1"); big = project.GetEvaluatedItemsByName ("ResolvedFiles"); @@ -113,7 +115,7 @@ namespace MonoTests.Microsoft.Build.Tasks { { engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); - project.LoadXml (ResolveAssembly (null, @"Test\resources\binary\Testing.dll")); + project.LoadXml (ResolveAssembly (null, TestResourceHelper.GetFullPathOfResource ("Test/resources/binary/Testing.dll"))); Assert.IsTrue (project.Build ("A"), "A1"); big = project.GetEvaluatedItemsByName ("ResolvedFiles"); @@ -129,7 +131,7 @@ namespace MonoTests.Microsoft.Build.Tasks { { engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); - project.LoadXml (ResolveAssembly (null, @"Test\resources\binary\XbuildReferenceBugTest.exe")); + project.LoadXml (ResolveAssembly (null, TestResourceHelper.GetFullPathOfResource ("Test/resources/binary/XbuildReferenceBugTest.exe"))); Assert.IsTrue (project.Build ("A"), "A1"); big = project.GetEvaluatedItemsByName ("ResolvedFiles"); @@ -148,7 +150,7 @@ namespace MonoTests.Microsoft.Build.Tasks { { engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); - project.LoadXml (ResolveAssembly (null, @"Test\resources\binary\FancyStuff.dll", @"Test\resources\binary\XbuildReferenceBugTest.exe")); + project.LoadXml (ResolveAssembly (null, TestResourceHelper.GetFullPathOfResource ("Test/resources/binary/FancyStuff.dll"), TestResourceHelper.GetFullPathOfResource ("Test/resources/binary/XbuildReferenceBugTest.exe"))); Assert.IsTrue (project.Build ("A"), "A1"); big = project.GetEvaluatedItemsByName ("ResolvedFiles"); @@ -167,7 +169,7 @@ namespace MonoTests.Microsoft.Build.Tasks { { engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); - project.LoadXml (ResolveAssembly (null, @"Test\resources\binary\XbuildReferenceBugTest.exe", @"Test\resources\binary\XbuildReferenceBugTest2.exe")); + project.LoadXml (ResolveAssembly (null, TestResourceHelper.GetFullPathOfResource ("Test/resources/binary/XbuildReferenceBugTest.exe"), TestResourceHelper.GetFullPathOfResource ("Test/resources/binary/XbuildReferenceBugTest2.exe"))); Assert.IsTrue (project.Build ("A"), "A1"); big = project.GetEvaluatedItemsByName ("ResolvedFiles"); diff --git a/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/FancyStuff.dll b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/FancyStuff.dll new file mode 100755 index 0000000000..38f303301f Binary files /dev/null and b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/FancyStuff.dll differ diff --git a/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/FancyStuff.dll.mdb b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/FancyStuff.dll.mdb new file mode 100644 index 0000000000..61c4ed3610 Binary files /dev/null and b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/FancyStuff.dll.mdb differ diff --git a/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/SimpleWrite.dll b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/SimpleWrite.dll new file mode 100755 index 0000000000..0152e5181a Binary files /dev/null and b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/SimpleWrite.dll differ diff --git a/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/SimpleWrite.dll.mdb b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/SimpleWrite.dll.mdb new file mode 100644 index 0000000000..8480d3ce08 Binary files /dev/null and b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/SimpleWrite.dll.mdb differ diff --git a/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/Testing.dll b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/Testing.dll new file mode 100755 index 0000000000..f04aca0ac0 Binary files /dev/null and b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/Testing.dll differ diff --git a/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/Testing.dll.mdb b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/Testing.dll.mdb new file mode 100644 index 0000000000..3dcceb06aa Binary files /dev/null and b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/Testing.dll.mdb differ diff --git a/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/XbuildReferenceBugTest.exe b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/XbuildReferenceBugTest.exe new file mode 100755 index 0000000000..c57f791529 Binary files /dev/null and b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/XbuildReferenceBugTest.exe differ diff --git a/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/XbuildReferenceBugTest.exe.mdb b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/XbuildReferenceBugTest.exe.mdb new file mode 100644 index 0000000000..e924bd7c4a Binary files /dev/null and b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/XbuildReferenceBugTest.exe.mdb differ diff --git a/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/XbuildReferenceBugTest2.exe b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/XbuildReferenceBugTest2.exe new file mode 100755 index 0000000000..2f2d165061 Binary files /dev/null and b/mcs/class/Microsoft.Build.Tasks/Test/resources/binary/XbuildReferenceBugTest2.exe differ diff --git a/mcs/class/Microsoft.Build.Utilities/Makefile b/mcs/class/Microsoft.Build.Utilities/Makefile index a94ef61a3a..7d4f990ef8 100644 --- a/mcs/class/Microsoft.Build.Utilities/Makefile +++ b/mcs/class/Microsoft.Build.Utilities/Makefile @@ -30,4 +30,4 @@ CLEAN_FILES += $(TEST_RESX_RESOURCES) $(TEST_RESX_RESOURCES): %.resources: %.resx $(RESGEN) $< || cp $@.prebuilt $@ -$(test_lib_output): $(TEST_RESX_RESOURCES) | $(test_lib_dir) +$(test_lib_output): $(TEST_RESX_RESOURCES) $(test_lib_dir) diff --git a/mcs/class/Microsoft.Build.Utilities/Test/Microsoft.Build.Utilities/ToolTaskTest.cs b/mcs/class/Microsoft.Build.Utilities/Test/Microsoft.Build.Utilities/ToolTaskTest.cs index 7c2a3843b6..cdc179c4d7 100644 --- a/mcs/class/Microsoft.Build.Utilities/Test/Microsoft.Build.Utilities/ToolTaskTest.cs +++ b/mcs/class/Microsoft.Build.Utilities/Test/Microsoft.Build.Utilities/ToolTaskTest.cs @@ -42,35 +42,7 @@ namespace MonoTests.Microsoft.Build.Utilities { [TestFixture] public class ToolTaskTest { -//NUnit 2.6 gives much better reporting of individual failures, but Mono currently uses 2.4.x -#if !NUNIT_2_6 - [Test] - public void LogEventsFromTextOutput () - { - foreach (var test in GetErrorParsingTestData ()) { - LogEventsFromTextOutput (test.Raw, test.ExpectedResult); - } - } - - class TestCaseData - { - public TestCaseData (string raw, LogEvent expectedResult) - { - Raw = raw; - ExpectedResult = expectedResult; - } - - public string Raw { get; private set; } - public LogEvent ExpectedResult { get; private set; } - - public TestCaseData SetName (string name) - { - return this; - } - } -#else - [Test, TestCaseSource ("GetErrorParsingTestData")] -#endif + [Test, TestCaseSource (nameof (GetErrorParsingTestData))] public void LogEventsFromTextOutput (string lineText, LogEvent expected) { var task = new LogEventsFromTextOutputToolTask (); @@ -443,11 +415,12 @@ namespace MonoTests.Microsoft.Build.Utilities { { var t = new TestExecuteToolTask (); t.BuildEngine = new MockBuildEngine (); - t.ToolPath = Directory.GetCurrentDirectory (); - t.ToolExe = "Makefile"; + var monoProcess = Process.GetCurrentProcess ().MainModule.FileName; + t.ToolPath = Path.GetDirectoryName (monoProcess); + t.ToolExe = Path.GetFileName (monoProcess); t.OnExecuteTool = (pathToTool, responseFileCommands, commandLineCommands) => { - Assert.AreEqual (Path.Combine (Directory.GetCurrentDirectory (), "Makefile"), pathToTool, "#1"); + Assert.AreEqual (monoProcess, pathToTool, "#1"); Assert.AreEqual ("", responseFileCommands, "#2"); Assert.AreEqual ("", commandLineCommands, "#3"); diff --git a/mcs/class/Microsoft.Build/Makefile b/mcs/class/Microsoft.Build/Makefile index 1a711069b0..932e596bf5 100644 --- a/mcs/class/Microsoft.Build/Makefile +++ b/mcs/class/Microsoft.Build/Makefile @@ -12,16 +12,19 @@ KEYFILE = ../msfinal.pub LIB_MCS_FLAGS = \ /d:MICROSOFT_BUILD_DLL -TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) +TEST_RESOURCE_FILES = \ + Test/resources/FunctionalTestReferenceProject.csproj \ + Test/resources/FunctionalTestReferenceProject3.csproj \ + Test/resources/Microsoft.Build.Test.csproj \ + Test/resources/Microsoft.Build.csproj + +TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) TEST_LIB_REFS = $(XBUILD_UTILITIES) TEST_NUNITLITE_APP_CONFIG_RUNTIME=Test/test-config-file-$(PROFILE) EXTRA_DISTFILES = \ Microsoft.Build.Internal/ExpressionParser.jay \ - Test/FunctionalTestReferenceProject.csproj \ - Test/FunctionalTestReferenceProject3.csproj \ - Test/Microsoft.Build.Test.csproj \ - Test/Microsoft.Build.csproj + $(TEST_RESOURCE_FILES) EXPR_PARSER = Microsoft.Build.Internal/ExpressionParser diff --git a/mcs/class/Microsoft.Build/Microsoft.Build_test.dll.sources b/mcs/class/Microsoft.Build/Microsoft.Build_test.dll.sources index 28c4af1277..944028bc1d 100644 --- a/mcs/class/Microsoft.Build/Microsoft.Build_test.dll.sources +++ b/mcs/class/Microsoft.Build/Microsoft.Build_test.dll.sources @@ -1,4 +1,5 @@ ../../test-helpers/NunitHelpers.cs +../../test-helpers/TestResourceHelper.cs FunctionalTest.cs Microsoft.Build.Construction/ProjectItemElementTest.cs Microsoft.Build.Construction/ProjectRootElementTest.cs diff --git a/mcs/class/Microsoft.Build/Test/FunctionalTest.cs b/mcs/class/Microsoft.Build/Test/FunctionalTest.cs index 4b6467a070..b28ae3f69a 100644 --- a/mcs/class/Microsoft.Build/Test/FunctionalTest.cs +++ b/mcs/class/Microsoft.Build/Test/FunctionalTest.cs @@ -36,6 +36,8 @@ using Microsoft.Build.Evaluation; using System.IO; using System.Globalization; +using MonoTests.Helpers; + namespace MonoTests.Microsoft.Build { [TestFixture] @@ -55,29 +57,27 @@ namespace MonoTests.Microsoft.Build project.Save (projectFileName); Assert.AreEqual (projectGuid, GetProjectId (project), "#01"); - FileAssert.AreEqual (String.Format ("Test{0}FunctionalTestReferenceProject.csproj", - Path.DirectorySeparatorChar), String.Format ("Test{0}FunctionalTestProject.csproj", - Path.DirectorySeparatorChar), "#02"); + FileAssert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/FunctionalTestReferenceProject.csproj"), + String.Format ("Test{0}FunctionalTestProject.csproj", Path.DirectorySeparatorChar), "#02"); } [Test] public void TestLoadAndSave () { - var project = ProjectRootElement.Open (Path.Combine ("Test", "Microsoft.Build.csproj")); + var project = ProjectRootElement.Open (TestResourceHelper.GetFullPathOfResource ("Test/resources/Microsoft.Build.csproj")); var projectFileName = String.Format ("Test{0}FunctionalTestProject2.csproj", Path.DirectorySeparatorChar); project.Save (projectFileName); Assert.AreEqual (new Guid ("{B2012E7F-8F8D-4908-8045-413F2BD1022D}"), GetProjectId (project), "#03"); - FileAssert.AreEqual (Path.Combine ("Test", "Microsoft.Build.csproj"), projectFileName, "#04"); + FileAssert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/Microsoft.Build.csproj"), projectFileName, "#04"); } [Test] public void TestLoadAndSave3 () { - var referenceProject = String.Format ( - "Test{0}FunctionalTestReferenceProject3.csproj", Path.DirectorySeparatorChar); + var referenceProject = TestResourceHelper.GetFullPathOfResource ("Test/resources/FunctionalTestReferenceProject3.csproj"); var project = ProjectRootElement.Open (referenceProject); var projectFileName = String.Format ("Test{0}FunctionalTestProject3.csproj", Path.DirectorySeparatorChar); diff --git a/mcs/class/Microsoft.Build/Test/Microsoft.Build.Construction/ProjectRootElementTest.cs b/mcs/class/Microsoft.Build/Test/Microsoft.Build.Construction/ProjectRootElementTest.cs index 7d107c20a9..a4e25e236f 100644 --- a/mcs/class/Microsoft.Build/Test/Microsoft.Build.Construction/ProjectRootElementTest.cs +++ b/mcs/class/Microsoft.Build/Test/Microsoft.Build.Construction/ProjectRootElementTest.cs @@ -31,12 +31,8 @@ namespace MonoTests.Microsoft.Build.Construction // This creator does not fill FullPath... var root = ProjectRootElement.Create (xml); - // Expected to run from mcs/class/lib/profile/tests - var dir_name = Path.GetDirectoryName (new Uri (GetType ().Assembly.CodeBase).LocalPath); - var namespace_path = Path.Combine (Directory.GetParent (dir_name).Parent.Parent.FullName, "Microsoft.Build"); - Assert.IsNull (root.FullPath, "#2"); - Assert.AreEqual (namespace_path, root.DirectoryPath, "#3"); + Assert.AreEqual (Environment.CurrentDirectory, root.DirectoryPath, "#3"); } [Test] @@ -45,10 +41,7 @@ namespace MonoTests.Microsoft.Build.Construction var root = ProjectRootElement.Create (); root.FullPath = "test" + Path.DirectorySeparatorChar + "foo.xml"; - // Expected to run from mcs/class/lib/profile/tests - var dir_name = Path.GetDirectoryName (new Uri (GetType ().Assembly.CodeBase).LocalPath); - var namespace_path = Path.Combine (Directory.GetParent (dir_name).Parent.Parent.FullName, "Microsoft.Build"); - var full = Path.Combine (namespace_path, "test", "foo.xml"); + var full = Path.Combine (Environment.CurrentDirectory, "test", "foo.xml"); Assert.AreEqual (full, root.FullPath, "#1"); Assert.AreEqual (Path.GetDirectoryName (full), root.DirectoryPath, "#1"); } diff --git a/mcs/class/Microsoft.Build/Test/Microsoft.Build.Execution/ProjectInstanceTest.cs b/mcs/class/Microsoft.Build/Test/Microsoft.Build.Execution/ProjectInstanceTest.cs index c4fe2401bd..6f24d20993 100644 --- a/mcs/class/Microsoft.Build/Test/Microsoft.Build.Execution/ProjectInstanceTest.cs +++ b/mcs/class/Microsoft.Build/Test/Microsoft.Build.Execution/ProjectInstanceTest.cs @@ -162,6 +162,7 @@ namespace MonoTests.Microsoft.Build.Execution public void FirstUsingTaskTakesPrecedenceCommon (bool importFirst, bool buildShouldSucceed) { string thisAssembly = new Uri (GetType ().Assembly.CodeBase).LocalPath; + Directory.CreateDirectory ("Test"); string filename = "Test/ProjectTargetInstanceTest.FirstUsingTaskTakesPrecedence.Import.proj"; string imported_xml = string.Format (@" diff --git a/mcs/class/Microsoft.Build/Test/FunctionalTestReferenceProject.csproj b/mcs/class/Microsoft.Build/Test/resources/FunctionalTestReferenceProject.csproj similarity index 100% rename from mcs/class/Microsoft.Build/Test/FunctionalTestReferenceProject.csproj rename to mcs/class/Microsoft.Build/Test/resources/FunctionalTestReferenceProject.csproj diff --git a/mcs/class/Microsoft.Build/Test/FunctionalTestReferenceProject3.csproj b/mcs/class/Microsoft.Build/Test/resources/FunctionalTestReferenceProject3.csproj similarity index 100% rename from mcs/class/Microsoft.Build/Test/FunctionalTestReferenceProject3.csproj rename to mcs/class/Microsoft.Build/Test/resources/FunctionalTestReferenceProject3.csproj diff --git a/mcs/class/Microsoft.Build/Test/Microsoft.Build.Test.csproj b/mcs/class/Microsoft.Build/Test/resources/Microsoft.Build.Test.csproj similarity index 100% rename from mcs/class/Microsoft.Build/Test/Microsoft.Build.Test.csproj rename to mcs/class/Microsoft.Build/Test/resources/Microsoft.Build.Test.csproj diff --git a/mcs/class/Microsoft.Build/Test/Microsoft.Build.csproj b/mcs/class/Microsoft.Build/Test/resources/Microsoft.Build.csproj similarity index 100% rename from mcs/class/Microsoft.Build/Test/Microsoft.Build.csproj rename to mcs/class/Microsoft.Build/Test/resources/Microsoft.Build.csproj diff --git a/mcs/class/Microsoft.CSharp/monotouch_tv_Microsoft.CSharp_xtest.dll.exclude.sources b/mcs/class/Microsoft.CSharp/monotouch_tv_Microsoft.CSharp_xtest.dll.exclude.sources new file mode 100644 index 0000000000..7bd8105634 --- /dev/null +++ b/mcs/class/Microsoft.CSharp/monotouch_tv_Microsoft.CSharp_xtest.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_Microsoft.CSharp_xtest.dll.exclude.sources diff --git a/mcs/class/Microsoft.CSharp/monotouch_watch_Microsoft.CSharp_xtest.dll.exclude.sources b/mcs/class/Microsoft.CSharp/monotouch_watch_Microsoft.CSharp_xtest.dll.exclude.sources new file mode 100644 index 0000000000..7bd8105634 --- /dev/null +++ b/mcs/class/Microsoft.CSharp/monotouch_watch_Microsoft.CSharp_xtest.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_Microsoft.CSharp_xtest.dll.exclude.sources diff --git a/mcs/class/Mono.Cecil.Mdb/Makefile b/mcs/class/Mono.Cecil.Mdb/Makefile index 2da359a1d3..1303411bfd 100644 --- a/mcs/class/Mono.Cecil.Mdb/Makefile +++ b/mcs/class/Mono.Cecil.Mdb/Makefile @@ -10,6 +10,7 @@ API_BUILD := $(filter basic build, $(PROFILE)) ifdef API_BUILD DEFAULT_REFERENCES = API_BIN_REFS = System mscorlib +LIBRARY_USE_INTERMEDIATE_FILE = 1 else LIB_REFS = System endif diff --git a/mcs/class/Mono.Cecil/Makefile b/mcs/class/Mono.Cecil/Makefile index 8d123642ea..76e08539a0 100644 --- a/mcs/class/Mono.Cecil/Makefile +++ b/mcs/class/Mono.Cecil/Makefile @@ -10,6 +10,7 @@ API_BUILD := $(filter basic build, $(PROFILE)) ifdef API_BUILD DEFAULT_REFERENCES = API_BIN_REFS = System.Core System mscorlib +LIBRARY_USE_INTERMEDIATE_FILE = 1 else LIB_REFS = System.Core System endif diff --git a/mcs/class/Mono.Data.Sqlite/Makefile b/mcs/class/Mono.Data.Sqlite/Makefile index bde698a46e..8ac64602af 100644 --- a/mcs/class/Mono.Data.Sqlite/Makefile +++ b/mcs/class/Mono.Data.Sqlite/Makefile @@ -15,10 +15,13 @@ KEYFILE = ../mono.pub LIB_MCS_FLAGS = /unsafe \ $(RESOURCES:%=-resource:%) -d:SQLITE_STANDARD -TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) /nowarn:618 +TEST_RESOURCE_FILES = Test/test.db + +TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) /nowarn:618 $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) EXTRA_DISTFILES = Test/SqliteTest.cs \ Test/test.sql \ + $(TEST_RESOURCE_FILES) \ resources/SR.resx \ resources/DataTypes.xml \ resources/MetaDataCollections.xml \ @@ -29,11 +32,9 @@ CLEAN_FILES += $(RESX_RESOURCES) CLEAN_FILES = $(RESX_RESOURCES) -test-local: test.db - -test.db: Test/test.sql +Test/test.db: Test/test.sql rm -f $@ - sqlite3 $@ < $< || : + sqlite3 $@ < $< include ../../build/library.make diff --git a/mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_test.dll.sources b/mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_test.dll.sources index 643c40a86d..68bd0d4eb2 100644 --- a/mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_test.dll.sources +++ b/mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_test.dll.sources @@ -1,3 +1,4 @@ +../../test-helpers/TestResourceHelper.cs SqliteCommandUnitTests.cs SqliteConnectionTest.cs SqliteDataAdapterUnitTests.cs diff --git a/mcs/class/Mono.Data.Sqlite/Test/SqliteDataReaderTest.cs b/mcs/class/Mono.Data.Sqlite/Test/SqliteDataReaderTest.cs index 262c68e191..99d4d0bd76 100644 --- a/mcs/class/Mono.Data.Sqlite/Test/SqliteDataReaderTest.cs +++ b/mcs/class/Mono.Data.Sqlite/Test/SqliteDataReaderTest.cs @@ -37,12 +37,14 @@ using Mono.Data.Sqlite; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.Mono.Data.Sqlite { [TestFixture] public class SqliteDataReaderTest { - readonly static string _uri = "./test.db"; + readonly static string _uri = TestResourceHelper.GetFullPathOfResource("Test/test.db"); readonly static string _connectionString = "URI=file://" + _uri + ", version=3"; SqliteConnection _conn = new SqliteConnection (); diff --git a/mcs/class/Mono.Data.Sqlite/Test/test.db b/mcs/class/Mono.Data.Sqlite/Test/test.db new file mode 100644 index 0000000000..ac99004a37 Binary files /dev/null and b/mcs/class/Mono.Data.Sqlite/Test/test.db differ diff --git a/mcs/class/Mono.Data.Sqlite/monodroid_Mono.Data.Sqlite_test.dll.sources b/mcs/class/Mono.Data.Sqlite/monodroid_Mono.Data.Sqlite_test.dll.sources deleted file mode 100644 index 80f57882c5..0000000000 --- a/mcs/class/Mono.Data.Sqlite/monodroid_Mono.Data.Sqlite_test.dll.sources +++ /dev/null @@ -1 +0,0 @@ -#include Mono.Data.Sqlite_test.dll.sources diff --git a/mcs/class/Mono.Data.Sqlite/monotouch_Mono.Data.Sqlite_test.dll.exclude.sources b/mcs/class/Mono.Data.Sqlite/monotouch_Mono.Data.Sqlite_test.dll.exclude.sources index bac4ef31eb..0bea1d86fb 100644 --- a/mcs/class/Mono.Data.Sqlite/monotouch_Mono.Data.Sqlite_test.dll.exclude.sources +++ b/mcs/class/Mono.Data.Sqlite/monotouch_Mono.Data.Sqlite_test.dll.exclude.sources @@ -1 +1,3 @@ Bug27864.cs +SqliteDataReaderTest.cs +SqliteTests.cs diff --git a/mcs/class/Mono.Data.Sqlite/monotouch_tv_Mono.Data.Sqlite_test.dll.exclude.sources b/mcs/class/Mono.Data.Sqlite/monotouch_tv_Mono.Data.Sqlite_test.dll.exclude.sources new file mode 100644 index 0000000000..da3d3f2bb8 --- /dev/null +++ b/mcs/class/Mono.Data.Sqlite/monotouch_tv_Mono.Data.Sqlite_test.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_Mono.Data.Sqlite_test.dll.exclude.sources diff --git a/mcs/class/Mono.Data.Sqlite/monotouch_watch_Mono.Data.Sqlite_test.dll.exclude.sources b/mcs/class/Mono.Data.Sqlite/monotouch_watch_Mono.Data.Sqlite_test.dll.exclude.sources new file mode 100644 index 0000000000..da3d3f2bb8 --- /dev/null +++ b/mcs/class/Mono.Data.Sqlite/monotouch_watch_Mono.Data.Sqlite_test.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_Mono.Data.Sqlite_test.dll.exclude.sources diff --git a/mcs/class/Mono.Debugger.Soft/Makefile b/mcs/class/Mono.Debugger.Soft/Makefile index a3afe51be8..9a4e01840c 100644 --- a/mcs/class/Mono.Debugger.Soft/Makefile +++ b/mcs/class/Mono.Debugger.Soft/Makefile @@ -8,18 +8,13 @@ LIB_REFS = System Mono.Cecil System.Core LIB_MCS_FLAGS = /unsafe -D:MONO_DATACONVERTER_STATIC_METHODS /publicsign KEYFILE = $(LIBRARY_SNK) -TEST_MCS_FLAGS = TEST_LIB_REFS = Mono.Cecil System System.Core VALID_TEST_PROFILE := $(filter net_4_x, $(PROFILE)) -# The test exe is not profile specific, and compiling a 2.0 will make the 4.5 tests fail ifdef VALID_TEST_PROFILE -test-local: dtest-app.exe dtest-excfilter.exe - -dtest-excfilter.exe: Test/dtest-excfilter.il - $(ILASM) -out:$@ /exe /debug Test/dtest-excfilter.il +test-local: build-dtest else @@ -28,20 +23,29 @@ check: endif +test_output_dir=$(topdir)/class/lib/$(PROFILE)/tests + +$(test_output_dir): + mkdir -p $@ + +build-dtest: $(test_output_dir)/dtest-app.exe $(test_output_dir)/dtest-excfilter.exe + +$(test_output_dir)/dtest-excfilter.exe: Test/dtest-excfilter.il | $(test_output_dir) + $(ILASM) -out:$@ /exe /debug Test/dtest-excfilter.il + +$(test_output_dir)/dtest-app.exe: Test/dtest-app.cs $(TEST_HELPERS_SOURCES) | $(test_output_dir) + $(CSCOMPILE) -r:$(topdir)/class/lib/$(PROFILE)/mscorlib.dll -r:$(topdir)/class/lib/$(PROFILE)/System.Core.dll -r:$(topdir)/class/lib/$(PROFILE)/System.dll -out:$@ -unsafe $(PLATFORM_DEBUG_FLAGS) -optimize- Test/dtest-app.cs $(TEST_HELPERS_SOURCES) + TEST_HELPERS_SOURCES = \ ../test-helpers/NetworkHelpers.cs \ Test/TypeLoadClass.cs -dtest-app.exe: Test/dtest-app.cs $(TEST_HELPERS_SOURCES) - $(CSCOMPILE) -r:$(topdir)/class/lib/$(PROFILE)/mscorlib.dll -r:$(topdir)/class/lib/$(PROFILE)/System.Core.dll -r:$(topdir)/class/lib/$(PROFILE)/System.dll -out:$@ -unsafe $(PLATFORM_DEBUG_FLAGS) -optimize- Test/dtest-app.cs $(TEST_HELPERS_SOURCES) - -CLEAN_FILES = dtest-app.exe dtest-app.exe.mdb dtest-app.pdb dtest-excfilter.exe dtest-excfilter.exe.mdb dtest-excfilter.pdb - EXTRA_DISTFILES = \ Test/dtest-app.cs \ Test/dtest.cs \ - Test/dtest-excfilter.il + Test/dtest-excfilter.il \ + $(TEST_HELPERS_SOURCES) -#NO_TEST = yes +CLEAN_FILES = $(addprefix $(test_output_dir)/, dtest-app.exe dtest-app.exe.mdb dtest-app.pdb dtest-excfilter.exe dtest-excfilter.exe.mdb dtest-excfilter.pdb) include ../../build/library.make diff --git a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs index ebdfc519e9..979f92a8fa 100644 --- a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs +++ b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs @@ -420,7 +420,7 @@ namespace Mono.Debugger.Soft * with newer runtimes, and vice versa. */ internal const int MAJOR_VERSION = 2; - internal const int MINOR_VERSION = 47; + internal const int MINOR_VERSION = 48; enum WPSuspendPolicy { NONE = 0, @@ -593,6 +593,11 @@ namespace Mono.Debugger.Soft BINDING_FLAGS_IGNORE_CASE = 0x70000000, } + enum MemberListTypeExtensions { + CaseSensitive = 1, + CaseInsensitive = 2 + } + enum CmdStackFrame { GET_VALUES = 1, GET_THIS = 2, @@ -2319,7 +2324,11 @@ namespace Mono.Debugger.Soft public long[] Type_GetMethodsByNameFlags (long id, string name, int flags, bool ignoreCase) { flags |= ignoreCase ? (int)BindingFlagsExtensions.BINDING_FLAGS_IGNORE_CASE : 0; - PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.CMD_TYPE_GET_METHODS_BY_NAME_FLAGS, new PacketWriter ().WriteId (id).WriteString (name).WriteInt (flags)); + int listType = ignoreCase ? (int)MemberListTypeExtensions.CaseInsensitive : (int)MemberListTypeExtensions.CaseSensitive; + var w = new PacketWriter ().WriteId (id).WriteString (name).WriteInt (flags); + if (Version.AtLeast (2, 48)) + w.WriteInt (listType); + PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.CMD_TYPE_GET_METHODS_BY_NAME_FLAGS, w); int len = r.ReadInt (); long[] res = new long [len]; for (int i = 0; i < len; ++i) diff --git a/mcs/class/Mono.Debugger.Soft/Test/TypeLoadClass.cs b/mcs/class/Mono.Debugger.Soft/Test/TypeLoadClass.cs new file mode 100644 index 0000000000..dfe4c3e150 --- /dev/null +++ b/mcs/class/Mono.Debugger.Soft/Test/TypeLoadClass.cs @@ -0,0 +1,11 @@ + +class TypeLoadClass +{ + static TypeLoadClass () + { + } +} + +class TypeLoadClass2 +{ +} \ No newline at end of file diff --git a/mcs/class/Mono.Debugger.Soft/Test/dtest-app.cs b/mcs/class/Mono.Debugger.Soft/Test/dtest-app.cs index 6da9419e93..667aa8fb23 100644 --- a/mcs/class/Mono.Debugger.Soft/Test/dtest-app.cs +++ b/mcs/class/Mono.Debugger.Soft/Test/dtest-app.cs @@ -394,6 +394,7 @@ public class Tests : TestsBase, ITest2 set_ip (); step_filters (); pointers (); + ref_return (); if (args.Length > 0 && args [0] == "local-reflect") local_reflect (); if (args.Length > 0 && args [0] == "domain-test") @@ -491,6 +492,8 @@ public class Tests : TestsBase, ITest2 ss_fp_clobber (); ss_no_frames (); ss_await (); + ss_nested_with_three_args_wrapper(); + ss_nested_twice_with_two_args_wrapper(); } [MethodImplAttribute (MethodImplOptions.NoInlining)] @@ -602,6 +605,18 @@ public class Tests : TestsBase, ITest2 ss_nested_with_two_args(ss_nested_arg (), ss_nested_arg ()); } + [MethodImplAttribute (MethodImplOptions.NoInlining)] + public static void ss_nested_with_three_args_wrapper () { + ss_nested_with_three_args(ss_nested_arg1 (), ss_nested_arg2 (), ss_nested_arg3 ()); + } + + [MethodImplAttribute (MethodImplOptions.NoInlining)] + public static void ss_nested_twice_with_two_args_wrapper () { + ss_nested_with_two_args(ss_nested_arg1 (), ss_nested_with_two_args(ss_nested_arg2 (), ss_nested_arg3 ())); + } + + + [MethodImplAttribute (MethodImplOptions.NoInlining)] public static void inspect_enumerator_in_generic_struct() { TestEnumeratorInsideGenericStruct generic_struct = new TestEnumeratorInsideGenericStruct(new KeyValuePair("0", "f1")); @@ -612,11 +627,31 @@ public class Tests : TestsBase, ITest2 return a1 + a2; } + [MethodImplAttribute (MethodImplOptions.NoInlining)] + public static int ss_nested_with_three_args (int a1, int a2, int a3) { + return a1 + a2 + a3; + } + [MethodImplAttribute (MethodImplOptions.NoInlining)] public static int ss_nested_arg () { return 0; } + [MethodImplAttribute (MethodImplOptions.NoInlining)] + public static int ss_nested_arg1 () { + return 0; + } + + [MethodImplAttribute (MethodImplOptions.NoInlining)] + public static int ss_nested_arg2 () { + return 0; + } + + [MethodImplAttribute (MethodImplOptions.NoInlining)] + public static int ss_nested_arg3 () { + return 0; + } + [MethodImplAttribute (MethodImplOptions.NoInlining)] public static void ss_nested_1 (int i) { } @@ -1828,6 +1863,27 @@ public class Tests : TestsBase, ITest2 fixed (int* pa = a) pointer_arguments (pa, &s); } + + [MethodImplAttribute (MethodImplOptions.NoInlining)] + public static void ref_return () { + + } + + static int ret_val = 1; + public static ref int get_ref_int() { + return ref ret_val; + } + + static string ref_return_string = "byref"; + public static ref string get_ref_string() { + return ref ref_return_string; + } + + + static BlittableStruct ref_return_struct = new BlittableStruct () { i = 1, d = 2.0 }; + public static ref BlittableStruct get_ref_struct() { + return ref ref_return_struct; + } } public class SentinelClass : MarshalByRefObject { diff --git a/mcs/class/Mono.Debugger.Soft/Test/dtest.cs.REMOVED.git-id b/mcs/class/Mono.Debugger.Soft/Test/dtest.cs.REMOVED.git-id index 8ccc9c3b62..db6824b206 100644 --- a/mcs/class/Mono.Debugger.Soft/Test/dtest.cs.REMOVED.git-id +++ b/mcs/class/Mono.Debugger.Soft/Test/dtest.cs.REMOVED.git-id @@ -1 +1 @@ -a57e595679838703ee0f1cc00d816eb02c1202dd \ No newline at end of file +b1e11e72870372caded79930ec46585d2f79d6a0 \ No newline at end of file diff --git a/mcs/class/Mono.Options/Documentation/en/examples/commands.cs b/mcs/class/Mono.Options/Documentation/en/examples/commands.cs index 619a856a18..4d515f84cd 100644 --- a/mcs/class/Mono.Options/Documentation/en/examples/commands.cs +++ b/mcs/class/Mono.Options/Documentation/en/examples/commands.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; +using System.Linq; using Mono.Options; @@ -25,6 +26,9 @@ class CommandDemo { new Command ("echo", "Echo arguments to the screen") { Run = ca => Console.WriteLine ("{0}", string.Join (" ", ca)), }, + new Command ("equinox", "Does something with the equinox?") { + Run = ca => Console.WriteLine ("{0}", string.Join (" ", ca)), + }, new RequiresArgsCommand (), "Commands with spaces are supported:", new Command ("has spaces", "spaces?!") { @@ -35,8 +39,20 @@ class CommandDemo { new Command ("file type", "Does something or other.") { Run = ca => Console.WriteLine ("File type set to: {0}", string.Join (" ", ca)), }, + new Command ("output", "Sets output location") { + Run = ca => Console.WriteLine ("Output set to: {0}", string.Join (" ", ca)), + }, }, }; + commands.Add (new Command ("completions", "Show CommandSet completions") { + Run = ca => { + var start = ca.Any() ? string.Join (" ", ca) : ""; + Console.WriteLine ($"Showing CommandSet completions for prefix '{start}':"); + foreach (var completion in commands.GetCompletions (start)) { + Console.WriteLine ($"\tcompletion: {completion}"); + } + }, + }); commands.Add (commands); return commands.Run (args); } diff --git a/mcs/class/Mono.Options/Documentation/en/examples/commands.in b/mcs/class/Mono.Options/Documentation/en/examples/commands.in index 8c2e1a1cbd..ae16748e87 100644 --- a/mcs/class/Mono.Options/Documentation/en/examples/commands.in +++ b/mcs/class/Mono.Options/Documentation/en/examples/commands.in @@ -27,3 +27,11 @@ mono Documentation/en/examples/commands.exe help invalid-command mono Documentation/en/examples/commands.exe has spaces mono Documentation/en/examples/commands.exe set file type whatever + +mono Documentation/en/examples/commands.exe completions + +mono Documentation/en/examples/commands.exe completions e + +mono Documentation/en/examples/commands.exe completions s + +mono Documentation/en/examples/commands.exe completions s o diff --git a/mcs/class/Mono.Options/Documentation/en/examples/commands.txt b/mcs/class/Mono.Options/Documentation/en/examples/commands.txt index 0bfa31d9dc..9a2cc07080 100644 --- a/mcs/class/Mono.Options/Documentation/en/examples/commands.txt +++ b/mcs/class/Mono.Options/Documentation/en/examples/commands.txt @@ -2,7 +2,6 @@ $ mono commands.exe Use `commands help` for usage. $ mono commands.exe --help -# HelpCommand.Invoke: arguments= usage: commands COMMAND [OPTIONS] Mono.Options.CommandSet sample app. @@ -12,15 +11,17 @@ Global options: Available commands: echo Echo arguments to the screen + equinox Does something with the equinox? requires-args Class-based Command subclass Commands with spaces are supported: has spaces spaces?! Nested CommandSets are also supported. They're invoked similarly to commands with spaces. set file type Does something or other. + set output Sets output location + completions Show CommandSet completions $ mono commands.exe help -# HelpCommand.Invoke: arguments= usage: commands COMMAND [OPTIONS] Mono.Options.CommandSet sample app. @@ -30,28 +31,32 @@ Global options: Available commands: echo Echo arguments to the screen + equinox Does something with the equinox? requires-args Class-based Command subclass Commands with spaces are supported: has spaces spaces?! Nested CommandSets are also supported. They're invoked similarly to commands with spaces. set file type Does something or other. + set output Sets output location + completions Show CommandSet completions $ mono commands.exe help --help -# HelpCommand.Invoke: arguments=--help Usage: commands COMMAND [OPTIONS] Use `commands help COMMAND` for help on a specific command. Available commands: + completions Show CommandSet completions echo Echo arguments to the screen + equinox Does something with the equinox? has spaces spaces?! requires-args Class-based Command subclass set file type Does something or other. + set output Sets output location help Show this message and exit $ mono commands.exe help echo -# HelpCommand.Invoke: arguments=echo --help $ mono commands.exe echo --help @@ -65,7 +70,6 @@ commands: Missing required argument `--name=NAME`. commands: Use `commands help requires-args` for details. $ mono commands.exe help requires-args -# HelpCommand.Invoke: arguments=requires-args usage: commands requires-args [OPTIONS] Class-based Command subclass example. @@ -87,7 +91,6 @@ commands: Unknown command: invalid-command commands: Use `commands help` for usage. $ mono commands.exe help invalid-command -# HelpCommand.Invoke: arguments=invalid-command commands: Unknown command: invalid-command commands: Use `commands help` for usage. @@ -96,3 +99,28 @@ spaces, yo! $ mono commands.exe set file type whatever File type set to: whatever + +$ mono commands.exe completions +Showing CommandSet completions for prefix '': + completion: echo + completion: equinox + completion: requires-args + completion: has spaces + completion: completions + completion: help + completion: set file type + completion: set output + +$ mono commands.exe completions e +Showing CommandSet completions for prefix 'e': + completion: echo + completion: equinox + +$ mono commands.exe completions s +Showing CommandSet completions for prefix 's': + completion: set file type + completion: set output + +$ mono commands.exe completions s o +Showing CommandSet completions for prefix 's o': + completion: set output diff --git a/mcs/class/Mono.Options/Makefile b/mcs/class/Mono.Options/Makefile index 28d27326fe..6c4c9194d7 100644 --- a/mcs/class/Mono.Options/Makefile +++ b/mcs/class/Mono.Options/Makefile @@ -59,6 +59,7 @@ Documentation/en/examples/Mono.Options.dll: $(the_lib) %.exe: %.cs Documentation/en/examples/Mono.Options.dll $(CSCOMPILE) -debug:portable -r:$(topdir)/class/lib/$(PROFILE)/Mono.Posix.dll -r:$(topdir)/class/lib/$(PROFILE)/System.Core.dll -r:$(topdir)/class/lib/$(PROFILE)/System.dll \ + -r:$(topdir)/class/lib/$(PROFILE)/mscorlib.dll \ -r:$(topdir)/class/lib/$(PROFILE)/Mono.Options.dll -out:$@ $< Documentation/en/examples/locale/es/LC_MESSAGES/localization.mo: Documentation/en/examples/localization-es.po @@ -72,7 +73,8 @@ Documentation/en/examples/localization.exe: Documentation/en/examples/locale/es/ while read line 0<&3 ; do \ if test -n "$$line" ; then \ echo "$$ $$line" | sed 's#Documentation/en/examples/##' >> $@ ; \ - sh -c "$$line" >> $@ 2>&1 ; \ + cmd=`echo "$$line" | sed 's,mono ,MONO_PATH="$(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)$(PLATFORM_PATH_SEPARATOR)" $(RUNTIME) ,g'` ; \ + sh -c "$$cmd" >> $@ 2>&1 ; \ else \ echo "" >> $@ ; \ fi ; \ diff --git a/mcs/class/Mono.Options/Mono.Options/Options.cs b/mcs/class/Mono.Options/Mono.Options/Options.cs index 780530a8da..821937e759 100644 --- a/mcs/class/Mono.Options/Mono.Options/Options.cs +++ b/mcs/class/Mono.Options/Mono.Options/Options.cs @@ -1782,6 +1782,53 @@ namespace Mono.Options return false; } + public IEnumerable GetCompletions (string prefix = null) + { + string rest; + ExtractToken (ref prefix, out rest); + + foreach (var command in this) { + if (command.Name.StartsWith (prefix, StringComparison.OrdinalIgnoreCase)) { + yield return command.Name; + } + } + + if (NestedCommandSets == null) + yield break; + + foreach (var subset in NestedCommandSets) { + if (subset.Suite.StartsWith (prefix, StringComparison.OrdinalIgnoreCase)) { + foreach (var c in subset.GetCompletions (rest)) { + yield return $"{subset.Suite} {c}"; + } + } + } + } + + static void ExtractToken (ref string input, out string rest) + { + rest = ""; + input = input ?? ""; + + int top = input.Length; + for (int i = 0; i < top; i++) { + if (char.IsWhiteSpace (input [i])) + continue; + + for (int j = i; j < top; j++) { + if (char.IsWhiteSpace (input [j])) { + rest = input.Substring (j).Trim (); + input = input.Substring (i, j).Trim (); + return; + } + } + rest = ""; + if (i != 0) + input = input.Substring (i).Trim (); + return; + } + } + public int Run (IEnumerable arguments) { if (arguments == null) @@ -1879,7 +1926,6 @@ namespace Mono.Options public override int Invoke (IEnumerable arguments) { var extra = new List (arguments ?? new string [0]); - Console.WriteLine ($"# HelpCommand.Invoke: arguments={string.Join (" ", arguments)}"); var _ = CommandSet.Options.MessageLocalizer; if (extra.Count == 0) { CommandSet.Options.WriteOptionDescriptions (CommandSet.Out); diff --git a/mcs/class/Mono.Options/Test/Mono.Options/CommandSetTest.cs b/mcs/class/Mono.Options/Test/Mono.Options/CommandSetTest.cs index 89ee149474..93dbb3f21c 100644 --- a/mcs/class/Mono.Options/Test/Mono.Options/CommandSetTest.cs +++ b/mcs/class/Mono.Options/Test/Mono.Options/CommandSetTest.cs @@ -129,6 +129,42 @@ namespace MonoTests.Mono.Options Assert.Throws (() => s.Add (new Command ("value"))); } + [Test] + public void GetCompletions () + { + var commands = new CommandSet ("example") { + new Command ("a"), + new Command ("aa"), + new Command ("a a"), + new Command ("cs c"), + new CommandSet ("cs") { + new CommandSet ("cs2") { + new CommandSet ("cs3") { + new Command ("cs-cs2-cs3-c"), + }, + }, + }, + }; + Assert.IsTrue (new[]{ + "a", + "aa", + "a a", + "cs c", + "cs cs2 cs3 cs-cs2-cs3-c", + }.SequenceEqual (commands.GetCompletions ())); + + Assert.IsTrue (new[]{ + "a", + "aa", + "a a", + }.SequenceEqual (commands.GetCompletions ("a"))); + + Assert.IsTrue (new[]{ + "cs c", + "cs cs2 cs3 cs-cs2-cs3-c", + }.SequenceEqual (commands.GetCompletions ("cs"))); + } + [Test] public void Run_Help () { diff --git a/mcs/class/Mono.Posix/Test/Mono.Unix.Native/StdlibTest.cs b/mcs/class/Mono.Posix/Test/Mono.Unix.Native/StdlibTest.cs index e429af7f72..945d3e5abc 100644 --- a/mcs/class/Mono.Posix/Test/Mono.Unix.Native/StdlibTest.cs +++ b/mcs/class/Mono.Posix/Test/Mono.Unix.Native/StdlibTest.cs @@ -29,6 +29,14 @@ namespace MonoTests.Mono.Unix.Native { } } + + [Test] + public void GetPid () + { + var currentPID = Syscall.getpid(); + Assert.AreNotEqual (0, currentPID); + } + // [Test] public void Signal () { diff --git a/mcs/class/Mono.Security/Mono.Security.X509.Extensions/BasicConstraintsExtension.cs b/mcs/class/Mono.Security/Mono.Security.X509.Extensions/BasicConstraintsExtension.cs index 335fe92c65..4bdfc658aa 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509.Extensions/BasicConstraintsExtension.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509.Extensions/BasicConstraintsExtension.cs @@ -47,7 +47,7 @@ namespace Mono.Security.X509.Extensions { * pathLenConstraint INTEGER (0..MAX) OPTIONAL * } */ -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public diff --git a/mcs/class/Mono.Security/Mono.Security.X509.Extensions/KeyUsageExtension.cs b/mcs/class/Mono.Security/Mono.Security.X509.Extensions/KeyUsageExtension.cs index d0ad93c925..7084aa7d30 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509.Extensions/KeyUsageExtension.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509.Extensions/KeyUsageExtension.cs @@ -53,7 +53,7 @@ namespace Mono.Security.X509.Extensions { */ // note: because nothing is simple in ASN.1 bits are reversed [Flags] -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public @@ -71,7 +71,7 @@ namespace Mono.Security.X509.Extensions { none = 0x0 } -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public diff --git a/mcs/class/Mono.Security/Mono.Security.X509.Extensions/SubjectKeyIdentifierExtension.cs b/mcs/class/Mono.Security/Mono.Security.X509.Extensions/SubjectKeyIdentifierExtension.cs index 8f15c28e34..c12758e260 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509.Extensions/SubjectKeyIdentifierExtension.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509.Extensions/SubjectKeyIdentifierExtension.cs @@ -45,7 +45,7 @@ namespace Mono.Security.X509.Extensions { * KeyIdentifier ::= OCTET STRING */ -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public diff --git a/mcs/class/Mono.Security/Mono.Security.X509/PKCS12.cs b/mcs/class/Mono.Security/Mono.Security.X509/PKCS12.cs index c37e52c2dd..be3da4eca8 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509/PKCS12.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509/PKCS12.cs @@ -42,7 +42,7 @@ using Mono.Security.Cryptography; namespace Mono.Security.X509 { -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public @@ -59,7 +59,7 @@ namespace Mono.Security.X509 { public PKCS5 () {} } -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public @@ -92,7 +92,7 @@ namespace Mono.Security.X509 { } -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public diff --git a/mcs/class/Mono.Security/Mono.Security.X509/X501Name.cs b/mcs/class/Mono.Security/Mono.Security.X509/X501Name.cs index 8c9dad7da2..a5bcd72673 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509/X501Name.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509/X501Name.cs @@ -49,7 +49,7 @@ namespace Mono.Security.X509 { * * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue */ -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public diff --git a/mcs/class/Mono.Security/Mono.Security.X509/X509CRL.cs b/mcs/class/Mono.Security/Mono.Security.X509/X509CRL.cs index daa5a5841f..0553d398de 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509/X509CRL.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509/X509CRL.cs @@ -60,7 +60,7 @@ namespace Mono.Security.X509 { * crlExtensions [0] Extensions OPTIONAL } * -- if present, MUST be v2 */ -#if !INSIDE_CORLIB +#if !INSIDE_CORLIB && !INSIDE_SYSTEM public #endif class X509Crl { diff --git a/mcs/class/Mono.Security/Mono.Security.X509/X509Certificate.cs b/mcs/class/Mono.Security/Mono.Security.X509/X509Certificate.cs index 99791bb4b3..331b662c9f 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509/X509Certificate.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509/X509Certificate.cs @@ -44,7 +44,7 @@ namespace Mono.Security.X509 { // b. ITU ASN.1 standards (free download) // http://www.itu.int/ITU-T/studygroups/com17/languages/ -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal class X509Certificate : ISerializable { #else public class X509Certificate : ISerializable { diff --git a/mcs/class/Mono.Security/Mono.Security.X509/X509CertificateCollection.cs b/mcs/class/Mono.Security/Mono.Security.X509/X509CertificateCollection.cs index 3fd834b0cf..6b273da53b 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509/X509CertificateCollection.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509/X509CertificateCollection.cs @@ -34,7 +34,7 @@ using System.Collections; namespace Mono.Security.X509 { [Serializable] -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public diff --git a/mcs/class/Mono.Security/Mono.Security.X509/X509Chain.cs b/mcs/class/Mono.Security/Mono.Security.X509/X509Chain.cs index 6edd5feac4..07714f38c0 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509/X509Chain.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509/X509Chain.cs @@ -35,7 +35,7 @@ using System; using System.Security; using System.Security.Permissions; -#if !INSIDE_CORLIB +#if !INSIDE_CORLIB && !INSIDE_SYSTEM using System.Net; #endif @@ -43,7 +43,7 @@ using Mono.Security.X509.Extensions; namespace Mono.Security.X509 { -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public @@ -203,7 +203,7 @@ namespace Mono.Security.X509 { // TODO - we should check for CRITICAL but unknown extensions // X509ChainStatusFlags.InvalidExtension -#if !INSIDE_CORLIB +#if !INSIDE_CORLIB && !INSIDE_SYSTEM if (ServicePointManager.CheckCertificateRevocationList) { // TODO - check revocation (CRL, OCSP ...) // X509ChainStatusFlags.RevocationStatusUnknown diff --git a/mcs/class/Mono.Security/Mono.Security.X509/X509ChainStatusFlags.cs b/mcs/class/Mono.Security/Mono.Security.X509/X509ChainStatusFlags.cs index 48472c30da..85de078e61 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509/X509ChainStatusFlags.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509/X509ChainStatusFlags.cs @@ -37,7 +37,7 @@ namespace Mono.Security.X509 { [Serializable] [Flags] -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public diff --git a/mcs/class/Mono.Security/Mono.Security.X509/X509Extension.cs b/mcs/class/Mono.Security/Mono.Security.X509/X509Extension.cs index 637e74b48c..c15f0fc7cb 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509/X509Extension.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509/X509Extension.cs @@ -41,7 +41,7 @@ namespace Mono.Security.X509 { * extnValue OCTET STRING * } */ -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public diff --git a/mcs/class/Mono.Security/Mono.Security.X509/X509Extensions.cs b/mcs/class/Mono.Security/Mono.Security.X509/X509Extensions.cs index cb8e15defa..ec03327820 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509/X509Extensions.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509/X509Extensions.cs @@ -40,7 +40,7 @@ namespace Mono.Security.X509 { * * Note: 1..MAX -> There shouldn't be 0 Extensions in the ASN1 structure */ -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public diff --git a/mcs/class/Mono.Security/Mono.Security.X509/X509Store.cs b/mcs/class/Mono.Security/Mono.Security.X509/X509Store.cs index 1821075635..4a6d48b59a 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509/X509Store.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509/X509Store.cs @@ -42,7 +42,7 @@ using SSCX = System.Security.Cryptography.X509Certificates; namespace Mono.Security.X509 { -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public diff --git a/mcs/class/Mono.Security/Mono.Security.X509/X509StoreManager.cs b/mcs/class/Mono.Security/Mono.Security.X509/X509StoreManager.cs index 7f31713b1b..2b55683365 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509/X509StoreManager.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509/X509StoreManager.cs @@ -36,7 +36,7 @@ using Mono.Security.X509.Extensions; namespace Mono.Security.X509 { -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public diff --git a/mcs/class/Mono.Security/Mono.Security.X509/X509Stores.cs b/mcs/class/Mono.Security/Mono.Security.X509/X509Stores.cs index 071faa70dd..3ef6a2528d 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509/X509Stores.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509/X509Stores.cs @@ -36,7 +36,7 @@ using Mono.Security.X509.Extensions; namespace Mono.Security.X509 { -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public diff --git a/mcs/class/Mono.Security/Mono.Security.X509/X520Attributes.cs b/mcs/class/Mono.Security/Mono.Security.X509/X520Attributes.cs index b8506aab79..22fe8a91d5 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509/X520Attributes.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509/X520Attributes.cs @@ -55,7 +55,7 @@ namespace Mono.Security.X509 { * * AttributeValue ::= ANY DEFINED BY AttributeType */ -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public diff --git a/mcs/class/Mono.Security/Mono.Security/PKCS7.cs b/mcs/class/Mono.Security/Mono.Security/PKCS7.cs index a03b405f18..31bcc0a619 100644 --- a/mcs/class/Mono.Security/Mono.Security/PKCS7.cs +++ b/mcs/class/Mono.Security/Mono.Security/PKCS7.cs @@ -37,7 +37,7 @@ using Mono.Security.X509; namespace Mono.Security { -#if INSIDE_CORLIB +#if INSIDE_CORLIB || INSIDE_SYSTEM internal #else public diff --git a/mcs/class/System.ComponentModel.Composition.4.5/monotouch_tv_System.ComponentModel.Composition_xtest.dll.exclude.sources b/mcs/class/System.ComponentModel.Composition.4.5/monotouch_tv_System.ComponentModel.Composition_xtest.dll.exclude.sources new file mode 100644 index 0000000000..852cae50e2 --- /dev/null +++ b/mcs/class/System.ComponentModel.Composition.4.5/monotouch_tv_System.ComponentModel.Composition_xtest.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_System.ComponentModel.Composition_xtest.dll.exclude.sources diff --git a/mcs/class/System.ComponentModel.Composition.4.5/monotouch_watch_System.ComponentModel.Composition_xtest.dll.exclude.sources b/mcs/class/System.ComponentModel.Composition.4.5/monotouch_watch_System.ComponentModel.Composition_xtest.dll.exclude.sources new file mode 100644 index 0000000000..852cae50e2 --- /dev/null +++ b/mcs/class/System.ComponentModel.Composition.4.5/monotouch_watch_System.ComponentModel.Composition_xtest.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_System.ComponentModel.Composition_xtest.dll.exclude.sources diff --git a/mcs/class/System.Configuration/Makefile b/mcs/class/System.Configuration/Makefile index 6e948af0a2..e5405751bd 100644 --- a/mcs/class/System.Configuration/Makefile +++ b/mcs/class/System.Configuration/Makefile @@ -17,7 +17,7 @@ LIBRARY_WARN_AS_ERROR = yes include ../../build/library.make test-local: - cp Test/appSettings.config $(dir $(NUNITLITE_CONFIG_FILE))/Test-appSettings.config + cp -f Test/appSettings.config $(dir $(NUNITLITE_CONFIG_FILE))/System.Configuration-appSettings.config run-test: $(MAKE) -C Test/standalone diff --git a/mcs/class/System.Configuration/Test/System.Configuration/AppSettingsSectionTest.cs b/mcs/class/System.Configuration/Test/System.Configuration/AppSettingsSectionTest.cs index f044581033..068345b9af 100644 --- a/mcs/class/System.Configuration/Test/System.Configuration/AppSettingsSectionTest.cs +++ b/mcs/class/System.Configuration/Test/System.Configuration/AppSettingsSectionTest.cs @@ -67,7 +67,7 @@ namespace MonoTests.System.Configuration var currentAssembly = TestUtil.ThisApplicationPath; var config = ConfigurationManager.OpenExeConfiguration (currentAssembly); - Assert.AreEqual ("Test-appSettings.config", config.AppSettings.File, "#A01"); + Assert.AreEqual ("System.Configuration-appSettings.config", config.AppSettings.File, "#A01"); Assert.AreEqual ("foo", ConfigurationSettings.AppSettings["TestKey1"], "#A02"); Assert.AreEqual ("bar", ConfigurationSettings.AppSettings["TestKey2"], "#A03"); } diff --git a/mcs/class/System.Core/Test/System.IO.MemoryMappedFiles/MemoryMappedFileTest.cs b/mcs/class/System.Core/Test/System.IO.MemoryMappedFiles/MemoryMappedFileTest.cs index 9e64e03dd6..20014bd152 100644 --- a/mcs/class/System.Core/Test/System.IO.MemoryMappedFiles/MemoryMappedFileTest.cs +++ b/mcs/class/System.Core/Test/System.IO.MemoryMappedFiles/MemoryMappedFileTest.cs @@ -393,7 +393,7 @@ namespace MonoTests.System.IO.MemoryMappedFiles { [Test] public void CreateViewStreamAlignToPageSize () { -#if __WATCHOS__ +#if MONOTOUCH_WATCH int pageSize = 4096; #elif MONOTOUCH // iOS bugs on ARM64 - bnc #27667 - apple # diff --git a/mcs/class/System.Core/corefx/Interop.cs b/mcs/class/System.Core/corefx/Interop.cs new file mode 100644 index 0000000000..4f7aeb50c6 --- /dev/null +++ b/mcs/class/System.Core/corefx/Interop.cs @@ -0,0 +1,18 @@ +using System; + +internal static partial class Interop +{ + internal static partial class Sys + { + internal static uint GetEUid () + { + throw new PlatformNotSupportedException (); + } + + internal static int SetEUid (uint euid) + { + throw new PlatformNotSupportedException (); + } + + } +} diff --git a/mcs/class/System.Core/monotouch_tv_System.Core_xtest.dll.exclude.sources b/mcs/class/System.Core/monotouch_tv_System.Core_xtest.dll.exclude.sources new file mode 100644 index 0000000000..b364b199ce --- /dev/null +++ b/mcs/class/System.Core/monotouch_tv_System.Core_xtest.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_System.Core_xtest.dll.exclude.sources diff --git a/mcs/class/System.Core/monotouch_watch_System.Core_xtest.dll.exclude.sources b/mcs/class/System.Core/monotouch_watch_System.Core_xtest.dll.exclude.sources new file mode 100644 index 0000000000..b364b199ce --- /dev/null +++ b/mcs/class/System.Core/monotouch_watch_System.Core_xtest.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_System.Core_xtest.dll.exclude.sources diff --git a/mcs/class/System.Core/unix_net_4_x_System.Core.dll.sources b/mcs/class/System.Core/unix_net_4_x_System.Core.dll.sources index 0d1cdcde9b..0628602aa3 100644 --- a/mcs/class/System.Core/unix_net_4_x_System.Core.dll.sources +++ b/mcs/class/System.Core/unix_net_4_x_System.Core.dll.sources @@ -35,5 +35,8 @@ System.IO.Pipes/AnonymousPipeServerStream.Unix.cs ../../../external/corefx/src/Common/src/Interop/Unix/System.Native/Interop.Stat.cs ../../../external/corefx/src/Common/src/Interop/Unix/System.Native/Interop.Stat.Pipe.cs ../../../external/corefx/src/Common/src/Interop/Unix/System.Native/Interop.GetPeerID.cs -../../../external/corefx/src/Common/src/Interop/Unix/System.Native/Interop.GetEUid.cs -../../../external/corefx/src/Common/src/Interop/Unix/System.Native/Interop.SetEUid.cs + +# FIXME: the native side is not there yet. +# ../../../external/corefx/src/Common/src/Interop/Unix/System.Native/Interop.GetEUid.cs +# ../../../external/corefx/src/Common/src/Interop/Unix/System.Native/Interop.SetEUid.cs +corefx/Interop.cs diff --git a/mcs/class/System.Data.DataSetExtensions/Makefile b/mcs/class/System.Data.DataSetExtensions/Makefile index 407e7c2e3b..4b3a395a2b 100644 --- a/mcs/class/System.Data.DataSetExtensions/Makefile +++ b/mcs/class/System.Data.DataSetExtensions/Makefile @@ -8,10 +8,11 @@ LIB_REFS = System.Core System System.Data System.Xml KEYFILE = ../ecma.pub LIB_MCS_FLAGS = -nowarn:436 -d:COREFX -TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -nowarn:219 -nowarn:169 $(NUNIT_RESOURCE_FILES:%=/resource:%) +TEST_RESOURCE_FILES = Test/System.Data/testdataset1.xml -EXTRA_DISTFILES = $(RESOURCE_FILES) \ - Test/System.Data/testdataset1.xml +TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -nowarn:219 -nowarn:169 $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) + +EXTRA_DISTFILES = $(TEST_RESOURCE_FILES) RESX_RESOURCE_STRING = \ ../../../external/corefx/src/System.Data.DataSetExtensions/src/Resources/Strings.resx diff --git a/mcs/class/System.Data.DataSetExtensions/System.Data.DataSetExtensions_test.dll.sources b/mcs/class/System.Data.DataSetExtensions/System.Data.DataSetExtensions_test.dll.sources index 15566f8d6c..c87ab65a71 100644 --- a/mcs/class/System.Data.DataSetExtensions/System.Data.DataSetExtensions_test.dll.sources +++ b/mcs/class/System.Data.DataSetExtensions/System.Data.DataSetExtensions_test.dll.sources @@ -1,3 +1,4 @@ +../../test-helpers/TestResourceHelper.cs System.Data/DataRowComparerTest.cs System.Data/DataRowExtensionsTest.cs System.Data/DataTableExtensionsTest.cs diff --git a/mcs/class/System.Data.DataSetExtensions/Test/System.Data/DataTableExtensionsTest.cs b/mcs/class/System.Data.DataSetExtensions/Test/System.Data/DataTableExtensionsTest.cs index 31f2d75a4f..72733eddfd 100644 --- a/mcs/class/System.Data.DataSetExtensions/Test/System.Data/DataTableExtensionsTest.cs +++ b/mcs/class/System.Data.DataSetExtensions/Test/System.Data/DataTableExtensionsTest.cs @@ -34,6 +34,8 @@ using System.Data; using System.Linq; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Data { [TestFixture] @@ -77,7 +79,7 @@ namespace MonoTests.System.Data public void AsEnumerable () { DataSet ds = new DataSet (); - ds.ReadXml ("Test/System.Data/testdataset1.xml"); + ds.ReadXml (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/testdataset1.xml")); DataTable dt = ds.Tables [0]; Assert.AreEqual ("ScoreList", dt.TableName, "TableName"); var dv = dt.AsEnumerable (); @@ -94,7 +96,7 @@ namespace MonoTests.System.Data public void AsDataView () { DataSet ds = new DataSet (); - ds.ReadXml ("Test/System.Data/testdataset1.xml"); + ds.ReadXml (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/testdataset1.xml")); DataTable dt = ds.Tables [0]; var dv = dt.AsEnumerable ().Where ((DataRow r) => (int) r ["Score"] > 60).AsDataView (); Assert.AreEqual (1, dv [0] ["ID"], "#1"); diff --git a/mcs/class/System.Data.DataSetExtensions/Test/System.Data/EnumerableRowCollectionTest.cs b/mcs/class/System.Data.DataSetExtensions/Test/System.Data/EnumerableRowCollectionTest.cs index 841b31ec78..868ff80617 100644 --- a/mcs/class/System.Data.DataSetExtensions/Test/System.Data/EnumerableRowCollectionTest.cs +++ b/mcs/class/System.Data.DataSetExtensions/Test/System.Data/EnumerableRowCollectionTest.cs @@ -33,6 +33,8 @@ using System.Collections.Generic; using System.Data; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Data { [TestFixture] @@ -42,7 +44,7 @@ namespace MonoTests.System.Data public void QueryWhere () { var ds = new DataSet (); - ds.ReadXml ("Test/System.Data/testdataset1.xml"); + ds.ReadXml (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/testdataset1.xml")); var table = ds.Tables [0]; /* schema generated as ... var table = ds.Tables.Add ("ScoreList"); @@ -64,12 +66,11 @@ namespace MonoTests.System.Data } } - /* FIXME: enable it when it gets fixed: https://bugzilla.novell.com/show_bug.cgi?id=389795 [Test] public void QueryWhereSelect () { var ds = new DataSet (); - ds.ReadXml ("Test/System.Data/testdataset1.xml"); + ds.ReadXml (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/testdataset1.xml")); var table = ds.Tables [0]; var q = from line in table.AsEnumerable () where line.Field ("Score") > 80 @@ -90,7 +91,7 @@ namespace MonoTests.System.Data public void QueryWhereSelectOrderBy () { var ds = new DataSet (); - ds.ReadXml ("Test/System.Data/testdataset1.xml"); + ds.ReadXml (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/testdataset1.xml")); var table = ds.Tables [0]; var q = from line in table.AsEnumerable () where line.Field ("Score") >= 80 @@ -103,13 +104,14 @@ namespace MonoTests.System.Data foreach (var ql in q) { switch (prevID) { case -1: - Assert.AreEqual (4, ql.StudentID, "#1"); + Assert.AreEqual (1, ql.StudentID, "#1"); break; - case 4: - Assert.AreEqual (1, ql.StudentID, "#2"); + case 1: + Assert.AreEqual (4, ql.StudentID, "#2"); break; default: Assert.Fail ("should match only one raw"); + break; } prevID = ql.StudentID; } @@ -119,7 +121,7 @@ namespace MonoTests.System.Data public void QueryWhereSelectOrderByDescending () { var ds = new DataSet (); - ds.ReadXml ("Test/System.Data/testdataset1.xml"); + ds.ReadXml (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/testdataset1.xml")); var table = ds.Tables [0]; var q = from line in table.AsEnumerable () where line.Field ("Score") >= 80 @@ -132,13 +134,14 @@ namespace MonoTests.System.Data foreach (var ql in q) { switch (prevID) { case -1: - Assert.AreEqual (1, ql.StudentID, "#1"); + Assert.AreEqual (4, ql.StudentID, "#1"); break; case 4: - Assert.AreEqual (4, ql.StudentID, "#2"); + Assert.AreEqual (1, ql.StudentID, "#2"); break; default: - Assert.Fail ("should match only one raw"); + Assert.Fail ("should match only one raw, ID: " + ql.StudentID); + break; } prevID = ql.StudentID; } @@ -148,7 +151,7 @@ namespace MonoTests.System.Data public void ThenBy () { var ds = new DataSet (); - ds.ReadXml ("Test/System.Data/testdataset1.xml"); + ds.ReadXml (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/testdataset1.xml")); var table = ds.Tables [0]; var q = from line in table.AsEnumerable () where line.Field ("Score") >= 80 @@ -158,6 +161,36 @@ namespace MonoTests.System.Data StudentName = line.Field ("Name"), StudentScore = line.Field ("Score") }; int prevID = -1; + foreach (var ql in q) { + switch (prevID) { + case -1: + Assert.AreEqual (1, ql.StudentID, "#1"); + break; + case 1: + Assert.AreEqual (4, ql.StudentID, "#2"); + break; + default: + Assert.Fail ("should match only one raw, ID: " + ql.StudentID); + break; + } + prevID = ql.StudentID; + } + } + + [Test] + public void ThenByDescending () + { + var ds = new DataSet (); + ds.ReadXml (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/testdataset1.xml")); + var table = ds.Tables [0]; + var q = from line in table.AsEnumerable () + where line.Field ("Score") >= 80 + orderby line.Field ("Gender"), line.Field ("ID") descending + select new { + StudentID = line.Field ("ID"), + StudentName = line.Field ("Name"), + StudentScore = line.Field ("Score") }; + int prevID = -1; foreach (var ql in q) { switch (prevID) { case -1: @@ -167,40 +200,11 @@ namespace MonoTests.System.Data Assert.AreEqual (1, ql.StudentID, "#2"); break; default: - Assert.Fail ("should match only one raw"); + Assert.Fail ("should match only one raw, ID: " + ql.StudentID); + break; } prevID = ql.StudentID; } } - - [Test] - public void ThenByDescending () - { - var ds = new DataSet (); - ds.ReadXml ("Test/System.Data/testdataset1.xml"); - var table = ds.Tables [0]; - var q = from line in table.AsEnumerable () - where line.Field ("Score") >= 80 - orderby line.Field ("Gender"), line.Field ("ID") descending - select new { - StudentID = line.Field ("ID"), - StudentName = line.Field ("Name"), - StudentScore = line.Field ("Score") }; - int prevID = -1; - foreach (var ql in q) { - switch (prevID) { - case -1: - Assert.AreEqual (1, ql.StudentID, "#1"); - break; - case 4: - Assert.AreEqual (4, ql.StudentID, "#2"); - break; - default: - Assert.Fail ("should match only one raw"); - } - prevID = ql.StudentID; - } - } - */ } } diff --git a/mcs/class/System.Data.Linq/src/DbLinq/Schema/Dbml/Adapter/EnumType.cs b/mcs/class/System.Data.Linq/src/DbLinq/Schema/Dbml/Adapter/EnumType.cs index 8d2a5f67e8..1df830139f 100644 --- a/mcs/class/System.Data.Linq/src/DbLinq/Schema/Dbml/Adapter/EnumType.cs +++ b/mcs/class/System.Data.Linq/src/DbLinq/Schema/Dbml/Adapter/EnumType.cs @@ -139,7 +139,7 @@ namespace DbLinq.Schema.Dbml.Adapter string literalType = string.IsNullOrEmpty(Name) ? "enum" : Name; literalType += " "; literalType += string.Join(", ", keyValues.ToArray()); - MemberInfoExtensions.SetMemberValue(memberInfo, owner, literalType); + DbLinqMemberInfoExtensions.SetMemberValue(memberInfo, owner, literalType); } internal EnumType(object owner, MemberInfo memberInfo) diff --git a/mcs/class/System.Data.Linq/src/DbLinq/Util/MemberInfoExtensions.cs b/mcs/class/System.Data.Linq/src/DbLinq/Util/MemberInfoExtensions.cs index cbc9324022..d750ef4ee6 100644 --- a/mcs/class/System.Data.Linq/src/DbLinq/Util/MemberInfoExtensions.cs +++ b/mcs/class/System.Data.Linq/src/DbLinq/Util/MemberInfoExtensions.cs @@ -35,7 +35,7 @@ namespace DbLinq.Util #if !MONO_STRICT public #endif - static class MemberInfoExtensions + static class DbLinqMemberInfoExtensions { /// /// Returns the type of the specified member diff --git a/mcs/class/System.Data/Makefile b/mcs/class/System.Data/Makefile index f863c7b413..a2af630db5 100644 --- a/mcs/class/System.Data/Makefile +++ b/mcs/class/System.Data/Makefile @@ -25,6 +25,12 @@ ifdef MONO_FEATURE_APPLETLS LIB_MCS_FLAGS += -d:MONO_FEATURE_APPLETLS endif +ifdef ENABLE_GSS +ifndef NO_GSS +LIB_MCS_FLAGS += -d:ENABLE_GSS +endif +endif + ifndef PROFILE_DISABLE_BTLS ifdef HAVE_BTLS LIB_MCS_FLAGS += -d:MONO_FEATURE_BTLS @@ -37,8 +43,20 @@ RESX_RESOURCE_STRING = \ ../../../external/corefx/src/System.Data.SqlClient/src/Resources/Strings.resx \ ../../../external/corefx/src/System.Data.Odbc/src/Resources/Strings.resx +TEST_RESOURCE_FILES = \ + $(wildcard Test/System.Data/*.xml) \ + $(wildcard Test/System.Data/*.xsd) \ + $(wildcard Test/System.Xml/*.xml) \ + $(wildcard Test/System.Xml/*.xsd) \ + $(wildcard Test/System.Data/schemas/*.xml) \ + $(wildcard Test/System.Data/schemas/*.xsd) \ + $(wildcard Test/System.Data/binserialize/*.bin) \ + $(wildcard Test/ProviderTests/sql/*.sql) \ + Test/Mono.Data.SqlExpressions/dateComparisonTest.xml \ + Test/System.Data.Common/SqliteTest.db + TEST_LIB_REFS = System.Core Mono.Data.Sqlite -TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -nowarn:618,169,612,219,168 +TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -nowarn:618,169,612,219,168 $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) TEST_NUNITLITE_APP_CONFIG_GLOBAL=Test/test-config-file @@ -46,14 +64,7 @@ USE_XTEST_REMOTE_EXECUTOR = YES XTEST_LIB_REFS = System System.Core System.Xml Facades/System.Text.Encoding.CodePages Facades/System.Threading.Tasks Facades/System.Runtime.InteropServices.RuntimeInformation Facades/System.Text.RegularExpressions EXTRA_DISTFILES = \ - $(wildcard Test/System.Data/*.xml) \ - $(wildcard Test/System.Data/*.xsd) \ - $(wildcard Test/System.Xml/*.xml) \ - $(wildcard Test/System.Xml/*.xsd) \ - $(wildcard Test/System.Data/schemas/*.xsd) \ - Test/test-config-file \ - Test/System.Data/binserialize/*.bin \ - Test/ProviderTests/sql/*.sql \ - SqliteTest.db + $(TEST_RESOURCE_FILES) \ + Test/test-config-file include ../../build/library.make diff --git a/mcs/class/System.Data/System.Data_test.dll.sources b/mcs/class/System.Data/System.Data_test.dll.sources index 0f350aa258..78f5c72236 100644 --- a/mcs/class/System.Data/System.Data_test.dll.sources +++ b/mcs/class/System.Data/System.Data_test.dll.sources @@ -1,3 +1,4 @@ +../../test-helpers/TestResourceHelper.cs System.Data.Test.Utils/DataProvider.cs System.Data.SqlTypes/SqlBinaryTest.cs System.Data.SqlTypes/SqlBooleanTest.cs diff --git a/mcs/class/System.Data/Test/Mono.Data.SqlExpressions/DateComparisonTest.cs b/mcs/class/System.Data/Test/Mono.Data.SqlExpressions/DateComparisonTest.cs index 752b03407e..ea54aa3743 100644 --- a/mcs/class/System.Data/Test/Mono.Data.SqlExpressions/DateComparisonTest.cs +++ b/mcs/class/System.Data/Test/Mono.Data.SqlExpressions/DateComparisonTest.cs @@ -2,6 +2,8 @@ using System; using System.Data; using NUnit.Framework; +using MonoTests.Helpers; + namespace Monotests_Mono.Data.SqlExpressions { [TestFixture] @@ -13,7 +15,7 @@ namespace Monotests_Mono.Data.SqlExpressions public void SetUp() { dataSet = new DataSet(); - dataSet.ReadXml("Test/Mono.Data.SqlExpressions/dateComparisonTest.xml", XmlReadMode.InferSchema); + dataSet.ReadXml(TestResourceHelper.GetFullPathOfResource ("Test/Mono.Data.SqlExpressions/dateComparisonTest.xml"), XmlReadMode.InferSchema); } [Test] diff --git a/mcs/class/System.Data/Test/ProviderTests/Common/ConnectionManager.cs b/mcs/class/System.Data/Test/ProviderTests/Common/ConnectionManager.cs index f0613feecc..db36b3d5d4 100644 --- a/mcs/class/System.Data/Test/ProviderTests/Common/ConnectionManager.cs +++ b/mcs/class/System.Data/Test/ProviderTests/Common/ConnectionManager.cs @@ -41,6 +41,8 @@ using System.Linq; using System.Text.RegularExpressions; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Data.Connected { public class ConnectionManager @@ -128,7 +130,7 @@ namespace MonoTests.System.Data.Connected sql.ConnectionString = sql.ConnectionString.Replace(sql.Connection.Database, DatabaseName); sql.CloseConnection(); - string query = File.ReadAllText(@"Test/ProviderTests/sql/sqlserver.sql"); + string query = File.ReadAllText(TestResourceHelper.GetFullPathOfResource ("Test/ProviderTests/sql/sqlserver.sql")); var queries = SplitSqlStatements(query); foreach (var subQuery in queries) @@ -144,7 +146,7 @@ namespace MonoTests.System.Data.Connected odbc.Connection.ChangeDatabase(DatabaseName); odbc.ConnectionString += $"database={DatabaseName}"; - string query = File.ReadAllText("Test/ProviderTests/sql/MySQL_5.sql"); + string query = File.ReadAllText(TestResourceHelper.GetFullPathOfResource ("Test/ProviderTests/sql/MySQL_5.sql")); var groups = query.Replace("delimiter ", "") .Split(new[] { "//\n" }, StringSplitOptions.RemoveEmptyEntries); diff --git a/mcs/class/System.Data/Test/System.Data.Common/DbDataAdapterTest.cs b/mcs/class/System.Data/Test/System.Data.Common/DbDataAdapterTest.cs index 3cd936090f..6c51cc7253 100644 --- a/mcs/class/System.Data/Test/System.Data.Common/DbDataAdapterTest.cs +++ b/mcs/class/System.Data/Test/System.Data.Common/DbDataAdapterTest.cs @@ -39,6 +39,8 @@ using Mono.Data.Sqlite; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Data.Common { [TestFixture] @@ -194,7 +196,7 @@ namespace MonoTests.System.Data.Common [Category ("NotWorking")] // Requires newer sqlite than is on wrench public void XimarinBugzillaBug853Test() { - const string connectionString = "URI = file:./SqliteTest.db; Version = 3";//will be in System.Data directory + string connectionString = "URI = file:" + TestResourceHelper.GetFullPathOfResource ("Test/System.Data.Common/SqliteTest.db") + "; Version = 3";//will be in System.Data directory SqliteConnection dbConnection = new SqliteConnection(connectionString); dbConnection.Open(); SqliteCommand ClearTableEntry=new SqliteCommand("DELETE FROM Primus;",dbConnection); diff --git a/mcs/class/System.Data/SqliteTest.db b/mcs/class/System.Data/Test/System.Data.Common/SqliteTest.db similarity index 100% rename from mcs/class/System.Data/SqliteTest.db rename to mcs/class/System.Data/Test/System.Data.Common/SqliteTest.db diff --git a/mcs/class/System.Data/Test/System.Data/BinarySerializationTest.cs b/mcs/class/System.Data/Test/System.Data/BinarySerializationTest.cs index 1fa1edbf73..0ad05db9f0 100644 --- a/mcs/class/System.Data/Test/System.Data/BinarySerializationTest.cs +++ b/mcs/class/System.Data/Test/System.Data/BinarySerializationTest.cs @@ -11,6 +11,8 @@ using System.Threading; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Data { [TestFixture] @@ -151,7 +153,7 @@ public class BinarySerializationTest tb1.Rows[1].Delete(); BinaryFormatter bf = new BinaryFormatter (); - FileStream fs = new FileStream ("Test/System.Data/binserialize/BS-tb1.bin", FileMode.Open, FileAccess.Read); + FileStream fs = new FileStream (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/binserialize/BS-tb1.bin"), FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader (fs); byte [] serializedStream = r.ReadBytes ((int)fs.Length); r.Close (); @@ -285,7 +287,7 @@ public class BinarySerializationTest BinaryFormatter bf = new BinaryFormatter (); tb1.RemotingFormat = SerializationFormat.Xml; - FileStream fs = new FileStream ("Test/System.Data/binserialize/BS-tb2.bin", FileMode.Open, FileAccess.Read); + FileStream fs = new FileStream (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/binserialize/BS-tb2.bin"), FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader (fs); byte [] serializedStream = r.ReadBytes ((int)fs.Length); r.Close (); @@ -342,7 +344,7 @@ public class BinarySerializationTest //tb1.Rows.Add (new object[] {3, dateTime}); BinaryFormatter bf = new BinaryFormatter (); tb1.RemotingFormat = SerializationFormat.Binary; - FileStream fs = new FileStream ("Test/System.Data/binserialize/BS-tb3.bin", FileMode.Open, FileAccess.Read); + FileStream fs = new FileStream (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/binserialize/BS-tb3.bin"), FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader (fs); byte [] serializedStream = r.ReadBytes ((int) fs.Length); r.Close (); @@ -477,7 +479,7 @@ public class BinarySerializationTest //SerializeDataSet BinaryFormatter bf = new BinaryFormatter (); ds.RemotingFormat = SerializationFormat.Xml; - FileStream fs = new FileStream ("Test/System.Data/binserialize/BS-tb4.bin", FileMode.Open, FileAccess.Read); + FileStream fs = new FileStream (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/binserialize/BS-tb4.bin"), FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader (fs); byte [] serializedStream = r.ReadBytes ((int) fs.Length); r.Close (); @@ -711,7 +713,7 @@ public class BinarySerializationTest //SerializeDataSet BinaryFormatter bf = new BinaryFormatter (); ds.RemotingFormat = SerializationFormat.Xml; - FileStream fs = new FileStream ("Test/System.Data/binserialize/BS-tb5.bin", FileMode.Open, FileAccess.Read); + FileStream fs = new FileStream (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/binserialize/BS-tb5.bin"), FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader (fs); byte [] serializedStream = r.ReadBytes ((int)fs.Length); r.Close (); diff --git a/mcs/class/System.Data/Test/System.Data/DataRelationTest.cs b/mcs/class/System.Data/Test/System.Data/DataRelationTest.cs index f020a208e6..5e7f4c772a 100644 --- a/mcs/class/System.Data/Test/System.Data/DataRelationTest.cs +++ b/mcs/class/System.Data/Test/System.Data/DataRelationTest.cs @@ -35,6 +35,8 @@ using NUnit.Framework; using System; using System.Data; +using MonoTests.Helpers; + namespace MonoTests.System.Data { [TestFixture] @@ -382,7 +384,7 @@ namespace MonoTests.System.Data public void RelationFromSchema () { DataSet Set = new DataSet (); - Set.ReadXmlSchema ("Test/System.Data/store.xsd"); + Set.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/store.xsd")); DataTable Table = Set.Tables [0]; Assert.That (Table.CaseSensitive, Is.False, "test#01"); diff --git a/mcs/class/System.Data/Test/System.Data/DataSetReadXmlSchemaTest.cs b/mcs/class/System.Data/Test/System.Data/DataSetReadXmlSchemaTest.cs index 08909cf76f..3f786ab7eb 100644 --- a/mcs/class/System.Data/Test/System.Data/DataSetReadXmlSchemaTest.cs +++ b/mcs/class/System.Data/Test/System.Data/DataSetReadXmlSchemaTest.cs @@ -38,6 +38,8 @@ using System.Threading; using System.Xml; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Data { [TestFixture] @@ -499,19 +501,19 @@ namespace MonoTests.System.Data public void TestSampleFileNoTables () { DataSet ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test001.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test001.xsd")); AssertDataSet ("001", ds, "NewDataSet", 0, 0); ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test002.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test002.xsd")); AssertDataSet ("002", ds, "NewDataSet", 0, 0); ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test003.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test003.xsd")); AssertDataSet ("003", ds, "NewDataSet", 0, 0); ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test004.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test004.xsd")); AssertDataSet ("004", ds, "NewDataSet", 0, 0); } @@ -519,7 +521,7 @@ namespace MonoTests.System.Data public void TestSampleFileSimpleTables () { DataSet ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test005.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test005.xsd")); AssertDataSet ("005", ds, "NewDataSet", 1, 0); DataTable dt = ds.Tables [0]; AssertDataTable ("tab", dt, "foo", 2, 0, 0, 0, 0, 0); @@ -527,7 +529,7 @@ namespace MonoTests.System.Data AssertDataColumn ("text", dt.Columns [1], "foo_text", false, false, 0, 1, "foo_text", MappingType.SimpleContent, typeof (long), DBNull.Value, String.Empty, -1, String.Empty, 1, String.Empty, false, false); ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test006.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test006.xsd")); AssertDataSet ("006", ds, "NewDataSet", 1, 0); dt = ds.Tables [0]; AssertDataTable ("tab", dt, "foo", 2, 0, 0, 0, 0, 0); @@ -540,7 +542,7 @@ namespace MonoTests.System.Data { // Nested simple type element DataSet ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test007.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test007.xsd")); AssertDataSet ("007", ds, "NewDataSet", 2, 1); DataTable dt = ds.Tables [0]; AssertDataTable ("tab1", dt, "uno", 1, 0, 0, 1, 1, 1); @@ -553,7 +555,7 @@ namespace MonoTests.System.Data // External simple type element ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test008.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test008.xsd")); AssertDataSet ("008", ds, "NewDataSet", 2, 1); dt = ds.Tables [0]; AssertDataTable ("tab1", dt, "uno", 1, 0, 0, 1, 1, 1); @@ -571,7 +573,7 @@ namespace MonoTests.System.Data public void TestSampleFileValueConstraints () { DataSet ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test009.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test009.xsd")); AssertDataSet ("009", ds, "NewDataSet", 2, 1); DataTable dt = ds.Tables [0]; @@ -606,7 +608,7 @@ namespace MonoTests.System.Data DataSet ds = new DataSet (); XmlTextReader xtr = null; try { - xtr = new XmlTextReader ("Test/System.Data/schemas/test010.xsd"); + xtr = new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test010.xsd")); xtr.XmlResolver = null; ds.ReadXmlSchema (xtr); } finally { @@ -625,7 +627,7 @@ namespace MonoTests.System.Data public void TestSampleFileComplexTables2 () { DataSet ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test011.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test011.xsd")); AssertDataSet ("011", ds, "NewDataSet", 2, 1); DataTable dt = ds.Tables [0]; @@ -645,7 +647,7 @@ namespace MonoTests.System.Data public void TestSampleFileComplexTables3 () { DataSet ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test013.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test013.xsd")); AssertDataSet ("013", ds, "root", 1, 0); DataTable dt = ds.Tables [0]; @@ -659,14 +661,14 @@ namespace MonoTests.System.Data public void TestSampleFileXPath () { DataSet ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test103.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test103.xsd")); } [Test] public void TestAnnotatedRelation1 () { DataSet ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test101.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test101.xsd")); AssertDataSet ("101", ds, "root", 2, 1); DataTable dt = ds.Tables [0]; AssertDataTable ("parent_table", dt, "p", 2, 0, 0, 1, 0, 0); @@ -683,7 +685,7 @@ namespace MonoTests.System.Data public void TestAnnotatedRelation2 () { DataSet ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test102.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test102.xsd")); AssertDataSet ("102", ds, "ds", 2, 1); DataTable dt = ds.Tables [0]; AssertDataTable ("parent_table", dt, "p", 2, 0, 0, 1, 0, 0); @@ -700,7 +702,7 @@ namespace MonoTests.System.Data public void RepeatableSimpleElement () { DataSet ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test012.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test012.xsd")); AssertDataSet ("012", ds, "NewDataSet", 2, 1); DataTable dt = ds.Tables [0]; AssertDataTable ("parent", dt, "Foo", 1, 0, 0, 1, 1, 1); @@ -718,7 +720,7 @@ namespace MonoTests.System.Data public void TestMoreThanOneRepeatableColumns () { DataSet ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test014.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test014.xsd")); AssertDataSet ("014", ds, "NewDataSet", 3, 2); DataTable dt = ds.Tables [0]; @@ -757,7 +759,7 @@ namespace MonoTests.System.Data public void ReadConstraints () { DataSet ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test015.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test015.xsd")); Assert.AreEqual (0, ds.Relations.Count, "#1"); Assert.AreEqual (1, ds.Tables [0].Constraints.Count, "#2" ); @@ -769,7 +771,7 @@ namespace MonoTests.System.Data public void ReadAnnotatedRelations_MultipleColumns () { DataSet ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/test016.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test016.xsd")); Assert.AreEqual (1, ds.Relations.Count, "#1"); Assert.AreEqual ("rel", ds.Relations [0].RelationName, "#2"); diff --git a/mcs/class/System.Data/Test/System.Data/DataSetReadXmlTest.cs b/mcs/class/System.Data/Test/System.Data/DataSetReadXmlTest.cs index ff5caaf20c..0304ac8c98 100644 --- a/mcs/class/System.Data/Test/System.Data/DataSetReadXmlTest.cs +++ b/mcs/class/System.Data/Test/System.Data/DataSetReadXmlTest.cs @@ -37,6 +37,8 @@ using System.Xml.Serialization; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Data { [TestFixture] @@ -781,7 +783,7 @@ namespace MonoTests.System.Data } DataSet dataSet2 = new DataSet(); - dataSet2.ReadXml("Test/System.Data/schemas/b582732.xml", XmlReadMode.ReadSchema); + dataSet2.ReadXml(TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/b582732.xml"), XmlReadMode.ReadSchema); Assert.AreEqual (dataSet1.ExtendedProperties["DS1"], dataSet2.ExtendedProperties["DS1"], "DSExtProp#1: DS extended properties mismatch"); diff --git a/mcs/class/System.Data/Test/System.Data/DataSetTest.cs.REMOVED.git-id b/mcs/class/System.Data/Test/System.Data/DataSetTest.cs.REMOVED.git-id index 5459e2c565..d07cb78944 100644 --- a/mcs/class/System.Data/Test/System.Data/DataSetTest.cs.REMOVED.git-id +++ b/mcs/class/System.Data/Test/System.Data/DataSetTest.cs.REMOVED.git-id @@ -1 +1 @@ -560620c3c2a145b950445cc2976533cf251b9134 \ No newline at end of file +cb15d8ba56678e66fd3473fef709b88a22cb9f48 \ No newline at end of file diff --git a/mcs/class/System.Data/Test/System.Data/DataSetTest2.cs.REMOVED.git-id b/mcs/class/System.Data/Test/System.Data/DataSetTest2.cs.REMOVED.git-id index 37d577f32a..ea68a30eb3 100644 --- a/mcs/class/System.Data/Test/System.Data/DataSetTest2.cs.REMOVED.git-id +++ b/mcs/class/System.Data/Test/System.Data/DataSetTest2.cs.REMOVED.git-id @@ -1 +1 @@ -e785bce6e510e38a87bfcec7c30e698ad193ce0b \ No newline at end of file +090f6babf4967ffa56e3c3b9e8a865c9dff0a6f6 \ No newline at end of file diff --git a/mcs/class/System.Data/Test/System.Data/DataSetTypedDataSetTest.cs b/mcs/class/System.Data/Test/System.Data/DataSetTypedDataSetTest.cs index 357c2b3ef5..6184024e90 100644 --- a/mcs/class/System.Data/Test/System.Data/DataSetTypedDataSetTest.cs +++ b/mcs/class/System.Data/Test/System.Data/DataSetTypedDataSetTest.cs @@ -38,6 +38,8 @@ using System.Xml.Schema; using System.IO; using System.Globalization; +using MonoTests.Helpers; + namespace MonoTests.System.Data { [TestFixture] @@ -57,7 +59,7 @@ namespace MonoTests.System.Data Assert.AreEqual(typeof(myTypedDataSet), ds.GetType() ,"TDS1" ); // fill dataset - ds.ReadXml("Test/System.Data/TypedDataSet.xml"); + ds.ReadXml(TestResourceHelper.GetFullPathOfResource ("Test/System.Data/TypedDataSet.xml")); // check DataSet named property "Orders" myTypedDataSet.OrdersDataTable tblOrders = null; diff --git a/mcs/class/System.Data/Test/System.Data/DataTableReadXmlSchemaTest.cs b/mcs/class/System.Data/Test/System.Data/DataTableReadXmlSchemaTest.cs index c7d78cff76..7b885f4150 100644 --- a/mcs/class/System.Data/Test/System.Data/DataTableReadXmlSchemaTest.cs +++ b/mcs/class/System.Data/Test/System.Data/DataTableReadXmlSchemaTest.cs @@ -39,6 +39,8 @@ using System.Threading; using System.Xml; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Data { [TestFixture] @@ -413,7 +415,7 @@ namespace MonoTests.System.Data { DataSet ds = new DataSet (); ds.Tables.Add (new DataTable ("foo")); - ds.Tables[0].ReadXmlSchema ("Test/System.Data/schemas/test005.xsd"); + ds.Tables[0].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test005.xsd")); AssertDataSet ("005", ds, "NewDataSet", 1, 0); DataTable dt = ds.Tables [0]; AssertDataTable ("tab", dt, "foo", 2, 0, 0, 0, 0, 0); @@ -422,7 +424,7 @@ namespace MonoTests.System.Data ds = new DataSet (); ds.Tables.Add (new DataTable ("foo")); - ds.Tables[0].ReadXmlSchema ("Test/System.Data/schemas/test006.xsd"); + ds.Tables[0].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test006.xsd")); AssertDataSet ("006", ds, "NewDataSet", 1, 0); dt = ds.Tables [0]; AssertDataTable ("tab", dt, "foo", 2, 0, 0, 0, 0, 0); @@ -437,7 +439,7 @@ namespace MonoTests.System.Data // Nested simple type element DataSet ds = new DataSet (); ds.Tables.Add (new DataTable ("uno")); - ds.Tables[0].ReadXmlSchema ("Test/System.Data/schemas/test007.xsd"); + ds.Tables[0].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test007.xsd")); } [Test] @@ -447,7 +449,7 @@ namespace MonoTests.System.Data // External simple type element DataSet ds = new DataSet (); ds.Tables.Add (new DataTable ("uno")); - ds.Tables[0].ReadXmlSchema ("Test/System.Data/schemas/test008.xsd"); + ds.Tables[0].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test008.xsd")); } [Test] @@ -458,7 +460,7 @@ namespace MonoTests.System.Data ds.Tables.Add( new DataTable("foo")); XmlTextReader xtr = null; try { - xtr = new XmlTextReader ("Test/System.Data/schemas/test010.xsd"); + xtr = new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test010.xsd")); xtr.XmlResolver = null; ds.Tables[0].ReadXmlSchema (xtr); } finally { @@ -479,13 +481,13 @@ namespace MonoTests.System.Data DataSet ds = new DataSet (); ds.Tables.Add (new DataTable ("e")); ds.Tables.Add (new DataTable ("root")); - ds.Tables[0].ReadXmlSchema ("Test/System.Data/schemas/test011.xsd"); + ds.Tables[0].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test011.xsd")); DataTable dt = ds.Tables[0]; AssertDataTable ("root", dt, "e", 3, 0, 0, 0, 0, 0); AssertDataColumn ("attr", dt.Columns [0], "a", true, false, 0, 1, "a", MappingType.Attribute, typeof (string), DBNull.Value, String.Empty, -1, "http://xsdtesting", 0, String.Empty, false, false); AssertDataColumn ("simple", dt.Columns [1], "e_text", false, false, 0, 1, "e_text", MappingType.SimpleContent, typeof (decimal), DBNull.Value, String.Empty, -1, "", 1, String.Empty, false, false); AssertDataColumn ("hidden", dt.Columns [2], "root_Id", true, false, 0, 1, "root_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, "", 2, String.Empty, false, false); - ds.Tables[1].ReadXmlSchema ("Test/System.Data/schemas/test011.xsd"); + ds.Tables[1].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test011.xsd")); } [Test] @@ -493,7 +495,7 @@ namespace MonoTests.System.Data { DataSet ds = new DataSet (); ds.Tables.Add (new DataTable ("e")); - ds.Tables[0].ReadXmlSchema ("Test/System.Data/schemas/test013.xsd"); + ds.Tables[0].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test013.xsd")); DataTable dt = ds.Tables [0]; AssertDataTable ("root", dt, "e", 2, 0, 0, 0, 0, 0); AssertDataColumn ("attr", dt.Columns [0], "a", true, false, 0, 1, "a", MappingType.Attribute, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, false); @@ -506,7 +508,7 @@ namespace MonoTests.System.Data { DataSet ds = new DataSet (); ds.Tables.Add (new DataTable ("Track")); - ds.Tables[0].ReadXmlSchema ("Test/System.Data/schemas/test103.xsd"); + ds.Tables[0].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test103.xsd")); } [Test] @@ -516,8 +518,8 @@ namespace MonoTests.System.Data DataSet ds = new DataSet (); ds.Tables.Add (new DataTable ("p")); ds.Tables.Add (new DataTable ("c")); - ds.Tables[0].ReadXmlSchema ("Test/System.Data/schemas/test101.xsd"); - ds.Tables[1].ReadXmlSchema ("Test/System.Data/schemas/test101.xsd"); + ds.Tables[0].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test101.xsd")); + ds.Tables[1].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test101.xsd")); DataTable dt = ds.Tables [0]; AssertDataTable ("parent_table", dt, "p", 2, 0, 0, 1, 0, 0); @@ -537,8 +539,8 @@ namespace MonoTests.System.Data DataSet ds = new DataSet (); ds.Tables.Add (new DataTable ("p")); ds.Tables.Add (new DataTable ("c")); - ds.Tables[0].ReadXmlSchema ("Test/System.Data/schemas/test102.xsd"); - ds.Tables[1].ReadXmlSchema ("Test/System.Data/schemas/test102.xsd"); + ds.Tables[0].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test102.xsd")); + ds.Tables[1].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test102.xsd")); DataTable dt = ds.Tables [0]; AssertDataTable ("parent_table", dt, "p", 2, 0, 0, 1, 0, 0); @@ -558,8 +560,8 @@ namespace MonoTests.System.Data DataSet ds = new DataSet (); ds.Tables.Add (new DataTable ("Foo")); ds.Tables.Add (new DataTable ("Bar")); - ds.Tables[0].ReadXmlSchema ("Test/System.Data/schemas/test012.xsd"); - ds.Tables[1].ReadXmlSchema ("Test/System.Data/schemas/test012.xsd"); + ds.Tables[0].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test012.xsd")); + ds.Tables[1].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test012.xsd")); AssertDataSet ("012", ds, "NewDataSet", 2, 1); DataTable dt = ds.Tables [0]; @@ -582,9 +584,9 @@ namespace MonoTests.System.Data ds.Tables.Add (new DataTable ("root")); ds.Tables.Add (new DataTable ("x")); ds.Tables.Add (new DataTable ("y")); - ds.Tables[0].ReadXmlSchema ("Test/System.Data/schemas/test014.xsd"); - ds.Tables[1].ReadXmlSchema ("Test/System.Data/schemas/test014.xsd"); - ds.Tables[2].ReadXmlSchema ("Test/System.Data/schemas/test014.xsd"); + ds.Tables[0].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test014.xsd")); + ds.Tables[1].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test014.xsd")); + ds.Tables[2].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test014.xsd")); AssertDataSet ("014", ds, "NewDataSet", 3, 2); DataTable dt = ds.Tables [0]; @@ -612,8 +614,8 @@ namespace MonoTests.System.Data DataSet ds = new DataSet (); ds.Tables.Add (new DataTable ()); ds.Tables.Add (new DataTable ()); - ds.Tables[0].ReadXmlSchema ("Test/System.Data/schemas/test015.xsd"); - ds.Tables[1].ReadXmlSchema ("Test/System.Data/schemas/test015.xsd"); + ds.Tables[0].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test015.xsd")); + ds.Tables[1].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test015.xsd")); Assert.AreEqual (0, ds.Relations.Count, "#1"); Assert.AreEqual (1, ds.Tables [0].Constraints.Count, "#2" ); Assert.AreEqual (0, ds.Tables [1].Constraints.Count, "#3" ); @@ -627,8 +629,8 @@ namespace MonoTests.System.Data DataSet ds = new DataSet (); ds.Tables.Add (new DataTable ()); ds.Tables.Add (new DataTable ()); - ds.Tables[0].ReadXmlSchema ("Test/System.Data/schemas/test016.xsd"); - ds.Tables[1].ReadXmlSchema ("Test/System.Data/schemas/test016.xsd"); + ds.Tables[0].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test016.xsd")); + ds.Tables[1].ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/test016.xsd")); Assert.AreEqual (1, ds.Relations.Count, "#1"); Assert.AreEqual ("rel", ds.Relations [0].RelationName, "#2"); Assert.AreEqual (2, ds.Relations [0].ParentColumns.Length, "#3"); diff --git a/mcs/class/System.Data/Test/System.Data/DataTableTest.cs.REMOVED.git-id b/mcs/class/System.Data/Test/System.Data/DataTableTest.cs.REMOVED.git-id index 27f6f41bc2..8cb77d0637 100644 --- a/mcs/class/System.Data/Test/System.Data/DataTableTest.cs.REMOVED.git-id +++ b/mcs/class/System.Data/Test/System.Data/DataTableTest.cs.REMOVED.git-id @@ -1 +1 @@ -12aeaa4ad4d536103f019c69e9ab187d19cfd6fe \ No newline at end of file +ec78ea8650efd71487f1f860931a3c13055e73c7 \ No newline at end of file diff --git a/mcs/class/System.Data/Test/System.Data/TypedDataSetGeneratorTest.cs b/mcs/class/System.Data/Test/System.Data/TypedDataSetGeneratorTest.cs index 8b35f50b83..0dc72504e6 100644 --- a/mcs/class/System.Data/Test/System.Data/TypedDataSetGeneratorTest.cs +++ b/mcs/class/System.Data/Test/System.Data/TypedDataSetGeneratorTest.cs @@ -37,6 +37,8 @@ using System.Data; using NUnit.Framework; using Microsoft.CSharp; +using MonoTests.Helpers; + namespace MonoTests.System.Data { [TestFixture] @@ -91,7 +93,7 @@ namespace MonoTests.System.Data public void RelationConnectsSameTable () { DataSet ds = new DataSet (); - ds.ReadXmlSchema ("Test/System.Data/schemas/bug77248.xsd"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/schemas/bug77248.xsd")); CodeNamespace cns = new CodeNamespace (); TypedDataSetGenerator.Generate (ds, cns, gen); CodeCompileUnit ccu = new CodeCompileUnit (); diff --git a/mcs/class/System.Data/Test/System.Data/XmlDataReaderTest.cs b/mcs/class/System.Data/Test/System.Data/XmlDataReaderTest.cs index e39b5f5298..e5556337f4 100644 --- a/mcs/class/System.Data/Test/System.Data/XmlDataReaderTest.cs +++ b/mcs/class/System.Data/Test/System.Data/XmlDataReaderTest.cs @@ -32,6 +32,8 @@ using System.Xml.Serialization; using System.Xml.Schema; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Data { [TestFixture] @@ -41,8 +43,8 @@ namespace MonoTests.System.Data public void XmlLoadTest () { DataSet ds = new DataSet(); - ds.ReadXmlSchema ("Test/System.Data/TestReadXmlSchema1.xml"); - ds.ReadXml ("Test/System.Data/TestReadXml1.xml"); + ds.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/TestReadXmlSchema1.xml")); + ds.ReadXml (TestResourceHelper.GetFullPathOfResource ("Test/System.Data/TestReadXml1.xml")); } // Test for Bug#377146 diff --git a/mcs/class/System.Data/Test/System.Xml/XmlDataDocumentTest.cs b/mcs/class/System.Data/Test/System.Xml/XmlDataDocumentTest.cs index 93b0cc6ff3..8daf200139 100755 --- a/mcs/class/System.Data/Test/System.Xml/XmlDataDocumentTest.cs +++ b/mcs/class/System.Data/Test/System.Xml/XmlDataDocumentTest.cs @@ -42,6 +42,8 @@ using System.Xml.XPath; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Data.Xml { [TestFixture] @@ -114,8 +116,8 @@ namespace MonoTests.System.Data.Xml { XmlDataDocument doc = new XmlDataDocument (); - doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); - doc.Load ("Test/System.Xml/region.xml"); + doc.DataSet.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xsd")); + doc.Load (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml")); XmlDataDocument doc2 = (XmlDataDocument)doc.CloneNode (false); @@ -136,15 +138,15 @@ namespace MonoTests.System.Data.Xml public void EditingXmlTree () { XmlDataDocument doc = new XmlDataDocument (); - doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); - doc.Load ("Test/System.Xml/region.xml"); + doc.DataSet.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xsd")); + doc.Load (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml")); XmlElement Element = doc.GetElementFromRow (doc.DataSet.Tables [0].Rows [1]); Element.FirstChild.InnerText = "64"; Assert.AreEqual ("64", doc.DataSet.Tables [0].Rows [1] [0], "test#01"); DataSet Set = new DataSet (); - Set.ReadXml ("Test/System.Xml/region.xml"); + Set.ReadXml (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml")); doc = new XmlDataDocument (Set); Element = doc.GetElementFromRow (doc.DataSet.Tables [0].Rows [1]); @@ -168,7 +170,7 @@ namespace MonoTests.System.Data.Xml { string xml = "1Eastern" + Environment.NewLine + " 2Western" + Environment.NewLine + " 3Northern" + Environment.NewLine + " 4Southern" + Environment.NewLine + " 12Hi There12Hi There"; - XmlReader Reader = new XmlTextReader ("Test/System.Xml/region.xml"); + XmlReader Reader = new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml")); XmlDataDocument Doc = new XmlDataDocument (); Doc.DataSet.ReadXml (Reader); StringWriter sw = new StringWriter (); @@ -189,8 +191,8 @@ namespace MonoTests.System.Data.Xml public void CreateElement1 () { XmlDataDocument doc = new XmlDataDocument (); - doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); - doc.Load ("Test/System.Xml/region.xml"); + doc.DataSet.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xsd")); + doc.Load (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml")); XmlElement Element = doc.CreateElement ("prefix", "localname", "namespaceURI"); Assert.AreEqual ("prefix", Element.Prefix, "test#01"); @@ -232,8 +234,8 @@ namespace MonoTests.System.Data.Xml public void CreateElement2 () { XmlDataDocument doc = new XmlDataDocument (); - doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); - doc.Load ("Test/System.Xml/region.xml"); + doc.DataSet.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xsd")); + doc.Load (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml")); XmlElement Element = doc.CreateElement ("ElementName"); Assert.AreEqual (string.Empty, Element.Prefix, "test#01"); @@ -250,8 +252,8 @@ namespace MonoTests.System.Data.Xml public void CreateElement3 () { XmlDataDocument doc = new XmlDataDocument (); - doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); - doc.Load ("Test/System.Xml/region.xml"); + doc.DataSet.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xsd")); + doc.Load (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml")); XmlElement Element = doc.CreateElement ("ElementName", "namespace"); Assert.AreEqual (string.Empty, Element.Prefix, "test#01"); @@ -268,8 +270,8 @@ namespace MonoTests.System.Data.Xml public void Navigator () { XmlDataDocument doc = new XmlDataDocument (); - doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); - doc.Load ("Test/System.Xml/region.xml"); + doc.DataSet.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xsd")); + doc.Load (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml")); XPathNavigator Nav = doc.CreateNavigator (); @@ -301,9 +303,9 @@ namespace MonoTests.System.Data.Xml XmlDataDocument doc = new XmlDataDocument(); //Load the schema file. - doc.DataSet.ReadXmlSchema("Test/System.Xml/store.xsd"); + doc.DataSet.ReadXmlSchema(TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/store.xsd")); //Load the XML data. - doc.Load("Test/System.Xml/2books.xml"); + doc.Load(TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/2books.xml")); //Update the price on the first book using the DataSet methods. DataTable books = doc.DataSet.Tables["book"]; @@ -371,10 +373,10 @@ namespace MonoTests.System.Data.Xml { DataSet RegionDS = new DataSet (); DataRow RegionRow; - RegionDS.ReadXmlSchema ("Test/System.Xml/region.xsd"); + RegionDS.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xsd")); Assert.AreEqual (1, RegionDS.Tables.Count, "Was read correct?"); XmlDataDocument DataDoc = new XmlDataDocument (RegionDS); - DataDoc.Load("Test/System.Xml/region.xml" ); + DataDoc.Load(TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml") ); RegionRow = RegionDS.Tables[0].Rows[0]; @@ -509,8 +511,8 @@ namespace MonoTests.System.Data.Xml { XmlDataDocument DataDoc = new XmlDataDocument (); DataSet dataset = DataDoc.DataSet; - dataset.ReadXmlSchema ("Test/System.Xml/region.xsd"); - DataDoc.Load("Test/System.Xml/region.xml" ); + dataset.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xsd")); + DataDoc.Load(TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml") ); DataDoc.GetElementsByTagName ("Region") [0].RemoveAll (); @@ -601,9 +603,9 @@ namespace MonoTests.System.Data.Xml { DataSet RegionDS = new DataSet (); - RegionDS.ReadXmlSchema ("Test/System.Xml/region.xsd"); + RegionDS.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xsd")); XmlDataDocument DataDoc = new XmlDataDocument (RegionDS); - DataDoc.Load ("Test/System.Xml/region.xml"); + DataDoc.Load (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml")); Assert.IsTrue (RegionDS.EnforceConstraints); DataTable table = DataDoc.DataSet.Tables ["Region"]; DataRow newRow = table.NewRow (); @@ -764,9 +766,9 @@ namespace MonoTests.System.Data.Xml { DataSet RegionDS = new DataSet (); - RegionDS.ReadXmlSchema ("Test/System.Xml/region.xsd"); + RegionDS.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xsd")); XmlDataDocument DataDoc = new XmlDataDocument (RegionDS); - DataDoc.Load("Test/System.Xml/region.xml" ); + DataDoc.Load(TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml") ); try { DataDoc.DocumentElement.AppendChild (DataDoc.DocumentElement.FirstChild); Assert.Fail ("#G01"); @@ -819,9 +821,9 @@ namespace MonoTests.System.Data.Xml { DataSet RegionDS = new DataSet (); - RegionDS.ReadXmlSchema ("Test/System.Xml/region.xsd"); + RegionDS.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xsd")); XmlDataDocument DataDoc = new XmlDataDocument (RegionDS); - DataDoc.Load("Test/System.Xml/region.xml" ); + DataDoc.Load(TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml") ); DataDoc.DataSet.EnforceConstraints = false; XmlElement newNode = DataDoc.CreateElement ("Region"); @@ -873,8 +875,8 @@ namespace MonoTests.System.Data.Xml public void GetElementFromRow () { XmlDataDocument doc = new XmlDataDocument (); - doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); - doc.Load ("Test/System.Xml/region.xml"); + doc.DataSet.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xsd")); + doc.Load (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml")); DataTable table = doc.DataSet.Tables ["Region"]; XmlElement element = doc.GetElementFromRow (table.Rows [2]); @@ -894,8 +896,8 @@ namespace MonoTests.System.Data.Xml public void GetRowFromElement () { XmlDataDocument doc = new XmlDataDocument (); - doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); - doc.Load ("Test/System.Xml/region.xml"); + doc.DataSet.ReadXmlSchema (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xsd")); + doc.Load (TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/region.xml")); XmlElement root = doc.DocumentElement; DataRow row = doc.GetRowFromElement((XmlElement)root.FirstChild); diff --git a/mcs/class/System.Data/corefx.unix.sources b/mcs/class/System.Data/corefx.unix.sources index 71c996f892..715e7753ba 100644 --- a/mcs/class/System.Data/corefx.unix.sources +++ b/mcs/class/System.Data/corefx.unix.sources @@ -4,10 +4,9 @@ ../../../external/corefx/src/Common/src/System/Net/Security/Unix/SafeDeleteContext.cs ../../../external/corefx/src/Common/src/System/Net/Security/Unix/SafeFreeCredentials.cs ../../../external/corefx/src/Common/src/Microsoft/Win32/SafeHandles/GssSafeHandles.cs -corefx/Interop.NetSecurityNative.cs -#../../../external/corefx/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs +../../../external/corefx/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs ../../../external/corefx/src/Common/src/System/Net/Security/Unix/SafeFreeNegoCredentials.cs -../../../external/corefx/src/Common/src/Interop/Unix/Interop.Libraries.cs +corefx/Interop.Libraries.cs ../../../external/corefx/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssBuffer.cs ../../../external/corefx/src/Common/src/System/Net/Security/Unix/SafeDeleteNegoContext.cs ../../../external/corefx/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssApiException.cs diff --git a/mcs/class/System.Data/corefx/Interop.Libraries.cs b/mcs/class/System.Data/corefx/Interop.Libraries.cs new file mode 100644 index 0000000000..ffcaab805d --- /dev/null +++ b/mcs/class/System.Data/corefx/Interop.Libraries.cs @@ -0,0 +1,11 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +internal static partial class Interop +{ + internal static partial class Libraries + { + internal const string NetSecurityNative = "System.Net.Security.Native"; + } +} diff --git a/mcs/class/System.Data/corefx/Interop.NetSecurityNative.cs b/mcs/class/System.Data/corefx/Interop.NetSecurityNative.cs deleted file mode 100644 index 4fc99ddf2c..0000000000 --- a/mcs/class/System.Data/corefx/Interop.NetSecurityNative.cs +++ /dev/null @@ -1,147 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Text; -using Microsoft.Win32.SafeHandles; - -// stubs for external/corefx/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs -// needed for https://github.com/mono/mono/issues/6766 -// or can be implemented via pal_gssapi (see https://github.com/mono/mono/pull/6806) -static partial class Interop -{ - static partial class NetSecurityNative - { - internal static void ReleaseGssBuffer ( - IntPtr bufferPtr, - UInt64 length) => throw new NotSupportedException (); - - internal static Status DisplayMinorStatus ( - out Status minorStatus, - Status statusValue, - ref GssBuffer buffer) => throw new NotSupportedException (); - - internal static Status DisplayMajorStatus ( - out Status minorStatus, - Status statusValue, - ref GssBuffer buffer) => throw new NotSupportedException (); - - internal static Status ImportUserName ( - out Status minorStatus, - string inputName, - int inputNameByteCount, - out SafeGssNameHandle outputName) => throw new NotSupportedException (); - - internal static Status ImportPrincipalName ( - out Status minorStatus, - string inputName, - int inputNameByteCount, - out SafeGssNameHandle outputName) => throw new NotSupportedException (); - - internal static Status ReleaseName ( - out Status minorStatus, - ref IntPtr inputName) => throw new NotSupportedException (); - - internal static Status InitiateCredSpNego ( - out Status minorStatus, - SafeGssNameHandle desiredName, - out SafeGssCredHandle outputCredHandle) => throw new NotSupportedException (); - - internal static Status InitiateCredWithPassword ( - out Status minorStatus, - bool isNtlm, - SafeGssNameHandle desiredName, - string password, - int passwordLen, - out SafeGssCredHandle outputCredHandle) => throw new NotSupportedException (); - - internal static Status ReleaseCred ( - out Status minorStatus, - ref IntPtr credHandle) => throw new NotSupportedException (); - - internal static Status InitSecContext ( - out Status minorStatus, - SafeGssCredHandle initiatorCredHandle, - ref SafeGssContextHandle contextHandle, - bool isNtlmOnly, - SafeGssNameHandle targetName, - uint reqFlags, - byte[] inputBytes, - int inputLength, - ref GssBuffer token, - out uint retFlags, - out int isNtlmUsed) => throw new NotSupportedException (); - - internal static Status AcceptSecContext ( - out Status minorStatus, - ref SafeGssContextHandle acceptContextHandle, - byte[] inputBytes, - int inputLength, - ref GssBuffer token) => throw new NotSupportedException (); - - internal static Status DeleteSecContext ( - out Status minorStatus, - ref IntPtr contextHandle) => throw new NotSupportedException (); - - static Status Wrap( - out Status minorStatus, - SafeGssContextHandle contextHandle, - bool isEncrypt, - byte[] inputBytes, - int offset, - int count, - ref GssBuffer outBuffer) => throw new NotSupportedException (); - - static Status Unwrap ( - out Status minorStatus, - SafeGssContextHandle contextHandle, - byte[] inputBytes, - int offset, - int count, - ref GssBuffer outBuffer) => throw new NotSupportedException (); - - internal static Status WrapBuffer ( - out Status minorStatus, - SafeGssContextHandle contextHandle, - bool isEncrypt, - byte[] inputBytes, - int offset, - int count, - ref GssBuffer outBuffer) => throw new NotSupportedException (); - - internal static Status UnwrapBuffer ( - out Status minorStatus, - SafeGssContextHandle contextHandle, - byte[] inputBytes, - int offset, - int count, - ref GssBuffer outBuffer) => throw new NotSupportedException (); - - internal enum Status : uint - { - GSS_S_COMPLETE = 0, - GSS_S_CONTINUE_NEEDED = 1 - } - - [Flags] - internal enum GssFlags : uint - { - GSS_C_DELEG_FLAG = 0x1, - GSS_C_MUTUAL_FLAG = 0x2, - GSS_C_REPLAY_FLAG = 0x4, - GSS_C_SEQUENCE_FLAG = 0x8, - GSS_C_CONF_FLAG = 0x10, - GSS_C_INTEG_FLAG = 0x20, - GSS_C_ANON_FLAG = 0x40, - GSS_C_PROT_READY_FLAG = 0x80, - GSS_C_TRANS_FLAG = 0x100, - GSS_C_DCE_STYLE = 0x1000, - GSS_C_IDENTIFY_FLAG = 0x2000, - GSS_C_EXTENDED_ERROR_FLAG = 0x4000, - GSS_C_DELEG_POLICY_FLAG = 0x8000 - } - } -} diff --git a/mcs/class/System.Drawing/Makefile b/mcs/class/System.Drawing/Makefile index 9f2cae0161..61478a9edb 100644 --- a/mcs/class/System.Drawing/Makefile +++ b/mcs/class/System.Drawing/Makefile @@ -26,11 +26,8 @@ endif TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -define:TEST -resource:Test/resources/indexed.png,indexed.png \ -nowarn:0618 -nowarn:219 -nowarn:169 -XTEST_LIB_REFS = System System.Core Facades/System.Threading.Tasks - -include ../../build/library.make - -EXTRA_DISTFILES = Test/resources/indexed.png \ +TEST_RESOURCE_FILES = \ + Test/resources/indexed.png \ Test/System.Drawing/bitmaps/1bit.png \ Test/System.Drawing/bitmaps/81674-2bpp.png \ Test/System.Drawing/bitmaps/4bit.png \ @@ -48,6 +45,7 @@ EXTRA_DISTFILES = Test/resources/indexed.png \ Test/System.Drawing/bitmaps/nature24bits.jpg \ Test/System.Drawing/bitmaps/nature-greyscale.jpg \ Test/System.Drawing/bitmaps/smiley.ico \ + Test/System.Drawing/bitmaps/only256.ico \ Test/System.Drawing/bitmaps/VisualPng1.ico \ Test/System.Drawing/bitmaps/VisualPng.ico \ Test/System.Drawing/bitmaps/16x16x16.ico \ @@ -61,7 +59,16 @@ EXTRA_DISTFILES = Test/resources/indexed.png \ Test/System.Drawing/bitmaps/415581.ico \ Test/System.Drawing/bitmaps/non-inverted.bmp \ Test/System.Drawing/bitmaps/milkmateya01.emf \ - Test/System.Drawing/bitmaps/telescope_01.wmf \ + Test/System.Drawing/bitmaps/telescope_01.wmf + +TEST_MCS_FLAGS += $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) + +XTEST_LIB_REFS = System System.Core Facades/System.Threading.Tasks + +include ../../build/library.make + +EXTRA_DISTFILES = \ + $(TEST_RESOURCE_FILES) \ Assembly/Application.ico \ Assembly/Asterisk.ico \ Assembly/Error.ico \ diff --git a/mcs/class/System.Drawing/System.Drawing_test.dll.sources b/mcs/class/System.Drawing/System.Drawing_test.dll.sources index aa4ba34fd1..fceb8af156 100644 --- a/mcs/class/System.Drawing/System.Drawing_test.dll.sources +++ b/mcs/class/System.Drawing/System.Drawing_test.dll.sources @@ -1,4 +1,5 @@ ../../test-helpers/NunitHelpers.cs +../../test-helpers/TestResourceHelper.cs ../../../build/common/Locale.cs ../System.Drawing/gdipEnums.cs diff --git a/mcs/class/System.Drawing/Test/System.Drawing.Imaging/GifCodecTest.cs b/mcs/class/System.Drawing/Test/System.Drawing.Imaging/GifCodecTest.cs index c259672451..c88f6d0c56 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing.Imaging/GifCodecTest.cs +++ b/mcs/class/System.Drawing/Test/System.Drawing.Imaging/GifCodecTest.cs @@ -35,6 +35,7 @@ using System.Security.Permissions; using System.Text; using NUnit.Framework; +using MonoTests.Helpers; namespace MonoTests.System.Drawing.Imaging { [TestFixture] @@ -59,17 +60,6 @@ namespace MonoTests.System.Drawing.Imaging { return s; } - /* Get the input directory depending on the runtime*/ - internal string getInFile (string file) - { - string sRslt = Path.GetFullPath ("../System.Drawing/" + file); - - if (!File.Exists (sRslt)) - sRslt = "Test/System.Drawing/" + file; - - return sRslt; - } - /* Checks bitmap features on a know 1bbp bitmap */ /* Checks bitmap features on a know 1bbp bitmap */ private void Bitmap8bitsFeatures (string filename) @@ -95,13 +85,13 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap8bitsFeatures_Gif89 () { - Bitmap8bitsFeatures (getInFile ("bitmaps/nature24bits.gif")); + Bitmap8bitsFeatures (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/nature24bits.gif")); } [Test] public void Bitmap8bitsFeatures_Gif87 () { - Bitmap8bitsFeatures (getInFile ("bitmaps/nature24bits87.gif")); + Bitmap8bitsFeatures (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/nature24bits87.gif")); } private void Bitmap8bitsPixels (string filename) @@ -137,19 +127,19 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap8bitsPixels_Gif89 () { - Bitmap8bitsPixels (getInFile ("bitmaps/nature24bits.gif")); + Bitmap8bitsPixels (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/nature24bits.gif")); } [Test] public void Bitmap8bitsPixels_Gif87 () { - Bitmap8bitsPixels (getInFile ("bitmaps/nature24bits87.gif")); + Bitmap8bitsPixels (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/nature24bits87.gif")); } [Test] public void Bitmap8bitsData () { - string sInFile = getInFile ("bitmaps/nature24bits.gif"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/nature24bits.gif"); using (Bitmap bmp = new Bitmap (sInFile)) { BitmapData data = bmp.LockBits (new Rectangle (0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); try { @@ -212,7 +202,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Interlaced () { - string sInFile = getInFile ("bitmaps/81773-interlaced.gif"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/81773-interlaced.gif"); using (Bitmap bmp = new Bitmap (sInFile)) { for (int i = 0; i < 255; i++) { Color c = bmp.GetPixel (0, i); diff --git a/mcs/class/System.Drawing/Test/System.Drawing.Imaging/IconCodecTest.cs.REMOVED.git-id b/mcs/class/System.Drawing/Test/System.Drawing.Imaging/IconCodecTest.cs.REMOVED.git-id index 27f1f5a457..1c72ad2711 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing.Imaging/IconCodecTest.cs.REMOVED.git-id +++ b/mcs/class/System.Drawing/Test/System.Drawing.Imaging/IconCodecTest.cs.REMOVED.git-id @@ -1 +1 @@ -31c8341496836d547566eaa10c9ed628d5763137 \ No newline at end of file +3d0ecd17dde259c819533beea93ec1983a69f31f \ No newline at end of file diff --git a/mcs/class/System.Drawing/Test/System.Drawing.Imaging/MetafileTest.cs b/mcs/class/System.Drawing/Test/System.Drawing.Imaging/MetafileTest.cs index 957a93d093..b35063f002 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing.Imaging/MetafileTest.cs +++ b/mcs/class/System.Drawing/Test/System.Drawing.Imaging/MetafileTest.cs @@ -35,25 +35,16 @@ using System.Runtime.InteropServices; using System.Security.Permissions; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Drawing.Imaging { [TestFixture] public class MetafileTest { - public const string Bitmap = "bitmaps/non-inverted.bmp"; - public const string WmfPlaceable = "bitmaps/telescope_01.wmf"; - public const string Emf = "bitmaps/milkmateya01.emf"; - - // Get the input directory depending on the runtime - static public string getInFile (string file) - { - string sRslt = Path.GetFullPath ("../System.Drawing/" + file); - - if (!File.Exists (sRslt)) - sRslt = "Test/System.Drawing/" + file; - - return sRslt; - } + public static string Bitmap = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/non-inverted.bmp"); + public static string WmfPlaceable = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/telescope_01.wmf"); + public static string Emf = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/milkmateya01.emf"); [Test] public void Metafile_Stream_Null () @@ -76,14 +67,14 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Metafile_String_FileDoesNotExists () { - string filename = getInFile ("telescope_02.wmf"); + string filename = "non_existing.wmf"; Assert.Throws (() => new Metafile (filename)); } [Test] public void Metafile_String () { - string filename = getInFile (WmfPlaceable); + string filename = WmfPlaceable; Metafile mf = new Metafile (filename); Metafile clone = (Metafile) mf.Clone (); } @@ -91,7 +82,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void GetMetafileHeader_Bitmap () { - Assert.Throws (() => new Metafile (getInFile (Bitmap))); + Assert.Throws (() => new Metafile (Bitmap)); } static public void Check_MetaHeader_WmfPlaceable (MetaHeader mh) @@ -138,7 +129,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void GetMetafileHeader_WmfPlaceable () { - using (Metafile mf = new Metafile (getInFile (WmfPlaceable))) { + using (Metafile mf = new Metafile (WmfPlaceable)) { MetafileHeader header1 = mf.GetMetafileHeader (); Check_MetafileHeader_WmfPlaceable (header1); @@ -150,7 +141,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void GetMetafileHeader_FromFile_WmfPlaceable () { - using (Metafile mf = new Metafile (getInFile (WmfPlaceable))) { + using (Metafile mf = new Metafile (WmfPlaceable)) { MetafileHeader header1 = mf.GetMetafileHeader (); Check_MetafileHeader_WmfPlaceable (header1); @@ -165,7 +156,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void GetMetafileHeader_FromFileStream_WmfPlaceable () { - using (FileStream fs = File.OpenRead (getInFile (WmfPlaceable))) { + using (FileStream fs = File.OpenRead (WmfPlaceable)) { using (Metafile mf = new Metafile (fs)) { MetafileHeader header1 = mf.GetMetafileHeader (); Check_MetafileHeader_WmfPlaceable (header1); @@ -183,7 +174,7 @@ namespace MonoTests.System.Drawing.Imaging { public void GetMetafileHeader_FromMemoryStream_WmfPlaceable () { MemoryStream ms; - string filename = getInFile (WmfPlaceable); + string filename = WmfPlaceable; using (FileStream fs = File.OpenRead (filename)) { byte[] data = new byte[fs.Length]; fs.Read (data, 0, data.Length); @@ -243,7 +234,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void GetMetafileHeader_FromFile_Emf () { - using (Metafile mf = new Metafile (getInFile (Emf))) { + using (Metafile mf = new Metafile (Emf)) { MetafileHeader header1 = mf.GetMetafileHeader (); Check_MetafileHeader_Emf (header1); } @@ -252,7 +243,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void GetMetafileHeader_FromFileStream_Emf () { - using (FileStream fs = File.OpenRead (getInFile (Emf))) { + using (FileStream fs = File.OpenRead (Emf)) { using (Metafile mf = new Metafile (fs)) { MetafileHeader header1 = mf.GetMetafileHeader (); Check_MetafileHeader_Emf (header1); @@ -264,7 +255,7 @@ namespace MonoTests.System.Drawing.Imaging { public void GetMetafileHeader_FromMemoryStream_Emf () { MemoryStream ms; - string filename = getInFile (Emf); + string filename = Emf; using (FileStream fs = File.OpenRead (filename)) { byte[] data = new byte[fs.Length]; fs.Read (data, 0, data.Length); @@ -286,7 +277,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Static_GetMetafileHeader_Stream () { - string filename = getInFile (WmfPlaceable); + string filename = WmfPlaceable; using (FileStream fs = File.OpenRead (filename)) { MetafileHeader header = Metafile.GetMetafileHeader (fs); Check_MetafileHeader_WmfPlaceable (header); @@ -302,7 +293,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Static_GetMetafileHeader_Filename () { - string filename = getInFile (WmfPlaceable); + string filename = WmfPlaceable; MetafileHeader header = Metafile.GetMetafileHeader (filename); Check_MetafileHeader_WmfPlaceable (header); } @@ -332,7 +323,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Static_GetMetafileHeader_IntPtr () { - string filename = MetafileTest.getInFile (MetafileTest.WmfPlaceable); + string filename = MetafileTest.WmfPlaceable; using (Metafile mf = new Metafile (filename)) { IntPtr hemf = mf.GetHenhmetafile (); diff --git a/mcs/class/System.Drawing/Test/System.Drawing.Imaging/PngCodecTest.cs b/mcs/class/System.Drawing/Test/System.Drawing.Imaging/PngCodecTest.cs index c9c30962b3..4508c18a86 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing.Imaging/PngCodecTest.cs +++ b/mcs/class/System.Drawing/Test/System.Drawing.Imaging/PngCodecTest.cs @@ -35,6 +35,8 @@ using System.Security.Permissions; using System.Text; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Drawing.Imaging { [TestFixture] @@ -59,17 +61,6 @@ namespace MonoTests.System.Drawing.Imaging { return s; } - /* Get the input directory depending on the runtime*/ - internal string getInFile (string file) - { - string sRslt = Path.GetFullPath ("../System.Drawing/" + file); - - if (!File.Exists (sRslt)) - sRslt = "Test/System.Drawing/" + file; - - return sRslt; - } - private bool IsArm64Process () { if (Environment.OSVersion.Platform != PlatformID.Unix || !Environment.Is64BitProcess) @@ -95,7 +86,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap1bitFeatures () { - string sInFile = getInFile ("bitmaps/1bit.png"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/1bit.png"); using (Bitmap bmp = new Bitmap (sInFile)) { GraphicsUnit unit = GraphicsUnit.World; RectangleF rect = bmp.GetBounds (ref unit); @@ -123,7 +114,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap1bitPixels () { - string sInFile = getInFile ("bitmaps/1bit.png"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/1bit.png"); using (Bitmap bmp = new Bitmap (sInFile)) { #if false for (int x = 0; x < bmp.Width; x += 32) { @@ -205,7 +196,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap1bitData () { - string sInFile = getInFile ("bitmaps/1bit.png"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/1bit.png"); using (Bitmap bmp = new Bitmap (sInFile)) { BitmapData data = bmp.LockBits (new Rectangle (0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); try { @@ -314,7 +305,7 @@ namespace MonoTests.System.Drawing.Imaging { if (IsArm64Process ()) Assert.Ignore ("https://bugzilla.xamarin.com/show_bug.cgi?id=41171"); - string sInFile = getInFile ("bitmaps/81674-2bpp.png"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/81674-2bpp.png"); using (Bitmap bmp = new Bitmap (sInFile)) { GraphicsUnit unit = GraphicsUnit.World; RectangleF rect = bmp.GetBounds (ref unit); @@ -346,7 +337,7 @@ namespace MonoTests.System.Drawing.Imaging { if (IsArm64Process ()) Assert.Ignore ("https://bugzilla.xamarin.com/show_bug.cgi?id=41171"); - string sInFile = getInFile ("bitmaps/81674-2bpp.png"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/81674-2bpp.png"); using (Bitmap bmp = new Bitmap (sInFile)) { #if false for (int x = 0; x < bmp.Width; x += 32) { @@ -382,7 +373,7 @@ namespace MonoTests.System.Drawing.Imaging { if (IsArm64Process ()) Assert.Ignore ("https://bugzilla.xamarin.com/show_bug.cgi?id=41171"); - string sInFile = getInFile ("bitmaps/81674-2bpp.png"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/81674-2bpp.png"); using (Bitmap bmp = new Bitmap (sInFile)) { BitmapData data = bmp.LockBits (new Rectangle (0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); try { @@ -443,7 +434,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap4bitFeatures () { - string sInFile = getInFile ("bitmaps/4bit.png"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/4bit.png"); using (Bitmap bmp = new Bitmap (sInFile)) { GraphicsUnit unit = GraphicsUnit.World; RectangleF rect = bmp.GetBounds (ref unit); @@ -485,7 +476,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap4bitPixels () { - string sInFile = getInFile ("bitmaps/4bit.png"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/4bit.png"); using (Bitmap bmp = new Bitmap (sInFile)) { #if false for (int x = 0; x < bmp.Width; x += 32) { @@ -568,7 +559,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap4bitData () { - string sInFile = getInFile ("bitmaps/4bit.png"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/4bit.png"); using (Bitmap bmp = new Bitmap (sInFile)) { BitmapData data = bmp.LockBits (new Rectangle (0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); try { diff --git a/mcs/class/System.Drawing/Test/System.Drawing.Imaging/TestBmpCodec.cs b/mcs/class/System.Drawing/Test/System.Drawing.Imaging/TestBmpCodec.cs index c39f30d39a..1bd5de1891 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing.Imaging/TestBmpCodec.cs +++ b/mcs/class/System.Drawing/Test/System.Drawing.Imaging/TestBmpCodec.cs @@ -37,6 +37,8 @@ using System.Security.Cryptography; using System.Security.Permissions; using System.Text; +using MonoTests.Helpers; + namespace MonoTests.System.Drawing.Imaging { [TestFixture] @@ -61,22 +63,11 @@ namespace MonoTests.System.Drawing.Imaging { return s; } - /* Get the input directory depending on the runtime*/ - internal string getInFile(string file) - { - string sRslt = Path.GetFullPath ("../System.Drawing/" + file); - - if (!File.Exists (sRslt)) - sRslt = "Test/System.Drawing/" + file; - - return sRslt; - } - /* Checks bitmap features on a know 1bbp bitmap */ [Test] public void Bitmap1bitFeatures () { - string sInFile = getInFile ("bitmaps/almogaver1bit.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver1bit.bmp"); using (Bitmap bmp = new Bitmap (sInFile)) { GraphicsUnit unit = GraphicsUnit.World; RectangleF rect = bmp.GetBounds (ref unit); @@ -99,7 +90,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap1bitPixels () { - string sInFile = getInFile ("bitmaps/almogaver1bit.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver1bit.bmp"); using (Bitmap bmp = new Bitmap (sInFile)) { #if false for (int x = 0; x < bmp.Width; x += 32) { @@ -152,7 +143,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap8bitFeatures () { - string sInFile = getInFile ("bitmaps/almogaver8bits.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver8bits.bmp"); using (Bitmap bmp = new Bitmap (sInFile)) { GraphicsUnit unit = GraphicsUnit.World; RectangleF rect = bmp.GetBounds (ref unit); @@ -174,7 +165,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap8bitPixels () { - string sInFile = getInFile ("bitmaps/almogaver8bits.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver8bits.bmp"); using (Bitmap bmp = new Bitmap (sInFile)) { #if false for (int x = 0; x < bmp.Width; x += 32) { @@ -228,7 +219,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap24bitFeatures() { - string sInFile = getInFile ("bitmaps/almogaver24bits.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver24bits.bmp"); using (Bitmap bmp = new Bitmap (sInFile)) { GraphicsUnit unit = GraphicsUnit.World; RectangleF rect = bmp.GetBounds (ref unit); @@ -250,7 +241,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap24bitPixels () { - string sInFile = getInFile ("bitmaps/almogaver24bits.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver24bits.bmp"); using (Bitmap bmp = new Bitmap (sInFile)) { #if false for (int x = 0; x < bmp.Width; x += 32) { @@ -301,7 +292,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap24bitData () { - string sInFile = getInFile ("bitmaps/almogaver24bits.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver24bits.bmp"); using (Bitmap bmp = new Bitmap (sInFile)) { Assert.AreEqual (-3355456, bmp.GetPixel (163, 1).ToArgb (), "163,1"); BitmapData data = bmp.LockBits (new Rectangle (0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); @@ -428,7 +419,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap32bitFeatures () { - string sInFile = getInFile ("bitmaps/almogaver32bits.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver32bits.bmp"); using (Bitmap bmp = new Bitmap (sInFile)) { GraphicsUnit unit = GraphicsUnit.World; RectangleF rect = bmp.GetBounds (ref unit); @@ -449,7 +440,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap32bitPixels () { - string sInFile = getInFile ("bitmaps/almogaver32bits.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver32bits.bmp"); using (Bitmap bmp = new Bitmap (sInFile)) { Assert.AreEqual (PixelFormat.Format32bppRgb, bmp.PixelFormat, "PixelFormat"); #if false @@ -584,7 +575,7 @@ namespace MonoTests.System.Drawing.Imaging { public void NonInvertedBitmap () { // regression check against http://bugzilla.ximian.com/show_bug.cgi?id=80751 - string sInFile = getInFile ("bitmaps/non-inverted.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/non-inverted.bmp"); using (Bitmap bmp = new Bitmap (sInFile)) { GraphicsUnit unit = GraphicsUnit.World; RectangleF rect = bmp.GetBounds (ref unit); diff --git a/mcs/class/System.Drawing/Test/System.Drawing.Imaging/TestJpegCodec.cs b/mcs/class/System.Drawing/Test/System.Drawing.Imaging/TestJpegCodec.cs index 9ec46e2968..d3d5878771 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing.Imaging/TestJpegCodec.cs +++ b/mcs/class/System.Drawing/Test/System.Drawing.Imaging/TestJpegCodec.cs @@ -35,6 +35,8 @@ using NUnit.Framework; using System.IO; using System.Security.Permissions; +using MonoTests.Helpers; + namespace MonoTests.System.Drawing.Imaging { [TestFixture] @@ -59,21 +61,10 @@ namespace MonoTests.System.Drawing.Imaging { return s; } - /* Get the input directory depending on the runtime*/ - internal string getInFile (string file) - { - string sRslt = Path.GetFullPath ("../System.Drawing/" + file); - - if (!File.Exists (sRslt)) - sRslt = "Test/System.Drawing/" + file; - - return sRslt; - } - [Test] public void Bitmap8bbpIndexedGreyscaleFeatures () { - string sInFile = getInFile ("bitmaps/nature-greyscale.jpg"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/nature-greyscale.jpg"); using (Bitmap bmp = new Bitmap (sInFile)) { GraphicsUnit unit = GraphicsUnit.World; RectangleF rect = bmp.GetBounds (ref unit); @@ -112,7 +103,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap8bbpIndexedGreyscalePixels () { - string sInFile = getInFile ("bitmaps/nature-greyscale.jpg"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/nature-greyscale.jpg"); using (Bitmap bmp = new Bitmap (sInFile)) { #if false for (int x = 0; x < bmp.Width; x += 32) { @@ -144,7 +135,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap8bbpIndexedGreyscaleData () { - string sInFile = getInFile ("bitmaps/nature-greyscale.jpg"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/nature-greyscale.jpg"); using (Bitmap bmp = new Bitmap (sInFile)) { BitmapData data = bmp.LockBits (new Rectangle (0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); try { @@ -207,7 +198,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap24bitFeatures () { - string sInFile = getInFile ("bitmaps/nature24bits.jpg"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/nature24bits.jpg"); using (Bitmap bmp = new Bitmap (sInFile)) { GraphicsUnit unit = GraphicsUnit.World; RectangleF rect = bmp.GetBounds (ref unit); @@ -238,7 +229,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap24bitPixels () { - string sInFile = getInFile ("bitmaps/nature24bits.jpg"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/nature24bits.jpg"); using (Bitmap bmp = new Bitmap (sInFile)) { #if false for (int x = 0; x < bmp.Width; x += 32) { @@ -270,7 +261,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap24bitData () { - string sInFile = getInFile ("bitmaps/almogaver24bits.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver24bits.bmp"); using (Bitmap bmp = new Bitmap (sInFile)) { BitmapData data = bmp.LockBits (new Rectangle (0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); try { diff --git a/mcs/class/System.Drawing/Test/System.Drawing.Imaging/TiffCodecTest.cs b/mcs/class/System.Drawing/Test/System.Drawing.Imaging/TiffCodecTest.cs index 39539a4635..1bd8a516b5 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing.Imaging/TiffCodecTest.cs +++ b/mcs/class/System.Drawing/Test/System.Drawing.Imaging/TiffCodecTest.cs @@ -2,7 +2,7 @@ // TIFF Codec class testing unit // // Authors: -// Jordi Mas i Hernndez (jordi@ximian.com) +// Jordi Mas i Hern�ndez (jordi@ximian.com) // Sebastien Pouliot // // Copyright (C) 2006, 2007 Novell, Inc (http://www.novell.com) @@ -35,6 +35,8 @@ using System.Security.Permissions; using System.Text; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Drawing.Imaging { [TestFixture] @@ -65,22 +67,11 @@ namespace MonoTests.System.Drawing.Imaging { return s; } - /* Get the input directory depending on the runtime*/ - internal string getInFile (string file) - { - string sRslt = Path.GetFullPath ("../System.Drawing/" + file); - - if (!File.Exists (sRslt)) - sRslt = "Test/System.Drawing/" + file; - - return sRslt; - } - /* Checks bitmap features on a know 32bbp bitmap */ [Test] public void Bitmap32bitsFeatures () { - string sInFile = getInFile ("bitmaps/almogaver32bits.tif"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver32bits.tif"); using (Bitmap bmp = new Bitmap (sInFile)) { GraphicsUnit unit = GraphicsUnit.World; RectangleF rect = bmp.GetBounds (ref unit); @@ -102,7 +93,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap32bitsPixels () { - string sInFile = getInFile ("bitmaps/almogaver32bits.tif"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver32bits.tif"); using (Bitmap bmp = new Bitmap (sInFile)) { #if false for (int x = 0; x < bmp.Width; x += 32) { @@ -154,7 +145,7 @@ namespace MonoTests.System.Drawing.Imaging { [Test] public void Bitmap32bitsData () { - string sInFile = getInFile ("bitmaps/almogaver32bits.tif"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver32bits.tif"); using (Bitmap bmp = new Bitmap (sInFile)) { BitmapData data = bmp.LockBits (new Rectangle (0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); try { diff --git a/mcs/class/System.Drawing/Test/System.Drawing/GDIPlusTest.cs b/mcs/class/System.Drawing/Test/System.Drawing/GDIPlusTest.cs index 9d3ea165f7..620a34790e 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing/GDIPlusTest.cs +++ b/mcs/class/System.Drawing/Test/System.Drawing/GDIPlusTest.cs @@ -35,6 +35,8 @@ using System.IO; using System.Runtime.InteropServices; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Drawing { [TestFixture] @@ -841,7 +843,7 @@ namespace MonoTests.System.Drawing { [Test] public void Icon () { - string filename = TestBitmap.getInFile ("bitmaps/64x64x256.ico"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/64x64x256.ico"); IntPtr bitmap; Assert.AreEqual (Status.Ok, GDIPlus.GdipCreateBitmapFromFile (filename, out bitmap), "GdipCreateBitmapFromFile"); try { @@ -884,7 +886,7 @@ namespace MonoTests.System.Drawing { public void FromFile_IndexedBitmap () { // despite it's name it's a 4bpp indexed bitmap - string filename = TestBitmap.getInFile ("bitmaps/almogaver1bit.bmp"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver1bit.bmp"); IntPtr graphics; IntPtr image; @@ -1449,20 +1451,9 @@ namespace MonoTests.System.Drawing { Assert.AreEqual (Status.Ok, GDIPlus.GdipDisposeImage (image), "GdipDisposeImage"); } - // Get the input directory depending on the runtime - internal string getInFile (string file) - { - string sRslt = Path.GetFullPath ("../System.Drawing/" + file); - - if (!File.Exists (sRslt)) - sRslt = "Test/System.Drawing/" + file; - - return sRslt; - } - private void CheckMetafileHeader (MetafileHeader header) { - MetafileHeader mh1 = new Metafile (getInFile ("bitmaps/telescope_01.wmf")).GetMetafileHeader (); + MetafileHeader mh1 = new Metafile (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/telescope_01.wmf")).GetMetafileHeader (); // compare MetafileHeader Assert.AreEqual (mh1.Bounds.X, header.Bounds.X, "Bounds.X"); Assert.AreEqual (mh1.Bounds.Y, header.Bounds.Y, "Bounds.Y"); @@ -1491,7 +1482,7 @@ namespace MonoTests.System.Drawing { [Test] public void Metafile () { - string filename = getInFile ("bitmaps/telescope_01.wmf"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/telescope_01.wmf"); IntPtr metafile = IntPtr.Zero; Assert.AreEqual (Status.InvalidParameter, GDIPlus.GdipCreateMetafileFromFile (null, out metafile), "GdipCreateMetafileFromFile(null)"); @@ -1514,7 +1505,7 @@ namespace MonoTests.System.Drawing { // Assert.AreEqual (Status.InvalidParameter, GDIPlus.GdipGetMetafileHeaderFromMetafile (metafile, IntPtr.Zero), "GdipGetMetafileHeaderFromMetafile(metafile,null)"); Assert.AreEqual (Status.Ok, GDIPlus.GdipGetMetafileHeaderFromMetafile (metafile, header), "GdipGetMetafileHeaderFromMetafile(metafile,header)"); - MetafileHeader mh2 = new Metafile (getInFile ("bitmaps/telescope_01.wmf")).GetMetafileHeader (); + MetafileHeader mh2 = new Metafile (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/telescope_01.wmf")).GetMetafileHeader (); Marshal.PtrToStructure (header, mh2); CheckMetafileHeader (mh2); } @@ -1528,7 +1519,7 @@ namespace MonoTests.System.Drawing { [Test] public void Metafile_GetMetafileHeaderFromFile () { - string filename = getInFile ("bitmaps/telescope_01.wmf"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/telescope_01.wmf"); int size = Marshal.SizeOf (typeof (MetafileHeader)); IntPtr ptr = Marshal.AllocHGlobal (size); @@ -1539,7 +1530,7 @@ namespace MonoTests.System.Drawing { // Assert.AreEqual (Status.InvalidParameter, GDIPlus.GdipGetMetafileHeaderFromFile (filename, IntPtr.Zero), "GdipGetMetafileHeaderFromFile(file,null)"); Assert.AreEqual (Status.Ok, GDIPlus.GdipGetMetafileHeaderFromFile (filename, ptr), "GdipGetMetafileHeaderFromFile(file,ptr)"); - MetafileHeader header = new Metafile (getInFile ("bitmaps/telescope_01.wmf")).GetMetafileHeader (); + MetafileHeader header = new Metafile (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/telescope_01.wmf")).GetMetafileHeader (); Marshal.PtrToStructure (ptr, header); CheckMetafileHeader (header); } @@ -1551,7 +1542,7 @@ namespace MonoTests.System.Drawing { [Test] public void Metafile_Hemf () { - string filename = getInFile ("bitmaps/telescope_01.wmf"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/telescope_01.wmf"); IntPtr metafile = IntPtr.Zero; Assert.AreEqual (Status.Ok, GDIPlus.GdipCreateMetafileFromFile (filename, out metafile), "GdipCreateMetafileFromFile"); @@ -1688,7 +1679,7 @@ namespace MonoTests.System.Drawing { [Test] public void MetafileAsImage_InImageAPI () { - string filename = getInFile ("bitmaps/telescope_01.wmf"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/telescope_01.wmf"); IntPtr image = IntPtr.Zero; Assert.AreEqual (Status.Ok, GDIPlus.GdipLoadImageFromFile (filename, out image), "GdipLoadImageFromFile"); @@ -1703,7 +1694,7 @@ namespace MonoTests.System.Drawing { [Test] public void Metafile_InImageAPI () { - string filename = getInFile ("bitmaps/telescope_01.wmf"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/telescope_01.wmf"); IntPtr metafile = IntPtr.Zero; Assert.AreEqual (Status.Ok, GDIPlus.GdipCreateMetafileFromFile (filename, out metafile), "GdipCreateMetafileFromFile"); diff --git a/mcs/class/System.Drawing/Test/System.Drawing/TestBitmap.cs b/mcs/class/System.Drawing/Test/System.Drawing/TestBitmap.cs index 2d87ac21cd..fb0bcd2d32 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing/TestBitmap.cs +++ b/mcs/class/System.Drawing/Test/System.Drawing/TestBitmap.cs @@ -45,6 +45,8 @@ using System.Text; using System.Xml.Serialization; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Drawing { [TestFixture] @@ -501,21 +503,12 @@ namespace MonoTests.System.Drawing { return sRslt; } - - /* Get the input directory depending on the runtime*/ - public static string getInFile(string file) - { - string sRslt = Path.GetFullPath ("../System.Drawing/" + file); - if (!File.Exists (sRslt)) - sRslt = "Test/System.Drawing/" + file; - return sRslt; - } // note: this test fails when saving (for the same reason) on Mono and MS.NET //[Test] public void MakeTransparent() { - string sInFile = getInFile("bitmaps/maketransparent.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/maketransparent.bmp"); string sOutFile = getOutSubDir() + "transparent.bmp"; Bitmap bmp = new Bitmap(sInFile); @@ -532,7 +525,7 @@ namespace MonoTests.System.Drawing { [Test] public void Clone() { - string sInFile = getInFile ("bitmaps/almogaver24bits.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver24bits.bmp"); Rectangle rect = new Rectangle(0,0,50,50); Bitmap bmp = new Bitmap(sInFile); @@ -549,7 +542,7 @@ namespace MonoTests.System.Drawing { [Test] public void CloneImage() { - string sInFile = getInFile ("bitmaps/almogaver24bits.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver24bits.bmp"); Bitmap bmp = new Bitmap(sInFile); Bitmap bmpNew = (Bitmap) bmp.Clone (); @@ -563,7 +556,7 @@ namespace MonoTests.System.Drawing { [Test] public void Frames() { - string sInFile = getInFile ("bitmaps/almogaver24bits.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver24bits.bmp"); Bitmap bmp = new Bitmap(sInFile); int cnt = bmp.GetFrameCount(FrameDimension.Page); int active = bmp.SelectActiveFrame (FrameDimension.Page, 0); @@ -670,7 +663,7 @@ namespace MonoTests.System.Drawing { [Test] public void Rotate() { - string sInFile = getInFile ("bitmaps/almogaver24bits.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver24bits.bmp"); Bitmap bmp = new Bitmap(sInFile); Assert.AreEqual ("312958A3C67402E1299413794988A3", RotateBmp (bmp, RotateFlipType.Rotate90FlipNone)); @@ -695,8 +688,8 @@ namespace MonoTests.System.Drawing { Assert.Ignore("This does not work with Microsoft's GDIPLUS.DLL due to off-by-1 errors in their GdipBitmapRotateFlip function."); string[] files = { - getInFile ("bitmaps/1bit.png"), - getInFile ("bitmaps/4bit.png") + TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/1bit.png"), + TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/4bit.png") }; StringBuilder md5s = new StringBuilder(); @@ -1081,7 +1074,7 @@ namespace MonoTests.System.Drawing { public void Serialize_Icon () { // this cause a problem with resgen, see http://bugzilla.ximian.com/show_bug.cgi?id=80565 - string filename = getInFile ("bitmaps/16x16x16.ico"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/16x16x16.ico"); using (Bitmap icon = new Bitmap (filename)) { using (Stream s = Serialize (icon)) { using (Bitmap copy = (Bitmap)Deserialize (s)) { @@ -1113,7 +1106,7 @@ namespace MonoTests.System.Drawing { [Test] public void SoapSerialize_Icon () { - string filename = getInFile ("bitmaps/16x16x16.ico"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/16x16x16.ico"); using (Bitmap icon = new Bitmap (filename)) { using (Stream s = SoapSerialize (icon)) { using (Bitmap copy = (Bitmap) SoapDeserialize (s)) { @@ -1132,7 +1125,7 @@ namespace MonoTests.System.Drawing { [Test] public void SoapSerialize_Bitmap8 () { - string filename = getInFile ("bitmaps/almogaver8bits.bmp"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver8bits.bmp"); using (Bitmap bmp = new Bitmap (filename)) { using (Stream s = SoapSerialize (bmp)) { using (Bitmap copy = (Bitmap) SoapDeserialize (s)) { @@ -1149,7 +1142,7 @@ namespace MonoTests.System.Drawing { [Test] public void SoapSerialize_Bitmap24 () { - string filename = getInFile ("bitmaps/almogaver24bits.bmp"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver24bits.bmp"); using (Bitmap bmp = new Bitmap (filename)) { using (Stream s = SoapSerialize (bmp)) { using (Bitmap copy = (Bitmap) SoapDeserialize (s)) { @@ -1648,7 +1641,7 @@ namespace MonoTests.System.Drawing { { IntPtr hicon; int size; - using (Icon icon = new Icon (TestBitmap.getInFile ("bitmaps/16x16x16.ico"))) { + using (Icon icon = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/16x16x16.ico"))) { size = icon.Width; using (Bitmap bitmap = Bitmap.FromHicon (icon.Handle)) { HiconTest ("Icon.Handle/FromHicon", bitmap, size); @@ -1666,7 +1659,7 @@ namespace MonoTests.System.Drawing { { IntPtr hicon; int size; - using (Icon icon = new Icon (TestBitmap.getInFile ("bitmaps/32x32x16.ico"))) { + using (Icon icon = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/32x32x16.ico"))) { size = icon.Width; using (Bitmap bitmap = Bitmap.FromHicon (icon.Handle)) { HiconTest ("Icon.Handle/FromHicon", bitmap, size); @@ -1683,7 +1676,7 @@ namespace MonoTests.System.Drawing { [Category ("NotWorking")] // libgdiplus has lost track of the original 1bpp state public void Hicon48 () { - using (Icon icon = new Icon (TestBitmap.getInFile ("bitmaps/48x48x1.ico"))) { + using (Icon icon = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/48x48x1.ico"))) { // looks like 1bbp icons aren't welcome as bitmaps ;-) Assert.Throws (() => Bitmap.FromHicon (icon.Handle)); } @@ -1694,7 +1687,7 @@ namespace MonoTests.System.Drawing { { IntPtr hicon; int size; - using (Icon icon = new Icon (TestBitmap.getInFile ("bitmaps/64x64x256.ico"))) { + using (Icon icon = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/64x64x256.ico"))) { size = icon.Width; using (Bitmap bitmap = Bitmap.FromHicon (icon.Handle)) { HiconTest ("Icon.Handle/FromHicon", bitmap, size); @@ -1712,7 +1705,7 @@ namespace MonoTests.System.Drawing { { IntPtr hicon; int size; - using (Icon icon = new Icon (TestBitmap.getInFile ("bitmaps/96x96x256.ico"))) { + using (Icon icon = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/96x96x256.ico"))) { size = icon.Width; using (Bitmap bitmap = Bitmap.FromHicon (icon.Handle)) { HiconTest ("Icon.Handle/FromHicon", bitmap, size); @@ -1729,7 +1722,7 @@ namespace MonoTests.System.Drawing { public void HBitmap () { IntPtr hbitmap; - string sInFile = TestBitmap.getInFile ("bitmaps/almogaver24bits.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver24bits.bmp"); using (Bitmap bitmap = new Bitmap (sInFile)) { Assert.AreEqual (PixelFormat.Format24bppRgb, bitmap.PixelFormat, "Original.PixelFormat"); Assert.AreEqual (0, bitmap.Palette.Entries.Length, "Original.Palette"); @@ -1754,7 +1747,7 @@ namespace MonoTests.System.Drawing { public void CreateMultipleBitmapFromSameHBITMAP () { IntPtr hbitmap; - string sInFile = TestBitmap.getInFile ("bitmaps/almogaver24bits.bmp"); + string sInFile = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver24bits.bmp"); using (Bitmap bitmap = new Bitmap (sInFile)) { Assert.AreEqual (PixelFormat.Format24bppRgb, bitmap.PixelFormat, "Original.PixelFormat"); Assert.AreEqual (0, bitmap.Palette.Entries.Length, "Original.Palette"); diff --git a/mcs/class/System.Drawing/Test/System.Drawing/TestGraphics.cs.REMOVED.git-id b/mcs/class/System.Drawing/Test/System.Drawing/TestGraphics.cs.REMOVED.git-id index a269f7ce7d..21ed3f550a 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing/TestGraphics.cs.REMOVED.git-id +++ b/mcs/class/System.Drawing/Test/System.Drawing/TestGraphics.cs.REMOVED.git-id @@ -1 +1 @@ -479736c63f90ed7a8aa90c833802c23e0eae7c67 \ No newline at end of file +5a3061a8046a7a45e4216423b7c18cd8438e603c \ No newline at end of file diff --git a/mcs/class/System.Drawing/Test/System.Drawing/TestIcon.cs b/mcs/class/System.Drawing/Test/System.Drawing/TestIcon.cs index 5473adbf91..8729b379d2 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing/TestIcon.cs +++ b/mcs/class/System.Drawing/Test/System.Drawing/TestIcon.cs @@ -37,6 +37,8 @@ using System.Reflection; using System.Security.Permissions; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Drawing { [TestFixture] @@ -57,15 +59,15 @@ namespace MonoTests.System.Drawing { [SetUp] public void SetUp () { - String path = TestBitmap.getInFile ("bitmaps/smiley.ico"); + String path = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/smiley.ico"); icon = new Icon (path); fs1 = new FileStream (path, FileMode.Open); - icon16 = new Icon (TestBitmap.getInFile ("bitmaps/16x16x16.ico")); - icon32 = new Icon (TestBitmap.getInFile ("bitmaps/32x32x16.ico")); - icon48 = new Icon (TestBitmap.getInFile ("bitmaps/48x48x1.ico")); - icon64 = new Icon (TestBitmap.getInFile ("bitmaps/64x64x256.ico")); - icon96 = new Icon (TestBitmap.getInFile ("bitmaps/96x96x256.ico")); + icon16 = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/16x16x16.ico")); + icon32 = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/32x32x16.ico")); + icon48 = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/48x48x1.ico")); + icon64 = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/64x64x256.ico")); + icon96 = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/96x96x256.ico")); } [TearDown] @@ -131,7 +133,7 @@ namespace MonoTests.System.Drawing { [Test] public void Constructor_Icon_GetNormalSizeFromIconWith256 () { - string filepath = TestBitmap.getInFile ("bitmaps/323511.ico"); + string filepath = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/323511.ico"); Icon orig = new Icon (filepath); Assert.AreEqual (32,orig.Height); @@ -145,7 +147,7 @@ namespace MonoTests.System.Drawing { [Test] public void Constructor_Icon_DoesntReturn256Passing0 () { - string filepath = TestBitmap.getInFile ("bitmaps/323511.ico"); + string filepath = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/323511.ico"); Icon orig = new Icon (filepath); Assert.AreEqual (32,orig.Height); @@ -159,7 +161,7 @@ namespace MonoTests.System.Drawing { [Test] public void Constructor_Icon_DoesntReturn256Passing1 () { - string filepath = TestBitmap.getInFile ("bitmaps/323511.ico"); + string filepath = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/323511.ico"); Icon orig = new Icon (filepath); Assert.AreEqual (32,orig.Height); @@ -249,7 +251,7 @@ namespace MonoTests.System.Drawing { private void XPIcon (int size) { // note: the Icon(string,Size) or Icon(string,int,int) doesn't exists under 1.x - using (FileStream fs = File.OpenRead (TestBitmap.getInFile ("bitmaps/32bpp.ico"))) { + using (FileStream fs = File.OpenRead (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/32bpp.ico"))) { using (Icon xp = new Icon (fs, size, size)) { Assert.AreEqual (size, xp.Height, "Height"); Assert.AreEqual (size, xp.Width, "Width"); @@ -286,7 +288,7 @@ namespace MonoTests.System.Drawing { [Test] public void SelectFromUnusualSize_Small16 () { - using (FileStream fs = File.OpenRead (TestBitmap.getInFile ("bitmaps/80509.ico"))) { + using (FileStream fs = File.OpenRead (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/80509.ico"))) { using (Icon xp = new Icon (fs, 16, 16)) { Assert.AreEqual (16, xp.Height, "Height"); Assert.AreEqual (10, xp.Width, "Width"); @@ -299,7 +301,7 @@ namespace MonoTests.System.Drawing { [Test] public void SelectFromUnusualSize_Normal32 () { - using (FileStream fs = File.OpenRead (TestBitmap.getInFile ("bitmaps/80509.ico"))) { + using (FileStream fs = File.OpenRead (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/80509.ico"))) { using (Icon xp = new Icon (fs, 32, 32)) { Assert.AreEqual (22, xp.Height, "Height"); Assert.AreEqual (11, xp.Width, "Width"); @@ -354,7 +356,7 @@ namespace MonoTests.System.Drawing { [Test] // bug #410608 public void Save_256 () { - string filepath = TestBitmap.getInFile ("bitmaps/323511.ico"); + string filepath = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/323511.ico"); using (Icon icon = new Icon (filepath)) { // bug #415809 fixed @@ -448,7 +450,7 @@ namespace MonoTests.System.Drawing { [Test] // bug #415581 public void Icon256ToBitmap () { - using (FileStream fs = File.OpenRead (TestBitmap.getInFile ("bitmaps/415581.ico"))) { + using (FileStream fs = File.OpenRead (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/415581.ico"))) { Icon icon = new Icon (fs, 48, 48); using (Bitmap b = icon.ToBitmap ()) { Assert.AreEqual (0, b.Palette.Entries.Length, "#A1"); @@ -460,7 +462,7 @@ namespace MonoTests.System.Drawing { icon.Dispose (); } - using (FileStream fs = File.OpenRead (TestBitmap.getInFile ("bitmaps/415581.ico"))) { + using (FileStream fs = File.OpenRead (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/415581.ico"))) { Icon icon = new Icon (fs, 256, 256); using (Bitmap b = icon.ToBitmap ()) { Assert.AreEqual (0, b.Palette.Entries.Length, "#B1"); @@ -476,7 +478,7 @@ namespace MonoTests.System.Drawing { public void Icon256ToBitmap_Request0 () { // 415581.ico has 2 images, the 256 and 48 - using (FileStream fs = File.OpenRead (TestBitmap.getInFile ("bitmaps/415581.ico"))) { + using (FileStream fs = File.OpenRead (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/415581.ico"))) { Icon icon = new Icon (fs, 0, 0); using (Bitmap b = icon.ToBitmap ()) { Assert.AreEqual (0, b.Palette.Entries.Length, "#B1"); @@ -491,7 +493,7 @@ namespace MonoTests.System.Drawing { [Test] public void Only256InFile () { - using (FileStream fs = File.OpenRead (TestBitmap.getInFile ("bitmaps/only256.ico"))) { + using (FileStream fs = File.OpenRead (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/only256.ico"))) { Assert.Throws (() => new Icon (fs, 0, 0)); } } @@ -537,7 +539,7 @@ namespace MonoTests.System.Drawing { public void HandleRoundtrip () { IntPtr handle; - using (Icon icon = new Icon (TestBitmap.getInFile ("bitmaps/16x16x16.ico"))) { + using (Icon icon = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/16x16x16.ico"))) { Assert.AreEqual (16, icon.Height, "Original.Height"); Assert.AreEqual (16, icon.Width, "Original.Width"); handle = icon.Handle; @@ -561,7 +563,7 @@ namespace MonoTests.System.Drawing { public void CreateMultipleIconFromSameHandle () { IntPtr handle; - using (Icon icon = new Icon (TestBitmap.getInFile ("bitmaps/16x16x16.ico"))) { + using (Icon icon = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/16x16x16.ico"))) { Assert.AreEqual (16, icon.Height, "Original.Height"); Assert.AreEqual (16, icon.Width, "Original.Width"); handle = icon.Handle; @@ -586,7 +588,7 @@ namespace MonoTests.System.Drawing { public void HiconRoundtrip () { IntPtr handle; - using (Icon icon = new Icon (TestBitmap.getInFile ("bitmaps/16x16x16.ico"))) { + using (Icon icon = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/16x16x16.ico"))) { Assert.AreEqual (16, icon.Height, "Original.Height"); Assert.AreEqual (16, icon.Width, "Original.Width"); handle = icon.ToBitmap ().GetHicon (); @@ -604,7 +606,7 @@ namespace MonoTests.System.Drawing { public void CreateMultipleIconFromSameHICON () { IntPtr handle; - using (Icon icon = new Icon (TestBitmap.getInFile ("bitmaps/16x16x16.ico"))) { + using (Icon icon = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/16x16x16.ico"))) { Assert.AreEqual (16, icon.Height, "Original.Height"); Assert.AreEqual (16, icon.Width, "Original.Width"); handle = icon.ToBitmap ().GetHicon (); diff --git a/mcs/class/System.Drawing/Test/System.Drawing/TestIconConverter.cs b/mcs/class/System.Drawing/Test/System.Drawing/TestIconConverter.cs index 5337d64b41..3dcdd0a206 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing/TestIconConverter.cs +++ b/mcs/class/System.Drawing/Test/System.Drawing/TestIconConverter.cs @@ -39,6 +39,8 @@ using System.Globalization; using System.IO; using System.Security.Permissions; +using MonoTests.Helpers; + namespace MonoTests.System.Drawing { [TestFixture] @@ -56,13 +58,13 @@ namespace MonoTests.System.Drawing [SetUp] public void SetUp () { - icon = new Icon (TestBitmap.getInFile ("bitmaps/VisualPng.ico")); + icon = new Icon (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/VisualPng.ico")); iconStr = icon.ToString (); icoConv = new IconConverter(); icoConvFrmTD = (IconConverter) TypeDescriptor.GetConverter (icon); - Stream stream = new FileStream (TestBitmap.getInFile ("bitmaps/VisualPng1.ico"), FileMode.Open); + Stream stream = new FileStream (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/VisualPng1.ico"), FileMode.Open); int length = (int) stream.Length; iconBytes = new byte [length]; diff --git a/mcs/class/System.Drawing/Test/System.Drawing/TestImage.cs b/mcs/class/System.Drawing/Test/System.Drawing/TestImage.cs index c0289aedd2..986093035f 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing/TestImage.cs +++ b/mcs/class/System.Drawing/Test/System.Drawing/TestImage.cs @@ -37,6 +37,8 @@ using System.Security.Permissions; using System.Xml.Serialization; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Drawing{ [TestFixture] @@ -222,7 +224,7 @@ namespace MonoTests.System.Drawing{ [Test] public void FromFile_Metafile_Wmf () { - string filename = TestBitmap.getInFile ("bitmaps/telescope_01.wmf"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/telescope_01.wmf"); using (Image img = Image.FromFile (filename)) { Wmf (img); } @@ -231,7 +233,7 @@ namespace MonoTests.System.Drawing{ [Test] public void FromStream_Metafile_Wmf () { - string filename = TestBitmap.getInFile ("bitmaps/telescope_01.wmf"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/telescope_01.wmf"); using (FileStream fs = File.OpenRead (filename)) { using (Image img = Image.FromStream (fs)) { Wmf (img); @@ -243,7 +245,7 @@ namespace MonoTests.System.Drawing{ [Category ("NotWorking")] // https://bugzilla.novell.com/show_bug.cgi?id=338779 public void FromStream_Metafile_Wmf_NotOrigin () { - string filename = TestBitmap.getInFile ("bitmaps/telescope_01.wmf"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/telescope_01.wmf"); using (FileStream fs = File.OpenRead (filename)) { fs.Position = fs.Length / 2; Assert.Throws (() => Image.FromStream (fs)); @@ -263,7 +265,7 @@ namespace MonoTests.System.Drawing{ [Test] public void FromFile_Metafile_Emf () { - string filename = TestBitmap.getInFile ("bitmaps/milkmateya01.emf"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/milkmateya01.emf"); using (Image img = Image.FromFile (filename)) { Emf (img); } @@ -272,7 +274,7 @@ namespace MonoTests.System.Drawing{ [Test] public void FromStream_Metafile_Emf () { - string filename = TestBitmap.getInFile ("bitmaps/milkmateya01.emf"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/milkmateya01.emf"); using (FileStream fs = File.OpenRead (filename)) { using (Image img = Image.FromStream (fs)) { Emf (img); @@ -284,7 +286,7 @@ namespace MonoTests.System.Drawing{ [Category ("NotWorking")] // https://bugzilla.novell.com/show_bug.cgi?id=338779 public void FromStream_Metafile_Emf_NotOrigin () { - string filename = TestBitmap.getInFile ("bitmaps/milkmateya01.emf"); + string filename = TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/milkmateya01.emf"); using (FileStream fs = File.OpenRead (filename)) { fs.Position = fs.Length / 2; Assert.Throws (() => Image.FromStream (fs)); diff --git a/mcs/class/System.Drawing/Test/System.Drawing/TestImageConverter.cs b/mcs/class/System.Drawing/Test/System.Drawing/TestImageConverter.cs index 0e41e411a4..e78498ef99 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing/TestImageConverter.cs +++ b/mcs/class/System.Drawing/Test/System.Drawing/TestImageConverter.cs @@ -38,6 +38,8 @@ using System.Globalization; using System.IO; using System.Security.Permissions; +using MonoTests.Helpers; + namespace MonoTests.System.Drawing { [TestFixture] @@ -52,13 +54,13 @@ namespace MonoTests.System.Drawing [SetUp] public void SetUp () { - image = Image.FromFile (TestBitmap.getInFile ("bitmaps/almogaver24bits.bmp")); + image = Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver24bits.bmp")); imageStr = image.ToString (); imgConv = new ImageConverter(); imgConvFrmTD = (ImageConverter) TypeDescriptor.GetConverter (image); - Stream stream = new FileStream (TestBitmap.getInFile ("bitmaps/almogaver24bits1.bmp"), FileMode.Open); + Stream stream = new FileStream (TestResourceHelper.GetFullPathOfResource ("Test/System.Drawing/bitmaps/almogaver24bits1.bmp"), FileMode.Open); int length = (int) stream.Length; imageBytes = new byte [length]; diff --git a/mcs/class/System.Drawing/Test/System.Drawing/bitmaps/only256.ico b/mcs/class/System.Drawing/Test/System.Drawing/bitmaps/only256.ico new file mode 100644 index 0000000000..d6fdd64e1c Binary files /dev/null and b/mcs/class/System.Drawing/Test/System.Drawing/bitmaps/only256.ico differ diff --git a/mcs/class/System.Drawing/wasm_System.Drawing_test.dll.exclude.sources b/mcs/class/System.Drawing/wasm_System.Drawing_test.dll.exclude.sources index d3c037e078..63a64dc1a1 100644 --- a/mcs/class/System.Drawing/wasm_System.Drawing_test.dll.exclude.sources +++ b/mcs/class/System.Drawing/wasm_System.Drawing_test.dll.exclude.sources @@ -5,3 +5,4 @@ System.Drawing/TestIcon.cs System.Drawing/TestIconConverter.cs System.Drawing/TestImage.cs System.Drawing/TestImageConverter.cs +System.Drawing/TestBitmap.cs diff --git a/mcs/class/System.IO.Compression.FileSystem/Makefile b/mcs/class/System.IO.Compression.FileSystem/Makefile index c66c602fd9..73fb0a1fae 100644 --- a/mcs/class/System.IO.Compression.FileSystem/Makefile +++ b/mcs/class/System.IO.Compression.FileSystem/Makefile @@ -6,7 +6,14 @@ LIBRARY = System.IO.Compression.FileSystem.dll LIB_REFS = System System.IO.Compression KEYFILE = ../ecma.pub LIB_MCS_FLAGS = -unsafe -nowarn:436 -TEST_MCS_FLAGS = + +TEST_RESOURCE_FILES = \ + Test/resources/foo/foo.txt \ + Test/resources/foo/bar.txt \ + Test/resources/foo/foobar/foo.txt \ + Test/resources/foo/foobar/bar.txt + +TEST_MCS_FLAGS = $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) TEST_LIB_REFS = System System.Core System.IO.Compression LIBRARY_WARN_AS_ERROR = yes diff --git a/mcs/class/System.IO.Compression.FileSystem/System.IO.Compression.FileSystem_test.dll.sources b/mcs/class/System.IO.Compression.FileSystem/System.IO.Compression.FileSystem_test.dll.sources index dc67ea0cf1..8e32b6ea22 100644 --- a/mcs/class/System.IO.Compression.FileSystem/System.IO.Compression.FileSystem_test.dll.sources +++ b/mcs/class/System.IO.Compression.FileSystem/System.IO.Compression.FileSystem_test.dll.sources @@ -1 +1,2 @@ +../../test-helpers/TestResourceHelper.cs System.IO.Compression.FileSystem/ZipTest.cs diff --git a/mcs/class/System.IO.Compression.FileSystem/Test/System.IO.Compression.FileSystem/ZipTest.cs b/mcs/class/System.IO.Compression.FileSystem/Test/System.IO.Compression.FileSystem/ZipTest.cs index ea6c65d4c7..d55d5c9ae4 100644 --- a/mcs/class/System.IO.Compression.FileSystem/Test/System.IO.Compression.FileSystem/ZipTest.cs +++ b/mcs/class/System.IO.Compression.FileSystem/Test/System.IO.Compression.FileSystem/ZipTest.cs @@ -31,6 +31,8 @@ using System.Linq; using System.Security.Cryptography; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.IO.Compression.FileSystem { [TestFixture] @@ -55,7 +57,7 @@ namespace MonoTests.System.IO.Compression.FileSystem if (File.Exists (tmpFile)) File.Delete (tmpFile); - ZipFile.CreateFromDirectory ("foo", tmpFile); + ZipFile.CreateFromDirectory (TestResourceHelper.GetFullPathOfResource ("Test/resources/foo"), tmpFile); Assert.IsTrue(File.Exists(tmpFile)); using (var archive = new ZipArchive (File.Open (tmpFile, FileMode.Open), @@ -75,7 +77,7 @@ namespace MonoTests.System.IO.Compression.FileSystem if (File.Exists (tmpFile)) File.Delete (tmpFile); - ZipFile.CreateFromDirectory ("foo", tmpFile, CompressionLevel.Fastest, + ZipFile.CreateFromDirectory (TestResourceHelper.GetFullPathOfResource ("Test/resources/foo"), tmpFile, CompressionLevel.Fastest, includeBaseDirectory: true); Assert.IsTrue (File.Exists (tmpFile)); @@ -100,7 +102,7 @@ namespace MonoTests.System.IO.Compression.FileSystem if (File.Exists (tmpFile)) File.Delete (tmpFile); - ZipFile.CreateFromDirectory ("foo", tmpFile); + ZipFile.CreateFromDirectory (TestResourceHelper.GetFullPathOfResource ("Test/resources/foo"), tmpFile); ZipFile.ExtractToDirectory (tmpFile, extractDir); Assert.IsTrue(Directory.Exists (extractDir)); @@ -120,7 +122,7 @@ namespace MonoTests.System.IO.Compression.FileSystem if (File.Exists (tmpFile)) File.Delete (tmpFile); - var file = "foo/foo.txt"; + var file = TestResourceHelper.GetFullPathOfResource ("Test/resources/foo/foo.txt"); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Create), ZipArchiveMode.Update)) { diff --git a/mcs/class/System.IO.Compression/Makefile b/mcs/class/System.IO.Compression/Makefile index 74aca83622..8d0c503e80 100644 --- a/mcs/class/System.IO.Compression/Makefile +++ b/mcs/class/System.IO.Compression/Makefile @@ -6,11 +6,14 @@ LIBRARY = System.IO.Compression.dll LIB_REFS = System KEYFILE = ../ecma.pub LIB_MCS_FLAGS = -TEST_MCS_FLAGS = +TEST_RESOURCE_FILES = Test/resources/archive.zip Test/resources/test.nupkg +TEST_MCS_FLAGS = $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) TEST_LIB_REFS = System System.Core LIBRARY_WARN_AS_ERROR = yes RESX_RESOURCE_STRING = \ ../../../external/corefx/src/System.IO.Compression/src/Resources/Strings.resx +EXTRA_DISTFILES = $(TEST_RESOURCE_FILES) + include ../../build/library.make diff --git a/mcs/class/System.IO.Compression/System.IO.Compression_test.dll.sources b/mcs/class/System.IO.Compression/System.IO.Compression_test.dll.sources index 2308abc665..30a862c8e2 100644 --- a/mcs/class/System.IO.Compression/System.IO.Compression_test.dll.sources +++ b/mcs/class/System.IO.Compression/System.IO.Compression_test.dll.sources @@ -1 +1,2 @@ +../../test-helpers/TestResourceHelper.cs System.IO.Compression/ZipTest.cs diff --git a/mcs/class/System.IO.Compression/Test/System.IO.Compression/ZipTest.cs b/mcs/class/System.IO.Compression/Test/System.IO.Compression/ZipTest.cs index 7df282b6bc..8e6c5d3142 100644 --- a/mcs/class/System.IO.Compression/Test/System.IO.Compression/ZipTest.cs +++ b/mcs/class/System.IO.Compression/Test/System.IO.Compression/ZipTest.cs @@ -30,6 +30,8 @@ using System.Linq; using System.Security.Cryptography; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.IO.Compression { [TestFixture] @@ -48,7 +50,7 @@ namespace MonoTests.System.IO.Compression public void ZipGetEntryReadMode() { var tmpFile = Path.GetTempFileName (); - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Read)) { @@ -66,7 +68,7 @@ namespace MonoTests.System.IO.Compression public void ZipGetEntryCreateMode() { var tmpFile = Path.GetTempFileName (); - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Create)) { @@ -86,7 +88,7 @@ namespace MonoTests.System.IO.Compression public void ZipGetEntryUpdateMode() { var tmpFile = Path.GetTempFileName (); - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Read)) { @@ -104,7 +106,7 @@ namespace MonoTests.System.IO.Compression public void ZipGetEntryOpen() { var tmpFile = Path.GetTempFileName (); - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Read)) { @@ -122,7 +124,7 @@ namespace MonoTests.System.IO.Compression { var tmpFile = Path.GetTempFileName (); try { - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Update)) { @@ -149,7 +151,7 @@ namespace MonoTests.System.IO.Compression public void ZipOpenCloseAndReopenEntry() { var tmpFile = Path.GetTempFileName (); - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Update)) { @@ -168,7 +170,7 @@ namespace MonoTests.System.IO.Compression public void ZipGetEntryDeleteReadMode() { var tmpFile = Path.GetTempFileName (); - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Update)) { @@ -192,7 +194,7 @@ namespace MonoTests.System.IO.Compression public void ZipDeleteEntryCheckEntries() { var tmpFile = Path.GetTempFileName (); - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Update)) { @@ -211,7 +213,7 @@ namespace MonoTests.System.IO.Compression public void ZipGetEntryDeleteUpdateMode() { var tmpFile = Path.GetTempFileName (); - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Update)) { @@ -269,7 +271,7 @@ namespace MonoTests.System.IO.Compression public void ZipEnumerateEntriesModifiedTime() { var tmpFile = Path.GetTempFileName (); - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); var date = DateTimeOffset.Now; using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Update)) @@ -295,7 +297,7 @@ namespace MonoTests.System.IO.Compression public void ZipEnumerateArchiveDefaultLastWriteTime() { var tmpFile = Path.GetTempFileName (); - File.Copy("test.nupkg", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/test.nupkg"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Read)) { @@ -309,7 +311,7 @@ namespace MonoTests.System.IO.Compression public void ZipGetArchiveEntryStreamLengthPosition(ZipArchiveMode mode) { var tmpFile = Path.GetTempFileName (); - File.Copy("test.nupkg", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/test.nupkg"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), mode)) { var entry = archive.GetEntry("_rels/.rels"); @@ -349,7 +351,7 @@ namespace MonoTests.System.IO.Compression public void ZipEnumerateEntriesReadMode() { var tmpFile = Path.GetTempFileName (); - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Read)) { @@ -370,7 +372,7 @@ namespace MonoTests.System.IO.Compression public void ZipWriteEntriesUpdateMode() { var tmpFile = Path.GetTempFileName (); - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Update)) { @@ -435,7 +437,7 @@ namespace MonoTests.System.IO.Compression public void ZipWriteEntriesUpdateModeNonZeroPosition() { var tmpFile = Path.GetTempFileName (); - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Update)) { @@ -470,7 +472,7 @@ namespace MonoTests.System.IO.Compression public void ZipEnumerateEntriesUpdateMode() { var tmpFile = Path.GetTempFileName (); - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Read)) { @@ -491,7 +493,7 @@ namespace MonoTests.System.IO.Compression public void ZipEnumerateEntriesCreateMode() { var tmpFile = Path.GetTempFileName (); - File.Copy("archive.zip", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/archive.zip"), tmpFile, overwrite: true); using (var archive = new ZipArchive(File.Open(tmpFile, FileMode.Open), ZipArchiveMode.Create)) { @@ -538,7 +540,7 @@ namespace MonoTests.System.IO.Compression public void ZipReadNonSeekableStream() { var tmpFile = Path.GetTempFileName (); - File.Copy("test.nupkg", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/test.nupkg"), tmpFile, overwrite: true); var stream = new MyFakeStream(tmpFile, FileMode.Open); using (var archive = new ZipArchive (stream, ZipArchiveMode.Read)) { @@ -550,7 +552,7 @@ namespace MonoTests.System.IO.Compression public void ZipWriteNonSeekableStream() { var tmpFile = Path.GetTempFileName (); - File.Copy("test.nupkg", tmpFile, overwrite: true); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/test.nupkg"), tmpFile, overwrite: true); var stream = new MyFakeStream(tmpFile, FileMode.Open ); using ( var archive = new ZipArchive( stream, ZipArchiveMode.Create ) ) { var entry = archive.CreateEntry( "foo" ); diff --git a/mcs/class/System.IO.Compression/Test/resources/archive.zip b/mcs/class/System.IO.Compression/Test/resources/archive.zip new file mode 100644 index 0000000000..91ba947a36 Binary files /dev/null and b/mcs/class/System.IO.Compression/Test/resources/archive.zip differ diff --git a/mcs/class/System.IO.Compression/Test/resources/test.nupkg b/mcs/class/System.IO.Compression/Test/resources/test.nupkg new file mode 100644 index 0000000000..0a7fe0575c Binary files /dev/null and b/mcs/class/System.IO.Compression/Test/resources/test.nupkg differ diff --git a/mcs/class/System.IdentityModel/Makefile b/mcs/class/System.IdentityModel/Makefile index 5d00d28a47..3685c90da4 100644 --- a/mcs/class/System.IdentityModel/Makefile +++ b/mcs/class/System.IdentityModel/Makefile @@ -29,17 +29,19 @@ LIB_REFS += System.Web.ApplicationServices endif endif -TEST_MCS_FLAGS = +TEST_RESOURCE_FILES = \ + Test/Resources/test.cer \ + Test/Resources/test_neg_serial.cer \ + Test/Resources/test.pfx \ + Test/Resources/test2.pfx + +TEST_MCS_FLAGS = $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) TEST_LIB_REFS = System System.Xml System.Security System.Runtime.Serialization ifdef MOBILE_PROFILE NO_TEST = yes endif -EXTRA_DISTFILES = \ - Test/Resources/test.cer \ - Test/Resources/test_neg_serial.cer \ - Test/Resources/test.pfx \ - Test/Resources/test2.pfx +EXTRA_DISTFILES = $(TEST_RESOURCE_FILES) include ../../build/library.make diff --git a/mcs/class/System.IdentityModel/System.IdentityModel_test.dll.sources b/mcs/class/System.IdentityModel/System.IdentityModel_test.dll.sources index 83cf424100..8fa384a8df 100644 --- a/mcs/class/System.IdentityModel/System.IdentityModel_test.dll.sources +++ b/mcs/class/System.IdentityModel/System.IdentityModel_test.dll.sources @@ -1,3 +1,4 @@ +../../test-helpers/TestResourceHelper.cs System.IdentityModel.Claims/ClaimSetTest.cs System.IdentityModel.Claims/ClaimTest.cs System.IdentityModel.Claims/ClaimTypesTest.cs diff --git a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Claims/ClaimTest.cs b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Claims/ClaimTest.cs index f870566f47..4f29670572 100644 --- a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Claims/ClaimTest.cs +++ b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Claims/ClaimTest.cs @@ -34,6 +34,8 @@ using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.IdentityModel.Claims { [TestFixture] @@ -80,7 +82,7 @@ namespace MonoTests.System.IdentityModel.Claims c = Claim.CreateRsaClaim (rsa); AssertClaim ("Rsa", c, ClaimTypes.Rsa, rsa, Rights.PossessProperty); - X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); byte [] chash = cert.GetCertHash (); c = Claim.CreateThumbprintClaim (chash); AssertClaim ("Thumbprint", c, ClaimTypes.Thumbprint, chash, Rights.PossessProperty); diff --git a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Claims/X509CertificateClaimSetTest.cs b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Claims/X509CertificateClaimSetTest.cs index 2dbbb35abb..785d4d29e7 100644 --- a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Claims/X509CertificateClaimSetTest.cs +++ b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Claims/X509CertificateClaimSetTest.cs @@ -35,12 +35,14 @@ using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.IdentityModel.Claims { [TestFixture] public class X509CertificateClaimSetTest { - static X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + static X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); [Test] [Ignore ("not up to date")] // X509Chain diff --git a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Selectors/RsaSecurityTokenAuthenticatorTest.cs b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Selectors/RsaSecurityTokenAuthenticatorTest.cs index 59e9077682..d12d1116a2 100644 --- a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Selectors/RsaSecurityTokenAuthenticatorTest.cs +++ b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Selectors/RsaSecurityTokenAuthenticatorTest.cs @@ -40,6 +40,8 @@ using NUnit.Framework; using Authenticator = System.IdentityModel.Selectors.RsaSecurityTokenAuthenticator; using PolicyCollection = System.Collections.ObjectModel.ReadOnlyCollection; +using MonoTests.Helpers; + namespace MonoTests.System.IdentityModel.Selectors { [TestFixture] @@ -48,7 +50,7 @@ namespace MonoTests.System.IdentityModel.Selectors [Test] public void Validation () { - RSA rsa = (RSA) new X509Certificate2 ("Test/Resources/test.cer").PublicKey.Key; + RSA rsa = (RSA) new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.cer")).PublicKey.Key; Authenticator a = new Authenticator (); PolicyCollection pl = a.ValidateToken (new RsaSecurityToken (rsa)); Assert.AreEqual (1, pl.Count, "#1"); diff --git a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Selectors/SamlSecurityTokenAuthenticatorTest.cs b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Selectors/SamlSecurityTokenAuthenticatorTest.cs index 62007bca67..43dd7a98a8 100644 --- a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Selectors/SamlSecurityTokenAuthenticatorTest.cs +++ b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Selectors/SamlSecurityTokenAuthenticatorTest.cs @@ -37,6 +37,8 @@ using System.Security.Cryptography.X509Certificates; using System.Xml; using NUnit.Framework; +using MonoTests.Helpers; + using MonoTests.System.IdentityModel.Common; using Authenticator = System.IdentityModel.Selectors.SamlSecurityTokenAuthenticator; @@ -101,7 +103,7 @@ namespace MonoTests.System.IdentityModel.Selectors a.Statements.Add (statement); a.Issuer = "my_hero"; - X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); X509AsymmetricSecurityKey key = new X509AsymmetricSecurityKey (cert); a.SigningCredentials = diff --git a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Selectors/X509SecurityTokenAuthenticatorTest.cs b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Selectors/X509SecurityTokenAuthenticatorTest.cs index cd235e9104..2bcd8a3d1b 100644 --- a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Selectors/X509SecurityTokenAuthenticatorTest.cs +++ b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Selectors/X509SecurityTokenAuthenticatorTest.cs @@ -39,6 +39,8 @@ using NUnit.Framework; using Authenticator = System.IdentityModel.Selectors.X509SecurityTokenAuthenticator; using PolicyCollection = System.Collections.ObjectModel.ReadOnlyCollection; +using MonoTests.Helpers; + namespace MonoTests.System.IdentityModel.Selectors { [TestFixture] @@ -54,7 +56,7 @@ namespace MonoTests.System.IdentityModel.Selectors [Test] public void Validation () { - X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.cer"); + X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.cer")); Authenticator a = new Authenticator ( X509CertificateValidator.None); PolicyCollection pl = a.ValidateToken (new X509SecurityToken (cert)); diff --git a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/InMemorySymmetricSecurityKeyTest.cs b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/InMemorySymmetricSecurityKeyTest.cs index 7100bf57c3..750847902b 100644 --- a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/InMemorySymmetricSecurityKeyTest.cs +++ b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/InMemorySymmetricSecurityKeyTest.cs @@ -38,6 +38,8 @@ using NUnit.Framework; using Key = System.IdentityModel.Tokens.InMemorySymmetricSecurityKey; using AES = System.Security.Cryptography.RijndaelManaged; +using MonoTests.Helpers; + namespace MonoTests.System.IdentityModel.Tokens { [TestFixture] @@ -49,7 +51,7 @@ namespace MonoTests.System.IdentityModel.Tokens static InMemorySymmetricSecurityKeyTest () { - cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); // randomly generated with RijndaelManaged // GenerateIV() and GenerateKey(). raw = Convert.FromBase64String ("eX2EeE969RCv/5Lx8OIGLHtJrSD5PzVzO3tTy9JxU58="); diff --git a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509AsymmetricSecurityKeyTest.cs b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509AsymmetricSecurityKeyTest.cs index 07d5cc400e..6d18f31504 100644 --- a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509AsymmetricSecurityKeyTest.cs +++ b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509AsymmetricSecurityKeyTest.cs @@ -35,13 +35,15 @@ using System.Security.Cryptography.Xml; using System.Xml; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.IdentityModel.Selectors { [TestFixture] public class X509AsymmetricSecurityKeyTest { - static readonly X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); - static readonly X509Certificate2 cert2 = new X509Certificate2 ("Test/Resources/test.cer"); + static readonly X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); + static readonly X509Certificate2 cert2 = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.cer")); [Test] public void GetAsymmetricAlgorithm () diff --git a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509IssuerSerialKeyIdentifierClauseTest.cs b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509IssuerSerialKeyIdentifierClauseTest.cs index 087a5b736a..1a5ba6ff74 100644 --- a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509IssuerSerialKeyIdentifierClauseTest.cs +++ b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509IssuerSerialKeyIdentifierClauseTest.cs @@ -34,14 +34,16 @@ using System.Security.Cryptography.X509Certificates; using System.Xml; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.IdentityModel.Selectors { [TestFixture] public class X509IssuerSerialKeyIdentifierClauseTest { - static readonly X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); - static readonly X509Certificate2 cert2 = new X509Certificate2 ("Test/Resources/test2.pfx", "mono"); - static readonly X509Certificate2 cert3 = new X509Certificate2("Test/Resources/test_neg_serial.cer"); + static readonly X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); + static readonly X509Certificate2 cert2 = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test2.pfx"), "mono"); + static readonly X509Certificate2 cert3 = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test_neg_serial.cer")); [Test] public void Properties () diff --git a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509SecurityTokenTest.cs b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509SecurityTokenTest.cs index 562e66ca44..ccb2df503f 100644 --- a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509SecurityTokenTest.cs +++ b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509SecurityTokenTest.cs @@ -33,13 +33,15 @@ using System.Security.Cryptography.X509Certificates; using System.Xml; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.IdentityModel.Selectors { [TestFixture] public class X509SecurityTokenTest { - static readonly X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); - static readonly X509Certificate2 cert2 = new X509Certificate2 ("Test/Resources/test2.pfx", "mono"); + static readonly X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); + static readonly X509Certificate2 cert2 = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test2.pfx"), "mono"); [Test] public void DefaultValues () diff --git a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509ThumbprintKeyIdentifierClauseTest.cs b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509ThumbprintKeyIdentifierClauseTest.cs index 749151a01e..f142b3e620 100644 --- a/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509ThumbprintKeyIdentifierClauseTest.cs +++ b/mcs/class/System.IdentityModel/Test/System.IdentityModel.Tokens/X509ThumbprintKeyIdentifierClauseTest.cs @@ -34,13 +34,15 @@ using System.Security.Cryptography.X509Certificates; using System.Xml; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.IdentityModel.Selectors { [TestFixture] public class X509ThumbprintKeyIdentifierClauseTest { - static readonly X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); - static readonly X509Certificate2 cert2 = new X509Certificate2 ("Test/Resources/test2.pfx", "mono"); + static readonly X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); + static readonly X509Certificate2 cert2 = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test2.pfx"), "mono"); [Test] public void Properties () diff --git a/mcs/class/System.Net.Http/System.Net.Http/HttpClient.cs b/mcs/class/System.Net.Http/System.Net.Http/HttpClient.cs index 3880d418dc..a4cb8ac68f 100644 --- a/mcs/class/System.Net.Http/System.Net.Http/HttpClient.cs +++ b/mcs/class/System.Net.Http/System.Net.Http/HttpClient.cs @@ -44,7 +44,7 @@ namespace System.Net.Http long buffer_size; TimeSpan timeout; -#if !XAMARIN_MODERN +#if !XAMARIN_MODERN && !WASM public HttpClient () : this (new HttpClientHandler (), true) { @@ -115,6 +115,8 @@ namespace System.Net.Http if (disposing && !disposed) { disposed = true; + //We don't use CancelPendingRequests() because we don't want to create new CancellationTokenSource + cts.Cancel (); cts.Dispose (); } diff --git a/mcs/class/System.Net.Http/System.Net.Http/HttpClient.wasm.cs b/mcs/class/System.Net.Http/System.Net.Http/HttpClient.wasm.cs new file mode 100644 index 0000000000..304d9de30c --- /dev/null +++ b/mcs/class/System.Net.Http/System.Net.Http/HttpClient.wasm.cs @@ -0,0 +1,36 @@ +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace System.Net.Http +{ + public partial class HttpClient + { + + private static Func GetHttpMessageHandler; + + public HttpClient() + : this(GetDefaultHandler(), true) + { + } + + static HttpMessageHandler GetDefaultHandler() + { + + if (GetHttpMessageHandler == null) + return GetFallback("No custom HttpClientHandler registered"); + + var handler = GetHttpMessageHandler(); + if (handler == null) + return GetFallback($"Custom HttpMessageHandler is not valid"); + + return handler; + } + + static HttpMessageHandler GetFallback(string message) + { + //Console.WriteLine(message + ". Defaulting to System.Net.Http.HttpClientHandler"); + return new HttpClientHandler(); + } + } +} \ No newline at end of file diff --git a/mcs/class/System.Net.Http/wasm_System.Net.Http.dll.sources b/mcs/class/System.Net.Http/wasm_System.Net.Http.dll.sources new file mode 100644 index 0000000000..0a12cc5b5a --- /dev/null +++ b/mcs/class/System.Net.Http/wasm_System.Net.Http.dll.sources @@ -0,0 +1,2 @@ +#include System.Net.Http.dll.sources +System.Net.Http/HttpClient.wasm.cs \ No newline at end of file diff --git a/mcs/class/System.Numerics/System.Numerics_xtest.dll.sources b/mcs/class/System.Numerics/System.Numerics_xtest.dll.sources index 96be08ccca..1b09a1c795 100644 --- a/mcs/class/System.Numerics/System.Numerics_xtest.dll.sources +++ b/mcs/class/System.Numerics/System.Numerics_xtest.dll.sources @@ -1,7 +1,7 @@ ../../../external/corefx/src/CoreFx.Private.TestUtilities/src/System/AssertExtensions.cs # ../../../external/corefx/src/System.Runtime.Numerics/tests/*.cs -#../../../external/corefx/src/System.Runtime.Numerics/tests/BigInteger/*.cs +../../../external/corefx/src/System.Runtime.Numerics/tests/BigInteger/*.cs ../../../external/corefx/src/Common/src/CoreLib/System/Numerics/ConstantHelper.cs diff --git a/mcs/class/System.Runtime.Serialization/Makefile b/mcs/class/System.Runtime.Serialization/Makefile index 01856392cd..c353ad1dc4 100644 --- a/mcs/class/System.Runtime.Serialization/Makefile +++ b/mcs/class/System.Runtime.Serialization/Makefile @@ -17,9 +17,13 @@ XTEST_LIB_REFS = System System.Core System.Xml System.Xml.Linq Facades/System.Th ifneq ($(PROFILE),monodroid) ifneq ($(PROFILE),monotouch) +ifneq ($(PROFILE),monotouch_tv) +ifneq ($(PROFILE),monotouch_watch) XTEST_LIB_REFS += System.Drawing endif endif +endif +endif ifneq (2.1, $(FRAMEWORK_VERSION)) LIB_REFS += System.Data System.Configuration SMDiagnostics @@ -33,15 +37,27 @@ LIB_MCS_FLAGS += /d:NO_CONFIGURATION endif TEST_RESOURCE_FILES = \ - Test/Resources/WSDL/collections.wsdl \ - Test/Resources/WSDL/custom-collections.wsdl + $(wildcard Test/Resources/FrameworkTypes/*.xml) \ + $(wildcard Test/Resources/Schemas/*.xsd) \ + Test/Resources/WSDL/collections.wsdl \ + Test/Resources/WSDL/custom-collections.wsdl \ + Test/Resources/one.xml -TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) $(TEST_RESOURCE_FILES:%=/resource:%) +# we need to write the test resource args into a response file to avoid +# hitting "argument list too long" errors because of too many files +TEST_RESOURCES_RESPONSE_FILE = $(depsdir)/$(LIBRARY)_test.resources.response + +$(TEST_RESOURCES_RESPONSE_FILE): $(TEST_RESOURCE_FILES) + @echo Creating $@ ... + @echo $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) > $(TEST_RESOURCES_RESPONSE_FILE) + +test-local: $(TEST_RESOURCES_RESPONSE_FILE) + +CLEAN_FILES += $(TEST_RESOURCES_RESPONSE_FILE) + +TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) @$(TEST_RESOURCES_RESPONSE_FILE) TEST_LIB_REFS = System.ServiceModel System.Web.Services -EXTRA_DISTFILES = $(RESOURCE_FILES) $(TEST_RESOURCE_FILES) \ - Test/Resources/FrameworkTypes/* \ - Test/Resources/Schemas/*.xsd \ - Test/System.Runtime.Serialization/one.xml +EXTRA_DISTFILES = $(RESOURCE_FILES) $(TEST_RESOURCE_FILES) include ../../build/library.make diff --git a/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization_test.dll.sources b/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization_test.dll.sources index 547733453e..ce49876201 100644 --- a/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization_test.dll.sources +++ b/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization_test.dll.sources @@ -1,3 +1,4 @@ +../../test-helpers/TestResourceHelper.cs System.Runtime.Serialization.Json/DataContractJsonSerializerTest.cs System.Runtime.Serialization.Json/JsonReaderTest.cs System.Runtime.Serialization.Json/JsonWriterTest.cs diff --git a/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/one.xml b/mcs/class/System.Runtime.Serialization/Test/Resources/one.xml similarity index 100% rename from mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/one.xml rename to mcs/class/System.Runtime.Serialization/Test/Resources/one.xml diff --git a/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XsdDataContractImporterTest.cs b/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XsdDataContractImporterTest.cs index 2e5ebe44d1..7f0d005c46 100644 --- a/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XsdDataContractImporterTest.cs +++ b/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XsdDataContractImporterTest.cs @@ -50,6 +50,8 @@ using NUnit.Framework; using QName = System.Xml.XmlQualifiedName; +using MonoTests.Helpers; + namespace MonoTests.System.Runtime.Serialization { [TestFixture] @@ -61,7 +63,7 @@ namespace MonoTests.System.Runtime.Serialization [SetUp] public void Setup () { - XmlReader xr = XmlTextReader.Create ("Test/System.Runtime.Serialization/one.xml"); + XmlReader xr = XmlTextReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/Resources/one.xml")); metadata = MetadataSet.ReadFrom (xr); NewXmlSchemaSet (); } @@ -374,8 +376,8 @@ namespace MonoTests.System.Runtime.Serialization var ccu = new CodeCompileUnit (); var xdi = new XsdDataContractImporter (ccu); var xss = new XmlSchemaSet (); - xss.Add (null, "Test/Resources/Schemas/schema1.xsd"); - xss.Add (null, "Test/Resources/Schemas/schema2.xsd"); + xss.Add (null, TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/schema1.xsd")); + xss.Add (null, TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/schema2.xsd")); xdi.Import (xss); var sw = new StringWriter (); new CSharpCodeProvider ().GenerateCodeFromCompileUnit (ccu, sw, null); @@ -388,9 +390,9 @@ namespace MonoTests.System.Runtime.Serialization var ccu = new CodeCompileUnit (); var xdi = new XsdDataContractImporter (ccu); var xss = new XmlSchemaSet (); - xss.Add (null, "Test/Resources/Schemas/schema1.xsd"); - xss.Add (null, "Test/Resources/Schemas/schema2.xsd"); - xss.Add (null, "Test/Resources/Schemas/schema3.xsd"); + xss.Add (null, TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/schema1.xsd")); + xss.Add (null, TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/schema2.xsd")); + xss.Add (null, TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/schema3.xsd")); xdi.Import (xss); var sw = new StringWriter (); bool t = false, te = false; @@ -446,52 +448,52 @@ namespace MonoTests.System.Runtime.Serialization [Test] public void ImportTestX0 () { - DoImport ("Test/Resources/Schemas/ns0.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns0.xsd")); } [Test] public void ImportTestX0_2 () { - var ccu = DoImport (true, "Test/Resources/Schemas/ns0.xsd"); + var ccu = DoImport (true, TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns0.xsd")); Assert.IsTrue (GenerateCode (ccu).IndexOf ("class") < 0, "#1"); } [Test] public void ImportTestX1 () { - DoImport ("Test/Resources/Schemas/ns1.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns1.xsd")); } [Test] public void ImportTestX1_2 () { - Assert.AreEqual (GenerateCode (DoImport ("Test/Resources/Schemas/ns1.xsd")), GenerateCode (DoImport (true, "Test/Resources/Schemas/ns1.xsd")), "#1"); + Assert.AreEqual (GenerateCode (DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns1.xsd"))), GenerateCode (DoImport (true, TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns1.xsd"))), "#1"); } [Test] public void ImportTestX2 () { - DoImport ("Test/Resources/Schemas/ns2.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns2.xsd")); } [Test] public void ImportTestX2_2 () { - Assert.AreEqual (GenerateCode (DoImport ("Test/Resources/Schemas/ns2.xsd")), GenerateCode (DoImport (true, "Test/Resources/Schemas/ns2.xsd")), "#1"); + Assert.AreEqual (GenerateCode (DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns2.xsd"))), GenerateCode (DoImport (true, TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns2.xsd"))), "#1"); } [Test] [ExpectedException (typeof (InvalidDataContractException))] public void ImportTestX3 () { - DoImport ("Test/Resources/Schemas/ns3.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns3.xsd")); } [Test] [Category ("NotWorking")] public void ImportTestX3_2 () { - var ccu = DoImport (true, "Test/Resources/Schemas/ns3.xsd"); + var ccu = DoImport (true, TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns3.xsd")); var code = GenerateCode (ccu); Assert.IsTrue (code.IndexOf ("class T2") > 0, "#1"); Assert.IsTrue (code.IndexOf ("IXmlSerializable") > 0, "#2"); @@ -504,208 +506,208 @@ namespace MonoTests.System.Runtime.Serialization [ExpectedException (typeof (InvalidDataContractException))] public void ImportTestX4 () { - DoImport ("Test/Resources/Schemas/ns4.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns4.xsd")); } [Test] [ExpectedException (typeof (InvalidDataContractException))] public void ImportTestX5 () { - DoImport ("Test/Resources/Schemas/ns5.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns5.xsd")); } [Test] public void ImportTestX6 () { - DoImport ("Test/Resources/Schemas/ns6.xsd", - "Test/Resources/Schemas/ns0.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns6.xsd"), + TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns0.xsd")); } [Test] [ExpectedException (typeof (InvalidDataContractException))] public void ImportTestX7 () { - DoImport ("Test/Resources/Schemas/ns7.xsd", - "Test/Resources/Schemas/ns0.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns7.xsd"), + TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns0.xsd")); } [Test] [ExpectedException (typeof (InvalidDataContractException))] public void ImportTestX8 () { - DoImport ("Test/Resources/Schemas/ns8.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns8.xsd")); } [Test] [ExpectedException (typeof (InvalidDataContractException))] public void ImportTestX9 () { - DoImport ("Test/Resources/Schemas/ns9.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns9.xsd")); } [Test] public void ImportTestX10 () { - DoImport ("Test/Resources/Schemas/ns10.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns10.xsd")); } [Test] [ExpectedException (typeof (InvalidDataContractException))] public void ImportTestX11 () { - DoImport ("Test/Resources/Schemas/ns11.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns11.xsd")); } [Test] [ExpectedException (typeof (InvalidDataContractException))] public void ImportTestX12 () { - DoImport ("Test/Resources/Schemas/ns12.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns12.xsd")); } [Test] [ExpectedException (typeof (InvalidDataContractException))] public void ImportTestX13 () { - DoImport ("Test/Resources/Schemas/ns13.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns13.xsd")); } [Test] public void ImportTestX14 () { - DoImport ("Test/Resources/Schemas/ns14.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns14.xsd")); } [Test] [ExpectedException (typeof (InvalidDataContractException))] public void ImportTestX15 () { - DoImport ("Test/Resources/Schemas/ns15.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns15.xsd")); } [Test] public void ImportTestX16 () { - DoImport ("Test/Resources/Schemas/ns16.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns16.xsd")); } [Test] [ExpectedException (typeof (InvalidDataContractException))] public void ImportTestX17 () { - DoImport ("Test/Resources/Schemas/ns17.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns17.xsd")); } [Test] public void ImportTestX18 () { - DoImport ("Test/Resources/Schemas/ns18.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns18.xsd")); } [Test] [ExpectedException (typeof (InvalidDataContractException))] public void ImportTestX19 () { - DoImport ("Test/Resources/Schemas/ns19.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns19.xsd")); } [Test] [ExpectedException (typeof (InvalidDataContractException))] public void ImportTestX20 () { - DoImport ("Test/Resources/Schemas/ns20.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns20.xsd")); } [Test] public void ImportTestX21 () { - DoImport ("Test/Resources/Schemas/ns21.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns21.xsd")); } [Test] public void ImportTestX22 () { - DoImport ("Test/Resources/Schemas/ns22.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns22.xsd")); } [Test] public void ImportTestX23 () { - DoImport ("Test/Resources/Schemas/ns23.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns23.xsd")); } [ExpectedException (typeof (InvalidDataContractException))] [Test] public void ImportTestX24 () { - DoImport ("Test/Resources/Schemas/ns24.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns24.xsd")); } [Test] public void ImportTestX25 () { - DoImport ("Test/Resources/Schemas/ns25.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns25.xsd")); } [Test] public void ImportTestX26 () { - DoImport ("Test/Resources/Schemas/ns26.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns26.xsd")); } [Test] public void ImportTestX27 () { - DoImport ("Test/Resources/Schemas/ns27.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns27.xsd")); } [Test] public void ImportTestX28 () { - DoImport ("Test/Resources/Schemas/ns28.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns28.xsd")); } [Test] [ExpectedException (typeof (InvalidDataContractException))] public void ImportTestX29 () { - DoImport ("Test/Resources/Schemas/ns29.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns29.xsd")); } [Test] public void ImportTestX30 () { - DoImport ("Test/Resources/Schemas/ns30.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns30.xsd")); } [Test] public void ImportTestX31 () { - DoImport ("Test/Resources/Schemas/ns31.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns31.xsd")); } [Test] public void ImportTestX32 () { - DoImport ("Test/Resources/Schemas/ns32.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns32.xsd")); } [Test] public void ImportTestX33 () { - DoImport ("Test/Resources/Schemas/ns33.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns33.xsd")); } [Test] public void ImportTestX34 () { - DoImport (true, "Test/Resources/Schemas/ns34.xsd", "Test/Resources/Schemas/ns34_2.xsd"); + DoImport (true, TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns34.xsd"), TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns34_2.xsd")); } [Test] public void CanImportTestX34 () { - DoCanImport (false, "Test/Resources/Schemas/ns34.xsd", "Test/Resources/Schemas/ns34_2.xsd"); + DoCanImport (false, TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns34.xsd"), TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/ns34_2.xsd")); } /* Helper methods */ @@ -780,7 +782,7 @@ namespace MonoTests.System.Runtime.Serialization [Test] public void ImportXsdBuiltInTypes () { - DoImport ("Test/Resources/Schemas/xml.xsd"); + DoImport (TestResourceHelper.GetFullPathOfResource ("Test/Resources/Schemas/xml.xsd")); } } diff --git a/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XsdDataContractImporterTest2.cs b/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XsdDataContractImporterTest2.cs index a3fb7edd90..05b8f19433 100644 --- a/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XsdDataContractImporterTest2.cs +++ b/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XsdDataContractImporterTest2.cs @@ -57,8 +57,8 @@ namespace MonoTests.System.Runtime.Serialization [SetUp] public void Setup () { - collectionsMetadata = WsdlHelper.GetMetadataSet ("collections.wsdl"); - customCollectionsMetadata = WsdlHelper.GetMetadataSet ("custom-collections.wsdl"); + collectionsMetadata = WsdlHelper.GetMetadataSet ("Test/Resources/WSDL/collections.wsdl"); + customCollectionsMetadata = WsdlHelper.GetMetadataSet ("Test/Resources/WSDL/custom-collections.wsdl"); } [Test] diff --git a/mcs/class/System.Runtime.Serialization/monotouch_tv_System.Runtime.Serialization_xtest.dll.exclude.sources b/mcs/class/System.Runtime.Serialization/monotouch_tv_System.Runtime.Serialization_xtest.dll.exclude.sources new file mode 100644 index 0000000000..8ca9bc71c3 --- /dev/null +++ b/mcs/class/System.Runtime.Serialization/monotouch_tv_System.Runtime.Serialization_xtest.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_System.Runtime.Serialization_xtest.dll.exclude.sources diff --git a/mcs/class/System.Runtime.Serialization/monotouch_watch_System.Runtime.Serialization_xtest.dll.exclude.sources b/mcs/class/System.Runtime.Serialization/monotouch_watch_System.Runtime.Serialization_xtest.dll.exclude.sources new file mode 100644 index 0000000000..8ca9bc71c3 --- /dev/null +++ b/mcs/class/System.Runtime.Serialization/monotouch_watch_System.Runtime.Serialization_xtest.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_System.Runtime.Serialization_xtest.dll.exclude.sources diff --git a/mcs/class/System.Security/Makefile b/mcs/class/System.Security/Makefile index e349d9ae94..3b77659577 100644 --- a/mcs/class/System.Security/Makefile +++ b/mcs/class/System.Security/Makefile @@ -14,11 +14,7 @@ LIB_MCS_FLAGS = -unsafe -nowarn:414,618 -d:SECURITY_DEP LOCAL_MCS_FLAGS = -TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -nowarn:168,169,183,219,414 - -XTEST_LIB_REFS = System.Core System Facades/System.Linq Facades/System.Threading.Tasks - -EXTRA_DISTFILES = \ +TEST_RESOURCE_FILES = \ Test/System.Security.Cryptography.Xml/sample.pfx \ Test/System.Security.Cryptography.Xml/EncryptedXmlSample1.xml \ Test/System.Security.Cryptography.Xml/EncryptedXmlSample2.xml \ @@ -26,4 +22,10 @@ EXTRA_DISTFILES = \ Test/System.Security.Cryptography.Pkcs/detached.data \ Test/System.Security.Cryptography.Pkcs/detached.p7 +TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -nowarn:168,169,183,219,414 $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) + +XTEST_LIB_REFS = System.Core System Facades/System.Linq Facades/System.Threading.Tasks + +EXTRA_DISTFILES = $(TEST_RESOURCE_FILES) + include ../../build/library.make diff --git a/mcs/class/System.Security/System.Security_test.dll.sources b/mcs/class/System.Security/System.Security_test.dll.sources index 31b9d8a3db..158777d508 100644 --- a/mcs/class/System.Security/System.Security_test.dll.sources +++ b/mcs/class/System.Security/System.Security_test.dll.sources @@ -1,4 +1,5 @@ ../../corlib/corefx/SR.cs +../../test-helpers/TestResourceHelper.cs System.Security.Cryptography/CryptographicAttributeObjectCollectionTest.cs System.Security.Cryptography/CryptographicAttributeObjectEnumeratorTest.cs System.Security.Cryptography/CryptographicAttributeTest.cs diff --git a/mcs/class/System.Security/Test/System.Security.Cryptography.Pkcs/SignedCmsTest.cs b/mcs/class/System.Security/Test/System.Security.Cryptography.Pkcs/SignedCmsTest.cs index 0a8c85e685..cd1979fd0d 100644 --- a/mcs/class/System.Security/Test/System.Security.Cryptography.Pkcs/SignedCmsTest.cs +++ b/mcs/class/System.Security/Test/System.Security.Cryptography.Pkcs/SignedCmsTest.cs @@ -38,6 +38,8 @@ using System.Security.Cryptography; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.X509Certificates; +using MonoTests.Helpers; + namespace MonoTests.System.Security.Cryptography.Pkcs { [TestFixture] @@ -441,9 +443,8 @@ namespace MonoTests.System.Security.Cryptography.Pkcs { [Test] public void CheckSignatureDetachedSignedCms () { - string path = Path.Combine ("Test", "System.Security.Cryptography.Pkcs"); - var signedBytes = File.ReadAllBytes (Path.Combine (path, "detached.data")); - var bytes = File.ReadAllBytes (Path.Combine (path, "detached.p7")); + var signedBytes = File.ReadAllBytes (TestResourceHelper.GetFullPathOfResource ("Test/System.Security.Cryptography.Pkcs/detached.data")); + var bytes = File.ReadAllBytes (TestResourceHelper.GetFullPathOfResource ("Test/System.Security.Cryptography.Pkcs/detached.p7")); var oid = new Oid ("1.2.840.113549.1.7.2"); var contentInfo = new ContentInfo (oid, signedBytes); diff --git a/mcs/class/System.Security/Test/System.Security.Cryptography.Xml/EncryptedXmlTest.cs b/mcs/class/System.Security/Test/System.Security.Cryptography.Xml/EncryptedXmlTest.cs index 82fc0fb433..021d29336f 100644 --- a/mcs/class/System.Security/Test/System.Security.Cryptography.Xml/EncryptedXmlTest.cs +++ b/mcs/class/System.Security/Test/System.Security.Cryptography.Xml/EncryptedXmlTest.cs @@ -18,6 +18,8 @@ using System.Xml; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Security.Cryptography.Xml { [TestFixture] @@ -26,7 +28,7 @@ namespace MonoTests.System.Security.Cryptography.Xml [Test] public void Sample1 () { - AssertDecryption1 ("Test/System.Security.Cryptography.Xml/EncryptedXmlSample1.xml"); + AssertDecryption1 (TestResourceHelper.GetFullPathOfResource ("Test/System.Security.Cryptography.Xml/EncryptedXmlSample1.xml")); } void AssertDecryption1 (string filename) @@ -35,7 +37,7 @@ namespace MonoTests.System.Security.Cryptography.Xml doc.PreserveWhitespace = true; doc.Load (filename); EncryptedXml encxml = new EncryptedXml (doc); - RSACryptoServiceProvider rsa = new X509Certificate2 ("Test/System.Security.Cryptography.Xml/sample.pfx", "mono").PrivateKey as RSACryptoServiceProvider; + RSACryptoServiceProvider rsa = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/System.Security.Cryptography.Xml/sample.pfx"), "mono").PrivateKey as RSACryptoServiceProvider; XmlNamespaceManager nm = new XmlNamespaceManager (doc.NameTable); nm.AddNamespace ("s", "http://www.w3.org/2003/05/soap-envelope"); nm.AddNamespace ("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); @@ -68,7 +70,7 @@ namespace MonoTests.System.Security.Cryptography.Xml XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = true; - doc.Load ("Test/System.Security.Cryptography.Xml/EncryptedXmlSample2.xml"); + doc.Load (TestResourceHelper.GetFullPathOfResource ("Test/System.Security.Cryptography.Xml/EncryptedXmlSample2.xml")); EncryptedXml encxml = new EncryptedXml (doc); EncryptedData edata = new EncryptedData (); edata.LoadXml (doc.DocumentElement); @@ -78,7 +80,7 @@ namespace MonoTests.System.Security.Cryptography.Xml [Test] public void Sample3 () { - AssertDecryption1 ("Test/System.Security.Cryptography.Xml/EncryptedXmlSample3.xml"); + AssertDecryption1 (TestResourceHelper.GetFullPathOfResource ("Test/System.Security.Cryptography.Xml/EncryptedXmlSample3.xml")); } [Test] diff --git a/mcs/class/System.Security/monotouch_tv_System.Security_test.dll.exclude.sources b/mcs/class/System.Security/monotouch_tv_System.Security_test.dll.exclude.sources new file mode 100644 index 0000000000..b4879846f7 --- /dev/null +++ b/mcs/class/System.Security/monotouch_tv_System.Security_test.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_System.Security_test.dll.exclude.sources diff --git a/mcs/class/System.Security/monotouch_watch_System.Security_test.dll.exclude.sources b/mcs/class/System.Security/monotouch_watch_System.Security_test.dll.exclude.sources new file mode 100644 index 0000000000..b4879846f7 --- /dev/null +++ b/mcs/class/System.Security/monotouch_watch_System.Security_test.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_System.Security_test.dll.exclude.sources diff --git a/mcs/class/System.Security/win32_net_4_x_System.Security.dll.exclude.sources b/mcs/class/System.Security/win32_net_4_x_System.Security.dll.exclude.sources new file mode 100644 index 0000000000..750d4469a2 --- /dev/null +++ b/mcs/class/System.Security/win32_net_4_x_System.Security.dll.exclude.sources @@ -0,0 +1 @@ +#include win32_System.Security.dll.exclude.sources \ No newline at end of file diff --git a/mcs/class/System.Security/win32_net_4_x_System.Security.dll.sources b/mcs/class/System.Security/win32_net_4_x_System.Security.dll.sources new file mode 100644 index 0000000000..dd7ad283a8 --- /dev/null +++ b/mcs/class/System.Security/win32_net_4_x_System.Security.dll.sources @@ -0,0 +1 @@ +#include win32_System.Security.dll.sources diff --git a/mcs/class/System.ServiceModel.Web/Makefile b/mcs/class/System.ServiceModel.Web/Makefile index cc4eaf3524..bd254996e7 100644 --- a/mcs/class/System.ServiceModel.Web/Makefile +++ b/mcs/class/System.ServiceModel.Web/Makefile @@ -28,12 +28,14 @@ else KEYFILE = ../winfx.pub endif -TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) - -EXTRA_DISTFILES = $(RESOURCE_FILES) \ +TEST_RESOURCE_FILES = \ Test/config/webHttpBinding \ Test/config/webHttpBinding.config +TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) + +EXTRA_DISTFILES = $(RESOURCE_FILES) $(TEST_RESOURCE_FILES) + VALID_PROFILE := $(filter 2 4, $(FRAMEWORK_VERSION_MAJOR)) ifndef VALID_PROFILE LIBRARY_NAME = dummy-System.ServiceModel.Web.dll diff --git a/mcs/class/System.ServiceModel.Web/System.ServiceModel.Web_test.dll.sources b/mcs/class/System.ServiceModel.Web/System.ServiceModel.Web_test.dll.sources index 8a6d9c8ead..26279bf9f9 100644 --- a/mcs/class/System.ServiceModel.Web/System.ServiceModel.Web_test.dll.sources +++ b/mcs/class/System.ServiceModel.Web/System.ServiceModel.Web_test.dll.sources @@ -1,4 +1,5 @@ ../../test-helpers/NetworkHelpers.cs +../../test-helpers/TestResourceHelper.cs System.ServiceModel.Activation/WebScriptServiceHostFactoryTest.cs System.ServiceModel.Channels/WebBodyFormatMessagePropertyTest.cs System.ServiceModel.Channels/WebMessageEncodingBindingElementTest.cs diff --git a/mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Configuration/WebHttpBindingElementTest.cs b/mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Configuration/WebHttpBindingElementTest.cs index e8cf4d55f0..3417cc3b10 100755 --- a/mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Configuration/WebHttpBindingElementTest.cs +++ b/mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Configuration/WebHttpBindingElementTest.cs @@ -6,6 +6,8 @@ using System.ServiceModel; using System.Text; using System.Configuration; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Configuration { [TestFixture] @@ -53,7 +55,7 @@ namespace MonoTests.System.ServiceModel.Configuration private WebHttpBinding CreateBindingFromConfig () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/webHttpBinding").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/webHttpBinding")).GetSectionGroup ("system.serviceModel"); WebHttpBindingCollectionElement collectionElement = (WebHttpBindingCollectionElement) config.Bindings ["webHttpBinding"]; WebHttpBindingElement el = collectionElement.Bindings ["WebHttpBinding1_Service"]; diff --git a/mcs/class/System.ServiceModel/Dummy_2_1.cs b/mcs/class/System.ServiceModel/Dummy_2_1.cs index 0c50b70aa0..bc5e510042 100644 --- a/mcs/class/System.ServiceModel/Dummy_2_1.cs +++ b/mcs/class/System.ServiceModel/Dummy_2_1.cs @@ -177,39 +177,34 @@ namespace System.ServiceModel // introduced for silverlight sdk compatibility internal interface IDuplexHelper { } - [FriendAccessAllowed ()] - internal class DiagnosticUtility + internal static class DiagnosticUtility { - [FriendAccessAllowed ()] - internal class ExceptionUtility + internal static class ExceptionUtility { - public static Exception ThrowHelperArgument (string message) { throw new NotImplementedException (); } - - public static Exception ThrowHelperArgument (string paramName, string message) { throw new NotImplementedException (); } - - public static Exception ThrowHelperArgumentNull (string arg) + internal static ArgumentException ThrowHelperArgument (string message) { - return new ArgumentNullException (arg); + return (ArgumentException)ThrowHelperError (new ArgumentException (message)); } - [FriendAccessAllowed] - internal static Exception ThrowHelperCallback (Exception e) { throw new NotImplementedException (); } - - [FriendAccessAllowed] - internal static Exception ThrowHelperCallback (string message, Exception innerException) { throw new NotImplementedException (); } - - public static Exception ThrowHelperError (Exception error) + internal static ArgumentException ThrowHelperArgument (string paramName, string message) { - return error; + return (ArgumentException)ThrowHelperError (new ArgumentException (message, paramName)); + } + + internal static ArgumentNullException ThrowHelperArgumentNull (string paramName) + { + return (ArgumentNullException)ThrowHelperError (new ArgumentNullException (paramName)); + } + + internal static Exception ThrowHelperError (Exception exception) + { + return exception; + } + + internal static Exception ThrowHelperWarning (Exception exception) + { + return exception; } - - [FriendAccessAllowed] - internal static Exception ThrowHelperFatal (string message, Exception innerException) { throw new NotImplementedException (); } - - [FriendAccessAllowed] - internal static Exception ThrowHelperInternal (bool fatal) { throw new NotImplementedException (); } - - public static Exception ThrowHelperWarning (Exception e) { throw new NotImplementedException (); } } } } diff --git a/mcs/class/System.ServiceModel/Dummy_XM_4_5.cs b/mcs/class/System.ServiceModel/Dummy_XM_4_5.cs index 989c4dddc5..d21ed9eaea 100644 --- a/mcs/class/System.ServiceModel/Dummy_XM_4_5.cs +++ b/mcs/class/System.ServiceModel/Dummy_XM_4_5.cs @@ -149,4 +149,38 @@ namespace System.ServiceModel.Description namespace System.ServiceModel.Channels { public interface ITransportTokenAssertionProvider {} +} + +namespace System.ServiceModel +{ + internal static class DiagnosticUtility + { + internal static class ExceptionUtility + { + internal static ArgumentException ThrowHelperArgument (string message) + { + return (ArgumentException)ThrowHelperError (new ArgumentException (message)); + } + + internal static ArgumentException ThrowHelperArgument (string paramName, string message) + { + return (ArgumentException)ThrowHelperError (new ArgumentException (message, paramName)); + } + + internal static ArgumentNullException ThrowHelperArgumentNull (string paramName) + { + return (ArgumentNullException)ThrowHelperError (new ArgumentNullException (paramName)); + } + + internal static Exception ThrowHelperError (Exception exception) + { + return exception; + } + + internal static Exception ThrowHelperWarning (Exception exception) + { + return exception; + } + } + } } \ No newline at end of file diff --git a/mcs/class/System.ServiceModel/Makefile b/mcs/class/System.ServiceModel/Makefile index bb9d5bb4a6..b7e91a5eec 100644 --- a/mcs/class/System.ServiceModel/Makefile +++ b/mcs/class/System.ServiceModel/Makefile @@ -47,17 +47,14 @@ endif # (2.1, $(FRAMEWORK_VERSION)) TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -TEST_EXTRA_FILES = \ - System.ServiceModel_test_net_3_0.dll.config \ - Test/config/* \ - Test/Resources/* \ - Test/XmlFiles/* \ - Test/System.ServiceModel.Channels/soap-fault*.xml \ - Test/System.ServiceModel.Channels/binary-message.raw \ - Test/System.ServiceModel.Description/dump.xml \ - Test/MetadataTests/Resources/* +TEST_RESOURCE_FILES = \ + $(wildcard Test/config/*) \ + $(wildcard Test/Resources/*) \ + $(wildcard Test/MetadataTests/Resources/*) -EXTRA_DISTFILES = $(RESOURCE_FILES) $(TEST_EXTRA_FILES) +TEST_MCS_FLAGS += $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) + +EXTRA_DISTFILES = $(RESOURCE_FILES) $(TEST_RESOURCE_FILES) # Useful for debugging under Visual Studio 2005 # NO_SIGN_ASSEMBLY = yes diff --git a/mcs/class/System.ServiceModel/ReferenceSources/SR.cs b/mcs/class/System.ServiceModel/ReferenceSources/SR.cs new file mode 100644 index 0000000000..25a5f10ae5 --- /dev/null +++ b/mcs/class/System.ServiceModel/ReferenceSources/SR.cs @@ -0,0 +1,12 @@ +partial class SR +{ + public const string CannotAddTwoItemsWithTheSameKeyToSynchronizedKeyedCollection0 = "Cannot add two items with the same key to SynchronizedKeyedCollection."; + public const string DuplicateBehavior1 = "The value could not be added to the collection, as the collection already contains an item of the same type: '{0}'. This collection only supports one instance of each type."; + public const string ItemDoesNotExistInSynchronizedKeyedCollection0 = "Item does not exist in SynchronizedKeyedCollection."; + public const string SFxCollectionReadOnly = "This operation is not supported because the collection is read-only."; + public const string SFxCollectionWrongType2 = "The collection of type {0} does not support values of type {1}."; + public const string SFxCopyToRequiresICollection = "SynchronizedReadOnlyCollection's CopyTo only works if the underlying list implements ICollection."; + public const string SynchronizedCollectionWrongType1 = "A value of type '{0}' cannot be added to the generic collection, because the collection has been parameterized with a different type."; + public const string SynchronizedCollectionWrongTypeNull = "A null value cannot be added to the generic collection, because the collection has been parameterized with a value type."; + public const string ValueMustBeInRange = "The value of this argument must fall within the range {0} to {1}."; +} diff --git a/mcs/class/System.ServiceModel/System.Collections.Generic/KeyedByTypeCollection.cs b/mcs/class/System.ServiceModel/System.Collections.Generic/KeyedByTypeCollection.cs deleted file mode 100644 index dc046928ad..0000000000 --- a/mcs/class/System.ServiceModel/System.Collections.Generic/KeyedByTypeCollection.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -// KeyedByTypeCollection.cs -// -// Author: -// Atsushi Enomoto -// -// Copyright (C) 2005 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 System; -using System.Collections.ObjectModel; - -namespace System.Collections.Generic -{ - public class KeyedByTypeCollection - : KeyedCollection - { - public KeyedByTypeCollection () - { - } - - public KeyedByTypeCollection (IEnumerable items) - { - foreach (TItem item in items) - Add (item); - } - - protected override Type GetKeyForItem (TItem item) - { - return item.GetType (); - } - - public T Find () - { - foreach (TItem k in this) - if (k is T) - return (T) (object) k; - return default (T); - } - - public Collection FindAll () - { - Collection list = new Collection (); - foreach (TItem k in this) - if (k is T) - list.Add ((T) (object) k); - return list; - } - - protected override void InsertItem (int index, TItem item) - { - base.InsertItem (index, item); - } - - protected override void SetItem (int index, TItem item) - { - base.SetItem (index, item); - } - - public T Remove () - { - foreach (TItem k in this) - if (k is T) { - Remove (k); - return (T) (object) k; - } - return default (T); - } - - public Collection RemoveAll () - { - return RemoveAll (); - } - } -} diff --git a/mcs/class/System.ServiceModel/System.Collections.Generic/SynchronizedCollection.cs b/mcs/class/System.ServiceModel/System.Collections.Generic/SynchronizedCollection.cs deleted file mode 100644 index 39d102a9e0..0000000000 --- a/mcs/class/System.ServiceModel/System.Collections.Generic/SynchronizedCollection.cs +++ /dev/null @@ -1,261 +0,0 @@ -// -// SynchronizedCollection.cs -// -// Author: -// Atsushi Enomoto -// -// Copyright (C) 2005 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 System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.InteropServices; - -namespace System.Collections.Generic -{ - [ComVisibleAttribute (false)] - public class SynchronizedCollection : IList, ICollection, - IEnumerable, IList, ICollection, IEnumerable - { - object root; - List list; - - public SynchronizedCollection () - : this (new object (), null, false) - { - } - - public SynchronizedCollection (object syncRoot) - : this (syncRoot, null, false) - { - } - - public SynchronizedCollection (object syncRoot, - IEnumerable list) - : this (syncRoot, new List (list), false) - { - } - - public SynchronizedCollection (object syncRoot, - params T [] list) - : this (syncRoot, new List (list), false) - { - } - - public SynchronizedCollection (object syncRoot, - List list, bool makeCopy) - { - if (syncRoot == null) - syncRoot = new object (); - root = syncRoot; - if (list == null) - this.list = new List (); - else if (makeCopy) - this.list = new List (list); - else - this.list = list; - } - - public int Count { - get { - lock (root) { - return list.Count; - } - } - } - - public T this [int index] { - get { - lock (root) { - return list [index]; - } - } - set { - SetItem (index, value); - } - } - - public object SyncRoot { - get { return root; } - } - - protected List Items { - get { return list; } - } - - public void Add (T item) - { - InsertItem (list.Count, item); - } - - public void Clear () - { - ClearItems (); - } - - public bool Contains (T item) - { - lock (root) { - return list.Contains (item); - } - } - - public void CopyTo (T [] array, int index) - { - lock (root) { - list.CopyTo (array, index); - } - } - - [MonoTODO ("Should be synchronized enumerator?")] - public IEnumerator GetEnumerator () - { - lock (root) { - return list.GetEnumerator (); - } - } - - public int IndexOf (T item) - { - lock (root) { - return list.IndexOf (item); - } - } - - public void Insert (int index, T item) - { - InsertItem (index, item); - } - - public bool Remove (T item) - { - lock (root) { - int index = IndexOf (item); - if (index < 0) - return false; - RemoveAt (index); - return true; - } - } - - public void RemoveAt (int index) - { - RemoveItem (index); - } - - protected virtual void ClearItems () - { - lock (root) { - list.Clear (); - } - } - - protected virtual void InsertItem (int index, T item) - { - lock (root) { - list.Insert (index, item); - } - } - - protected virtual void RemoveItem (int index) - { - lock (root) { - list.RemoveAt (index); - } - } - - protected virtual void SetItem (int index, T item) - { - lock (root) { - list [index] = item; - } - } - - #region Explicit interface implementations - - void ICollection.CopyTo (Array array, int index) - { - CopyTo ((T []) array, index); - } - - IEnumerator IEnumerable.GetEnumerator () - { - return GetEnumerator (); - } - - int IList.Add (object value) - { - lock (root) { - Add ((T) value); - return list.Count - 1; - } - } - - bool IList.Contains (object value) - { - return Contains ((T) value); - } - - int IList.IndexOf (object value) - { - return IndexOf ((T) value); - } - - void IList.Insert (int index, object value) - { - Insert (index, (T) value); - } - - void IList.Remove (object value) - { - Remove ((T) value); - } - - bool ICollection.IsReadOnly { - get { return false; } - } - - bool ICollection.IsSynchronized { - get { return true; } - } - - object ICollection.SyncRoot { - get { return root; } - } - - bool IList.IsFixedSize { - get { return false; } - } - - bool IList.IsReadOnly { - get { return false; } - } - - object IList.this [int index] { - get { return this [index]; } - set { this [index] = (T) value; } - } - - #endregion - } -} diff --git a/mcs/class/System.ServiceModel/System.Collections.Generic/SynchronizedKeyedCollection.cs b/mcs/class/System.ServiceModel/System.Collections.Generic/SynchronizedKeyedCollection.cs deleted file mode 100644 index b110d15f24..0000000000 --- a/mcs/class/System.ServiceModel/System.Collections.Generic/SynchronizedKeyedCollection.cs +++ /dev/null @@ -1,142 +0,0 @@ -// -// SynchronizedKeyedCollection.cs -// -// Author: -// Atsushi Enomoto -// -// Copyright (C) 2005 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 System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.ServiceModel.Channels; - -namespace System.Collections.Generic -{ - [ComVisibleAttribute (false)] - public abstract class SynchronizedKeyedCollection - : SynchronizedCollection - { - Dictionary dict; - - protected SynchronizedKeyedCollection () - : this (new object ()) - { - } - - protected SynchronizedKeyedCollection (object syncRoot) - : base (syncRoot) - { - dict = new Dictionary (); - } - - protected SynchronizedKeyedCollection (object syncRoot, - IEqualityComparer comparer) - : base (syncRoot) - { - dict = new Dictionary (comparer); - } - - protected SynchronizedKeyedCollection (object syncRoot, - IEqualityComparer comparer, int dictionaryCreationThreshold) - : base (syncRoot) - { - dict = new Dictionary (dictionaryCreationThreshold, comparer); - } - - // see bug #76417 - /* - public T this [int index] { - get { return base [index]; } - set { base [index] = value; } - } - */ - - public T this [K key] { - get { - lock (SyncRoot) { - return dict [key]; - } - } - } - - protected IDictionary Dictionary { - get { return dict; } - } - - public bool Contains (K key) - { - lock (SyncRoot) { - return dict.ContainsKey (key); - } - } - - public bool Remove (K key) - { - lock (SyncRoot) { - return dict.Remove (key); - } - } - - protected void ChangeItemKey (T item, K newKey) - { - lock (SyncRoot) { - K old = GetKeyForItem (item); - dict [old] = default (T); - dict [newKey] = item; - } - } - - [MonoTODO ("This lock is not an atomic.")] - protected override void ClearItems () - { - base.ClearItems (); - lock (SyncRoot) { - dict.Clear (); - } - } - - protected abstract K GetKeyForItem (T item); - - [MonoTODO ("This lock is not an atomic.")] - protected override void InsertItem (int index, T item) - { - base.InsertItem (index, item); - dict.Add (GetKeyForItem (item), item); - } - - [MonoTODO ("This lock is not an atomic.")] - protected override void RemoveItem (int index) - { - K key = GetKeyForItem (base [index]); - base.RemoveItem (index); - dict.Remove (key); - } - - [MonoTODO ("This lock is not an atomic.")] - protected override void SetItem (int index, T item) - { - base.SetItem (index, item); - dict [GetKeyForItem (item)] = item; - } - } -} diff --git a/mcs/class/System.ServiceModel/System.Collections.Generic/SynchronizedReadOnlyCollection.cs b/mcs/class/System.ServiceModel/System.Collections.Generic/SynchronizedReadOnlyCollection.cs deleted file mode 100644 index b7924ff5a7..0000000000 --- a/mcs/class/System.ServiceModel/System.Collections.Generic/SynchronizedReadOnlyCollection.cs +++ /dev/null @@ -1,223 +0,0 @@ -// -// System.ServiceModel.SynchronizedReadOnlyCollection.cs -// -// Author: Duncan Mak (duncan@novell.com) -// -// Copyright (C) 2005 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 System; -using System.Collections; -using System.Runtime.InteropServices; - -namespace System.Collections.Generic -{ - [ComVisible (false)] - public class SynchronizedReadOnlyCollection - : IList, ICollection, IEnumerable, IList, ICollection, IEnumerable - { - List l; - object sync_root; - - public SynchronizedReadOnlyCollection () - : this (new object ()) - { - } - - public SynchronizedReadOnlyCollection (object syncRoot) - : this (syncRoot, new List ()) - { - } - - public SynchronizedReadOnlyCollection (object syncRoot, IEnumerable list) - { - if (syncRoot == null) - throw new ArgumentNullException ("syncRoot"); - - if (list == null) - throw new ArgumentNullException ("list"); - - this.sync_root = syncRoot; - this.l = new List (list); - } - - public SynchronizedReadOnlyCollection (object syncRoot, params T [] list) - : this (syncRoot, (IEnumerable) list) - { - } - - public SynchronizedReadOnlyCollection (object sync_root, List list, bool make_copy) - : this (sync_root, - list == null ? null : make_copy ? new List (list) : list) - { - } - - public bool Contains (T value) - { - bool retval; - - lock (sync_root) { - retval = l.Contains (value); - } - - return retval; - } - - public void CopyTo (T [] array, int index) - { - lock (sync_root) { - l.CopyTo (array, index); - } - } - - public IEnumerator GetEnumerator () - { - IEnumerator retval; - - lock (sync_root) { - retval = l.GetEnumerator (); - } - - return retval; - } - - public int IndexOf (T value) - { - int retval; - - lock (sync_root) { - retval = l.IndexOf (value); - } - - return retval; - } - - void ICollection.Add (T value) { throw new NotSupportedException (); } - void ICollection.Clear () { throw new NotSupportedException (); } - bool ICollection.Remove (T value) { throw new NotSupportedException (); } - - void IList.Insert (int index, T value) { throw new NotSupportedException (); } - void IList.RemoveAt (int index) { throw new NotSupportedException (); } - - void ICollection.CopyTo (Array array, int index) - { - ICollection a = array as ICollection; - - if (a == null) - throw new ArgumentException ("The array type is not compatible."); - - lock (sync_root) { - ((ICollection) l).CopyTo (array, index); - } - } - - IEnumerator IEnumerable.GetEnumerator () - { - return GetEnumerator (); - } - - int IList.Add (object value) { throw new NotSupportedException (); } - void IList.Clear () { throw new NotSupportedException (); } - - bool IList.Contains (object value) - { - if (typeof (T).IsValueType) - throw new ArgumentException ("This is a collection of ValueTypes."); - - // null always gets thru - if (value is T == false && value != null) - throw new ArgumentException ("value is not of the same type as this collection."); - - bool retval; - T val = (T) value; - lock (sync_root) { - retval = l.Contains (val); - } - - return retval; - } - - int IList.IndexOf (object value) - { - if (typeof (T).IsValueType) - throw new ArgumentException ("This is a collection of ValueTypes."); - - if (value is T == false) - throw new ArgumentException ("value is not of the same type as this collection."); - - int retval; - T val = (T) value; - lock (sync_root) { - retval = l.IndexOf (val); - } - - return retval; - } - - void IList.Insert (int index, object value) { throw new NotSupportedException (); } - void IList.Remove (object value) { throw new NotSupportedException (); } - void IList.RemoveAt (int index) { throw new NotSupportedException (); } - - public int Count { - get { - int retval; - lock (sync_root) { - retval = l.Count; - } - return retval; - } - } - - public T this [int index] { - get { - T retval; - lock (sync_root) { - retval = l [index]; - } - return retval; - } - } - - protected IList Items { - get { return l; } - } - - - bool ICollection.IsReadOnly { get { return true; }} - - bool ICollection.IsSynchronized { get { return true; }} - object ICollection.SyncRoot { get { return sync_root; }} - - bool IList.IsFixedSize { get { return true; }} - bool IList.IsReadOnly { get { return true; }} - - T IList.this [int index] { - get { return this [index]; } - set { throw new NotSupportedException (); } - } - - object IList.this [int index] { - get { return this [index]; } - set { throw new NotSupportedException (); } - } - } -} \ No newline at end of file diff --git a/mcs/class/System.ServiceModel/System.IO/PipeException.cs b/mcs/class/System.ServiceModel/System.IO/PipeException.cs deleted file mode 100644 index 48f1b3a801..0000000000 --- a/mcs/class/System.ServiceModel/System.IO/PipeException.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.IO; -using System.Runtime.Serialization; -using System.ServiceModel.Channels; - -namespace System.IO -{ - public class PipeException : IOException - { - public PipeException () - { - } - - public PipeException (string message): base (message) - { - } - - protected PipeException (SerializationInfo info, StreamingContext context) - : base (info, context) - { - } - - public PipeException (string message, Exception inner) - : base (message, inner) - { - } - - public PipeException (string message, int errorCode) - : base (message, errorCode) - { - } - - public virtual int ErrorCode { - get { - // we re-use the HResult for the error code here. - return HResult; - } - } - } -} - diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.dll.sources b/mcs/class/System.ServiceModel/System.ServiceModel.dll.sources index a2834ac049..994b7712e0 100644 --- a/mcs/class/System.ServiceModel/System.ServiceModel.dll.sources +++ b/mcs/class/System.ServiceModel/System.ServiceModel.dll.sources @@ -3,6 +3,7 @@ ../../build/common/SR.cs ../../build/common/MonoTODOAttribute.cs corefx/SR.cs +ReferenceSources/SR.cs Assembly/AssemblyInfo.cs Mono.CodeGeneration/CodeAdd.cs Mono.CodeGeneration/CodeAnd.cs @@ -66,11 +67,11 @@ Mono.Xml.XPath/DTMXPathDocumentBuilder2.cs Mono.Xml.XPath/DTMXPathDocumentWriter2.cs Mono.Xml.XPath/DTMXPathNavigator2.cs Mono.Xml.XPath/DTMXPathNode2.cs -System.Collections.Generic/KeyedByTypeCollection.cs -System.Collections.Generic/SynchronizedCollection.cs -System.Collections.Generic/SynchronizedKeyedCollection.cs -System.Collections.Generic/SynchronizedReadOnlyCollection.cs -System.IO/PipeException.cs +../referencesource/System.ServiceModel/System/ServiceModel/KeyedByTypeCollection.cs +../referencesource/System.ServiceModel/System/ServiceModel/SynchronizedCollection.cs +../referencesource/System.ServiceModel/System/ServiceModel/SynchronizedKeyedCollection.cs +../referencesource/System.ServiceModel/System/ServiceModel/SynchronizedReadOnlyCollection.cs +../referencesource/System.ServiceModel/System/ServiceModel/Channels/PipeException.cs System.ServiceModel.Activation/AspNetIntegrationRequirementsAttribute.cs System.ServiceModel.Activation/ServiceHostFactoryBase.cs System.ServiceModel.Activation/VirtualPathExtension.cs diff --git a/mcs/class/System.ServiceModel/System.ServiceModel_test.dll.sources b/mcs/class/System.ServiceModel/System.ServiceModel_test.dll.sources index d19ab6a056..d45c241f7f 100644 --- a/mcs/class/System.ServiceModel/System.ServiceModel_test.dll.sources +++ b/mcs/class/System.ServiceModel/System.ServiceModel_test.dll.sources @@ -1,4 +1,5 @@ ../../test-helpers/NunitHelpers.cs +../../test-helpers/TestResourceHelper.cs NUnitMoonHelper.cs FeatureBased/Features.Client/AsyncCallTesterProxy.cs FeatureBased/Features.Client/AsyncPatternServer.cs @@ -198,6 +199,7 @@ System.ServiceModel/ServiceHostBaseTest.cs System.ServiceModel/ServiceHostTest.cs System.ServiceModel/ServiceKnownTypeAttributeTest.cs System.ServiceModel/SynchronizedReadOnlyCollectionTest.cs +System.ServiceModel/SynchronizedCollectionTest.cs System.ServiceModel/TransactionProtocolTest.cs System.ServiceModel/UriSchemeKeyedCollectionTest.cs System.ServiceModel/WSFederationHttpBindingTest.cs diff --git a/mcs/class/System.ServiceModel/System.ServiceModel_test_net_3_0.dll.config b/mcs/class/System.ServiceModel/System.ServiceModel_test_net_3_0.dll.config deleted file mode 100644 index 162fae760a..0000000000 --- a/mcs/class/System.ServiceModel/System.ServiceModel_test_net_3_0.dll.config +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/mcs/class/System.ServiceModel/Test/MetadataTests/TestContext.cs b/mcs/class/System.ServiceModel/Test/MetadataTests/TestContext.cs index c8d0d86d51..db39217f99 100644 --- a/mcs/class/System.ServiceModel/Test/MetadataTests/TestContext.cs +++ b/mcs/class/System.ServiceModel/Test/MetadataTests/TestContext.cs @@ -39,6 +39,8 @@ using System.ServiceModel.Description; using SysConfig = System.Configuration.Configuration; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.MetadataTests { public abstract class TestContext { @@ -111,20 +113,12 @@ namespace MonoTests.System.ServiceModel.MetadataTests { public static MetadataSet LoadMetadata (string name) { -#if USE_EMBEDDED_METADATA - return LoadMetadataFromResource (name); -#else return LoadMetadataFromFile (name); -#endif } public static XmlDocument LoadConfiguration (string name) { -#if USE_EMBEDDED_METADATA - return LoadConfigurationFromResource (name); -#else return LoadConfigurationFromFile (name); -#endif } public static void SaveMetadata (string name, MetadataSet metadata) @@ -137,32 +131,9 @@ namespace MonoTests.System.ServiceModel.MetadataTests { var asm = Assembly.GetExecutingAssembly (); if (!name.EndsWith (".xml")) name = name + ".xml"; - var uri = new Uri (asm.CodeBase); - // Run from mcs/class/lib/ - var path = Path.GetDirectoryName (uri.AbsolutePath); - path = Directory.GetParent (path).Parent.Parent.FullName; - path = Path.Combine (path, "System.ServiceModel"); - path = Path.Combine (path, "Test"); - path = Path.Combine (path, "MetadataTests"); - path = Path.Combine (path, "Resources"); - var filename = Path.Combine (path, name); - using (var stream = new StreamReader (filename)) { - var reader = new XmlTextReader (stream); - return MetadataSet.ReadFrom (reader); - } - } - public static MetadataSet LoadMetadataFromResource (string name) - { - var asm = Assembly.GetExecutingAssembly (); - if (!name.EndsWith (".xml")) - name = name + ".xml"; - - var resname = "MetadataTests.Resources." + name; - using (var stream = asm.GetManifestResourceStream (resname)) { - if (stream == null) - throw new InvalidOperationException ( - "No such resource: " + name); + var filename = TestResourceHelper.GetFullPathOfResource ("Test/MetadataTests/Resources/" + name); + using (var stream = new StreamReader (filename)) { var reader = new XmlTextReader (stream); return MetadataSet.ReadFrom (reader); } @@ -173,32 +144,9 @@ namespace MonoTests.System.ServiceModel.MetadataTests { var asm = Assembly.GetExecutingAssembly (); if (!name.EndsWith (".config")) name = name + ".config"; - var uri = new Uri (asm.CodeBase); - var path = Path.GetDirectoryName (uri.AbsolutePath); - path = Directory.GetParent (path).Parent.Parent.FullName; - path = Path.Combine (path, "System.ServiceModel"); - path = Path.Combine (path, "Test"); - path = Path.Combine (path, "MetadataTests"); - path = Path.Combine (path, "Resources"); - var filename = Path.Combine (path, name); - using (var stream = new StreamReader (filename)) { - var xml = new XmlDocument (); - xml.Load (stream); - return xml; - } - } - public static XmlDocument LoadConfigurationFromResource (string name) - { - var asm = Assembly.GetExecutingAssembly (); - if (!name.EndsWith (".config")) - name = name + ".config"; - - var resname = "MetadataTests.Resources." + name; - using (var stream = asm.GetManifestResourceStream (resname)) { - if (stream == null) - throw new InvalidOperationException ( - "No such resource: " + name); + var filename = TestResourceHelper.GetFullPathOfResource ("Test/MetadataTests/Resources/" + name); + using (var stream = new StreamReader (filename)) { var xml = new XmlDocument (); xml.Load (stream); return xml; diff --git a/mcs/class/System.ServiceModel/Test/XmlFiles/670945.wsdl b/mcs/class/System.ServiceModel/Test/Resources/670945.wsdl similarity index 100% rename from mcs/class/System.ServiceModel/Test/XmlFiles/670945.wsdl rename to mcs/class/System.ServiceModel/Test/Resources/670945.wsdl diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/binary-message.raw b/mcs/class/System.ServiceModel/Test/Resources/binary-message.raw similarity index 100% rename from mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/binary-message.raw rename to mcs/class/System.ServiceModel/Test/Resources/binary-message.raw diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/dump.xml b/mcs/class/System.ServiceModel/Test/Resources/dump.xml similarity index 100% rename from mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/dump.xml rename to mcs/class/System.ServiceModel/Test/Resources/dump.xml diff --git a/mcs/class/System.ServiceModel/Test/XmlFiles/one.xml b/mcs/class/System.ServiceModel/Test/Resources/one.xml similarity index 100% rename from mcs/class/System.ServiceModel/Test/XmlFiles/one.xml rename to mcs/class/System.ServiceModel/Test/Resources/one.xml diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/soap-fault-incomplete.xml b/mcs/class/System.ServiceModel/Test/Resources/soap-fault-incomplete.xml similarity index 100% rename from mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/soap-fault-incomplete.xml rename to mcs/class/System.ServiceModel/Test/Resources/soap-fault-incomplete.xml diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/soap-fault-incomplete4.xml b/mcs/class/System.ServiceModel/Test/Resources/soap-fault-incomplete4.xml similarity index 100% rename from mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/soap-fault-incomplete4.xml rename to mcs/class/System.ServiceModel/Test/Resources/soap-fault-incomplete4.xml diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/soap-fault.xml b/mcs/class/System.ServiceModel/Test/Resources/soap-fault.xml similarity index 100% rename from mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/soap-fault.xml rename to mcs/class/System.ServiceModel/Test/Resources/soap-fault.xml diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/AsymmetricSecurityBindingElementTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/AsymmetricSecurityBindingElementTest.cs index a5ad0952d4..5f8baad5d0 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/AsymmetricSecurityBindingElementTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/AsymmetricSecurityBindingElementTest.cs @@ -51,8 +51,8 @@ namespace MonoTests.System.ServiceModel.Channels [TestFixture] public class AsymmetricSecurityBindingElementTest { - static X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); - static X509Certificate2 cert2 = new X509Certificate2 ("Test/Resources/test.cer"); + static X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); + static X509Certificate2 cert2 = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.cer")); // InitiatorTokenParameters should have asymmetric key. [Test] @@ -246,7 +246,7 @@ namespace MonoTests.System.ServiceModel.Channels binding, new Uri ("http://localhost:" + NetworkHelpers.FindFreePort ())); ServiceCredentials cred = new ServiceCredentials (); cred.ServiceCertificate.Certificate = - new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); cred.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None; host.Description.Behaviors.Add (cred); diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/BinaryMessageEncodingBindingElementTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/BinaryMessageEncodingBindingElementTest.cs index 9a523bea39..ed10d3e256 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/BinaryMessageEncodingBindingElementTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/BinaryMessageEncodingBindingElementTest.cs @@ -119,7 +119,7 @@ namespace MonoTests.System.ServiceModel.Channels [Test] public void ReadMessage () { - using (var ms = File.OpenRead ("Test/System.ServiceModel.Channels/binary-message.raw")) { + using (var ms = File.OpenRead (TestResourceHelper.GetFullPathOfResource ("Test/Resources/binary-message.raw"))) { var session = new XmlBinaryReaderSession (); byte [] rsbuf = new BinaryFrameSupportReader (ms).ReadSizedChunk (); diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/CustomBindingTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/CustomBindingTest.cs index 5b7a1eaa34..cb05d50ea1 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/CustomBindingTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/CustomBindingTest.cs @@ -215,7 +215,7 @@ namespace MonoTests.System.ServiceModel.Channels EndpointAddress address = new EndpointAddress ( new Uri ("http://localhost:" + NetworkHelpers.FindFreePort ()), - new X509CertificateEndpointIdentity (new X509Certificate2 ("Test/Resources/test.pfx", "mono"))); + new X509CertificateEndpointIdentity (new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"))); ChannelFactory cf = new ChannelFactory (binding, address); @@ -263,7 +263,7 @@ namespace MonoTests.System.ServiceModel.Channels EndpointAddress address = new EndpointAddress ( new Uri ("http://localhost:" + NetworkHelpers.FindFreePort ()), - new X509CertificateEndpointIdentity (new X509Certificate2 ("Test/Resources/test.pfx", "mono"))); + new X509CertificateEndpointIdentity (new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"))); ChannelProtectionRequirements reqs = new ChannelProtectionRequirements (); diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/MessageFaultTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/MessageFaultTest.cs index 5c73c05932..04398e9f74 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/MessageFaultTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/MessageFaultTest.cs @@ -8,6 +8,8 @@ using System.Text; using System.Xml; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Channels { [TestFixture] @@ -16,7 +18,7 @@ namespace MonoTests.System.ServiceModel.Channels [Test] public void CreateFault () { - var msg = Message.CreateMessage (XmlReader.Create (new StreamReader ("Test/System.ServiceModel.Channels/soap-fault.xml")), 0x10000, MessageVersion.Default); + var msg = Message.CreateMessage (XmlReader.Create (new StreamReader (TestResourceHelper.GetFullPathOfResource ("Test/Resources/soap-fault.xml"))), 0x10000, MessageVersion.Default); MessageFault.CreateFault (msg, 0x10000); } @@ -33,7 +35,7 @@ namespace MonoTests.System.ServiceModel.Channels [ExpectedException (typeof (CommunicationException))] public void CreateFaultIncomplete () { - var msg = Message.CreateMessage (XmlReader.Create (new StreamReader ("Test/System.ServiceModel.Channels/soap-fault-incomplete.xml")), 0x10000, MessageVersion.Default); + var msg = Message.CreateMessage (XmlReader.Create (new StreamReader (TestResourceHelper.GetFullPathOfResource ("Test/Resources/soap-fault-incomplete.xml"))), 0x10000, MessageVersion.Default); MessageFault.CreateFault (msg, 0x10000); } @@ -55,7 +57,7 @@ namespace MonoTests.System.ServiceModel.Channels [ExpectedException (typeof (CommunicationException))] public void CreateFaultIncomplete4 () { - var msg = Message.CreateMessage (XmlReader.Create (new StreamReader ("Test/System.ServiceModel.Channels/soap-fault-incomplete4.xml")), 0x10000, MessageVersion.Default); + var msg = Message.CreateMessage (XmlReader.Create (new StreamReader (TestResourceHelper.GetFullPathOfResource ("Test/Resources/soap-fault-incomplete4.xml"))), 0x10000, MessageVersion.Default); MessageFault.CreateFault (msg, 0x10000); } diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/SecurityBindingElementTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/SecurityBindingElementTest.cs index 455f9b86e1..b7bd16e3d0 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/SecurityBindingElementTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/SecurityBindingElementTest.cs @@ -430,7 +430,7 @@ namespace MonoTests.System.ServiceModel.Channels Binding b = new CustomBinding (be, new HttpTransportBindingElement ()); ClientCredentials cred = new ClientCredentials (); cred.ClientCertificate.Certificate = - new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); IChannelFactory ch = b.BuildChannelFactory (new Uri ("http://localhost:" + NetworkHelpers.FindFreePort ()), cred); try { ch.Open (); @@ -458,7 +458,7 @@ namespace MonoTests.System.ServiceModel.Channels Binding b = new CustomBinding (be, new HttpTransportBindingElement ()); ServiceCredentials cred = new ServiceCredentials (); cred.ServiceCertificate.Certificate = - new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); IChannelListener ch = b.BuildChannelListener (new Uri ("http://localhost:" + NetworkHelpers.FindFreePort ()), cred); try { ch.Open (); @@ -480,7 +480,7 @@ namespace MonoTests.System.ServiceModel.Channels be.EndpointSupportingTokenParameters.Endorsing.Add ( new UserNameSecurityTokenParameters ()); Binding b = new CustomBinding (be, new HttpTransportBindingElement ()); - X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); EndpointAddress ea = new EndpointAddress (new Uri ("http://localhost:" + NetworkHelpers.FindFreePort ()), new X509CertificateEndpointIdentity (cert)); CalcProxy client = new CalcProxy (b, ea); client.ClientCredentials.UserName.UserName = "rupert"; diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/SslStreamSecurityBindingElementTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/SslStreamSecurityBindingElementTest.cs index 19694189ef..35efbc7482 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/SslStreamSecurityBindingElementTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/SslStreamSecurityBindingElementTest.cs @@ -37,6 +37,8 @@ using System.ServiceModel.Security; using System.Text; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Channels { [TestFixture] @@ -100,7 +102,7 @@ namespace MonoTests.System.ServiceModel.Channels { ServiceCredentials cred = new ServiceCredentials (); X509Certificate2 cert = - new X509Certificate2 ("Test/Resources/test.cer"); + new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.cer")); cred.ServiceCertificate.Certificate = cert; X509CertificateEndpointIdentity ident = new X509CertificateEndpointIdentity (cert); diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/SymmetricSecurityBindingElementTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/SymmetricSecurityBindingElementTest.cs index ce32cb0dba..3bec13231e 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/SymmetricSecurityBindingElementTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/SymmetricSecurityBindingElementTest.cs @@ -42,6 +42,8 @@ using System.ServiceModel.Security.Tokens; using System.Xml; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Channels { [TestFixture] @@ -150,7 +152,7 @@ namespace MonoTests.System.ServiceModel.Channels EndpointAddress CreateX509EndpointAddress (string uri) { EndpointIdentity identity = - new X509CertificateEndpointIdentity (new X509Certificate2 ("Test/Resources/test.pfx", "mono")); + new X509CertificateEndpointIdentity (new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono")); return new EndpointAddress (new Uri (uri), identity); } @@ -161,7 +163,7 @@ namespace MonoTests.System.ServiceModel.Channels new BindingParameterCollection (); ServiceCredentials cred = new ServiceCredentials (); cred.ServiceCertificate.Certificate = - new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); IServiceBehavior sb = cred; sb.AddBindingParameters (null, null, null, bpl); IChannelListener listener = rb.BuildChannelListener (bpl); @@ -239,7 +241,7 @@ namespace MonoTests.System.ServiceModel.Channels return null; }); ClientCredentials cred = new ClientCredentials (); - cred.ServiceCertificate.DefaultCertificate = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + cred.ServiceCertificate.DefaultCertificate = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); BindingParameterCollection parameters = new BindingParameterCollection (); parameters.Add (cred); @@ -486,7 +488,7 @@ namespace MonoTests.System.ServiceModel.Channels new BindingParameterCollection (); ServiceCredentials cred = new ServiceCredentials (); cred.ServiceCertificate.Certificate = - new X509Certificate2 ("Test/Resources/test.cer"); + new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.cer")); IServiceBehavior sb = cred; sb.AddBindingParameters (null, null, null, bpl); IChannelListener listener = rb.BuildChannelListener (bpl); @@ -551,7 +553,7 @@ Console.Error.WriteLine ("Processing a reply."); public void FullRequest () { EndpointIdentity identity = - new X509CertificateEndpointIdentity (new X509Certificate2 ("Test/Resources/test.pfx", "mono")); + new X509CertificateEndpointIdentity (new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono")); EndpointAddress address = new EndpointAddress (new Uri ("stream:dummy"), identity); diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/AddressHeaderCollectionElementTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/AddressHeaderCollectionElementTest.cs index 122fafed41..76d3ad5458 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/AddressHeaderCollectionElementTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/AddressHeaderCollectionElementTest.cs @@ -34,6 +34,8 @@ using System.ServiceModel.Configuration; using System.ServiceModel.Channels; using System.Configuration; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Configuration { [TestFixture] @@ -41,7 +43,7 @@ namespace MonoTests.System.ServiceModel.Configuration { [Test] public void ReadConfiguration () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/client.endpoint").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/client.endpoint")).GetSectionGroup ("system.serviceModel"); AddressHeaderCollection col = config.Client.Endpoints [0].Headers.Headers; Assert.AreEqual (2, col.Count, "count"); diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/BindingsSectionTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/BindingsSectionTest.cs index 93118ecfa0..8fc2eb0d8d 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/BindingsSectionTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/BindingsSectionTest.cs @@ -34,6 +34,8 @@ using System.ServiceModel.Configuration; using System.ServiceModel.Channels; using System.Configuration; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Configuration { [TestFixture] @@ -44,7 +46,7 @@ namespace MonoTests.System.ServiceModel.Configuration [Category("NotWorking")] [Ignore ("fails under .NET; I never bothered to fix the test")] public void UserConfiguration () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/userBinding").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/userBinding")).GetSectionGroup ("system.serviceModel"); BindingsSection section = config.Bindings; diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/CustomBindingElementTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/CustomBindingElementTest.cs index cc531afd3f..43fdecfeb0 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/CustomBindingElementTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/CustomBindingElementTest.cs @@ -37,13 +37,15 @@ using System.Net; using System.ServiceModel; using System.Net.Security; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Configuration { [TestFixture] public class CustomBindingElementTest { CustomBindingCollectionElement OpenConfig () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/customBinding").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/customBinding")).GetSectionGroup ("system.serviceModel"); Assert.AreEqual (7, config.Bindings.CustomBinding.Bindings.Count, "CustomBinding count"); return config.Bindings.CustomBinding; } diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/EndpointBehaviorElementTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/EndpointBehaviorElementTest.cs index 5055ee589c..106fc5c00f 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/EndpointBehaviorElementTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/EndpointBehaviorElementTest.cs @@ -37,13 +37,15 @@ using System.Security.Cryptography.X509Certificates; using System.ServiceModel.Security; using System.Security.Principal; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Configuration { [TestFixture] public class EndpointBehaviorElementTest { EndpointBehaviorElement OpenConfig () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/endpointBehaviors").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/endpointBehaviors")).GetSectionGroup ("system.serviceModel"); return config.Behaviors.EndpointBehaviors [0]; } diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ExtensionsSectionTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ExtensionsSectionTest.cs index 7d968dc714..4024830433 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ExtensionsSectionTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ExtensionsSectionTest.cs @@ -33,6 +33,8 @@ using System.ServiceModel.Configuration; using System.Configuration; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Configuration { [TestFixture] @@ -63,7 +65,7 @@ namespace MonoTests.System.ServiceModel.Configuration [Test] public void BindingExtensions () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/extensions").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/extensions")).GetSectionGroup ("system.serviceModel"); Assert.AreEqual (typeof (BasicHttpBindingCollectionElement).AssemblyQualifiedName, config.Extensions.BindingExtensions ["basicHttpBinding"].Type, "baseHttpBinding"); Assert.AreEqual (typeof (NetTcpBindingCollectionElement).AssemblyQualifiedName, config.Extensions.BindingExtensions ["netTcpBinding"].Type, "baseHttpBinding"); @@ -74,7 +76,7 @@ namespace MonoTests.System.ServiceModel.Configuration [Test] public void BehaviorExtensions () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/extensions").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/extensions")).GetSectionGroup ("system.serviceModel"); Assert.AreEqual (typeof (ServiceAuthorizationElement).AssemblyQualifiedName, config.Extensions.BehaviorExtensions ["serviceAuthorization"].Type, "serviceAuthorization"); Assert.AreEqual ("MyBehaviorElement", config.Extensions.BehaviorExtensions ["behaviorExtensions1"].Type, "MyBehaviorElement"); @@ -83,7 +85,7 @@ namespace MonoTests.System.ServiceModel.Configuration [Test] public void BindingElementExtensions () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/extensions").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/extensions")).GetSectionGroup ("system.serviceModel"); Assert.AreEqual (typeof (BinaryMessageEncodingElement).AssemblyQualifiedName, config.Extensions.BindingElementExtensions ["binaryMessageEncoding"].Type, "binaryMessageEncoding"); Assert.AreEqual ("MyBindingElementElement", config.Extensions.BindingElementExtensions ["bindingElementExtensions1"].Type, "MyBindingElementElement"); diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/MetadataElementTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/MetadataElementTest.cs index 818dfb1aa6..3f93ae2c66 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/MetadataElementTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/MetadataElementTest.cs @@ -35,13 +35,15 @@ using System.Configuration; using System.ServiceModel.Channels; using System.ServiceModel.Description; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Configuration { [TestFixture] public class MetadataElementTest { ServiceModelSectionGroup OpenConfig (string name) { - return (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/" + name).GetSectionGroup ("system.serviceModel"); + return (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/" + name)).GetSectionGroup ("system.serviceModel"); } [Test] diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ServiceBehaviorElementTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ServiceBehaviorElementTest.cs index 2b8be0ebfd..c285f9636d 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ServiceBehaviorElementTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ServiceBehaviorElementTest.cs @@ -37,13 +37,15 @@ using System.ServiceModel; using System.Security.Cryptography.X509Certificates; using System.ServiceModel.Security; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Configuration { [TestFixture] public class ServiceBehaviorElementTest { ServiceBehaviorElement OpenConfig () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/serviceBehaviors").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/serviceBehaviors")).GetSectionGroup ("system.serviceModel"); return config.Behaviors.ServiceBehaviors [0]; } diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ServiceElementTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ServiceElementTest.cs index 096401772f..1f9a229b91 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ServiceElementTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ServiceElementTest.cs @@ -33,6 +33,8 @@ using NUnit.Framework; using System.ServiceModel.Configuration; using System.Configuration; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Configuration { [TestFixture] @@ -40,7 +42,7 @@ namespace MonoTests.System.ServiceModel.Configuration { [Test] public void ReadConfiguration () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/service").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/service")).GetSectionGroup ("system.serviceModel"); ServiceElement service = config.Services.Services [0]; Assert.AreEqual ("ServiceType", service.Name, "Name"); @@ -76,7 +78,7 @@ namespace MonoTests.System.ServiceModel.Configuration [Test] public void ServiceEndpointCollection () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/service").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/service")).GetSectionGroup ("system.serviceModel"); ServiceElement service = config.Services.Services [1]; Assert.AreEqual (3, service.Endpoints.Count, "Count"); diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ServiceModelSectionGroupTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ServiceModelSectionGroupTest.cs index ee0bab450d..3da18639fa 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ServiceModelSectionGroupTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/ServiceModelSectionGroupTest.cs @@ -40,6 +40,8 @@ using NUnit.Framework; using ConfigurationType = System.Configuration.Configuration; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Configuration { [TestFixture] @@ -57,7 +59,7 @@ namespace MonoTests.System.ServiceModel.Configuration [Test] public void GetSectionGroup () { - ServiceModelSectionGroup g = GetConfig ("Test/config/test1"); + ServiceModelSectionGroup g = GetConfig (TestResourceHelper.GetFullPathOfResource ("Test/config/test1")); Assert.IsNotNull (g.Bindings, "bindings"); Assert.IsNotNull (g.Client, "client"); Assert.IsNotNull (g.Services, "services"); @@ -68,7 +70,7 @@ namespace MonoTests.System.ServiceModel.Configuration [Category ("NotWorking")] [Ignore ("fails under .NET; I never bothered to fix the test")] public void BindingCollections () { - ServiceModelSectionGroup g = GetConfig ("Test/config/test1.config"); + ServiceModelSectionGroup g = GetConfig (TestResourceHelper.GetFullPathOfResource ("Test/config/test1.config")); List coll = g.Bindings.BindingCollections; Assert.AreEqual (20, coll.Count, "Count"); } @@ -76,7 +78,7 @@ namespace MonoTests.System.ServiceModel.Configuration [Test] public void Endpoints () { - ServiceModelSectionGroup g = GetConfig ("Test/config/test1"); + ServiceModelSectionGroup g = GetConfig (TestResourceHelper.GetFullPathOfResource ("Test/config/test1")); ChannelEndpointElementCollection col = g.Client.Endpoints; Assert.AreEqual (1, col.Count, "initial count"); ChannelEndpointElement e = col [0]; diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/StandardBindingElementCollectionTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/StandardBindingElementCollectionTest.cs index 66296f9c1c..96f1461912 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/StandardBindingElementCollectionTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Configuration/StandardBindingElementCollectionTest.cs @@ -35,6 +35,8 @@ using System.ServiceModel.Security; using System.ServiceModel; using System.Net.Security; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Configuration { [TestFixture] @@ -42,7 +44,7 @@ namespace MonoTests.System.ServiceModel.Configuration { [Test] public void BasicHttpBinding () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/basicHttpBinding").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/basicHttpBinding")).GetSectionGroup ("system.serviceModel"); BasicHttpBindingCollectionElement basicHttpBinding = config.Bindings.BasicHttpBinding; Assert.AreEqual (2, basicHttpBinding.Bindings.Count, "count"); @@ -55,7 +57,7 @@ namespace MonoTests.System.ServiceModel.Configuration [Test] public void NetTcpBinding () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/netTcpBinding").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/netTcpBinding")).GetSectionGroup ("system.serviceModel"); NetTcpBindingCollectionElement netTcpBinding = config.Bindings.NetTcpBinding; Assert.AreEqual (1, netTcpBinding.Bindings.Count, "count"); @@ -71,7 +73,7 @@ namespace MonoTests.System.ServiceModel.Configuration [Test] public void WSHttpBinding () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/wsHttpBinding").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/wsHttpBinding")).GetSectionGroup ("system.serviceModel"); WSHttpBindingCollectionElement wsHttpBinding = config.Bindings.WSHttpBinding; Assert.AreEqual (1, wsHttpBinding.Bindings.Count, "count"); diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/MetadataResolverTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/MetadataResolverTest.cs index 4e9f9112bc..348294ebde 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/MetadataResolverTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/MetadataResolverTest.cs @@ -52,7 +52,7 @@ namespace MonoTests.System.ServiceModel.Description IAsyncResult current_request; int remaining, port; - static readonly string mex = File.ReadAllText ("Test/System.ServiceModel.Description/dump.xml"); + static readonly string mex = File.ReadAllText (TestResourceHelper.GetFullPathOfResource ("Test/Resources/dump.xml")); [SetUp] public void StartupServer () diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/MetadataSetTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/MetadataSetTest.cs index 6e4ed7596a..01e78a5a57 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/MetadataSetTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/MetadataSetTest.cs @@ -37,6 +37,8 @@ using System.Xml; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Description { [TestFixture] @@ -52,7 +54,7 @@ namespace MonoTests.System.ServiceModel.Description [Test] public void ReadFrom () { - XmlReader xr = XmlTextReader.Create ("Test/XmlFiles/one.xml"); + XmlReader xr = XmlTextReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/Resources/one.xml")); var metadata = MetadataSet.ReadFrom (xr); Assert.AreEqual (5, metadata.MetadataSections.Count, "#1"); Assert.AreEqual (2, metadata.MetadataSections.Where (m => m.Dialect == MetadataSection.ServiceDescriptionDialect).Count (), "#2"); diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/WsdlImporterTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/WsdlImporterTest.cs index 875d5f8a1d..d4de4b753f 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/WsdlImporterTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/WsdlImporterTest.cs @@ -45,6 +45,8 @@ using NUnit.Framework; using WSServiceDescription = System.Web.Services.Description.ServiceDescription; using SMBinding = System.ServiceModel.Channels.Binding; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Description { [TestFixture] @@ -58,7 +60,7 @@ namespace MonoTests.System.ServiceModel.Description { XmlReaderSettings xs = new XmlReaderSettings (); xs.IgnoreWhitespace = true; - xtr = XmlTextReader.Create ("Test/System.ServiceModel.Description/dump.xml", xs); + xtr = XmlTextReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/Resources/dump.xml"), xs); xtr.Read (); @@ -188,7 +190,7 @@ namespace MonoTests.System.ServiceModel.Description { XmlReaderSettings xs = new XmlReaderSettings (); xs.IgnoreWhitespace = true; - xtr = XmlTextReader.Create ("Test/System.ServiceModel.Description/dump.xml", xs); + xtr = XmlTextReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/Resources/dump.xml"), xs); xtr.Read (); @@ -473,7 +475,7 @@ namespace MonoTests.System.ServiceModel.Description XmlReaderSettings xs = new XmlReaderSettings (); xs.IgnoreWhitespace = true; //xtr = XmlTextReader.Create ("Test/System.ServiceModel.Description/test2a.xml", xs); - xtr = XmlTextReader.Create ("Test/System.ServiceModel.Description/dump.xml", xs); + xtr = XmlTextReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/Resources/dump.xml"), xs); xtr.Read (); @@ -546,7 +548,7 @@ namespace MonoTests.System.ServiceModel.Description [Ignore ("Until make dist gets fixed I won't enable any of new external-source-dependent tests")] public void ImportMethodWithArrayOfint () { - var ms = GetMetadataSetFromWsdl ("Test/Resources/xml/service1.wsdl"); + var ms = GetMetadataSetFromWsdl (TestResourceHelper.GetFullPathOfResource ("Test/Resources/xml/service1.wsdl")); var imp = new WsdlImporter (ms); var cg = new ServiceContractGenerator (); var cd = imp.ImportAllContracts () [0]; @@ -566,7 +568,7 @@ namespace MonoTests.System.ServiceModel.Description var mset = new MetadataSet (); WSServiceDescription sd = null; - sd = WSServiceDescription.Read (XmlReader.Create ("Test/XmlFiles/670945.wsdl")); + sd = WSServiceDescription.Read (XmlReader.Create (TestResourceHelper.GetFullPathOfResource (TestResourceHelper.GetFullPathOfResource ("Test/Resources/670945.wsdl")))); mset.MetadataSections.Add (new MetadataSection () { Dialect = MetadataSection.ServiceDescriptionDialect, Metadata = sd }); @@ -581,7 +583,7 @@ namespace MonoTests.System.ServiceModel.Description [Ignore ("FIXME: Using external source")] public void ImportMethodWithDateTime () { - var ms = GetMetadataSetFromWsdl ("Test/Resources/DateTime.wsdl"); + var ms = GetMetadataSetFromWsdl (TestResourceHelper.GetFullPathOfResource ("Test/Resources/DateTime.wsdl")); var imp = new WsdlImporter (ms); var cg = new ServiceContractGenerator (); var cd = imp.ImportAllContracts () [0]; diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security.Tokens/IssuedSecurityTokenProviderTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security.Tokens/IssuedSecurityTokenProviderTest.cs index 55072eac96..785fbdccf7 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security.Tokens/IssuedSecurityTokenProviderTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security.Tokens/IssuedSecurityTokenProviderTest.cs @@ -44,6 +44,8 @@ using NUnit.Framework; using MonoTests.System.ServiceModel.Channels; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Security.Tokens { [TestFixture] @@ -303,7 +305,7 @@ namespace MonoTests.System.ServiceModel.Security.Tokens //* XmlDocument doc = new XmlDocument (); doc.LoadXml ("RESPONSE"); - X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); SignedXml sxml = new SignedXml (doc); MemoryStream ms = new MemoryStream (new byte [] {1, 2, 3}); sxml.AddReference (new Reference (ms)); @@ -466,7 +468,7 @@ Console.Error.Flush (); PaddingMode mode = PaddingMode.PKCS7; // not sure which is correct ... ANSIX923, ISO10126, PKCS7, Zeros, None. EncryptedXml encXml = new EncryptedXml (doc); encXml.Padding = mode; - X509Certificate2 cert2 = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + X509Certificate2 cert2 = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable); nsmgr.AddNamespace ("s", "http://www.w3.org/2003/05/soap-envelope"); nsmgr.AddNamespace ("c", "http://schemas.xmlsoap.org/ws/2005/02/sc"); @@ -603,7 +605,7 @@ Console.Error.WriteLine ("============= Decrypted Body End ==========="); { return new EndpointAddress (new Uri (uri), new X509CertificateEndpointIdentity ( - new X509Certificate2 ("Test/Resources/test.pfx", "mono"))); + new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"))); } IssuedSecurityTokenProvider SetupProvider (Binding binding) diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security.Tokens/WrappedKeySecurityTokenTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security.Tokens/WrappedKeySecurityTokenTest.cs index 535e97eb69..3c5d55251d 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security.Tokens/WrappedKeySecurityTokenTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security.Tokens/WrappedKeySecurityTokenTest.cs @@ -38,13 +38,15 @@ using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel { [TestFixture] public class WrappedKeySecurityTokenTest { static readonly X509Certificate2 cert = - new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); WrappedKeySecurityToken GetReferent () { diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security.Tokens/X509SecurityTokenParametersTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security.Tokens/X509SecurityTokenParametersTest.cs index b926e39268..ff920095f6 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security.Tokens/X509SecurityTokenParametersTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security.Tokens/X509SecurityTokenParametersTest.cs @@ -38,6 +38,8 @@ using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel { [TestFixture] @@ -109,7 +111,7 @@ namespace MonoTests.System.ServiceModel MyX509SecurityTokenParameters p = new MyX509SecurityTokenParameters (); X509SecurityToken token = new X509SecurityToken ( - new X509Certificate2 ("Test/Resources/test.pfx", "mono")); + new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono")); clause = p.CallCreateKeyIdentifierClause ( token, SecurityTokenReferenceStyle.External); Assert.AreEqual (typeof (X509IssuerSerialKeyIdentifierClause), clause.GetType (), "#1"); diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/SecurityMessagePropertyTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/SecurityMessagePropertyTest.cs index c5ccb23ed4..560c3abf94 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/SecurityMessagePropertyTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/SecurityMessagePropertyTest.cs @@ -50,8 +50,8 @@ namespace MonoTests.System.ServiceModel.Security [TestFixture] public class SecurityMessagePropertyTest { - static X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); - static X509Certificate2 cert2 = new X509Certificate2 ("Test/Resources/test2.pfx", "mono"); + static X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); + static X509Certificate2 cert2 = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test2.pfx"), "mono"); [ServiceContract] public interface ICalc diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/ServiceCredentialsSecurityTokenManagerTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/ServiceCredentialsSecurityTokenManagerTest.cs index b599bd1dd3..3437d78ae8 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/ServiceCredentialsSecurityTokenManagerTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/ServiceCredentialsSecurityTokenManagerTest.cs @@ -41,6 +41,8 @@ using NUnit.Framework; using ReqType = System.ServiceModel.Security.Tokens.ServiceModelSecurityTokenRequirement; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Security { [TestFixture] @@ -253,7 +255,7 @@ namespace MonoTests.System.ServiceModel.Security SecurityTokenRequirement r = new RecipientServiceModelSecurityTokenRequirement (); r.TokenType = SecurityTokenTypes.X509Certificate; - X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.cer"); + X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.cer")); def_c.ServiceCredentials.ServiceCertificate.Certificate = cert; def_c.CreateSecurityTokenProvider (r); } @@ -265,7 +267,7 @@ namespace MonoTests.System.ServiceModel.Security new RecipientServiceModelSecurityTokenRequirement (); r.TokenType = SecurityTokenTypes.X509Certificate; def_c.ServiceCredentials.ServiceCertificate.Certificate = - new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); X509SecurityTokenProvider p = def_c.CreateSecurityTokenProvider (r) as X509SecurityTokenProvider; @@ -282,7 +284,7 @@ namespace MonoTests.System.ServiceModel.Security r.KeyUsage = SecurityKeyUsage.Exchange; // ClientCredential is somehow required ... def_c.ServiceCredentials.ServiceCertificate.Certificate = - new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); X509SecurityTokenProvider p = def_c.CreateSecurityTokenProvider (r) diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/WSSecurityTokenSerializerTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/WSSecurityTokenSerializerTest.cs index babc52155e..b045197f27 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/WSSecurityTokenSerializerTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/WSSecurityTokenSerializerTest.cs @@ -42,6 +42,8 @@ using System.IdentityModel.Tokens; using System.Xml; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel.Security { [TestFixture] @@ -50,7 +52,7 @@ namespace MonoTests.System.ServiceModel.Security const string wssNS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; const string wsuNS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"; - static X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); + static X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); const string derived_key_token1 = @" @@ -168,7 +170,7 @@ namespace MonoTests.System.ServiceModel.Security StringWriter sw = new StringWriter (); XmlElement xml = new XmlDocument ().CreateElement ("foo"); - SecurityToken token = new X509SecurityToken (new X509Certificate2 ("Test/Resources/test.pfx", "mono")); + SecurityToken token = new X509SecurityToken (new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono")); SecurityKeyIdentifierClause intref = token.CreateKeyIdentifierClause (); SecurityKeyIdentifierClause extref = diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel/BasicHttpBindingTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel/BasicHttpBindingTest.cs index c6c787ed6b..d0507d7b33 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel/BasicHttpBindingTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel/BasicHttpBindingTest.cs @@ -38,6 +38,8 @@ using System.ServiceModel.Configuration; using System.Configuration; using System.Text; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel { [TestFixture] @@ -316,7 +318,7 @@ namespace MonoTests.System.ServiceModel private BasicHttpBinding CreateBindingFromConfig () { - ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration ("Test/config/basicHttpBinding").GetSectionGroup ("system.serviceModel"); + ServiceModelSectionGroup config = (ServiceModelSectionGroup) ConfigurationManager.OpenExeConfiguration (TestResourceHelper.GetFullPathOfResource ("Test/config/basicHttpBinding")).GetSectionGroup ("system.serviceModel"); BindingsSection section = (BindingsSection) config.Bindings; BasicHttpBindingElement el = section.BasicHttpBinding.Bindings ["BasicHttpBinding2_Service"]; diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel/ClientCredentialsSecurityTokenManagerTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel/ClientCredentialsSecurityTokenManagerTest.cs index db1b1f145a..c1838d3a0e 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel/ClientCredentialsSecurityTokenManagerTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel/ClientCredentialsSecurityTokenManagerTest.cs @@ -51,8 +51,8 @@ namespace MonoTests.System.ServiceModel public class ClientCredentialsSecurityTokenManagerTest { MyManager def_c; - X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); - X509Certificate2 certpub = new X509Certificate2 ("Test/Resources/test.cer"); + X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.pfx"), "mono"); + X509Certificate2 certpub = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.cer")); [SetUp] public void Initialize () diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel/EndpointAddressTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel/EndpointAddressTest.cs index 674626cb65..6a00dabd19 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel/EndpointAddressTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel/EndpointAddressTest.cs @@ -40,6 +40,8 @@ using System.Xml.Schema; using System.Xml.Serialization; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel { [TestFixture] @@ -371,7 +373,7 @@ namespace MonoTests.System.ServiceModel [Test] public void WriteToWSA10 () { - X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.cer"); + X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.cer")); EndpointAddress a = new EndpointAddress ( new Uri ("http://localhost:8080"), new X509CertificateEndpointIdentity (cert)); @@ -387,7 +389,7 @@ namespace MonoTests.System.ServiceModel [Test] public void WriteContentsToWSA10 () { - X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.cer"); + X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.cer")); EndpointAddress a = new EndpointAddress ( new Uri ("http://localhost:8080"), new X509CertificateEndpointIdentity (cert)); diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel/EndpointIdentityTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel/EndpointIdentityTest.cs index 48154dd7ad..d3ce5f05c0 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel/EndpointIdentityTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel/EndpointIdentityTest.cs @@ -36,12 +36,14 @@ using System.ServiceModel; using System.Xml; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.ServiceModel { [TestFixture] public class EndpointIdentityTest { - static readonly X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.cer"); + static readonly X509Certificate2 cert = new X509Certificate2 (TestResourceHelper.GetFullPathOfResource ("Test/Resources/test.cer")); [Test] public void CreateX509CertificateIdentity () diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel/SynchronizedCollectionTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel/SynchronizedCollectionTest.cs new file mode 100644 index 0000000000..b3577bfad6 --- /dev/null +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel/SynchronizedCollectionTest.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Threading; +using NUnit.Framework; + +namespace MonoTests.System.ServiceModel +{ + [TestFixture] + public class SynchronizedCollectionTest + { + [Test] // from https://bugzilla.xamarin.com/show_bug.cgi?id=43447 + public void TestConcurrentAddRemove () + { + var c = new SynchronizedCollection (); + for (int i = 0; i < 10000; i++) + { + c.Add(i); + } + + var wait = new CountdownEvent (2); + ThreadStart add = () => + { + wait.Signal (); + wait.Wait (); + for (int i = 10000; i < 20000; i++) + { + c.Add (i); + } + }; + + ThreadStart remove = () => + { + wait.Signal (); + wait.Wait (); + for(int i = 9999; i >= 0; i--) + { + c.Remove (i); + } + }; + + var t1 = new Thread (add); + var t2 = new Thread (remove); + t1.Start (); + t2.Start (); + + t1.Join (); + t2.Join (); + } + } +} diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel/SynchronizedReadOnlyCollectionTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel/SynchronizedReadOnlyCollectionTest.cs index 2867a63e6b..ad526d4ead 100644 --- a/mcs/class/System.ServiceModel/Test/System.ServiceModel/SynchronizedReadOnlyCollectionTest.cs +++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel/SynchronizedReadOnlyCollectionTest.cs @@ -37,7 +37,7 @@ namespace MonoTests.System.ServiceModel Assert.IsFalse (((IList) d).Contains (null)); } - [Test, ExpectedException (typeof (ArgumentException))] + [Test] public void TestICollectionCopyTo () { SynchronizedReadOnlyCollection c = new SynchronizedReadOnlyCollection (); diff --git a/mcs/class/System.ServiceModel/fixup-config.xml b/mcs/class/System.ServiceModel/fixup-config.xml deleted file mode 100644 index 0ba3a0da59..0000000000 --- a/mcs/class/System.ServiceModel/fixup-config.xml +++ /dev/null @@ -1,11 +0,0 @@ - -
-
-
-
-
-
-
-
- - diff --git a/mcs/class/System.ServiceModel/fixup-config2.xml b/mcs/class/System.ServiceModel/fixup-config2.xml deleted file mode 100644 index dd0e79b6a6..0000000000 --- a/mcs/class/System.ServiceModel/fixup-config2.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/mcs/class/System.ServiceModel/mobile_System.ServiceModel.dll.sources b/mcs/class/System.ServiceModel/mobile_System.ServiceModel.dll.sources index f16d0b952e..6c8f6fa46c 100644 --- a/mcs/class/System.ServiceModel/mobile_System.ServiceModel.dll.sources +++ b/mcs/class/System.ServiceModel/mobile_System.ServiceModel.dll.sources @@ -1,6 +1,7 @@ ../../build/common/Consts.cs ../../build/common/MonoTODOAttribute.cs ../../build/common/SR.cs +ReferenceSources/SR.cs Assembly/AssemblyInfo.cs Mono.CodeGeneration/CodeAdd.cs Mono.CodeGeneration/CodeAnd.cs @@ -50,10 +51,10 @@ Mono.CodeGeneration/CodeWhen.cs Mono.CodeGeneration/CodeWhile.cs Mono.CodeGeneration/CodeWriter.cs Mono.CodeGeneration/Exp.cs -System.Collections.Generic/KeyedByTypeCollection.cs -System.Collections.Generic/SynchronizedCollection.cs -System.Collections.Generic/SynchronizedKeyedCollection.cs -System.Collections.Generic/SynchronizedReadOnlyCollection.cs +../referencesource/System.ServiceModel/System/ServiceModel/KeyedByTypeCollection.cs +../referencesource/System.ServiceModel/System/ServiceModel/SynchronizedCollection.cs +../referencesource/System.ServiceModel/System/ServiceModel/SynchronizedKeyedCollection.cs +../referencesource/System.ServiceModel/System/ServiceModel/SynchronizedReadOnlyCollection.cs System.ServiceModel.Channels/AddressHeader.cs System.ServiceModel.Channels/AddressHeaderCollection.cs System.ServiceModel.Channels/AddressingVersion.cs diff --git a/mcs/class/System.Web.Services/Makefile b/mcs/class/System.Web.Services/Makefile index 308990590f..6df8b1f470 100644 --- a/mcs/class/System.Web.Services/Makefile +++ b/mcs/class/System.Web.Services/Makefile @@ -44,11 +44,15 @@ ifndef NO_THREAD_SUSPEND_RESUME TEST_MCS_FLAGS += -d:MONO_FEATURE_THREAD_SUSPEND_RESUME endif +TEST_RESOURCE_FILES = $(wildcard Test/System.Web.Services.Description/*.wsdl) + +TEST_MCS_FLAGS += $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) + EXTRA_DISTFILES = \ System.Web.Services.Description/web-reference.xsd \ System.Web.Services.Description/wsdl-1.1.xsd \ System.Web.Services.Description/wsdl-1.1-soap.xsd \ System.Web.Services.Description/wsdl.genxs \ - Test/System.Web.Services.Description/*.wsdl + $(TEST_RESOURCE_FILES) include ../../build/library.make diff --git a/mcs/class/System.Web.Services/System.Web.Services_test.dll.sources b/mcs/class/System.Web.Services/System.Web.Services_test.dll.sources index 8d6ab724f1..4c8731a7b4 100644 --- a/mcs/class/System.Web.Services/System.Web.Services_test.dll.sources +++ b/mcs/class/System.Web.Services/System.Web.Services_test.dll.sources @@ -35,3 +35,4 @@ System.Web.Services.Protocols/SoapHttpClientProtocolTest.cs System.Web.Services.Protocols/WebClientProtocolTest.cs System.Web.Services.Protocols/SoapServerTypeTest.cs ../../test-helpers/SocketResponder.cs +../../test-helpers/TestResourceHelper.cs diff --git a/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ServiceDescriptionImporterTest.cs b/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ServiceDescriptionImporterTest.cs index 41f594f64f..6d4dc1a8fb 100644 --- a/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ServiceDescriptionImporterTest.cs +++ b/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ServiceDescriptionImporterTest.cs @@ -17,6 +17,8 @@ using System.CodeDom.Compiler; using Microsoft.CSharp; using System.Web.Services.Description; +using MonoTests.Helpers; + namespace MonoTests.System.Web.Services.Description { [TestFixture] @@ -68,7 +70,7 @@ namespace MonoTests.System.Web.Services.Description public void GenerateNullableTypes () { CodeNamespace cns = GenerateCodeFromWsdl ( - ServiceDescription.Read ("Test/System.Web.Services.Description/test2.wsdl")); + ServiceDescription.Read (TestResourceHelper.GetFullPathOfResource ("Test/System.Web.Services.Description/test2.wsdl"))); CodeTypeDeclaration td = FindTypeFrom (cns, "Service"); foreach (CodeTypeMember member in td.Members) { CodeMemberMethod method = member as CodeMemberMethod; @@ -101,7 +103,7 @@ namespace MonoTests.System.Web.Services.Description { ServiceDescriptionImporter imp = new ServiceDescriptionImporter (); - imp.AddServiceDescription (ServiceDescription.Read ("Test/System.Web.Services.Description/test3.wsdl"), null, null); + imp.AddServiceDescription (ServiceDescription.Read (TestResourceHelper.GetFullPathOfResource ("Test/System.Web.Services.Description/test3.wsdl")), null, null); CodeNamespace cns = new CodeNamespace (); CodeCompileUnit ccu = new CodeCompileUnit (); ccu.Namespaces.Add (cns); diff --git a/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ServiceDescriptionTest.cs b/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ServiceDescriptionTest.cs index 1aeb13d19f..34d5343747 100644 --- a/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ServiceDescriptionTest.cs +++ b/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ServiceDescriptionTest.cs @@ -18,6 +18,8 @@ using System.Xml; using System.Xml.Serialization; using System.Collections; +using MonoTests.Helpers; + namespace MonoTests.System.Web.Services.Description { [TestFixture] @@ -52,14 +54,14 @@ namespace MonoTests.System.Web.Services.Description public void ReadAndRetrievalUrl () { Assert.AreEqual (String.Empty, new ServiceDescription ().RetrievalUrl, "#1"); - ServiceDescription sd = ServiceDescription.Read ("Test/System.Web.Services.Description/test2.wsdl"); + ServiceDescription sd = ServiceDescription.Read (TestResourceHelper.GetFullPathOfResource ("Test/System.Web.Services.Description/test2.wsdl")); Assert.AreEqual (String.Empty, sd.RetrievalUrl, "#2"); } [Test] public void Namespaces () { - FileStream fs = new FileStream ("Test/System.Web.Services.Description/test.wsdl", FileMode.Open, FileAccess.Read); + FileStream fs = new FileStream (TestResourceHelper.GetFullPathOfResource ("Test/System.Web.Services.Description/test.wsdl"), FileMode.Open, FileAccess.Read); XmlTextReader xtr = new XmlTextReader (fs); ServiceDescription sd = ServiceDescription.Read (xtr); @@ -84,7 +86,7 @@ namespace MonoTests.System.Web.Services.Description [Test] public void ExtensibleAttributes () { - FileStream fs = new FileStream ("Test/System.Web.Services.Description/test.wsdl", FileMode.Open, FileAccess.Read); + FileStream fs = new FileStream (TestResourceHelper.GetFullPathOfResource ("Test/System.Web.Services.Description/test.wsdl"), FileMode.Open, FileAccess.Read); XmlTextReader xtr = new XmlTextReader(fs); ServiceDescription sd = ServiceDescription.Read(xtr); @@ -105,7 +107,7 @@ namespace MonoTests.System.Web.Services.Description [Test] public void Extensions () { - FileStream fs = new FileStream("Test/System.Web.Services.Description/test.wsdl", FileMode.Open, FileAccess.Read); + FileStream fs = new FileStream(TestResourceHelper.GetFullPathOfResource ("Test/System.Web.Services.Description/test.wsdl"), FileMode.Open, FileAccess.Read); XmlTextReader xtr = new XmlTextReader(fs); ServiceDescription sd = ServiceDescription.Read(xtr); diff --git a/mcs/class/System.Web.Services/Test/System.Web.Services.Description/WebServicesInteroperabilityTest.cs b/mcs/class/System.Web.Services/Test/System.Web.Services.Description/WebServicesInteroperabilityTest.cs index 5aaaedebc3..53ba343c3b 100644 --- a/mcs/class/System.Web.Services/Test/System.Web.Services.Description/WebServicesInteroperabilityTest.cs +++ b/mcs/class/System.Web.Services/Test/System.Web.Services.Description/WebServicesInteroperabilityTest.cs @@ -20,6 +20,8 @@ using System.Xml.Schema; using System.Xml.Serialization; using System.Collections; +using MonoTests.Helpers; + namespace MonoTests.System.Web.Services.Description { [TestFixture] @@ -31,7 +33,7 @@ namespace MonoTests.System.Web.Services.Description BasicProfileViolationCollection bc = new BasicProfileViolationCollection (); WebServicesInteroperability.CheckConformance ( WsiProfiles.BasicProfile1_1, - ServiceDescription.Read ("Test/System.Web.Services.Description/check-import.wsdl"), bc); + ServiceDescription.Read (TestResourceHelper.GetFullPathOfResource ("Test/System.Web.Services.Description/check-import.wsdl")), bc); } [Test] @@ -40,7 +42,7 @@ namespace MonoTests.System.Web.Services.Description BasicProfileViolationCollection bc = new BasicProfileViolationCollection (); WebServicesInteroperability.CheckConformance ( WsiProfiles.BasicProfile1_1, - ServiceDescription.Read ("Test/System.Web.Services.Description/443095.wsdl"), bc); + ServiceDescription.Read (TestResourceHelper.GetFullPathOfResource ("Test/System.Web.Services.Description/443095.wsdl")), bc); } [Test] @@ -49,7 +51,7 @@ namespace MonoTests.System.Web.Services.Description BasicProfileViolationCollection bc = new BasicProfileViolationCollection (); WebServicesInteroperability.CheckConformance ( WsiProfiles.BasicProfile1_1, - ServiceDescription.Read ("Test/System.Web.Services.Description/6041.wsdl"), bc); + ServiceDescription.Read (TestResourceHelper.GetFullPathOfResource ("Test/System.Web.Services.Description/6041.wsdl")), bc); } } diff --git a/mcs/class/System.Web.Services/monotouch_System.Web.Services_test.dll.exclude.sources b/mcs/class/System.Web.Services/monotouch_System.Web.Services_test.dll.exclude.sources index b2ec1637bb..54e315b498 100644 --- a/mcs/class/System.Web.Services/monotouch_System.Web.Services_test.dll.exclude.sources +++ b/mcs/class/System.Web.Services/monotouch_System.Web.Services_test.dll.exclude.sources @@ -5,4 +5,3 @@ System.Web.Services.Configuration/SoapExtensionTypeElementTest.cs System.Web.Services.Configuration/TypeElementTest.cs System.Web.Services.Configuration/WsdlHelpGeneratorElementTest.cs System.Web.Services.Configuration/WsiProfilesElementTest.cs - diff --git a/mcs/class/System.Web.Services/monotouch_tv_System.Web.Services_test.dll.exclude.sources b/mcs/class/System.Web.Services/monotouch_tv_System.Web.Services_test.dll.exclude.sources new file mode 100644 index 0000000000..caa96b23b9 --- /dev/null +++ b/mcs/class/System.Web.Services/monotouch_tv_System.Web.Services_test.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_System.Web.Services_test.dll.exclude.sources diff --git a/mcs/class/System.Web.Services/monotouch_watch_System.Web.Services_test.dll.exclude.sources b/mcs/class/System.Web.Services/monotouch_watch_System.Web.Services_test.dll.exclude.sources new file mode 100644 index 0000000000..caa96b23b9 --- /dev/null +++ b/mcs/class/System.Web.Services/monotouch_watch_System.Web.Services_test.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_System.Web.Services_test.dll.exclude.sources diff --git a/mcs/class/System.Web.Services/wasm_System.Web.Services_test.dll.exclude.sources b/mcs/class/System.Web.Services/wasm_System.Web.Services_test.dll.exclude.sources index b2ec1637bb..54e315b498 100644 --- a/mcs/class/System.Web.Services/wasm_System.Web.Services_test.dll.exclude.sources +++ b/mcs/class/System.Web.Services/wasm_System.Web.Services_test.dll.exclude.sources @@ -5,4 +5,3 @@ System.Web.Services.Configuration/SoapExtensionTypeElementTest.cs System.Web.Services.Configuration/TypeElementTest.cs System.Web.Services.Configuration/WsdlHelpGeneratorElementTest.cs System.Web.Services.Configuration/WsiProfilesElementTest.cs - diff --git a/mcs/class/System.Web/Makefile b/mcs/class/System.Web/Makefile index d71f7e957b..3fdfae2dfb 100644 --- a/mcs/class/System.Web/Makefile +++ b/mcs/class/System.Web/Makefile @@ -226,6 +226,10 @@ TEST_RESOURCE_FILES = \ Test/mainsoft/NunitWebResources/HtmlTitleCodeRender_Bug662918.aspx \ Test/mainsoft/NunitWebResources/CheckBoxList_CustomValues.aspx +TEST_RESOURCE_FILES_WITH_DIR = \ + $(wildcard Test/System.Web.Caching/CacheItemPriorityQueueTestData/*.list) \ + $(wildcard Test/System.Web.Caching/CacheItemPriorityQueueTestData/*.tests) + RESOURCE_DEFS = \ TranslationResources,resources/TranslationResources.resx @@ -257,6 +261,7 @@ LIB_MCS_FLAGS = \ TEST_LIB_REFS = SystemWebTestShim TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -doc:$(test_lib:.dll=.xml) -nowarn:219,169,1591 \ $(NUNIT_RESOURCE_FILES:%=/resource:%) \ + $(foreach r, $(TEST_RESOURCE_FILES_WITH_DIR), -resource:$(r),$(r)) \ $(foreach file,$(NUNIT_APP_CODE_FILES),$(shell echo $(file) | sed -e 's;\(.*\)/\(.*\);/resource:\1/\2,App_Code/\2 ;g')) \ $(foreach file,$(NUNIT_APP_GLOBALRESOURCES_FILES),$(shell echo $(file) | sed -e 's;\(.*\)/\(.*\);/resource:\1/\2,App_GlobalResources/\2 ;g')) @@ -265,6 +270,7 @@ EXTRA_DISTFILES = \ $(RESOURCE_FILES_2) \ $(RESOURCE_FILES_1) \ $(TEST_RESOURCE_FILES) \ + $(TEST_RESOURCE_FILES_WITH_DIR) \ $(TEST_APP_CODE_FILES) \ $(TEST_APP_GLOBALRESOURCES_FILES) \ UplevelHelperDefinitions.xml \ @@ -273,9 +279,11 @@ EXTRA_DISTFILES = \ $(shell find Test/standalone-tests/ -name "*.cs" -type f -printf "'%p' " -o -name "*.cs.in" -type f -printf "'%p' ") \ $(shell find Test/standalone/ -path '*/.svn' -prune -o -type f -printf "'%p' ") \ $(shell find Test/tools/ -path '*/.svn' -prune -o -type f -printf "'%p' ") \ - $(shell find Test/System.Web.Caching/CacheItemPriorityQueueTestData/ -name "Sequence*.*" -type f -printf "'%p' ") \ ASPState.sql +# This breaks for strange reason +# $(shell find Test/System.Web.Caching/CacheItemPriorityQueueTestData/ -name "Sequence*.*" -type f -printf "'%p' ") \ + BUILT_SOURCES = System.Web/UplevelHelper.cs include ../../build/library.make diff --git a/mcs/class/System.Web/System.Web_test.dll.sources b/mcs/class/System.Web/System.Web_test.dll.sources index d658e963f1..e377ebeaaf 100644 --- a/mcs/class/System.Web/System.Web_test.dll.sources +++ b/mcs/class/System.Web/System.Web_test.dll.sources @@ -1,4 +1,5 @@ ../../test-helpers/NunitHelpers.cs +../../test-helpers/TestResourceHelper.cs mainsoft/MainsoftWebTest/HtmlAgilityPack/AssemblyInfo.cs mainsoft/MainsoftWebTest/HtmlAgilityPack/crc32.cs mainsoft/MainsoftWebTest/HtmlAgilityPack/Header.cs diff --git a/mcs/class/System.Web/Test/System.Web.Caching/CacheItemPriorityQueueTest.cs b/mcs/class/System.Web/Test/System.Web.Caching/CacheItemPriorityQueueTest.cs index 2ca32b643e..e1e00a76cc 100644 --- a/mcs/class/System.Web/Test/System.Web.Caching/CacheItemPriorityQueueTest.cs +++ b/mcs/class/System.Web/Test/System.Web.Caching/CacheItemPriorityQueueTest.cs @@ -34,14 +34,13 @@ using System.Web.Caching; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Web.Caching { [TestFixture] public partial class CacheItemPriorityQueueTest { - const string DATA_DIR = "CacheItemPriorityQueueTestData"; - static readonly string dataDir; - sealed class TestCacheItem : CacheItem { public Guid Guid; @@ -89,20 +88,12 @@ namespace MonoTests.System.Web.Caching } } - static CacheItemPriorityQueueTest () - { - // Assumes this is compiled into mcs/class/lib//test - string class_dir = Directory.GetParent (Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location)).Parent.Parent.FullName; - string system_web_dir = Path.Combine (class_dir, "System.Web", "Test", "System.Web.Caching"); - dataDir = Path.Combine (system_web_dir, DATA_DIR); - } - void RunTest (string testsFileName, string listFileName) { var queue = new CacheItemPriorityQueue (); var cacheItems = new List (); - string listPath = Path.Combine (dataDir, listFileName); - string testsPath = Path.Combine (dataDir, testsFileName); + string listPath = TestResourceHelper.GetFullPathOfResource ("Test/System.Web.Caching/CacheItemPriorityQueueTestData/" + listFileName); + string testsPath = TestResourceHelper.GetFullPathOfResource ("Test/System.Web.Caching/CacheItemPriorityQueueTestData/" + testsFileName); string line; using (var sr = new StreamReader (listPath, Encoding.UTF8)) { diff --git a/mcs/class/System.Windows.Forms/Makefile b/mcs/class/System.Windows.Forms/Makefile index 5d2577a9c8..fb1f63586f 100644 --- a/mcs/class/System.Windows.Forms/Makefile +++ b/mcs/class/System.Windows.Forms/Makefile @@ -83,15 +83,15 @@ IMAGES_RESOURCES = \ resources/mono.ico \ resources/errorProvider.ico - -TEST_DISTFILES = \ - M.gif \ +TEST_RESOURCE_FILES = \ + Test/resources/M.gif \ Test/resources/a.cur \ Test/resources/32x32.ico \ Test/System.Resources/compat_1_1.resx \ Test/System.Resources/compat_2_0.resx \ - Test/System.Windows.Forms/bitmaps/a.png \ - Test/simple/Program.cs \ + Test/System.Windows.Forms/bitmaps/a.png + +DUMMY_ASSEMBLY_SRC = \ Test/DummyAssembly/AnotherSerializable.cs \ Test/DummyAssembly/Convertable.cs \ Test/DummyAssembly/Properties/AssemblyInfo.cs \ @@ -100,19 +100,19 @@ EXTRA_DISTFILES = \ README System.Windows.Forms.dll.resources \ $(RESX_RESOURCES:.resources=.resx) $(CUR_RESOURCES) $(PREBUILT) \ $(IMAGES_RESOURCES) \ - $(TEST_DISTFILES) + $(TEST_RESOURCE_FILES) \ + $(DUMMY_ASSEMBLY_SRC) \ + Test/simple/Program.cs TEST_LIB_REFS = System.Data System.Drawing Accessibility System System.Xml System.Runtime.Serialization.Formatters.Soap TEST_MCS_FLAGS = \ - -resource:Test/resources/a.cur,a.cur \ - -resource:Test/resources/32x32.ico,32x32.ico \ + $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) \ -nowarn:618,612 -DummyAssembly.dll: - $(CSCOMPILE) /target:library /out:$@ Test/DummyAssembly/AnotherSerializable.cs Test/DummyAssembly/Convertable.cs Test/DummyAssembly/Properties/AssemblyInfo.cs \ - -r:$(topdir)/class/lib/$(PROFILE)/mscorlib.dll -r:$(topdir)/class/lib/$(PROFILE)/System.dll +$(topdir)/class/lib/$(PROFILE)/tests/DummyAssembly.dll: $(DUMMY_ASSEMBLY_SRC) + $(CSCOMPILE) /target:library /out:$@ $^ -r:$(topdir)/class/lib/$(PROFILE)/mscorlib.dll -r:$(topdir)/class/lib/$(PROFILE)/System.dll -test-local: DummyAssembly.dll +test-local: $(topdir)/class/lib/$(PROFILE)/tests/DummyAssembly.dll include ../../build/library.make diff --git a/mcs/class/System.Windows.Forms/System.Windows.Forms.Layout/TableLayout.cs b/mcs/class/System.Windows.Forms/System.Windows.Forms.Layout/TableLayout.cs index f746c55620..7b5a655c4d 100644 --- a/mcs/class/System.Windows.Forms/System.Windows.Forms.Layout/TableLayout.cs +++ b/mcs/class/System.Windows.Forms/System.Windows.Forms.Layout/TableLayout.cs @@ -483,7 +483,7 @@ namespace System.Windows.Forms.Layout CalculateColumnWidths (settings, actual_positions, max_colspan, settings.ColumnStyles, auto_size, column_widths, false); // Calculate available width - int available_width = size.Width - (border_width * (columns + 1)); + int available_width = size.Width < Int16.MaxValue ? size.Width - (border_width * (columns + 1)) : 0; foreach (int width in column_widths) available_width -= width; @@ -516,7 +516,7 @@ namespace System.Windows.Forms.Layout CalculateRowHeights (settings, actual_positions, max_rowspan, settings.RowStyles, auto_size, column_widths, row_heights); // Calculate available height - int available_height = size.Height - (border_width * (rows + 1)); + int available_height = size.Height < Int16.MaxValue ? size.Height - (border_width * (rows + 1)) : 0; foreach (int height in row_heights) available_height -= height; diff --git a/mcs/class/System.Windows.Forms/System.Windows.Forms/Line.cs b/mcs/class/System.Windows.Forms/System.Windows.Forms/Line.cs index 8d9b2a27fc..d169d9adfd 100644 --- a/mcs/class/System.Windows.Forms/System.Windows.Forms/Line.cs +++ b/mcs/class/System.Windows.Forms/System.Windows.Forms/Line.cs @@ -472,6 +472,7 @@ namespace System.Windows.Forms int wrap_pos; int prev_height; int prev_ascent; + float add_width; pos = 0; len = this.text.Length; @@ -493,6 +494,7 @@ namespace System.Windows.Forms wrapped = false; wrap_pos = 0; + add_width = 0; while (pos < len) { @@ -517,14 +519,16 @@ namespace System.Windows.Forms { // MeasureText doesn't measure trailing spaces, so we do the best we can for those // in the else branch. + // It doesn't measure /t characters either, we need to add it manually with add_width. size = TextBoxTextRenderer.MeasureText (g, text.ToString (0, pos + 1), tag.Font); - newWidth = widths[0] + size.Width; + newWidth = widths[0] + size.Width + add_width; } else { size = tag.SizeOfPosition (g, pos); w = size.Width; newWidth = widths[pos] + w; + if (text[pos] == '\t') add_width += w; } if (Char.IsWhiteSpace (text[pos])) diff --git a/mcs/class/System.Windows.Forms/System.Windows.Forms_test.dll.sources b/mcs/class/System.Windows.Forms/System.Windows.Forms_test.dll.sources index 4fa596564d..f925f07610 100644 --- a/mcs/class/System.Windows.Forms/System.Windows.Forms_test.dll.sources +++ b/mcs/class/System.Windows.Forms/System.Windows.Forms_test.dll.sources @@ -1,4 +1,5 @@ ../../test-helpers/NunitHelpers.cs +../../test-helpers/TestResourceHelper.cs ../../../build/common/Consts.cs System.Windows.Forms/ApplicationTest.cs System.Windows.Forms/AutoCompleteStringCollectionTest.cs diff --git a/mcs/class/System.Windows.Forms/Test/System.Resources/CompatTest.cs b/mcs/class/System.Windows.Forms/Test/System.Resources/CompatTest.cs index 7c874f2d50..2f4a845ee0 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Resources/CompatTest.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Resources/CompatTest.cs @@ -12,6 +12,8 @@ using System.IO; using System.Resources; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Resources { [TestFixture] @@ -47,21 +49,13 @@ namespace MonoTests.System.Resources [Test] public void TestReader () { - string fileName = Path.Combine (Path.Combine ("Test", "System.Resources"), "compat_1_1.resx"); - if (!File.Exists (fileName)) - fileName = String.Format ("..{0}System.Resources{0}compat_1_1.resx", Path.DirectorySeparatorChar); - - Helper.TestReader (fileName); + Helper.TestReader (TestResourceHelper.GetFullPathOfResource ("Test/System.Resources/compat_1_1.resx")); } [Test] public void TestReader_2_0 () { - string fileName = Path.Combine (Path.Combine ("Test", "System.Resources"), "compat_2_0.resx"); - if (!File.Exists (fileName)) - fileName = String.Format ("..{0}System.Resources{0}compat_2_0.resx", Path.DirectorySeparatorChar); - - Helper.TestReader (fileName); + Helper.TestReader (TestResourceHelper.GetFullPathOfResource ("Test/System.Resources/compat_2_0.resx")); } } } diff --git a/mcs/class/System.Windows.Forms/Test/System.Resources/ResXResourceReaderTest.cs b/mcs/class/System.Windows.Forms/Test/System.Resources/ResXResourceReaderTest.cs index 519e342087..47b1ad61fe 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Resources/ResXResourceReaderTest.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Resources/ResXResourceReaderTest.cs @@ -20,6 +20,8 @@ using System.Runtime.Serialization; using NUnit.Framework; using System.Reflection; +using MonoTests.Helpers; + namespace MonoTests.System.Resources { [TestFixture] public class ResXResourceReaderTest : MonoTests.System.Windows.Forms.TestHelper @@ -116,9 +118,7 @@ namespace MonoTests.System.Resources { [Test] public void Close_FileName () { - string fileName = Path.Combine (Path.Combine ("Test", "System.Resources"), "compat_1_1.resx"); - if (!File.Exists (fileName)) - fileName = String.Format ("..{0}System.Resources{0}compat_1_1.resx", Path.DirectorySeparatorChar); + string fileName = TestResourceHelper.GetFullPathOfResource ("Test/System.Resources/compat_1_1.resx"); ResXResourceReader r1 = new ResXResourceReader (fileName); r1.GetEnumerator (); @@ -134,9 +134,7 @@ namespace MonoTests.System.Resources { [Test] public void Close_Reader () { - string fileName = Path.Combine (Path.Combine ("Test", "System.Resources"), "compat_1_1.resx"); - if (!File.Exists (fileName)) - fileName = String.Format ("..{0}System.Resources{0}compat_1_1.resx", Path.DirectorySeparatorChar); + string fileName = TestResourceHelper.GetFullPathOfResource ("Test/System.Resources/compat_1_1.resx"); using (StreamReader sr = new StreamReader (fileName)) { ResXResourceReader r = new ResXResourceReader (sr); @@ -172,9 +170,7 @@ namespace MonoTests.System.Resources { [Test] public void Close_Stream () { - string fileName = Path.Combine (Path.Combine ("Test", "System.Resources"), "compat_1_1.resx"); - if (!File.Exists (fileName)) - fileName = String.Format ("..{0}System.Resources{0}compat_1_1.resx", Path.DirectorySeparatorChar); + string fileName = TestResourceHelper.GetFullPathOfResource ("Test/System.Resources/compat_1_1.resx"); using (FileStream fs = File.OpenRead (fileName)) { ResXResourceReader r = new ResXResourceReader (fs); @@ -200,7 +196,7 @@ namespace MonoTests.System.Resources { public void ExternalFileReference_Icon () { string refFile = Path.Combine (_tempDirectory, "32x32.ico"); - WriteEmbeddedResource ("32x32.ico", refFile); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/32x32.ico"), refFile); string resxFile = Path.Combine (_tempDirectory, "resources.resx"); using (StreamWriter sw = new StreamWriter (resxFile, false, Encoding.UTF8)) { @@ -226,7 +222,7 @@ namespace MonoTests.System.Resources { File.Delete (resxFile); refFile = Path.Combine (_tempDirectory, "32x32.ICO"); - WriteEmbeddedResource ("32x32.ico", refFile); + File.Copy (TestResourceHelper.GetFullPathOfResource ("Test/resources/32x32.ico"), refFile); using (StreamWriter sw = new StreamWriter (resxFile, false, Encoding.UTF8)) { sw.Write (string.Format (CultureInfo.InvariantCulture, @@ -1473,8 +1469,7 @@ namespace MonoTests.System.Resources { [Test] public void UseResXDataNodes () { - string refFile = Path.Combine (_tempDirectory, "32x32.ico"); - WriteEmbeddedResource ("32x32.ico", refFile); + string refFile = TestResourceHelper.GetFullPathOfResource ("Test/resources/32x32.ico"); string resxFile = Path.Combine (_tempDirectory, "resources.resx"); using (StreamWriter sw = new StreamWriter (resxFile, false, Encoding.UTF8)) { @@ -1520,8 +1515,7 @@ namespace MonoTests.System.Resources { { // This test relies on a hashtable's enumerator being ordered, // when the ordering is not guaranteed. - string refFile = Path.Combine (_tempDirectory, "32x32.ico"); - WriteEmbeddedResource ("32x32.ico", refFile); + string refFile = TestResourceHelper.GetFullPathOfResource ("Test/resources/32x32.ico"); string resxFile = Path.Combine (_tempDirectory, "resources.resx"); using (StreamWriter sw = new StreamWriter (resxFile, false, Encoding.UTF8)) { @@ -1545,8 +1539,7 @@ namespace MonoTests.System.Resources { [Test] public void GetMetadataEnumerator () { - string refFile = Path.Combine (_tempDirectory, "32x32.ico"); - WriteEmbeddedResource ("32x32.ico", refFile); + string refFile = TestResourceHelper.GetFullPathOfResource ("Test/resources/32x32.ico"); string resxFile = Path.Combine (_tempDirectory, "resources.resx"); using (StreamWriter sw = new StreamWriter (resxFile, false, Encoding.UTF8)) { diff --git a/mcs/class/System.Windows.Forms/Test/System.Resources/ResourcesTestHelper.cs b/mcs/class/System.Windows.Forms/Test/System.Resources/ResourcesTestHelper.cs index aba3763c0a..cb18498b25 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Resources/ResourcesTestHelper.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Resources/ResourcesTestHelper.cs @@ -38,9 +38,10 @@ using System.Collections; using System.Drawing; using System.Runtime.Serialization.Formatters.Binary; +using MonoTests.Helpers; + namespace MonoTests.System.Resources { public class ResourcesTestHelper { - string tempFileWithIcon = null; string tempFileWithSerializable = null; [SetUp] @@ -82,45 +83,19 @@ namespace MonoTests.System.Resources { public ResXDataNode GetNodeEmdeddedIcon () { - Stream input = typeof (ResXDataNodeTest).Assembly. - GetManifestResourceStream ("32x32.ico"); - - Icon ico = new Icon (input); + Icon ico = new Icon (TestResourceHelper.GetStreamOfResource ("Test/resources/32x32.ico")); ResXDataNode node = new ResXDataNode ("test", ico); return node; } public ResXDataNode GetNodeFileRefToIcon () { - tempFileWithIcon = Path.GetTempFileName (); // remember to delete file in teardown - Path.ChangeExtension (tempFileWithIcon, "ico"); - - WriteEmbeddedResource ("32x32.ico", tempFileWithIcon); - ResXFileRef fileRef = new ResXFileRef (tempFileWithIcon, typeof (Icon).AssemblyQualifiedName); + ResXFileRef fileRef = new ResXFileRef (TestResourceHelper.GetFullPathOfResource ("Test/resources/32x32.ico"), typeof (Icon).AssemblyQualifiedName); ResXDataNode node = new ResXDataNode ("test", fileRef); return node; } - void WriteEmbeddedResource (string name, string filename) - { - const int size = 512; - byte [] buffer = new byte [size]; - int count = 0; - - Stream input = typeof (ResXDataNodeTest).Assembly. - GetManifestResourceStream (name); - Stream output = File.Open (filename, FileMode.Create); - - try { - while ((count = input.Read (buffer, 0, size)) > 0) { - output.Write (buffer, 0, count); - } - } finally { - output.Close (); - } - } - public ResXDataNode GetNodeEmdeddedBytes1To10 () { byte [] someBytes = new byte [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; @@ -166,11 +141,6 @@ namespace MonoTests.System.Resources { [TearDown] protected virtual void TearDown () { - if (tempFileWithIcon != null) { - File.Delete (tempFileWithIcon); - tempFileWithIcon = null; - } - if (tempFileWithSerializable != null) { File.Delete (tempFileWithSerializable); tempFileWithSerializable = null; diff --git a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ButtonTest.cs b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ButtonTest.cs index e394fd0d18..436695d0c1 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ButtonTest.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ButtonTest.cs @@ -11,6 +11,8 @@ using System.Windows.Forms; using System.Drawing; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Windows.Forms { [TestFixture] @@ -220,7 +222,7 @@ namespace MonoTests.System.Windows.Forms { Button B1 = new Button (); B1.Visible = true; - B1.Image = Image.FromFile ("M.gif"); + B1.Image = Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif")); Assert.AreEqual (ContentAlignment.MiddleCenter, B1.ImageAlign, "#2"); } @@ -228,13 +230,13 @@ namespace MonoTests.System.Windows.Forms public void ImageListTest () { Button B1 = new Button (); - B1.Image = Image.FromFile ("M.gif"); + B1.Image = Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif")); Assert.AreEqual (null, B1.ImageList, "#3a"); B1 = new Button (); ImageList ImageList1 = new ImageList (); - ImageList1.Images.Add(Image.FromFile ("M.gif")); - ImageList1.Images.Add(Image.FromFile ("M.gif")); + ImageList1.Images.Add(Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"))); + ImageList1.Images.Add(Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"))); Assert.AreEqual (2, ImageList1.Images.Count, "#3b"); B1.ImageList = ImageList1; Assert.AreEqual (-1, B1.ImageIndex, "#3c"); diff --git a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ControlEventTest.cs b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ControlEventTest.cs index c4a207299d..7aaa50f46d 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ControlEventTest.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ControlEventTest.cs @@ -5,6 +5,8 @@ using System.Windows.Forms; using System.Drawing; using System.Threading; +using MonoTests.Helpers; + namespace MonoTests.System.Windows.Forms { [TestFixture] @@ -33,7 +35,7 @@ namespace MonoTests.System.Windows.Forms Control c = new Control (); // Test BackgroundImageChanged Event c.BackgroundImageChanged += new EventHandler (Event_Handler1); - string abc = "M.gif"; + string abc = TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"); eventhandled = false; c.BackgroundImage = Image.FromFile (abc); Assert.AreEqual (true, eventhandled, "#A2"); diff --git a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/CursorTest.cs b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/CursorTest.cs index fd11142b00..427681c80f 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/CursorTest.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/CursorTest.cs @@ -10,6 +10,8 @@ using System.Windows.Forms; using System.Drawing; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Windows.Forms { [TestFixture] @@ -23,7 +25,8 @@ namespace MonoTests.System.Windows.Forms // this contains an and mask, it used to crash // - new Cursor (typeof (CursorTest).Assembly.GetManifestResourceStream ("a.cur")); + var c = new Cursor (TestResourceHelper.GetStreamOfResource ("Test/resources/a.cur")); + Assert.NotNull (c); } [Test] diff --git a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ImageListStreamerTest.cs b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ImageListStreamerTest.cs index f3ffac0d84..9573a96651 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ImageListStreamerTest.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ImageListStreamerTest.cs @@ -16,6 +16,8 @@ using System.Windows.Forms; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Windows.Forms { [TestFixture] @@ -28,8 +30,8 @@ namespace MonoTests.System.Windows.Forms Assembly a = typeof (ImageListStreamerTest).Assembly; ImageList imgList = new ImageList (); - imgList.Images.Add (Image.FromStream (a.GetManifestResourceStream ("32x32.ico"))); - imgList.Images.Add (Image.FromFile ("M.gif")); + imgList.Images.Add (Image.FromStream (TestResourceHelper.GetStreamOfResource ("Test/resources/32x32.ico"))); + imgList.Images.Add (Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"))); MemoryStream ms = new MemoryStream (); diff --git a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ImageListTest.cs b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ImageListTest.cs index 62893b6c04..a0f22df598 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ImageListTest.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ImageListTest.cs @@ -18,6 +18,8 @@ using System.Windows.Forms; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Windows.Forms { [TestFixture] @@ -40,7 +42,7 @@ namespace MonoTests.System.Windows.Forms Assert.AreEqual ("System.IntPtr", myimagelist.Handle.GetType ().FullName, "#H3"); // I - Image myImage = Image.FromFile("M.gif"); + Image myImage = Image.FromFile(TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif")); myimagelist.Images.Add (myImage); Assert.AreEqual (1, myimagelist.Images.Count, "#I1"); Assert.AreEqual (16, myimagelist.ImageSize.Height, "#I2"); @@ -86,7 +88,7 @@ namespace MonoTests.System.Windows.Forms // create an ImageList containing an image il = new ImageList (); - il.Images.Add (Image.FromFile ("M.gif")); + il.Images.Add (Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"))); Assert.IsFalse (colordepth_prop.ShouldSerializeValue (il), "13"); Assert.IsFalse (colordepth_prop.CanResetValue (il), "14"); @@ -125,7 +127,7 @@ namespace MonoTests.System.Windows.Forms ImageList imgList = new ImageList (); ImageList.ImageCollection coll = imgList.Images; - Image gif = Image.FromFile ("M.gif"); + Image gif = Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif")); coll.Add (gif); Bitmap bmp = new Bitmap (10, 10); coll.Add (bmp); @@ -170,7 +172,7 @@ namespace MonoTests.System.Windows.Forms myform.ShowInTaskbar = false; Graphics mygraphics = null; ImageList myimagelist = new ImageList (); - Image myImage = Image.FromFile("M.gif"); + Image myImage = Image.FromFile(TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif")); myimagelist.Images.Add (myImage); myimagelist.ColorDepth = ColorDepth.Depth8Bit; myimagelist.ImageSize = new Size (50,50); diff --git a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/LabelTest.cs b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/LabelTest.cs index 0d79488008..bf1a2e8d7b 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/LabelTest.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/LabelTest.cs @@ -12,6 +12,8 @@ using System.Windows.Forms; using System.Drawing; using System.Collections; +using MonoTests.Helpers; + namespace MonoTests.System.Windows.Forms { [TestFixture] @@ -403,7 +405,7 @@ namespace MonoTests.System.Windows.Forms l.Visible = true; myform.Controls.Add (l); l.BackgroundImageChanged += new EventHandler (Label_EventHandler); - l.BackgroundImage = Image.FromFile ("Test/System.Windows.Forms/bitmaps/a.png"); + l.BackgroundImage = Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/System.Windows.Forms/bitmaps/a.png")); Assert.AreEqual (true, eventhandled, "B4"); eventhandled = false; myform.Dispose(); @@ -770,7 +772,7 @@ public class MyLabel : Label myform.Visible = true; MyLabel l = new MyLabel (); myform.Controls.Add (l); - l.BackgroundImage = Image.FromFile ("Test/System.Windows.Forms/bitmaps/a.png"); + l.BackgroundImage = Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/System.Windows.Forms/bitmaps/a.png")); Assert.AreEqual (EventsWanted, ArrayListToString (l.Results)); myform.Dispose(); @@ -1152,7 +1154,7 @@ public class MyLabel2 : Label myform.Visible = true; MyLabel2 l = new MyLabel2 (); myform.Controls.Add (l); - l.BackgroundImage = Image.FromFile ("Test/System.Windows.Forms/bitmaps/a.png"); + l.BackgroundImage = Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/System.Windows.Forms/bitmaps/a.png")); Assert.AreEqual (EventsWanted, ArrayListToString (l.Results)); myform.Dispose(); diff --git a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/PictureBoxTest.cs b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/PictureBoxTest.cs index 708721573c..b6d0e7f17f 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/PictureBoxTest.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/PictureBoxTest.cs @@ -16,6 +16,8 @@ using System.Windows.Forms; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Windows.Forms { [TestFixture] @@ -53,18 +55,18 @@ namespace MonoTests.System.Windows.Forms Assert.IsNull (pb.ImageLocation, "#A"); - pb.ImageLocation = "M.gif"; + pb.ImageLocation = TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"); Application.DoEvents (); - Assert.AreEqual ("M.gif", pb.ImageLocation, "#B1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"), pb.ImageLocation, "#B1"); Assert.AreSame (pb.InitialImage, pb.Image, "#B2"); - using (Stream s = this.GetType ().Assembly.GetManifestResourceStream ("32x32.ico")) { + using (Stream s = TestResourceHelper.GetStreamOfResource ("Test/resources/32x32.ico")) { pb.Image = Image.FromStream (s); } Application.DoEvents (); - Assert.AreEqual ("M.gif", pb.ImageLocation, "#C1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"), pb.ImageLocation, "#C1"); Assert.IsNotNull (pb.Image, "#C2"); Assert.AreEqual (60, pb.Image.Height, "#C3"); Assert.AreEqual (150, pb.Image.Width, "#C4"); @@ -75,16 +77,16 @@ namespace MonoTests.System.Windows.Forms Assert.IsNull (pb.ImageLocation, "#D1"); Assert.IsNull (pb.Image, "#D2"); - pb.ImageLocation = "M.gif"; + pb.ImageLocation = TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"); Application.DoEvents (); - Assert.AreEqual ("M.gif", pb.ImageLocation, "#E1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"), pb.ImageLocation, "#E1"); Assert.IsNull (pb.Image, "#E2"); pb.Load (); Application.DoEvents (); - Assert.AreEqual ("M.gif", pb.ImageLocation, "#F1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"), pb.ImageLocation, "#F1"); Assert.IsNotNull (pb.Image, "#F2"); Assert.AreEqual (60, pb.Image.Height, "#F3"); Assert.AreEqual (150, pb.Image.Width, "#F4"); @@ -95,7 +97,7 @@ namespace MonoTests.System.Windows.Forms Assert.IsNull (pb.ImageLocation, "#G1"); Assert.IsNull (pb.Image, "#G2"); - pb.ImageLocation = "M.gif"; + pb.ImageLocation = TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"); pb.Load (); pb.ImageLocation = "XYZ.gif"; Application.DoEvents (); @@ -111,7 +113,7 @@ namespace MonoTests.System.Windows.Forms Assert.AreEqual (string.Empty, pb.ImageLocation, "#I1"); Assert.IsNull (pb.Image, "#I2"); - using (Stream s = this.GetType ().Assembly.GetManifestResourceStream ("32x32.ico")) { + using (Stream s = TestResourceHelper.GetStreamOfResource ("Test/resources/32x32.ico")) { pb.Image = Image.FromStream (s); } Application.DoEvents (); @@ -121,10 +123,10 @@ namespace MonoTests.System.Windows.Forms Assert.AreEqual (96, pb.Image.Height, "#J3"); Assert.AreEqual (96, pb.Image.Width, "#J4"); - pb.Load ("M.gif"); + pb.Load (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif")); Application.DoEvents (); - Assert.AreEqual ("M.gif", pb.ImageLocation, "#K1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"), pb.ImageLocation, "#K1"); Assert.IsNotNull (pb.Image, "#K2"); Assert.AreEqual (60, pb.Image.Height, "#K3"); Assert.AreEqual (150, pb.Image.Width, "#K4"); @@ -149,18 +151,18 @@ namespace MonoTests.System.Windows.Forms Assert.IsNull (pb.ImageLocation, "#A"); - pb.ImageLocation = "M.gif"; + pb.ImageLocation = TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"); - Assert.AreEqual ("M.gif", pb.ImageLocation, "#B1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"), pb.ImageLocation, "#B1"); Assert.IsNotNull (pb.Image, "#B2"); Assert.AreEqual (60, pb.Image.Height, "#B3"); Assert.AreEqual (150, pb.Image.Width, "#B4"); - using (Stream s = this.GetType ().Assembly.GetManifestResourceStream ("32x32.ico")) { + using (Stream s = TestResourceHelper.GetStreamOfResource ("Test/resources/32x32.ico")) { pb.Image = Image.FromStream (s); } - Assert.AreEqual ("M.gif", pb.ImageLocation, "#C1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"), pb.ImageLocation, "#C1"); Assert.IsNotNull (pb.Image, "#C2"); Assert.AreEqual (96, pb.Image.Height, "#C3"); Assert.AreEqual (96, pb.Image.Width, "#C4"); @@ -172,16 +174,16 @@ namespace MonoTests.System.Windows.Forms Assert.AreEqual (96, pb.Image.Height, "#D3"); Assert.AreEqual (96, pb.Image.Width, "#D4"); - pb.ImageLocation = "M.gif"; + pb.ImageLocation = TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"); - Assert.AreEqual ("M.gif", pb.ImageLocation, "#E1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"), pb.ImageLocation, "#E1"); Assert.IsNotNull (pb.Image, "#E2"); Assert.AreEqual (60, pb.Image.Height, "#E3"); Assert.AreEqual (150, pb.Image.Width, "#E4"); pb.Load (); - Assert.AreEqual ("M.gif", pb.ImageLocation, "#F1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"), pb.ImageLocation, "#F1"); Assert.IsNotNull (pb.Image, "#F2"); Assert.AreEqual (60, pb.Image.Height, "#F3"); Assert.AreEqual (150, pb.Image.Width, "#F4"); @@ -191,7 +193,7 @@ namespace MonoTests.System.Windows.Forms Assert.IsNull (pb.ImageLocation, "#G1"); Assert.IsNull (pb.Image, "#G2"); - using (Stream s = this.GetType ().Assembly.GetManifestResourceStream ("32x32.ico")) { + using (Stream s = TestResourceHelper.GetStreamOfResource ("Test/resources/32x32.ico")) { pb.Image = Image.FromStream (s); } @@ -200,9 +202,9 @@ namespace MonoTests.System.Windows.Forms Assert.AreEqual (96, pb.Image.Height, "#H3"); Assert.AreEqual (96, pb.Image.Width, "#H4"); - pb.Load ("M.gif"); + pb.Load (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif")); - Assert.AreEqual ("M.gif", pb.ImageLocation, "#I1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"), pb.ImageLocation, "#I1"); Assert.IsNotNull (pb.Image, "#I2"); Assert.AreEqual (60, pb.Image.Height, "#I3"); Assert.AreEqual (150, pb.Image.Width, "#I4"); @@ -212,9 +214,9 @@ namespace MonoTests.System.Windows.Forms Assert.AreEqual (string.Empty, pb.ImageLocation, "#J1"); Assert.IsNull (pb.Image, "#J2"); - pb.ImageLocation = "M.gif"; + pb.ImageLocation = TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"); - Assert.AreEqual ("M.gif", pb.ImageLocation, "#K1"); + Assert.AreEqual (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"), pb.ImageLocation, "#K1"); Assert.IsNotNull (pb.Image, "#K2"); Assert.AreEqual (60, pb.Image.Height, "#K3"); Assert.AreEqual (150, pb.Image.Width, "#K4"); @@ -242,7 +244,7 @@ namespace MonoTests.System.Windows.Forms PictureBox myPicBox = new PictureBox (); // I Assert.IsNull (myPicBox.Image, "#1"); - Image myImage = Image.FromFile ("M.gif"); + Image myImage = Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif")); myPicBox.Image = myImage; Assert.AreSame (myImage, myPicBox.Image, "#2"); Assert.AreEqual (60, myPicBox.Image.Height, "#3"); diff --git a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ProgressBarTest.cs b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ProgressBarTest.cs index 62c7f37d0c..b100d5c241 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ProgressBarTest.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ProgressBarTest.cs @@ -13,6 +13,8 @@ using System.Drawing; using System.Reflection; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Windows.Forms { [TestFixture] @@ -29,7 +31,7 @@ namespace MonoTests.System.Windows.Forms // B Assert.AreEqual ("Control", myProgressBar.BackColor.Name, "#B1"); Assert.AreEqual (null, myProgressBar.BackgroundImage, "#B3"); - string gif = "M.gif"; + string gif = TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"); myProgressBar.BackgroundImage = Image.FromFile (gif); // comparing image objects fails on MS .Net so using Size property Assert.AreEqual (Image.FromFile(gif, true).Size, myProgressBar.BackgroundImage.Size, "#B4"); diff --git a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/RichTextBoxTest.cs b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/RichTextBoxTest.cs index 6d3f1adfb7..9dda6676cf 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/RichTextBoxTest.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/RichTextBoxTest.cs @@ -15,6 +15,8 @@ using System.Windows.Forms; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Windows.Forms { [TestFixture] @@ -37,7 +39,7 @@ namespace MonoTests.System.Windows.Forms // B rTBox.BackColor = Color.White; Assert.AreEqual (null, rTBox.BackgroundImage, "#B1"); - string gif = "M.gif"; + string gif = TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"); rTBox.BackgroundImage = Image.FromFile (gif); // comparing image objects fails on MS .Net so using Size property Assert.AreEqual (Image.FromFile(gif, true).Size, rTBox.BackgroundImage.Size, "#B2"); @@ -103,7 +105,7 @@ namespace MonoTests.System.Windows.Forms public void CanPasteTest () { RichTextBox rTextBox = new RichTextBox (); - Bitmap myBitmap = new Bitmap ("M.gif"); + Bitmap myBitmap = new Bitmap (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif")); Clipboard.SetDataObject (myBitmap); DataFormats.Format myFormat = DataFormats.GetFormat (DataFormats.Bitmap); Assert.AreEqual (true, rTextBox.CanPaste (myFormat), "#Mtd1"); diff --git a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ScrollBarTest.cs b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ScrollBarTest.cs index e7c59f37c0..bbcf98e016 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ScrollBarTest.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ScrollBarTest.cs @@ -13,6 +13,8 @@ using System.Windows.Forms; using System.Drawing; using System.Collections; +using MonoTests.Helpers; + namespace MonoTests.System.Windows.Forms { @@ -286,7 +288,7 @@ public class MyScrollBar : HScrollBar // B myscrlbar.BackColor = Color.Red; Assert.AreEqual (255, myscrlbar.BackColor.R, "B2"); - myscrlbar.BackgroundImage = Image.FromFile ("Test/System.Windows.Forms/bitmaps/a.png"); + myscrlbar.BackgroundImage = Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/System.Windows.Forms/bitmaps/a.png")); Assert.AreEqual (16, myscrlbar.BackgroundImage.Height, "B3"); // F @@ -551,7 +553,7 @@ public class MyScrollBar : HScrollBar ScrollBar myHscrlbar = new HScrollBar (); myform.Controls.Add (myHscrlbar); myHscrlbar.BackgroundImageChanged += new EventHandler (ScrollBar_EventHandler); - myHscrlbar.BackgroundImage = Image.FromFile ("Test/System.Windows.Forms/bitmaps/a.png"); + myHscrlbar.BackgroundImage = Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/System.Windows.Forms/bitmaps/a.png")); Assert.AreEqual (true, eventhandled, "B5"); eventhandled = false; myform.Dispose (); @@ -820,7 +822,7 @@ public class MyVScrollBar : VScrollBar myform.Visible = true; MyScrollBar s = new MyScrollBar (); myform.Controls.Add (s); - s.BackgroundImage = Image.FromFile ("Test/System.Windows.Forms/bitmaps/a.png"); + s.BackgroundImage = Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/System.Windows.Forms/bitmaps/a.png")); Assert.AreEqual (EventsWanted, ArrayListToString (s.Results)); myform.Dispose (); @@ -1376,7 +1378,7 @@ public class MyScrollBar2 : HScrollBar myform.Visible = true; MyScrollBar2 s = new MyScrollBar2 (); myform.Controls.Add (s); - s.BackgroundImage = Image.FromFile ("Test/System.Windows.Forms/bitmaps/a.png"); + s.BackgroundImage = Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/System.Windows.Forms/bitmaps/a.png")); Assert.AreEqual (EventsWanted, ArrayListToString (s.Results)); myform.Dispose (); diff --git a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/TextBoxTest.cs b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/TextBoxTest.cs index 265230186b..559bf98cb5 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/TextBoxTest.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/TextBoxTest.cs @@ -15,6 +15,8 @@ using System.Text; using NUnit.Framework; using CategoryAttribute = NUnit.Framework.CategoryAttribute; +using MonoTests.Helpers; + namespace MonoTests.System.Windows.Forms { [TestFixture] @@ -45,7 +47,7 @@ namespace MonoTests.System.Windows.Forms Assert.AreEqual (true, textBox.AcceptsTab, "#1b"); Assert.AreEqual (true, textBox.AutoSize, "#2"); Assert.AreEqual (null, textBox.BackgroundImage, "#4a"); - string gif = "M.gif"; + string gif = TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"); textBox.BackgroundImage = Image.FromFile (gif); // comparing image objects fails on MS .Net so using Size property Assert.AreEqual (Image.FromFile(gif, true).Size, textBox.BackgroundImage.Size, "#4b"); diff --git a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ToolBarTest.cs b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ToolBarTest.cs index edec404ca2..e34dcef434 100644 --- a/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ToolBarTest.cs +++ b/mcs/class/System.Windows.Forms/Test/System.Windows.Forms/ToolBarTest.cs @@ -14,6 +14,8 @@ using System.Windows.Forms; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Windows.Forms { [TestFixture] @@ -46,7 +48,7 @@ namespace MonoTests.System.Windows.Forms // B Assert.AreEqual ("Control", myToolBar.BackColor.Name, "#B1"); - myToolBar.BackgroundImage = Image.FromFile ("M.gif"); + myToolBar.BackgroundImage = Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif")); Assert.AreEqual (60, myToolBar.BackgroundImage.Height, "#B3"); Assert.AreEqual (BorderStyle.None, myToolBar.BorderStyle, "#B4"); myToolBar.BorderStyle = BorderStyle.Fixed3D; @@ -64,7 +66,7 @@ namespace MonoTests.System.Windows.Forms // I ImageList myImageList = new ImageList (); - myImageList.Images.Add (Image.FromFile ("M.gif")); + myImageList.Images.Add (Image.FromFile (TestResourceHelper.GetFullPathOfResource ("Test/resources/M.gif"))); myToolBar.ImageList = myImageList; Assert.AreEqual (1, myToolBar.ImageList.Images.Count, "#I1"); Assert.AreEqual (16, myToolBar.ImageSize.Height, "#I2"); diff --git a/mcs/class/System.Windows.Forms/M.gif b/mcs/class/System.Windows.Forms/Test/resources/M.gif similarity index 100% rename from mcs/class/System.Windows.Forms/M.gif rename to mcs/class/System.Windows.Forms/Test/resources/M.gif diff --git a/mcs/class/System.XML/Makefile b/mcs/class/System.XML/Makefile index 9583f10ab9..9afb68bccd 100644 --- a/mcs/class/System.XML/Makefile +++ b/mcs/class/System.XML/Makefile @@ -22,9 +22,13 @@ XTEST_LIB_REFS = System System.Core System.Xml System.Xml.Linq Facades/System.Th ifneq ($(PROFILE),monodroid) ifneq ($(PROFILE),monotouch) +ifneq ($(PROFILE),monotouch_tv) +ifneq ($(PROFILE),monotouch_watch) XTEST_LIB_REFS += System.Drawing endif endif +endif +endif LIBRARY_WARN_AS_ERROR = yes @@ -36,28 +40,30 @@ LIB_MCS_FLAGS += -d:CONFIGURATION_DEP endif nist_dom_files = \ - ITest.cs readme.txt util.cs \ - files/noDTDXMLfile.xml files/otherDoc.xml files/staff.dtd files/staff.html files/staff.xml + ITest.cs readme.txt util.cs -xmlfiles_files = \ - nested-included.dtd literal-data.xml nested-dtd-test.dtd nested-dtd-test.xml simple.xml \ - xsl/empty.xsl \ - XsdValidation/1.xsd XsdValidation/2.xsd XsdValidation/3.xsd XsdValidation/4.xsd \ - xsd/1.xsd xsd/2.xsd xsd/3.xsd xsd/4.xsd xsd/5.xsd xsd/6.xsd xsd/xml.xsd xsd/81360.xsd xsd/81360inc1.xsd xsd/81360inc2.xsd - -EXTRA_DISTFILES = \ - $(wildcard System.Xml.Serialization/standalone_tests/*.cs) \ - $(wildcard System.Xml.Serialization/standalone_tests/*.output) \ - Test/XmlFiles/76102.xml \ - Test/XmlFiles/79683.dtd \ - Test/XmlFiles/496192.xml \ - Test/XmlFiles/*.xsd \ +TEST_RESOURCE_FILES = \ + Test/System.Xml/nist_dom/files/noDTDXMLfile.xml \ + Test/System.Xml/nist_dom/files/otherDoc.xml \ + Test/System.Xml/nist_dom/files/staff.dtd \ + Test/System.Xml/nist_dom/files/staff.html \ + Test/System.Xml/nist_dom/files/staff.xml \ + Test/XmlFiles/xsl/current-in-select.ref \ + $(wildcard Test/XmlFiles/*.xsd) \ + $(wildcard Test/XmlFiles/*.xml) \ + $(wildcard Test/XmlFiles/*.dtd) \ $(wildcard Test/XmlFiles/xsd/*.xml) \ $(wildcard Test/XmlFiles/xsd/*.xsd) \ $(wildcard Test/XmlFiles/xsl/*.xml) \ $(wildcard Test/XmlFiles/xsl/*.xsl) \ - Test/XmlFiles/xsl/current-in-select.ref \ - $(xmlfiles_files:%=Test/XmlFiles/%) \ + $(wildcard Test/XmlFiles/XsdValidation/*.xsd) + +TEST_MCS_FLAGS += $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) + +EXTRA_DISTFILES = \ + $(wildcard System.Xml.Serialization/standalone_tests/*.cs) \ + $(wildcard System.Xml.Serialization/standalone_tests/*.output) \ + $(TEST_RESOURCE_FILES) \ $(nist_dom_files:%=Test/System.Xml/nist_dom/%) include ../../build/library.make diff --git a/mcs/class/System.XML/System.Xml_test.dll.sources b/mcs/class/System.XML/System.Xml_test.dll.sources index 3698613cca..cad32a16a9 100644 --- a/mcs/class/System.XML/System.Xml_test.dll.sources +++ b/mcs/class/System.XML/System.Xml_test.dll.sources @@ -1,3 +1,4 @@ +../../test-helpers/TestResourceHelper.cs System.Xml/NameTableTests.cs System.Xml/XmlAssert.cs System.Xml/XmlAttributeCollectionTests.cs diff --git a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaAssertion.cs b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaAssertion.cs index d614b39bf8..72eb2e4b7e 100644 --- a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaAssertion.cs +++ b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaAssertion.cs @@ -13,13 +13,15 @@ using System.Xml; using System.Xml.Schema; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Xml { public class XmlSchemaAssertion { - public static XmlSchema GetSchema (string path) + public static XmlSchema GetSchema (string resourceName) { - XmlTextReader reader = new XmlTextReader (path); + XmlTextReader reader = new XmlTextReader (TestResourceHelper.GetFullPathOfResource (resourceName)); XmlSchema schema = XmlSchema.Read (reader, null); reader.Close (); return schema; diff --git a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaCollectionTests.cs b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaCollectionTests.cs index 141f9f3d47..9491e21a42 100644 --- a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaCollectionTests.cs +++ b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaCollectionTests.cs @@ -14,14 +14,16 @@ using System.Xml; using System.Xml.Schema; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Xml { [TestFixture] public class XmlSchemaCollectionTests { - private XmlSchema GetSchema (string path) + private XmlSchema GetSchema (string resourceName) { - return XmlSchema.Read (new XmlTextReader (path), null); + return XmlSchema.Read (new XmlTextReader (TestResourceHelper.GetFullPathOfResource (resourceName)), null); } private XmlQualifiedName QName (string name, string ns) diff --git a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaDatatypeTests.cs b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaDatatypeTests.cs index bf839ac30d..d39cbf1787 100644 --- a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaDatatypeTests.cs +++ b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaDatatypeTests.cs @@ -22,14 +22,16 @@ using SimpleType = System.Xml.Schema.XmlSchemaSimpleType; using SimpleRest = System.Xml.Schema.XmlSchemaSimpleTypeRestriction; using AssertType = NUnit.Framework.Assert; +using MonoTests.Helpers; + namespace MonoTests.System.Xml { [TestFixture] public class XmlSchemaDatatypeTests { - private XmlSchema GetSchema (string path) + private XmlSchema GetSchema (string resourceName) { - return XmlSchema.Read (new XmlTextReader (path), null); + return XmlSchema.Read (new XmlTextReader (TestResourceHelper.GetFullPathOfResource (resourceName)), null); } private XmlQualifiedName QName (string name, string ns) diff --git a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaSetTests.cs b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaSetTests.cs index 9b45b3f8aa..c8e0c53bb7 100644 --- a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaSetTests.cs +++ b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaSetTests.cs @@ -15,6 +15,8 @@ using System.Xml; using System.Xml.Schema; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Xml { [TestFixture] @@ -203,8 +205,8 @@ type=""xsd:string"" use=""required""/> // complexContent schema conformance check, and // 3) the included schema is already added to XmlSchemaSet. XmlSchemaSet xss = new XmlSchemaSet (); - xss.Add (null, "Test/XmlFiles/xsd/import-subst-dbr-base.xsd"); - xss.Add (null, "Test/XmlFiles/xsd/import-subst-dbr-ext.xsd"); + xss.Add (null, TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/import-subst-dbr-base.xsd")); + xss.Add (null, TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/import-subst-dbr-ext.xsd")); // should not result in lack of substitutionGroup // (and conformance error as its result) xss.Compile (); diff --git a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaTests.cs b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaTests.cs index 1c17e9745a..7d3b3eb1b4 100644 --- a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaTests.cs +++ b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaTests.cs @@ -15,6 +15,8 @@ using System.Xml.Schema; using System.Xml.Serialization; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Xml { [TestFixture] @@ -159,7 +161,7 @@ namespace MonoTests.System.Xml [Test] public void TestSimpleImport () { - XmlSchema schema = XmlSchema.Read (new XmlTextReader ("Test/XmlFiles/xsd/3.xsd"), null); + XmlSchema schema = XmlSchema.Read (new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/3.xsd")), null); Assert.AreEqual ("urn:foo", schema.TargetNamespace); XmlSchemaImport import = schema.Includes [0] as XmlSchemaImport; Assert.IsNotNull (import); @@ -177,7 +179,7 @@ namespace MonoTests.System.Xml [Category ("MobileNotWorking")] public void TestSimpleMutualImport () { - XmlReader r = new XmlTextReader ("Test/XmlFiles/xsd/inter-inc-1.xsd"); + XmlReader r = new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/inter-inc-1.xsd")); try { XmlSchema.Read (r, null).Compile (null); } finally { @@ -188,7 +190,7 @@ namespace MonoTests.System.Xml [Test] public void TestQualification () { - XmlSchema schema = XmlSchema.Read (new XmlTextReader ("Test/XmlFiles/xsd/5.xsd"), null); + XmlSchema schema = XmlSchema.Read (new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/5.xsd")), null); schema.Compile (null); XmlSchemaElement el = schema.Elements [QName ("Foo", "urn:bar")] as XmlSchemaElement; Assert.IsNotNull (el); @@ -197,7 +199,7 @@ namespace MonoTests.System.Xml XmlSchemaElement elp = seq.Items [0] as XmlSchemaElement; Assert.AreEqual (QName ("Bar", ""), elp.QualifiedName); - schema = XmlSchema.Read (new XmlTextReader ("Test/XmlFiles/xsd/6.xsd"), null); + schema = XmlSchema.Read (new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/6.xsd")), null); schema.Compile (null); el = schema.Elements [QName ("Foo", "urn:bar")] as XmlSchemaElement; Assert.IsNotNull (el); @@ -385,7 +387,7 @@ namespace MonoTests.System.Xml // bug #77687 public void CompileFillsSchemaPropertyInExternal () { - string schemaFileName = "Test/XmlFiles/xsd/77687.xsd"; + string schemaFileName = TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/77687.xsd"); XmlTextReader tr = new XmlTextReader (schemaFileName); XmlSchema schema = XmlSchema.Read (tr, null); @@ -401,8 +403,8 @@ namespace MonoTests.System.Xml // two different keys where one is in scope within another) public void DuplicateKeyFieldAttributePath () { - string schemaFileName = "Test/XmlFiles/xsd/78985.xsd"; - string xmlFileName = "Test/XmlFiles/xsd/78985.xml"; + string schemaFileName = TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/78985.xsd"); + string xmlFileName = TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/78985.xml"); XmlTextReader tr = new XmlTextReader (schemaFileName); XmlValidatingReader vr = new XmlValidatingReader ( @@ -415,7 +417,7 @@ namespace MonoTests.System.Xml [Test] public void ThreeLevelNestedInclusion () { - XmlTextReader r = new XmlTextReader ("Test/XmlFiles/xsd/361818.xsd"); + XmlTextReader r = new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/361818.xsd")); try { XmlSchema xs = XmlSchema.Read (r, null); xs.Compile (null); @@ -542,7 +544,7 @@ namespace MonoTests.System.Xml public void TestResolveUri () { XmlSchemaSet schemaSet = new XmlSchemaSet (); - FileStream stream = new FileStream ("Test/XmlFiles/xsd/resolveUriSchema.xsd", FileMode.Open, FileAccess.Read); + FileStream stream = new FileStream (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/resolveUriSchema.xsd"), FileMode.Open, FileAccess.Read); schemaSet.Add ("http://tempuri.org/resolveUriSchema.xsd", new XmlTextReader (stream)); XmlTestResolver resolver = new XmlTestResolver (); @@ -578,7 +580,7 @@ namespace MonoTests.System.Xml settings.Schemas.Add (schemaSet); settings.ValidationType = ValidationType.Schema; - XmlReader reader = XmlReader.Create ("Test/XmlFiles/xsd/xsdimporttest.xml", settings); + XmlReader reader = XmlReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/xsdimporttest.xml"), settings); // Parse the file. while (reader.Read()) {} diff --git a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaValidatorTests.cs b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaValidatorTests.cs index bb4935a6ea..d463c7409d 100755 --- a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaValidatorTests.cs +++ b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaValidatorTests.cs @@ -15,6 +15,8 @@ using System.Xml; using System.Xml.Schema; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Xml { [TestFixture] @@ -36,7 +38,7 @@ namespace MonoTests.System.Xml { // bug #358408 XmlSchemaSet schemas = new XmlSchemaSet (); - schemas.Add (null, "Test/XmlFiles/xsd/358408.xsd"); + schemas.Add (null, TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/358408.xsd")); XmlSchemaValidator v = new XmlSchemaValidator ( new NameTable (), schemas, @@ -83,12 +85,12 @@ namespace MonoTests.System.Xml [Test] public void SkipInvolved () // bug #422581 { - XmlReader schemaReader = XmlReader.Create ("Test/XmlFiles/xsd/422581.xsd"); + XmlReader schemaReader = XmlReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/422581.xsd")); XmlSchema schema = XmlSchema.Read (schemaReader, null); XmlReaderSettings settings = new XmlReaderSettings (); settings.ValidationType = ValidationType.Schema; settings.Schemas.Add (schema); - XmlReader reader = XmlReader.Create ("Test/XmlFiles/xsd/422581.xml", settings); + XmlReader reader = XmlReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/422581.xml"), settings); while (reader.Read ()); } @@ -149,8 +151,8 @@ namespace MonoTests.System.Xml [Test] public void Bug496192_496205 () { - using (var xmlr = new StreamReader ("Test/XmlFiles/496192.xml")) - using (var xsdr = new StreamReader ("Test/XmlFiles/496192.xsd")) + using (var xmlr = new StreamReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/496192.xml"))) + using (var xsdr = new StreamReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/496192.xsd"))) Validate (xmlr.ReadToEnd (), xsdr.ReadToEnd ()); } @@ -293,8 +295,8 @@ namespace MonoTests.System.Xml [Test] public void Bug584664 () { - Validate (File.ReadAllText ("Test/XmlFiles/xsd/584664a.xml"), File.ReadAllText ("Test/XmlFiles/xsd/584664a.xsd")); - Validate (File.ReadAllText ("Test/XmlFiles/xsd/584664b.xml"), File.ReadAllText ("Test/XmlFiles/xsd/584664b.xsd")); + Validate (File.ReadAllText (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/584664a.xml")), File.ReadAllText (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/584664a.xsd"))); + Validate (File.ReadAllText (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/584664b.xml")), File.ReadAllText (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/584664b.xsd"))); } [Test] @@ -332,7 +334,7 @@ namespace MonoTests.System.Xml public void FacetsOnBaseSimpleContentRestriction () { XmlReaderSettings settings = new XmlReaderSettings (); - settings.Schemas.Add (null, "Test/XmlFiles/595947.xsd"); + settings.Schemas.Add (null, TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/595947.xsd")); settings.ValidationType = ValidationType.Schema; settings.Schemas.Compile (); @@ -370,7 +372,7 @@ namespace MonoTests.System.Xml [Test] public void Bug676993 () { - Validate (File.ReadAllText ("Test/XmlFiles/676993.xml"), File.ReadAllText ("Test/XmlFiles/676993.xsd")); + Validate (File.ReadAllText (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/676993.xml")), File.ReadAllText (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/676993.xsd"))); } [Test] diff --git a/mcs/class/System.XML/Test/System.Xml.Serialization/ComplexDataStructure.cs b/mcs/class/System.XML/Test/System.Xml.Serialization/ComplexDataStructure.cs index e903d3b2f0..589d7f6082 100644 --- a/mcs/class/System.XML/Test/System.Xml.Serialization/ComplexDataStructure.cs +++ b/mcs/class/System.XML/Test/System.Xml.Serialization/ComplexDataStructure.cs @@ -17,6 +17,8 @@ using System.ComponentModel; using NUnit.Framework; using System.Linq; +using MonoTests.Helpers; + namespace MonoTests.System.XmlSerialization { [TestFixture] @@ -35,7 +37,7 @@ namespace MonoTests.System.XmlSerialization string serialized = sw.ToString (); serialized = XmlSerializerTests.Infoset (serialized); - StreamReader sr = new StreamReader ("Test/XmlFiles/literal-data.xml"); + StreamReader sr = new StreamReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/literal-data.xml")); string expected = sr.ReadToEnd (); sr.Close (); @@ -51,7 +53,7 @@ namespace MonoTests.System.XmlSerialization XmlSerializer ss = new XmlSerializer (GetLiteralTypeMapping ()); XmlSerializerNamespaces nams = new XmlSerializerNamespaces (); - StreamReader sr = new StreamReader ("Test/XmlFiles/literal-data.xml"); + StreamReader sr = new StreamReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/literal-data.xml")); Test data = (Test) ss.Deserialize (sr); sr.Close (); diff --git a/mcs/class/System.XML/Test/System.Xml.Serialization/XmlCodeExporterTests.cs b/mcs/class/System.XML/Test/System.Xml.Serialization/XmlCodeExporterTests.cs index bb8222543c..d08b16b98c 100644 --- a/mcs/class/System.XML/Test/System.Xml.Serialization/XmlCodeExporterTests.cs +++ b/mcs/class/System.XML/Test/System.Xml.Serialization/XmlCodeExporterTests.cs @@ -27,6 +27,8 @@ using NUnit.Framework; using MonoTests.System.Xml.TestClasses; +using MonoTests.Helpers; + namespace MonoTests.System.XmlSerialization { [TestFixture] @@ -931,7 +933,7 @@ namespace MonoTests.System.XmlSerialization [Test] public void DuplicateIdentifiers () { - XmlSchema xs = XmlSchema.Read (File.OpenText ("Test/XmlFiles/xsd/82078.xsd"), null); + XmlSchema xs = XmlSchema.Read (File.OpenText (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/82078.xsd")), null); XmlSchemas xss = new XmlSchemas (); xss.Add (xs); diff --git a/mcs/class/System.XML/Test/System.Xml.Serialization/XmlSchemaImporterTests.cs b/mcs/class/System.XML/Test/System.Xml.Serialization/XmlSchemaImporterTests.cs index f0883beaa6..c48fad629d 100644 --- a/mcs/class/System.XML/Test/System.Xml.Serialization/XmlSchemaImporterTests.cs +++ b/mcs/class/System.XML/Test/System.Xml.Serialization/XmlSchemaImporterTests.cs @@ -46,6 +46,8 @@ using NUnit.Framework; using MonoTests.System.Xml.TestClasses; +using MonoTests.Helpers; + namespace MonoTests.System.Xml.Serialization { [TestFixture] @@ -1159,8 +1161,8 @@ namespace MonoTests.System.Xml.Serialization public void ImportWildcardElementAsClass () { var xss = new XmlSchemas (); - xss.Add (XmlSchema.Read (XmlReader.Create ("Test/XmlFiles/xsd/670945-1.xsd"), null)); - xss.Add (XmlSchema.Read (XmlReader.Create ("Test/XmlFiles/xsd/670945-2.xsd"), null)); + xss.Add (XmlSchema.Read (XmlReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/670945-1.xsd")), null)); + xss.Add (XmlSchema.Read (XmlReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/670945-2.xsd")), null)); var imp = new XmlSchemaImporter (xss); var xtm = imp.ImportSchemaType (new XmlQualifiedName ("SystemDateTime", "http://www.onvif.org/ver10/schema")); var cns = new CodeNamespace (); diff --git a/mcs/class/System.XML/Test/System.Xml.Xsl/XslTransformTests.cs b/mcs/class/System.XML/Test/System.Xml.Xsl/XslTransformTests.cs index d85ff8afcc..9b29638f37 100644 --- a/mcs/class/System.XML/Test/System.Xml.Xsl/XslTransformTests.cs +++ b/mcs/class/System.XML/Test/System.Xml.Xsl/XslTransformTests.cs @@ -16,6 +16,8 @@ using System.Xml.XPath; using System.Xml.Xsl; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Xml.Xsl { [TestFixture] @@ -40,8 +42,8 @@ namespace MonoTests.System.Xml.Xsl { string output = Path.Combine (Path.GetTempPath (), "result.xml"); doc.LoadXml (""); - xslt.Load ("Test/XmlFiles/xsl/empty.xsl"); - xslt.Transform ("Test/XmlFiles/xsl/empty.xsl", output); + xslt.Load (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/empty.xsl")); + xslt.Transform (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/empty.xsl"), output); result.Load (output); Assert.AreEqual (2, result.ChildNodes.Count, "count"); } @@ -380,10 +382,10 @@ xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:msxsl='urn:schemas-micros "; XmlDocument d = new XmlDocument (); - d.Load ("Test/XmlFiles/xsl/91834.xml"); + d.Load (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/91834.xml")); XslTransform t = new XslTransform (); - t.Load ("Test/XmlFiles/xsl/91834.xsl"); + t.Load (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/91834.xsl")); StringWriter sw_raw = new StringWriter (); t.Transform (d, null, sw_raw); @@ -1912,9 +1914,9 @@ Services "; XslTransform t = new XslTransform (); - t.Load ("Test/XmlFiles/xsl/stripspace.xsl"); + t.Load (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/stripspace.xsl")); XPathDocument d = new XPathDocument ( - "Test/XmlFiles/xsl/stripspace.xml", XmlSpace.Preserve); + TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/stripspace.xml"), XmlSpace.Preserve); StringWriter sw = new StringWriter (); t.Transform (d, null, sw); Assert.AreEqual (result, sw.ToString ()); @@ -1924,13 +1926,13 @@ Services public void CurrentInSelect () { XslTransform t = new XslTransform (); - t.Load ("Test/XmlFiles/xsl/current-in-select.xsl"); + t.Load (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/current-in-select.xsl")); XPathDocument d = new XPathDocument ( - "Test/XmlFiles/xsl/current-in-select.xml", XmlSpace.Preserve); + TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/current-in-select.xml"), XmlSpace.Preserve); StringWriter sw = new StringWriter (); t.Transform (d, null, sw); using (StreamReader sr = File.OpenText ( - "Test/XmlFiles/xsl/current-in-select.ref")) { + TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/current-in-select.ref"))) { string s = sr.ReadToEnd (); Assert.AreEqual (s, sw.ToString ()); } @@ -1959,9 +1961,9 @@ Services public void Bug82493 () { XslTransform transformationObj = new XslTransform (); - transformationObj.Load ("Test/XmlFiles/xsl/82493.xsl"); + transformationObj.Load (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/82493.xsl")); XmlDocument doc = new XmlDocument (); - doc.Load ("Test/XmlFiles/xsl/82493.xml"); + doc.Load (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/82493.xml")); XslExtensionClass GetCalculation = new XslExtensionClass ("a4"); XsltArgumentList xslExtensionArgList = new XsltArgumentList (); xslExtensionArgList.AddExtensionObject ("urn:e", GetCalculation); @@ -1974,9 +1976,9 @@ Services public void BugNovell325482 () { XmlDocument doc = new XmlDocument (); - doc.Load ("Test/XmlFiles/xsl/325482.xml"); + doc.Load (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/325482.xml")); XslTransform xt = new XslTransform (); - xt.Load ("Test/XmlFiles/xsl/325482.xsl"); + xt.Load (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/325482.xsl")); xt.Transform (doc, null, TextWriter.Null); } @@ -2167,8 +2169,8 @@ Services [Test] // bug #316238 public void ResolveVariableInXsltArgumentList () { - ResolveVariableInXsltArgumentList ("Test/XmlFiles/xsl/316238-1.xsl"); - ResolveVariableInXsltArgumentList ("Test/XmlFiles/xsl/316238-2.xsl"); + ResolveVariableInXsltArgumentList (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/316238-1.xsl")); + ResolveVariableInXsltArgumentList (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/316238-2.xsl")); } void ResolveVariableInXsltArgumentList (string file) @@ -2360,9 +2362,9 @@ NO XslCompiledTransform xslTransform = new XslCompiledTransform (); XsltSettings settings = new XsltSettings (); settings.EnableDocumentFunction = true; - xslTransform.Load ("Test/XmlFiles/xsl/391424.xsl", settings, new XmlUrlResolver ()); + xslTransform.Load (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/391424.xsl"), settings, new XmlUrlResolver ()); StringWriter sw = new StringWriter (); - xslTransform.Transform (new XPathDocument ("Test/XmlFiles/xsl/391424.xml", XmlSpace.Preserve), null, sw); + xslTransform.Transform (new XPathDocument (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsl/391424.xml"), XmlSpace.Preserve), null, sw); Assert.AreEqual ("Document found", sw.ToString ()); } diff --git a/mcs/class/System.XML/Test/System.Xml/XmlNodeTests.cs b/mcs/class/System.XML/Test/System.Xml/XmlNodeTests.cs index 89e659542d..895475450a 100644 --- a/mcs/class/System.XML/Test/System.Xml/XmlNodeTests.cs +++ b/mcs/class/System.XML/Test/System.Xml/XmlNodeTests.cs @@ -16,6 +16,8 @@ using System.Xml; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Xml { [TestFixture] @@ -448,7 +450,7 @@ namespace MonoTests.System.Xml { // See bug #64120. XmlDocument doc = new XmlDocument (); - doc.Load ("Test/XmlFiles/simple.xml"); + doc.Load (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/simple.xml")); XmlElement el = doc.CreateElement ("foo"); Assert.AreEqual (String.Empty, el.BaseURI); doc.DocumentElement.AppendChild (el); diff --git a/mcs/class/System.XML/Test/System.Xml/XmlReaderCommonTests.cs b/mcs/class/System.XML/Test/System.Xml/XmlReaderCommonTests.cs index 764ce368cf..6cd8763187 100644 --- a/mcs/class/System.XML/Test/System.Xml/XmlReaderCommonTests.cs +++ b/mcs/class/System.XML/Test/System.Xml/XmlReaderCommonTests.cs @@ -20,6 +20,8 @@ using System.Threading.Tasks; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Xml { [TestFixture] @@ -1515,7 +1517,7 @@ namespace MonoTests.System.Xml { XmlReaderSettings s = new XmlReaderSettings (); s.ProhibitDtd = false; - XmlReader xr = XmlReader.Create ("Test/XmlFiles/nested-dtd-test.xml", s); + XmlReader xr = XmlReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/nested-dtd-test.xml"), s); xr.Read (); Assert.AreEqual (XmlNodeType.DocumentType, xr.NodeType, "#1"); xr.Read (); @@ -1528,7 +1530,7 @@ namespace MonoTests.System.Xml [ExpectedException (typeof (XmlException))] public void CreateSimpleProhibitDtd () { - XmlReader xr = XmlReader.Create ("Test/XmlFiles/nested-dtd-test.xml"); + XmlReader xr = XmlReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/nested-dtd-test.xml")); xr.Read (); } diff --git a/mcs/class/System.XML/Test/System.Xml/XmlReaderSettingsTests.cs b/mcs/class/System.XML/Test/System.Xml/XmlReaderSettingsTests.cs index 2b20f06e97..c596fa2338 100644 --- a/mcs/class/System.XML/Test/System.Xml/XmlReaderSettingsTests.cs +++ b/mcs/class/System.XML/Test/System.Xml/XmlReaderSettingsTests.cs @@ -18,6 +18,8 @@ using System.Reflection; using ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags; using AssertType = NUnit.Framework.Assert; +using MonoTests.Helpers; + namespace MonoTests.System.Xml { [TestFixture] @@ -150,7 +152,7 @@ namespace MonoTests.System.Xml public void CreateAndSettings () { Assert.IsNotNull (XmlReader.Create (CreateStream ("")).Settings); - Assert.IsNotNull (XmlReader.Create ("Test/XmlFiles/simple.xml").Settings); + Assert.IsNotNull (XmlReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/simple.xml")).Settings); } [Test] @@ -297,7 +299,7 @@ namespace MonoTests.System.Xml public void CreateValidatorFromNonIXmlNamespaceResolver () { XmlReaderSettings settings = new XmlReaderSettings (); - settings.Schemas.Add (null, "Test/XmlFiles/xsd/xml.xsd"); + settings.Schemas.Add (null, TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/xml.xsd")); settings.ValidationType = ValidationType.Schema; XmlReader xr = XmlReader.Create (new StringReader ("")); XmlReader dr = new Commons.Xml.XmlDefaultReader (xr); @@ -311,7 +313,7 @@ namespace MonoTests.System.Xml { XmlReaderSettings settings = new XmlReaderSettings (); settings.XmlResolver = null; - using (XmlReader xr = XmlReader.Create ("Test/XmlFiles/simple.xml", settings)) { + using (XmlReader xr = XmlReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/simple.xml"), settings)) { while (!xr.EOF) xr.Read (); } @@ -335,7 +337,7 @@ namespace MonoTests.System.Xml { XmlReaderSettings settings = new XmlReaderSettings (); settings.XmlResolver = new ThrowExceptionResolver (); - using (XmlReader xr = XmlReader.Create ("Test/XmlFiles/simple.xml", settings)) { + using (XmlReader xr = XmlReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/simple.xml"), settings)) { while (!xr.EOF) xr.Read (); } @@ -367,7 +369,7 @@ namespace MonoTests.System.Xml XmlSchema xs = new XmlSchema (); settings.Schemas.Add (xs); settings.ValidationType = ValidationType.Schema; - using (XmlReader r = XmlReader.Create ("Test/XmlFiles/simple.xml", settings)) { + using (XmlReader r = XmlReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/simple.xml"), settings)) { r.Read (); } } diff --git a/mcs/class/System.XML/Test/System.Xml/XmlTextReaderTests.cs b/mcs/class/System.XML/Test/System.Xml/XmlTextReaderTests.cs index 7205ea7d73..0fe11ec16e 100644 --- a/mcs/class/System.XML/Test/System.Xml/XmlTextReaderTests.cs +++ b/mcs/class/System.XML/Test/System.Xml/XmlTextReaderTests.cs @@ -15,6 +15,8 @@ using System.Text; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Xml { [TestFixture] @@ -651,7 +653,7 @@ namespace MonoTests.System.Xml public void ExternalDocument () { XmlDocument doc = new XmlDocument (); - doc.Load ("Test/XmlFiles/nested-dtd-test.xml"); + doc.Load (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/nested-dtd-test.xml")); } [Test] @@ -868,7 +870,7 @@ namespace MonoTests.System.Xml [Test] public void CloseIsNotAlwaysEOF2 () { - XmlTextReader xtr = new XmlTextReader ("Test/XmlFiles/simple.xml"); + XmlTextReader xtr = new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/simple.xml")); xtr.Close (); Assert.IsTrue (!xtr.EOF); // Close() != EOF } @@ -1119,7 +1121,7 @@ namespace MonoTests.System.Xml { XmlTextReader xtr = null; try { - xtr = new XmlTextReader (File.OpenText ("Test/XmlFiles/76102.xml")); + xtr = new XmlTextReader (File.OpenText (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/76102.xml"))); while (!xtr.EOF) xtr.Read (); } finally { diff --git a/mcs/class/System.XML/Test/System.Xml/XmlUrlResolverTests.cs b/mcs/class/System.XML/Test/System.Xml/XmlUrlResolverTests.cs index 6926379c96..9d085ec503 100644 --- a/mcs/class/System.XML/Test/System.Xml/XmlUrlResolverTests.cs +++ b/mcs/class/System.XML/Test/System.Xml/XmlUrlResolverTests.cs @@ -12,6 +12,8 @@ using System.Xml; using NUnit.Framework; using System.Reflection; +using MonoTests.Helpers; + namespace MonoTests.System.Xml { [TestFixture] @@ -28,7 +30,7 @@ namespace MonoTests.System.Xml [Test] public void FileUri () { - Uri resolved = resolver.ResolveUri (null, "Test/XmlFiles/xsd/xml.xsd"); + Uri resolved = resolver.ResolveUri (null, TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/xml.xsd")); Assert.AreEqual ("file", resolved.Scheme); Stream s = resolver.GetEntity (resolved, null, typeof (Stream)) as Stream; } diff --git a/mcs/class/System.XML/Test/System.Xml/XsdParticleValidationTests.cs b/mcs/class/System.XML/Test/System.Xml/XsdParticleValidationTests.cs index 69c12c7c52..079ea1d8c8 100644 --- a/mcs/class/System.XML/Test/System.Xml/XsdParticleValidationTests.cs +++ b/mcs/class/System.XML/Test/System.Xml/XsdParticleValidationTests.cs @@ -13,6 +13,8 @@ using NUnit.Framework; using ValidationException = System.Xml.Schema.XmlSchemaValidationException; +using MonoTests.Helpers; + namespace MonoTests.System.Xml { // using XmlValidatingReader = XmlTextReader; @@ -26,7 +28,7 @@ namespace MonoTests.System.Xml private void PrepareReader1 (string xsdUrl, string xml) { - schema = XmlSchema.Read (new XmlTextReader ("Test/XmlFiles/XsdValidation/" + xsdUrl), null); + schema = XmlSchema.Read (new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/XsdValidation/" + xsdUrl)), null); xr = new XmlTextReader (xml, XmlNodeType.Document, null); xvr = new XmlValidatingReader (xr); xvr.Schemas.Add (schema); diff --git a/mcs/class/System.XML/Test/System.Xml/XsdValidatingReaderTests.cs b/mcs/class/System.XML/Test/System.Xml/XsdValidatingReaderTests.cs index 8bbcf11706..ac5ced83bb 100644 --- a/mcs/class/System.XML/Test/System.Xml/XsdValidatingReaderTests.cs +++ b/mcs/class/System.XML/Test/System.Xml/XsdValidatingReaderTests.cs @@ -1,633 +1,635 @@ -// -// MonoTests.System.Xml.XsdValidatingReaderTests.cs -// -// Author: -// Atsushi Enomoto -// -// (C)2003 Atsushi Enomoto -// (C)2005-2007 Novell, Inc. -// -using System; -using System.IO; -using System.Net; -using System.Xml; -using System.Xml.Schema; -using NUnit.Framework; - -namespace MonoTests.System.Xml -{ - [TestFixture] - public class XsdValidatingReaderTests - { - public XsdValidatingReaderTests () - { - } - - XmlReader xtr; - XmlValidatingReader xvr; - - private XmlValidatingReader PrepareXmlReader (string xml) - { - XmlReader reader = new XmlTextReader (xml, XmlNodeType.Document, null); -// XmlDocument doc = new XmlDocument (); -// doc.LoadXml (xml); -// XmlReader reader = new XmlNodeReader (doc); - - return new XmlValidatingReader (reader); - } - - [Test] - public void TestEmptySchema () - { - string xml = ""; - xvr = PrepareXmlReader (xml); - xvr.ValidationType = ValidationType.Schema; - xvr.Read (); // Is is missing schema component. - } - - [Test] - public void TestSimpleValidation () - { - string xml = ""; - xvr = PrepareXmlReader (xml); - Assert.AreEqual (ValidationType.Auto, xvr.ValidationType); - XmlSchema schema = new XmlSchema (); - XmlSchemaElement elem = new XmlSchemaElement (); - elem.Name = "root"; - schema.Items.Add (elem); - xvr.Schemas.Add (schema); - xvr.Read (); // root - Assert.AreEqual (ValidationType.Auto, xvr.ValidationType); - xvr.Read (); // EOF - - xml = ""; - xvr = PrepareXmlReader (xml); - xvr.Schemas.Add (schema); - try { - xvr.Read (); - Assert.Fail ("element mismatch is incorrectly allowed"); - } catch (XmlSchemaException) { - } - - xml = ""; - xvr = PrepareXmlReader (xml); - xvr.Schemas.Add (schema); - try { - xvr.Read (); - Assert.Fail ("Element in different namespace is incorrectly allowed."); - } catch (XmlSchemaException) { - } - } - - [Test] - public void TestReadTypedValueSimple () - { - string xml = "12"; - XmlSchema schema = new XmlSchema (); - XmlSchemaElement elem = new XmlSchemaElement (); - elem.Name = "root"; - elem.SchemaTypeName = new XmlQualifiedName ("integer", XmlSchema.Namespace); - schema.Items.Add (elem); - - // Lap 1: - - xvr = PrepareXmlReader (xml); - xvr.Schemas.Add (schema); - // Read directly from root. - object o = xvr.ReadTypedValue (); - Assert.AreEqual (ReadState.Initial, xvr.ReadState); - Assert.IsNull (o); - - xvr.Read (); // element root - Assert.AreEqual (XmlNodeType.Element, xvr.NodeType); - Assert.IsNotNull (xvr.SchemaType); - Assert.IsTrue (xvr.SchemaType is XmlSchemaDatatype); - o = xvr.ReadTypedValue (); // read "12" - Assert.AreEqual (XmlNodeType.EndElement, xvr.NodeType); - Assert.IsNotNull (o); - Assert.AreEqual (typeof (decimal), o.GetType ()); - decimal n = (decimal) o; - Assert.AreEqual (12, n); - Assert.IsTrue (!xvr.EOF); - Assert.AreEqual ("root", xvr.Name); - Assert.IsNull (xvr.SchemaType); // EndElement's type - - // Lap 2: - - xvr = PrepareXmlReader (xml); - xvr.Schemas.Add (schema); - xvr.Read (); // root - XmlSchemaDatatype dt = xvr.SchemaType as XmlSchemaDatatype; - Assert.IsNotNull (dt); - Assert.AreEqual (typeof (decimal), dt.ValueType); - Assert.AreEqual (XmlTokenizedType.None, dt.TokenizedType); - xvr.Read (); // text "12" - Assert.IsNull (xvr.SchemaType); - o = xvr.ReadTypedValue (); - // ReadTypedValue is different from ReadString(). - Assert.IsNull (o); - } - - [Test] - [Ignore ("XML Schema validator should not be available for validating non namespace-aware XmlReader that handled colon as a name character")] - public void TestNamespacesFalse () - { - // This tests if Namespaces=false is specified, then - // the reader's NamespaceURI should be always string.Empty and - // validation should be done against such schema that has target ns as "". - string xml = ""; - xvr = PrepareXmlReader (xml); - xvr.Namespaces = false; - Assert.AreEqual (ValidationType.Auto, xvr.ValidationType); - XmlSchema schema = new XmlSchema (); - schema.TargetNamespace = "urn:foo"; - XmlSchemaElement elem = new XmlSchemaElement (); - elem.Name = "root"; - schema.Items.Add (elem); - xvr.Schemas.Add (schema); - xvr.Read (); // root - Assert.IsTrue (!xvr.Namespaces); - Assert.AreEqual ("x:root", xvr.Name); - // LocalName may contain colons. - Assert.AreEqual ("x:root", xvr.LocalName); - // NamespaceURI is not supplied. - Assert.AreEqual ("", xvr.NamespaceURI); - } - - [Test] - public void TestReadTypedAttributeValue () - { - string xml = ""; - XmlSchema schema = new XmlSchema (); - XmlSchemaElement elem = new XmlSchemaElement (); - elem.Name = "root"; - XmlSchemaComplexType ct = new XmlSchemaComplexType (); - XmlSchemaAttribute attr = new XmlSchemaAttribute (); - attr.Name = "attr"; - attr.SchemaTypeName = new XmlQualifiedName ("int", XmlSchema.Namespace); - ct.Attributes.Add (attr); - elem.SchemaType = ct; - schema.Items.Add (elem); - - xvr = PrepareXmlReader (xml); - xvr.Schemas.Add (schema); - xvr.Read (); - Assert.AreEqual ("root", xvr.Name); - Assert.IsTrue (xvr.MoveToNextAttribute ()); // attr - Assert.AreEqual ("attr", xvr.Name); - XmlSchemaDatatype dt = xvr.SchemaType as XmlSchemaDatatype; - Assert.IsNotNull (dt); - Assert.AreEqual (typeof (int), dt.ValueType); - Assert.AreEqual (XmlTokenizedType.None, dt.TokenizedType); - object o = xvr.ReadTypedValue (); - Assert.AreEqual (XmlNodeType.Attribute, xvr.NodeType); - Assert.AreEqual (typeof (int), o.GetType ()); - int n = (int) o; - Assert.AreEqual (12, n); - Assert.IsTrue (xvr.ReadAttributeValue ()); // can read = seems not proceed. - } - - [Test] - public void DuplicateSchemaAssignment () - { - string xml = @""; - string xsd = @" - "; - - string xmlns = "http://www.test.com/schemas/"; - - XmlValidatingReader xvr = new XmlValidatingReader ( - xml, XmlNodeType.Document, null); - XmlSchemaCollection schemas = new XmlSchemaCollection (); - schemas.Add (XmlSchema.Read (new XmlTextReader ( - xsd, XmlNodeType.Document, null), null)); - xvr.Schemas.Add (schemas); - while (!xvr.EOF) - xvr.Read (); - } - - [Test] // bug #76234 - public void DTDValidatorNamespaceHandling () - { - string xml = " "; - XmlValidatingReader vr = new XmlValidatingReader ( - xml, XmlNodeType.Document, null); - vr.Read (); - vr.Read (); // whitespace - Assert.AreEqual (String.Empty, vr.NamespaceURI, "#1"); - vr.Read (); // foo - Assert.AreEqual ("urn:a", vr.NamespaceURI, "#2"); - vr.Read (); // whitespace - vr.Read (); // a:bar - Assert.AreEqual ("urn:a", vr.NamespaceURI, "#3"); - vr.Read (); // whitespace - vr.Read (); // bug - Assert.AreEqual ("urn:a", vr.NamespaceURI, "#4"); - } - - [Test] - public void MultipleSchemaInSchemaLocation () - { - XmlTextReader xtr = new XmlTextReader ("Test/XmlFiles/xsd/multi-schemaLocation.xml"); - XmlValidatingReader vr = new XmlValidatingReader (xtr); - while (!vr.EOF) - vr.Read (); - } - - [Test] - public void ReadTypedValueSimpleTypeRestriction () - { - string xml = "xx"; - string xsd = @" - - - - - - - - -"; - XmlTextReader xir = - new XmlTextReader (xml, XmlNodeType.Document, null); - XmlTextReader xsr = - new XmlTextReader (xsd, XmlNodeType.Document, null); - XmlValidatingReader vr = new XmlValidatingReader (xir); - vr.Schemas.Add (XmlSchema.Read (xsr, null)); - vr.Read (); // root - Assert.AreEqual ("xx", vr.ReadTypedValue ()); - Assert.AreEqual (XmlNodeType.EndElement, vr.NodeType); - } - - // If we normalize string before validating with facets, - // this test will fail. It will also fail if ReadTypedValue() - // ignores whitespace nodes. - [Test] - public void ReadTypedValueWhitespaces () - { - string xml = " "; - string xsd = @" - - - - - - - - -"; - XmlTextReader xir = - new XmlTextReader (xml, XmlNodeType.Document, null); - XmlTextReader xsr = - new XmlTextReader (xsd, XmlNodeType.Document, null); - XmlValidatingReader vr = new XmlValidatingReader (xir); - vr.Schemas.Add (XmlSchema.Read (xsr, null)); - vr.Read (); // root - Assert.AreEqual (" ", vr.ReadTypedValue ()); - Assert.AreEqual (XmlNodeType.EndElement, vr.NodeType); - } - - [Test] // bug #77241 - public void EmptyContentAllowWhitespace () - { - string doc = @" - - - - -"; - string schema = @" - - - - - - - - - -"; - XmlValidatingReader reader = new XmlValidatingReader ( - new XmlTextReader (new StringReader (doc))); - reader.Schemas.Add (null, - new XmlTextReader (new StringReader (schema))); - while (reader.Read ()) - ; - } - - [Test] // bug #79650 +// +// MonoTests.System.Xml.XsdValidatingReaderTests.cs +// +// Author: +// Atsushi Enomoto +// +// (C)2003 Atsushi Enomoto +// (C)2005-2007 Novell, Inc. +// +using System; +using System.IO; +using System.Net; +using System.Xml; +using System.Xml.Schema; +using NUnit.Framework; + +using MonoTests.Helpers; + +namespace MonoTests.System.Xml +{ + [TestFixture] + public class XsdValidatingReaderTests + { + public XsdValidatingReaderTests () + { + } + + XmlReader xtr; + XmlValidatingReader xvr; + + private XmlValidatingReader PrepareXmlReader (string xml) + { + XmlReader reader = new XmlTextReader (xml, XmlNodeType.Document, null); +// XmlDocument doc = new XmlDocument (); +// doc.LoadXml (xml); +// XmlReader reader = new XmlNodeReader (doc); + + return new XmlValidatingReader (reader); + } + + [Test] + public void TestEmptySchema () + { + string xml = ""; + xvr = PrepareXmlReader (xml); + xvr.ValidationType = ValidationType.Schema; + xvr.Read (); // Is is missing schema component. + } + + [Test] + public void TestSimpleValidation () + { + string xml = ""; + xvr = PrepareXmlReader (xml); + Assert.AreEqual (ValidationType.Auto, xvr.ValidationType); + XmlSchema schema = new XmlSchema (); + XmlSchemaElement elem = new XmlSchemaElement (); + elem.Name = "root"; + schema.Items.Add (elem); + xvr.Schemas.Add (schema); + xvr.Read (); // root + Assert.AreEqual (ValidationType.Auto, xvr.ValidationType); + xvr.Read (); // EOF + + xml = ""; + xvr = PrepareXmlReader (xml); + xvr.Schemas.Add (schema); + try { + xvr.Read (); + Assert.Fail ("element mismatch is incorrectly allowed"); + } catch (XmlSchemaException) { + } + + xml = ""; + xvr = PrepareXmlReader (xml); + xvr.Schemas.Add (schema); + try { + xvr.Read (); + Assert.Fail ("Element in different namespace is incorrectly allowed."); + } catch (XmlSchemaException) { + } + } + + [Test] + public void TestReadTypedValueSimple () + { + string xml = "12"; + XmlSchema schema = new XmlSchema (); + XmlSchemaElement elem = new XmlSchemaElement (); + elem.Name = "root"; + elem.SchemaTypeName = new XmlQualifiedName ("integer", XmlSchema.Namespace); + schema.Items.Add (elem); + + // Lap 1: + + xvr = PrepareXmlReader (xml); + xvr.Schemas.Add (schema); + // Read directly from root. + object o = xvr.ReadTypedValue (); + Assert.AreEqual (ReadState.Initial, xvr.ReadState); + Assert.IsNull (o); + + xvr.Read (); // element root + Assert.AreEqual (XmlNodeType.Element, xvr.NodeType); + Assert.IsNotNull (xvr.SchemaType); + Assert.IsTrue (xvr.SchemaType is XmlSchemaDatatype); + o = xvr.ReadTypedValue (); // read "12" + Assert.AreEqual (XmlNodeType.EndElement, xvr.NodeType); + Assert.IsNotNull (o); + Assert.AreEqual (typeof (decimal), o.GetType ()); + decimal n = (decimal) o; + Assert.AreEqual (12, n); + Assert.IsTrue (!xvr.EOF); + Assert.AreEqual ("root", xvr.Name); + Assert.IsNull (xvr.SchemaType); // EndElement's type + + // Lap 2: + + xvr = PrepareXmlReader (xml); + xvr.Schemas.Add (schema); + xvr.Read (); // root + XmlSchemaDatatype dt = xvr.SchemaType as XmlSchemaDatatype; + Assert.IsNotNull (dt); + Assert.AreEqual (typeof (decimal), dt.ValueType); + Assert.AreEqual (XmlTokenizedType.None, dt.TokenizedType); + xvr.Read (); // text "12" + Assert.IsNull (xvr.SchemaType); + o = xvr.ReadTypedValue (); + // ReadTypedValue is different from ReadString(). + Assert.IsNull (o); + } + + [Test] + [Ignore ("XML Schema validator should not be available for validating non namespace-aware XmlReader that handled colon as a name character")] + public void TestNamespacesFalse () + { + // This tests if Namespaces=false is specified, then + // the reader's NamespaceURI should be always string.Empty and + // validation should be done against such schema that has target ns as "". + string xml = ""; + xvr = PrepareXmlReader (xml); + xvr.Namespaces = false; + Assert.AreEqual (ValidationType.Auto, xvr.ValidationType); + XmlSchema schema = new XmlSchema (); + schema.TargetNamespace = "urn:foo"; + XmlSchemaElement elem = new XmlSchemaElement (); + elem.Name = "root"; + schema.Items.Add (elem); + xvr.Schemas.Add (schema); + xvr.Read (); // root + Assert.IsTrue (!xvr.Namespaces); + Assert.AreEqual ("x:root", xvr.Name); + // LocalName may contain colons. + Assert.AreEqual ("x:root", xvr.LocalName); + // NamespaceURI is not supplied. + Assert.AreEqual ("", xvr.NamespaceURI); + } + + [Test] + public void TestReadTypedAttributeValue () + { + string xml = ""; + XmlSchema schema = new XmlSchema (); + XmlSchemaElement elem = new XmlSchemaElement (); + elem.Name = "root"; + XmlSchemaComplexType ct = new XmlSchemaComplexType (); + XmlSchemaAttribute attr = new XmlSchemaAttribute (); + attr.Name = "attr"; + attr.SchemaTypeName = new XmlQualifiedName ("int", XmlSchema.Namespace); + ct.Attributes.Add (attr); + elem.SchemaType = ct; + schema.Items.Add (elem); + + xvr = PrepareXmlReader (xml); + xvr.Schemas.Add (schema); + xvr.Read (); + Assert.AreEqual ("root", xvr.Name); + Assert.IsTrue (xvr.MoveToNextAttribute ()); // attr + Assert.AreEqual ("attr", xvr.Name); + XmlSchemaDatatype dt = xvr.SchemaType as XmlSchemaDatatype; + Assert.IsNotNull (dt); + Assert.AreEqual (typeof (int), dt.ValueType); + Assert.AreEqual (XmlTokenizedType.None, dt.TokenizedType); + object o = xvr.ReadTypedValue (); + Assert.AreEqual (XmlNodeType.Attribute, xvr.NodeType); + Assert.AreEqual (typeof (int), o.GetType ()); + int n = (int) o; + Assert.AreEqual (12, n); + Assert.IsTrue (xvr.ReadAttributeValue ()); // can read = seems not proceed. + } + + [Test] + public void DuplicateSchemaAssignment () + { + string xml = @""; + string xsd = @" + "; + + string xmlns = "http://www.test.com/schemas/"; + + XmlValidatingReader xvr = new XmlValidatingReader ( + xml, XmlNodeType.Document, null); + XmlSchemaCollection schemas = new XmlSchemaCollection (); + schemas.Add (XmlSchema.Read (new XmlTextReader ( + xsd, XmlNodeType.Document, null), null)); + xvr.Schemas.Add (schemas); + while (!xvr.EOF) + xvr.Read (); + } + + [Test] // bug #76234 + public void DTDValidatorNamespaceHandling () + { + string xml = " "; + XmlValidatingReader vr = new XmlValidatingReader ( + xml, XmlNodeType.Document, null); + vr.Read (); + vr.Read (); // whitespace + Assert.AreEqual (String.Empty, vr.NamespaceURI, "#1"); + vr.Read (); // foo + Assert.AreEqual ("urn:a", vr.NamespaceURI, "#2"); + vr.Read (); // whitespace + vr.Read (); // a:bar + Assert.AreEqual ("urn:a", vr.NamespaceURI, "#3"); + vr.Read (); // whitespace + vr.Read (); // bug + Assert.AreEqual ("urn:a", vr.NamespaceURI, "#4"); + } + + [Test] + public void MultipleSchemaInSchemaLocation () + { + XmlTextReader xtr = new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/multi-schemaLocation.xml")); + XmlValidatingReader vr = new XmlValidatingReader (xtr); + while (!vr.EOF) + vr.Read (); + } + + [Test] + public void ReadTypedValueSimpleTypeRestriction () + { + string xml = "xx"; + string xsd = @" + + + + + + + + +"; + XmlTextReader xir = + new XmlTextReader (xml, XmlNodeType.Document, null); + XmlTextReader xsr = + new XmlTextReader (xsd, XmlNodeType.Document, null); + XmlValidatingReader vr = new XmlValidatingReader (xir); + vr.Schemas.Add (XmlSchema.Read (xsr, null)); + vr.Read (); // root + Assert.AreEqual ("xx", vr.ReadTypedValue ()); + Assert.AreEqual (XmlNodeType.EndElement, vr.NodeType); + } + + // If we normalize string before validating with facets, + // this test will fail. It will also fail if ReadTypedValue() + // ignores whitespace nodes. + [Test] + public void ReadTypedValueWhitespaces () + { + string xml = " "; + string xsd = @" + + + + + + + + +"; + XmlTextReader xir = + new XmlTextReader (xml, XmlNodeType.Document, null); + XmlTextReader xsr = + new XmlTextReader (xsd, XmlNodeType.Document, null); + XmlValidatingReader vr = new XmlValidatingReader (xir); + vr.Schemas.Add (XmlSchema.Read (xsr, null)); + vr.Read (); // root + Assert.AreEqual (" ", vr.ReadTypedValue ()); + Assert.AreEqual (XmlNodeType.EndElement, vr.NodeType); + } + + [Test] // bug #77241 + public void EmptyContentAllowWhitespace () + { + string doc = @" + + + + +"; + string schema = @" + + + + + + + + + +"; + XmlValidatingReader reader = new XmlValidatingReader ( + new XmlTextReader (new StringReader (doc))); + reader.Schemas.Add (null, + new XmlTextReader (new StringReader (schema))); + while (reader.Read ()) + ; + } + + [Test] // bug #79650 // LAMESPEC: .NET does not throw XmlSchemaValidationException - [ExpectedException (typeof (XmlSchemaException))] - public void EnumerationFacetOnAttribute () - { - string xml = ""; - XmlSchema schema = XmlSchema.Read (new XmlTextReader ("Test/XmlFiles/xsd/79650.xsd"), null); - XmlValidatingReader xvr = new XmlValidatingReader (xml, XmlNodeType.Document, null); - xvr.ValidationType = ValidationType.Schema; - xvr.Schemas.Add (schema); - while (!xvr.EOF) - xvr.Read (); - } - - class XmlErrorResolver : XmlResolver - { - public override ICredentials Credentials { - set { } - } - - public override object GetEntity (Uri uri, string role, Type type) - { - throw new Exception (); - } - } - - [Test] // bug #79924 - public void ValidationTypeNoneIgnoreSchemaLocations () - { - string xml = ""; - XmlValidatingReader vr = new XmlValidatingReader ( - new XmlTextReader (new StringReader (xml))); - vr.ValidationType = ValidationType.None; - vr.XmlResolver = new XmlErrorResolver (); - while (!vr.EOF) - vr.Read (); - } - - [Test] // bug #336625 - public void ValidationTypeNoneIgnoreLocatedSchemaErrors () - { - string xml = ""; - XmlValidatingReader vr = new XmlValidatingReader ( - new XmlTextReader (new StringReader (xml))); - vr.ValidationType = ValidationType.None; - while (!vr.EOF) - vr.Read (); - } - - [Test] - public void Bug81360 () - { - string schemaFile = "Test/XmlFiles/xsd/81360.xsd"; - XmlTextReader treader = new XmlTextReader (schemaFile); - XmlSchema sc = XmlSchema.Read (treader, null); - sc.Compile (null); - string xml = @"
"; - XmlTextReader reader = new XmlTextReader (new StringReader (xml)); - XmlValidatingReader validator = new XmlValidatingReader (reader); - validator.Schemas.Add (sc); - validator.ValidationType = ValidationType.Schema; - while (!validator.EOF) - validator.Read (); - } - - [Test] - public void Bug81460 () - { - string xsd = ""; - string xml = ""; - XmlReaderSettings s = new XmlReaderSettings (); - s.ValidationType = ValidationType.Schema; - s.Schemas.Add (XmlSchema.Read (new StringReader (xsd), null)); - XmlReader r = XmlReader.Create (new StringReader (xml), s); - r.Read (); - r.MoveToFirstAttribute (); // default attribute - Assert.AreEqual (String.Empty, r.Prefix); - } - - [Test] - // annoyance - [ExpectedException (typeof (XmlSchemaValidationException))] - public void Bug82099 () - { - string xsd = @" - - - - - -"; - XmlSchema schema = XmlSchema.Read (new StringReader (xsd), null); - - string xml = " "; - - XmlReaderSettings settings = new XmlReaderSettings (); - settings.Schemas.Add (schema); - settings.ValidationType = ValidationType.Schema; - - XmlReader reader = XmlReader.Create (new StringReader (xml), settings); - - reader.Read (); - reader.Read (); - reader.Read (); - } - - [Test] - public void Bug82010 () - { - string xmlfile = "Test/XmlFiles/xsd/82010.xml"; - string xsdfile = "Test/XmlFiles/xsd/82010.xsd"; - XmlTextReader xr = null, xr2 = null; - try { - xr = new XmlTextReader (xsdfile); - xr2 = new XmlTextReader (xmlfile); - XmlValidatingReader xvr = new XmlValidatingReader (xr2); - xvr.Schemas.Add (XmlSchema.Read (xr, null)); - while (!xvr.EOF) - xvr.Read (); - } finally { - if (xr2 != null) - xr2.Close (); - if (xr != null) - xr.Close (); - } - } - - [Test] - public void Bug376395 () - { - string xmlfile = "Test/XmlFiles/xsd/376395.xml"; - string xsdfile = "Test/XmlFiles/xsd/376395.xsd"; - XmlTextReader xr = null, xr2 = null; - try { - xr = new XmlTextReader (xsdfile); - xr2 = new XmlTextReader (xmlfile); - XmlValidatingReader xvr = new XmlValidatingReader (xr2); - xvr.Schemas.Add (XmlSchema.Read (xr, null)); - while (!xvr.EOF) - xvr.Read (); - } finally { - if (xr2 != null) - xr2.Close (); - if (xr != null) - xr.Close (); - } - } - - [Test] - public void ValidateMixedInsideXsdAny () - { - string xml = @" - text - text -"; - string xsd = @" - - - - - - - - - - - - - - - -"; - XmlTextReader xtr = new XmlTextReader (new StringReader (xml)); - XmlValidatingReader xvr = new XmlValidatingReader (xtr); - XmlReader xsr = new XmlTextReader (new StringReader (xsd)); - xvr.Schemas.Add (XmlSchema.Read (xsr, null)); - while (!xvr.EOF) - xvr.Read (); - xtr = new XmlTextReader (new StringReader (xml)); - xsr = new XmlTextReader (new StringReader (xsd)); - var s = new XmlReaderSettings (); - s.Schemas.Add (XmlSchema.Read (xsr, null)); - s.ValidationType = ValidationType.Schema; - XmlReader xvr2 = XmlReader.Create (xtr, s); - while (!xvr2.EOF) - xvr2.Read (); - } - - [Test] - public void WhitespaceAndElementOnly () - { - string xsd = @" - - - - - - - -"; - string xml = @" - - - - - -"; - RunValidation (xml, xsd); - } - - [Test] - [ExpectedException (typeof (XmlSchemaValidationException))] - public void EnumerationFacet () - { - // bug #339934 - string xsd = @" - - - - - - - - - - - - -"; - string xml = @""; - - RunValidation (xml, xsd); - } - - [Test] - public void Bug501763 () - { - string xsd1 = @" - - - - - "; - - string xsd2 = @" - - - - - - - - - - - - - - - - "; - - - XmlDocument doc = new XmlDocument (); - - XmlSchema schema1 = XmlSchema.Read (XmlReader.Create (new StringReader (xsd1)), null); - XmlSchema schema2 = XmlSchema.Read (XmlReader.Create (new StringReader (xsd2)), null); - - doc.LoadXml (@" - "); - doc.Schemas.Add (schema2); - doc.Validate (null); - - doc = new XmlDocument(); - doc.LoadXml(@" - "); - doc.Schemas.Add (schema2); - doc.Schemas.Add (schema1); - doc.Validate (null); - } - - void RunValidation (string xml, string xsd) - { - XmlReaderSettings s = new XmlReaderSettings (); - s.ValidationType = ValidationType.Schema; - s.Schemas.Add (XmlSchema.Read (XmlReader.Create (new StringReader (xsd)), null)); - - XmlReader r = XmlReader.Create (new StringReader (xml), s); - while (!r.EOF) - r.Read (); - } - } -} + [ExpectedException (typeof (XmlSchemaException))] + public void EnumerationFacetOnAttribute () + { + string xml = ""; + XmlSchema schema = XmlSchema.Read (new XmlTextReader (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/xsd/79650.xsd")), null); + XmlValidatingReader xvr = new XmlValidatingReader (xml, XmlNodeType.Document, null); + xvr.ValidationType = ValidationType.Schema; + xvr.Schemas.Add (schema); + while (!xvr.EOF) + xvr.Read (); + } + + class XmlErrorResolver : XmlResolver + { + public override ICredentials Credentials { + set { } + } + + public override object GetEntity (Uri uri, string role, Type type) + { + throw new Exception (); + } + } + + [Test] // bug #79924 + public void ValidationTypeNoneIgnoreSchemaLocations () + { + string xml = ""; + XmlValidatingReader vr = new XmlValidatingReader ( + new XmlTextReader (new StringReader (xml))); + vr.ValidationType = ValidationType.None; + vr.XmlResolver = new XmlErrorResolver (); + while (!vr.EOF) + vr.Read (); + } + + [Test] // bug #336625 + public void ValidationTypeNoneIgnoreLocatedSchemaErrors () + { + string xml = ""; + XmlValidatingReader vr = new XmlValidatingReader ( + new XmlTextReader (new StringReader (xml))); + vr.ValidationType = ValidationType.None; + while (!vr.EOF) + vr.Read (); + } + + [Test] + public void Bug81360 () + { + string schemaResource = "Test/XmlFiles/xsd/81360.xsd"; + XmlTextReader treader = new XmlTextReader (TestResourceHelper.GetFullPathOfResource (schemaResource)); + XmlSchema sc = XmlSchema.Read (treader, null); + sc.Compile (null); + string xml = @"
"; + XmlTextReader reader = new XmlTextReader (new StringReader (xml)); + XmlValidatingReader validator = new XmlValidatingReader (reader); + validator.Schemas.Add (sc); + validator.ValidationType = ValidationType.Schema; + while (!validator.EOF) + validator.Read (); + } + + [Test] + public void Bug81460 () + { + string xsd = ""; + string xml = ""; + XmlReaderSettings s = new XmlReaderSettings (); + s.ValidationType = ValidationType.Schema; + s.Schemas.Add (XmlSchema.Read (new StringReader (xsd), null)); + XmlReader r = XmlReader.Create (new StringReader (xml), s); + r.Read (); + r.MoveToFirstAttribute (); // default attribute + Assert.AreEqual (String.Empty, r.Prefix); + } + + [Test] + // annoyance + [ExpectedException (typeof (XmlSchemaValidationException))] + public void Bug82099 () + { + string xsd = @" + + + + + +"; + XmlSchema schema = XmlSchema.Read (new StringReader (xsd), null); + + string xml = " "; + + XmlReaderSettings settings = new XmlReaderSettings (); + settings.Schemas.Add (schema); + settings.ValidationType = ValidationType.Schema; + + XmlReader reader = XmlReader.Create (new StringReader (xml), settings); + + reader.Read (); + reader.Read (); + reader.Read (); + } + + [Test] + public void Bug82010 () + { + string xmlresource = "Test/XmlFiles/xsd/82010.xml"; + string xsdresource = "Test/XmlFiles/xsd/82010.xsd"; + XmlTextReader xr = null, xr2 = null; + try { + xr = new XmlTextReader (TestResourceHelper.GetFullPathOfResource (xsdresource)); + xr2 = new XmlTextReader (TestResourceHelper.GetFullPathOfResource (xmlresource)); + XmlValidatingReader xvr = new XmlValidatingReader (xr2); + xvr.Schemas.Add (XmlSchema.Read (xr, null)); + while (!xvr.EOF) + xvr.Read (); + } finally { + if (xr2 != null) + xr2.Close (); + if (xr != null) + xr.Close (); + } + } + + [Test] + public void Bug376395 () + { + string xmlresource = "Test/XmlFiles/xsd/376395.xml"; + string xsdresource = "Test/XmlFiles/xsd/376395.xsd"; + XmlTextReader xr = null, xr2 = null; + try { + xr = new XmlTextReader (TestResourceHelper.GetFullPathOfResource (xsdresource)); + xr2 = new XmlTextReader (TestResourceHelper.GetFullPathOfResource (xmlresource)); + XmlValidatingReader xvr = new XmlValidatingReader (xr2); + xvr.Schemas.Add (XmlSchema.Read (xr, null)); + while (!xvr.EOF) + xvr.Read (); + } finally { + if (xr2 != null) + xr2.Close (); + if (xr != null) + xr.Close (); + } + } + + [Test] + public void ValidateMixedInsideXsdAny () + { + string xml = @" + text + text +"; + string xsd = @" + + + + + + + + + + + + + + + +"; + XmlTextReader xtr = new XmlTextReader (new StringReader (xml)); + XmlValidatingReader xvr = new XmlValidatingReader (xtr); + XmlReader xsr = new XmlTextReader (new StringReader (xsd)); + xvr.Schemas.Add (XmlSchema.Read (xsr, null)); + while (!xvr.EOF) + xvr.Read (); + xtr = new XmlTextReader (new StringReader (xml)); + xsr = new XmlTextReader (new StringReader (xsd)); + var s = new XmlReaderSettings (); + s.Schemas.Add (XmlSchema.Read (xsr, null)); + s.ValidationType = ValidationType.Schema; + XmlReader xvr2 = XmlReader.Create (xtr, s); + while (!xvr2.EOF) + xvr2.Read (); + } + + [Test] + public void WhitespaceAndElementOnly () + { + string xsd = @" + + + + + + + +"; + string xml = @" + + + + + +"; + RunValidation (xml, xsd); + } + + [Test] + [ExpectedException (typeof (XmlSchemaValidationException))] + public void EnumerationFacet () + { + // bug #339934 + string xsd = @" + + + + + + + + + + + + +"; + string xml = @""; + + RunValidation (xml, xsd); + } + + [Test] + public void Bug501763 () + { + string xsd1 = @" + + + + + "; + + string xsd2 = @" + + + + + + + + + + + + + + + + "; + + + XmlDocument doc = new XmlDocument (); + + XmlSchema schema1 = XmlSchema.Read (XmlReader.Create (new StringReader (xsd1)), null); + XmlSchema schema2 = XmlSchema.Read (XmlReader.Create (new StringReader (xsd2)), null); + + doc.LoadXml (@" + "); + doc.Schemas.Add (schema2); + doc.Validate (null); + + doc = new XmlDocument(); + doc.LoadXml(@" + "); + doc.Schemas.Add (schema2); + doc.Schemas.Add (schema1); + doc.Validate (null); + } + + void RunValidation (string xml, string xsd) + { + XmlReaderSettings s = new XmlReaderSettings (); + s.ValidationType = ValidationType.Schema; + s.Schemas.Add (XmlSchema.Read (XmlReader.Create (new StringReader (xsd)), null)); + + XmlReader r = XmlReader.Create (new StringReader (xml), s); + while (!r.EOF) + r.Read (); + } + } +} diff --git a/mcs/class/System.XML/Test/System.Xml/nist_dom/util.cs b/mcs/class/System.XML/Test/System.Xml/nist_dom/util.cs index ec03b3b79b..f06293b8ab 100644 --- a/mcs/class/System.XML/Test/System.Xml/nist_dom/util.cs +++ b/mcs/class/System.XML/Test/System.Xml/nist_dom/util.cs @@ -14,6 +14,8 @@ using System; using System.Xml; +using MonoTests.Helpers; + namespace nist_dom { public class XmlNodeArrayList : XmlNodeList @@ -117,12 +119,12 @@ namespace nist_dom try { //System.Console.WriteLine(System.IO.Directory.GetCurrentDirectory()); - masterDoc.Load("Test/System.Xml/nist_dom/files/staff.xml"); - originalDoc.Load("Test/System.Xml/nist_dom/files/staff.xml"); - masterXML.Load("Test/System.Xml/nist_dom/files/staff.html"); - otherDoc.Load("Test/System.Xml/nist_dom/files/otherDoc.xml"); - HTMLDoc.Load("Test/System.Xml/nist_dom/files/staff.html"); - noDTDXMLObject.Load("Test/System.Xml/nist_dom/files/noDTDXMLfile.xml"); + masterDoc.Load(TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/nist_dom/files/staff.xml")); + originalDoc.Load(TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/nist_dom/files/staff.xml")); + masterXML.Load(TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/nist_dom/files/staff.html")); + otherDoc.Load(TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/nist_dom/files/otherDoc.xml")); + HTMLDoc.Load(TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/nist_dom/files/staff.html")); + noDTDXMLObject.Load(TestResourceHelper.GetFullPathOfResource ("Test/System.Xml/nist_dom/files/noDTDXMLfile.xml")); } catch (System.Exception ex) { diff --git a/mcs/class/System.Xaml/Makefile b/mcs/class/System.Xaml/Makefile index 5f96dcbd7d..1651967c3c 100644 --- a/mcs/class/System.Xaml/Makefile +++ b/mcs/class/System.Xaml/Makefile @@ -8,12 +8,13 @@ LIBRARY = System.Xaml.dll LIB_REFS = System System.Xml System.Core LIB_MCS_FLAGS = $(RESOURCE_FILES:%=/resource:%) -TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) +TEST_RESOURCE_FILES = \ + $(wildcard Test/XmlFiles/*.xml) \ + $(wildcard Test/XmlFiles/*.xaml) -EXTRA_DISTFILES = $(RESOURCE_FILES) $(TEST_EXTRA_DISTFILES) -TEST_EXTRA_DISTFILES = \ - Test/XmlFiles/*.xml \ - Test/XmlFiles/*.xaml +TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) + +EXTRA_DISTFILES = $(RESOURCE_FILES) $(TEST_RESOURCE_FILES) VALID_PROFILE := $(filter 4, $(FRAMEWORK_VERSION_MAJOR)) ifndef VALID_PROFILE diff --git a/mcs/class/System.Xaml/System.Xaml_test.dll.sources b/mcs/class/System.Xaml/System.Xaml_test.dll.sources index 7ff9a23002..32a59af705 100644 --- a/mcs/class/System.Xaml/System.Xaml_test.dll.sources +++ b/mcs/class/System.Xaml/System.Xaml_test.dll.sources @@ -1,3 +1,4 @@ +../../test-helpers/TestResourceHelper.cs System.Windows.Markup/ArrayExtensionTest.cs System.Windows.Markup/ReferenceTest.cs System.Windows.Markup/StaticExtensionTest.cs diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlBackgroundReaderTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlBackgroundReaderTest.cs index 5f40fe552c..4652797575 100644 --- a/mcs/class/System.Xaml/Test/System.Xaml/XamlBackgroundReaderTest.cs +++ b/mcs/class/System.Xaml/Test/System.Xaml/XamlBackgroundReaderTest.cs @@ -35,6 +35,8 @@ using NUnit.Framework; using CategoryAttribute = NUnit.Framework.CategoryAttribute; +using MonoTests.Helpers; + namespace MonoTests.System.Xaml { [TestFixture] @@ -42,7 +44,7 @@ namespace MonoTests.System.Xaml { XamlReader GetReader (string filename) { - return new XamlXmlReader (XmlReader.Create (Path.Combine ("Test/XmlFiles", filename), new XmlReaderSettings () { CloseInput =true })); + return new XamlXmlReader (XmlReader.Create (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/" + filename), new XmlReaderSettings () { CloseInput =true })); } void ReadTest (string filename) diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlObjectWriterTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlObjectWriterTest.cs index 1aadbebcbb..fc462dc22e 100755 --- a/mcs/class/System.Xaml/Test/System.Xaml/XamlObjectWriterTest.cs +++ b/mcs/class/System.Xaml/Test/System.Xaml/XamlObjectWriterTest.cs @@ -35,6 +35,8 @@ using NUnit.Framework; using CategoryAttribute = NUnit.Framework.CategoryAttribute; +using MonoTests.Helpers; + namespace MonoTests.System.Xaml { [TestFixture] @@ -835,7 +837,7 @@ namespace MonoTests.System.Xaml XamlReader GetReader (string filename) { const string ver = "net_4_x"; - string xml = File.ReadAllText (Path.Combine ("Test/XmlFiles", filename)).Replace ("System.Xaml_test_net_4_0", ver + "_System.Xaml_test"); + string xml = File.ReadAllText (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/" + filename)).Replace ("System.Xaml_test_net_4_0", ver + "_System.Xaml_test"); return new XamlXmlReader (XmlReader.Create (new StringReader (xml))); } diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlReaderTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlReaderTest.cs index 85a4a59e28..b2d90b00e0 100755 --- a/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlReaderTest.cs +++ b/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlReaderTest.cs @@ -36,6 +36,8 @@ using NUnit.Framework; using CategoryAttribute = NUnit.Framework.CategoryAttribute; +using MonoTests.Helpers; + namespace MonoTests.System.Xaml { [TestFixture] @@ -46,7 +48,7 @@ namespace MonoTests.System.Xaml XamlReader GetReader (string filename) { const string ver = "net_4_x"; - string xml = File.ReadAllText (Path.Combine ("Test/XmlFiles", filename)).Replace ("System.Xaml_test_net_4_0", ver + "_System.Xaml_test"); + string xml = File.ReadAllText (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/" + filename)).Replace ("System.Xaml_test_net_4_0", ver + "_System.Xaml_test"); return new XamlXmlReader (XmlReader.Create (new StringReader (xml))); } @@ -722,7 +724,7 @@ namespace MonoTests.System.Xaml [Test] public void Bug680385 () { - XamlServices.Load ("Test/XmlFiles/CurrentVersion.xaml"); + XamlServices.Load (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/CurrentVersion.xaml")); } #endregion } diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlWriterTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlWriterTest.cs index e46771c9b3..e0fe218af5 100755 --- a/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlWriterTest.cs +++ b/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlWriterTest.cs @@ -34,6 +34,8 @@ using NUnit.Framework; using CategoryAttribute = NUnit.Framework.CategoryAttribute; +using MonoTests.Helpers; + namespace MonoTests.System.Xaml { [TestFixture] @@ -637,7 +639,7 @@ namespace MonoTests.System.Xaml string ReadXml (string name) { string ver = "net_4_x"; - return File.ReadAllText ("Test/XmlFiles/" + name).Trim ().Replace (">\n", ">\r\n").Replace ("System.Xaml_test_net_4_0", ver + "_System.Xaml_test").Replace ("\r\n", Environment.NewLine); + return File.ReadAllText (TestResourceHelper.GetFullPathOfResource ("Test/XmlFiles/" + name)).Trim ().Replace (">\n", ">\r\n").Replace ("System.Xaml_test_net_4_0", ver + "_System.Xaml_test").Replace ("\r\n", Environment.NewLine); } [Test] diff --git a/mcs/class/System/Makefile b/mcs/class/System/Makefile index 7853db352e..9056c801ab 100644 --- a/mcs/class/System/Makefile +++ b/mcs/class/System/Makefile @@ -32,10 +32,11 @@ RESX_RESOURCE_STRING = \ ../../../external/corefx/src/System.ComponentModel.TypeConverter/src/Resources/Strings.resx \ ../../../external/corefx/src/System.Security.Cryptography.Encoding/src/Resources/Strings.resx -TEST_RESOURCES = \ +TEST_RESOURCE_FILES = \ Test/System/test-uri-props.txt \ Test/System/test-uri-props-manual.txt \ - Test/System/test-uri-relative-props.txt + Test/System/test-uri-relative-props.txt \ + Test/compressed.bin USE_XTEST_REMOTE_EXECUTOR = YES XTEST_LIB_REFS = System System.Core System.Net Facades/System.Threading.Tasks Facades/System.Runtime.InteropServices.RuntimeInformation System.Net.Http @@ -63,7 +64,7 @@ TEST_LIB_REFS = $(MONO_SECURITY) System.Data System.Xml System.Core endif TEST_MCS_FLAGS = -nowarn:618,672,219,67,169,612 \ - $(foreach f, $(TEST_RESOURCES), -resource:$(f),$(notdir $(f))) + $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) TEST_NUNITLITE_APP_CONFIG_GLOBAL=Test/test-config-file @@ -128,11 +129,11 @@ EXTRA_DISTFILES = \ Test/System.Security.Cryptography.X509Certificates/pkits/README \ Test/System.Security.Cryptography.X509Certificates/pkits/x509build.cs \ $(RESOURCE_FILES) \ - $(TEST_RESOURCES) + $(TEST_RESOURCE_FILES) include ../../build/library.make -$(test_lib_output): $(TEST_RESOURCES) | $(test_lib_dir) +$(test_lib_output): $(TEST_RESOURCE_FILES) $(test_lib_dir) # Helper target to run the perl regex test suite regex-check: diff --git a/mcs/class/System/Microsoft.CSharp/CSharpCodeGenerator.cs b/mcs/class/System/Microsoft.CSharp/CSharpCodeGenerator.cs index 1c7070bb4d..9bb045dfab 100644 --- a/mcs/class/System/Microsoft.CSharp/CSharpCodeGenerator.cs +++ b/mcs/class/System/Microsoft.CSharp/CSharpCodeGenerator.cs @@ -67,7 +67,8 @@ namespace Microsoft.CSharp mcs.StartInfo.Arguments += BuildArgs (options, fileNames, _provOptions); - var mcsOutMutex = new Mutex (); + var stderr_completed = new ManualResetEvent (false); + var stdout_completed = new ManualResetEvent (false); /* string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH"); if (monoPath != null) @@ -93,15 +94,19 @@ namespace Microsoft.CSharp mcs.StartInfo.CreateNoWindow=true; mcs.StartInfo.UseShellExecute=false; + mcs.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; mcs.StartInfo.RedirectStandardOutput=true; mcs.StartInfo.RedirectStandardError=true; mcs.ErrorDataReceived += new DataReceivedEventHandler ((sender, args) => { - if (args.Data != null) { - mcsOutMutex.WaitOne (); + if (args.Data != null) results.Output.Add (args.Data); - mcsOutMutex.ReleaseMutex (); - } + else + stderr_completed.Set (); }); + mcs.OutputDataReceived += new DataReceivedEventHandler ((sender, args) => { + if (args.Data == null) + stdout_completed.Set (); + }); // Use same text decoder as mcs and not user set values in Console mcs.StartInfo.StandardOutputEncoding = @@ -125,8 +130,8 @@ namespace Microsoft.CSharp results.NativeCompilerReturnValue = mcs.ExitCode; } finally { - mcs.CancelErrorRead (); - mcs.CancelOutputRead (); + stderr_completed.WaitOne (TimeSpan.FromSeconds (30)); + stdout_completed.WaitOne (TimeSpan.FromSeconds (30)); mcs.Close(); } diff --git a/mcs/class/System/Mono.AppleTls/MonoCertificatePal.OSX.cs b/mcs/class/System/Mono.AppleTls/MonoCertificatePal.OSX.cs index 657756ae31..945588f407 100644 --- a/mcs/class/System/Mono.AppleTls/MonoCertificatePal.OSX.cs +++ b/mcs/class/System/Mono.AppleTls/MonoCertificatePal.OSX.cs @@ -27,6 +27,16 @@ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. + +#if !MONO_FEATURE_BTLS +#if MONO_SECURITY_ALIAS +extern alias MonoSecurity; +using MonoSecurity::Mono.Security.Cryptography; +#else +using Mono.Security.Cryptography; +#endif +#endif + using System; using System.Threading; using System.Runtime.InteropServices; @@ -38,8 +48,6 @@ using Mono.Net; #if MONO_FEATURE_BTLS using Mono.Btls; -#else -using Mono.Security.Cryptography; #endif namespace Mono.AppleTls diff --git a/mcs/class/System/Mono.Btls/MonoBtlsKey.cs b/mcs/class/System/Mono.Btls/MonoBtlsKey.cs index 4ba8f16baa..fcbe0026c8 100644 --- a/mcs/class/System/Mono.Btls/MonoBtlsKey.cs +++ b/mcs/class/System/Mono.Btls/MonoBtlsKey.cs @@ -24,6 +24,12 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if SECURITY_DEP && MONO_FEATURE_BTLS +#if MONO_SECURITY_ALIAS +extern alias MonoSecurity; +using MX = MonoSecurity::Mono.Security.Cryptography; +#else +using MX = Mono.Security.Cryptography; +#endif using System; using System.IO; using System.Text; @@ -109,7 +115,7 @@ namespace Mono.Btls public static MonoBtlsKey CreateFromRSAPrivateKey (System.Security.Cryptography.RSA privateKey) { - var keyData = Mono.Security.Cryptography.PKCS8.PrivateKeyInfo.Encode (privateKey); + var keyData = MX.PKCS8.PrivateKeyInfo.Encode (privateKey); var key = new MonoBtlsKey (new BoringKeyHandle (mono_btls_key_new ())); var ret = mono_btls_key_assign_rsa_private_key (key.Handle.DangerousGetHandle (), keyData, keyData.Length); diff --git a/mcs/class/System/Mono.Btls/X509CertificateImplBtls.cs b/mcs/class/System/Mono.Btls/X509CertificateImplBtls.cs index 0b170e2775..9aa3f55194 100644 --- a/mcs/class/System/Mono.Btls/X509CertificateImplBtls.cs +++ b/mcs/class/System/Mono.Btls/X509CertificateImplBtls.cs @@ -30,8 +30,10 @@ extern alias MonoSecurity; #if MONO_SECURITY_ALIAS using MX = MonoSecurity::Mono.Security.X509; +using MonoSecurity::Mono.Security.Cryptography; #else using MX = Mono.Security.X509; +using Mono.Security.Cryptography; #endif using System; @@ -41,7 +43,6 @@ using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Runtime.InteropServices; -using Mono.Security.Cryptography; using Microsoft.Win32.SafeHandles; namespace Mono.Btls diff --git a/mcs/class/System/Mono.Btls/X509ChainImplBtls.cs b/mcs/class/System/Mono.Btls/X509ChainImplBtls.cs index a50a0ecf34..87f5d88f8f 100644 --- a/mcs/class/System/Mono.Btls/X509ChainImplBtls.cs +++ b/mcs/class/System/Mono.Btls/X509ChainImplBtls.cs @@ -24,13 +24,18 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if SECURITY_DEP && MONO_FEATURE_BTLS +#if MONO_SECURITY_ALIAS +extern alias MonoSecurity; +using MX = MonoSecurity::Mono.Security.X509; +#else +using MX = Mono.Security.X509; +#endif using System; using System.Collections.Generic; using System.Text; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; -using MX = Mono.Security.X509; namespace Mono.Btls { diff --git a/mcs/class/System/Mono.Net.Security/MobileAuthenticatedStream.cs b/mcs/class/System/Mono.Net.Security/MobileAuthenticatedStream.cs index b89a982cfa..62c8f90388 100644 --- a/mcs/class/System/Mono.Net.Security/MobileAuthenticatedStream.cs +++ b/mcs/class/System/Mono.Net.Security/MobileAuthenticatedStream.cs @@ -178,7 +178,11 @@ namespace Mono.Net.Security }; var task = ProcessAuthentication (true, options, CancellationToken.None); - task.Wait (); + try { + task.Wait (); + } catch (Exception ex) { + throw HttpWebRequest.FlattenException (ex); + } } public IAsyncResult BeginAuthenticateAsClient (string targetHost, AsyncCallback asyncCallback, object asyncState) @@ -231,7 +235,11 @@ namespace Mono.Net.Security }; var task = ProcessAuthentication (true, options, CancellationToken.None); - task.Wait (); + try { + task.Wait (); + } catch (Exception ex) { + throw HttpWebRequest.FlattenException (ex); + } } public IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState) diff --git a/mcs/class/System/System.IO.Compression/DeflateStream.cs b/mcs/class/System/System.IO.Compression/DeflateStream.cs index 9c0702da46..cdd9c07168 100644 --- a/mcs/class/System/System.IO.Compression/DeflateStream.cs +++ b/mcs/class/System/System.IO.Compression/DeflateStream.cs @@ -32,6 +32,7 @@ using System; using System.IO; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Remoting.Messaging; using System.Threading; @@ -504,28 +505,7 @@ namespace System.IO.Compression throw new IOException (error + " " + where); } -#if MONOTOUCH || MONODROID - const string LIBNAME = "__Internal"; -#else - const string LIBNAME = "MonoPosixHelper"; -#endif - -#if !ORBIS - [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)] - static extern SafeDeflateStreamHandle CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data); - - [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)] - static extern int CloseZStream (IntPtr stream); - - [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)] - static extern int Flush (SafeDeflateStreamHandle stream); - - [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)] - static extern int ReadZStream (SafeDeflateStreamHandle stream, IntPtr buffer, int length); - - [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)] - static extern int WriteZStream (SafeDeflateStreamHandle stream, IntPtr buffer, int length); -#else +#if ORBIS static SafeDeflateStreamHandle CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data) { throw new PlatformNotSupportedException (); @@ -550,6 +530,82 @@ namespace System.IO.Compression { throw new PlatformNotSupportedException (); } +#elif MONOTOUCH || MONODROID + [MethodImplAttribute(MethodImplOptions.InternalCall)] + static extern IntPtr CreateZStream (int compress, bool gzip, IntPtr feeder, IntPtr data); + + static SafeDeflateStreamHandle CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data) + { + SafeDeflateStreamHandle res; + try {} finally { + res = new SafeDeflateStreamHandle (CreateZStream ((int) compress, gzip, Marshal.GetFunctionPointerForDelegate (feeder), data)); + } + + return res; + } + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + static extern int CloseZStream (IntPtr stream); + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + static extern int Flush (IntPtr stream); + + static int Flush (SafeDeflateStreamHandle stream) + { + bool release = false; + try { + stream.DangerousAddRef (ref release); + return Flush (stream.DangerousGetHandle ()); + } finally { + if (release) + stream.DangerousRelease (); + } + } + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + static extern int ReadZStream (IntPtr stream, IntPtr buffer, int length); + + static int ReadZStream (SafeDeflateStreamHandle stream, IntPtr buffer, int length) + { + bool release = false; + try { + stream.DangerousAddRef (ref release); + return ReadZStream (stream.DangerousGetHandle (), buffer, length); + } finally { + if (release) + stream.DangerousRelease (); + } + } + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + static extern int WriteZStream (IntPtr stream, IntPtr buffer, int length); + + static int WriteZStream (SafeDeflateStreamHandle stream, IntPtr buffer, int length) + { + bool release = false; + try { + stream.DangerousAddRef (ref release); + return WriteZStream (stream.DangerousGetHandle (), buffer, length); + } finally { + if (release) + stream.DangerousRelease (); + } + } +#else + [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)] + static extern SafeDeflateStreamHandle CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data); + + [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)] + static extern int CloseZStream (IntPtr stream); + + [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)] + static extern int Flush (SafeDeflateStreamHandle stream); + + [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)] + static extern int ReadZStream (SafeDeflateStreamHandle stream, IntPtr buffer, int length); + + [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)] + static extern int WriteZStream (SafeDeflateStreamHandle stream, IntPtr buffer, int length); #endif sealed class SafeDeflateStreamHandle : SafeHandle @@ -563,6 +619,10 @@ namespace System.IO.Compression { } + internal SafeDeflateStreamHandle(IntPtr handle) : base (handle, true) + { + } + override protected bool ReleaseHandle() { DeflateStreamNative.CloseZStream(handle); diff --git a/mcs/class/System/System.IO/FileSystemWatcher.cs b/mcs/class/System/System.IO/FileSystemWatcher.cs index 909e6880cc..adfd9cfc33 100644 --- a/mcs/class/System/System.IO/FileSystemWatcher.cs +++ b/mcs/class/System/System.IO/FileSystemWatcher.cs @@ -144,10 +144,6 @@ namespace System.IO { ok = FAMWatcher.GetInstance (out watcher, true); watcher_handle = this; break; - case 5: // inotify - ok = InotifyWatcher.GetInstance (out watcher, true); - watcher_handle = this; - break; case 6: // CoreFX ok = CoreFXFileSystemWatcherProxy.GetInstance (out watcher); watcher_handle = (watcher as CoreFXFileSystemWatcherProxy).NewWatcher (this); diff --git a/mcs/class/System/System.IO/InotifyWatcher.cs b/mcs/class/System/System.IO/InotifyWatcher.cs deleted file mode 100644 index 789567d0b9..0000000000 --- a/mcs/class/System/System.IO/InotifyWatcher.cs +++ /dev/null @@ -1,638 +0,0 @@ -// -// System.IO.Inotify.cs: interface with inotify -// -// Authors: -// Gonzalo Paniagua (gonzalo@novell.com) -// Anders Rune Jensen (anders@iola.dk) -// -// (c) 2006 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 System; -using System.Collections; -using System.ComponentModel; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; -using System.Threading; - -namespace System.IO { - - [Flags] - enum InotifyMask : uint { - Access = 1 << 0, - Modify = 1 << 1, - Attrib = 1 << 2, - CloseWrite = 1 << 3, - CloseNoWrite = 1 << 4, - Open = 1 << 5, - MovedFrom = 1 << 6, - MovedTo = 1 << 7, - Create = 1 << 8, - Delete = 1 << 9, - DeleteSelf = 1 << 10, - MoveSelf = 1 << 11, - BaseEvents = 0x00000fff, - // Can be sent at any time - Umount = 0x0002000, - Overflow = 0x0004000, - Ignored = 0x0008000, - - // Special flags. - OnlyDir = 0x01000000, - DontFollow = 0x02000000, - AddMask = 0x20000000, - Directory = 0x40000000, - OneShot = 0x80000000 - } - - struct InotifyEvent { // Our internal representation for the data returned by the kernel - public static readonly InotifyEvent Default = new InotifyEvent (); - public int WatchDescriptor; - public InotifyMask Mask; - public string Name; - - public override string ToString () - { - return String.Format ("[Descriptor: {0} Mask: {1} Name: {2}]", WatchDescriptor, Mask, Name); - } - } - - class ParentInotifyData - { - public bool IncludeSubdirs; - public bool Enabled; - public ArrayList children; // InotifyData - public InotifyData data; - } - - class InotifyData { - public FileSystemWatcher FSW; - public string Directory; - public int Watch; - } - - class InotifyWatcher : IFileWatcher - { - static bool failed; - static InotifyWatcher instance; - static Hashtable watches; // FSW to ParentInotifyData - static Hashtable requests; // FSW to InotifyData - static IntPtr FD; - static Thread thread; - static bool stop; - - private InotifyWatcher () - { - } - - // Locked by caller - public static bool GetInstance (out IFileWatcher watcher, bool gamin) - { - if (failed == true) { - watcher = null; - return false; - } - - if (instance != null) { - watcher = instance; - return true; - } - - FD = GetInotifyInstance (); - if ((long) FD == -1) { - failed = true; - watcher = null; - return false; - } - - watches = Hashtable.Synchronized (new Hashtable ()); - requests = Hashtable.Synchronized (new Hashtable ()); - instance = new InotifyWatcher (); - watcher = instance; - return true; - } - - public void StartDispatching (object handle) - { - if (handle == null) - return; - var fsw = handle as FileSystemWatcher; - ParentInotifyData parent; - lock (this) { - if ((long) FD == -1) - FD = GetInotifyInstance (); - - if (thread == null) { - thread = new Thread (new ThreadStart (Monitor)); - thread.IsBackground = true; - thread.Start (); - } - - parent = (ParentInotifyData) watches [fsw]; - } - - if (parent == null) { - InotifyData data = new InotifyData (); - data.FSW = fsw; - data.Directory = fsw.FullPath; - - parent = new ParentInotifyData(); - parent.IncludeSubdirs = fsw.IncludeSubdirectories; - parent.Enabled = true; - parent.children = new ArrayList(); - parent.data = data; - - watches [fsw] = parent; - - try { - StartMonitoringDirectory (data, false); - lock (this) { - AppendRequestData (data); - stop = false; - } - } catch {} // ignore the directory if StartMonitoringDirectory fails. - } - } - - static void AppendRequestData (InotifyData data) - { - int wd = data.Watch; - - object obj = requests [wd]; - ArrayList list = null; - if (obj == null) { - requests [data.Watch] = data; - } else if (obj is InotifyData) { - list = new ArrayList (); - list.Add (obj); - list.Add (data); - requests [data.Watch] = list; - } else { - list = (ArrayList) obj; - list.Add (data); - } - } - - static bool RemoveRequestData (InotifyData data) - { - int wd = data.Watch; - object obj = requests [wd]; - if (obj == null) - return true; - - if (obj is InotifyData) { - if (obj == data) { - requests.Remove (wd); - return true; - } - return false; - } - - ArrayList list = (ArrayList) obj; - list.Remove (data); - if (list.Count == 0) { - requests.Remove (wd); - return true; - } - return false; - } - - // Attempt to match MS and linux behavior. - static InotifyMask GetMaskFromFilters (NotifyFilters filters) - { - InotifyMask mask = InotifyMask.Create | InotifyMask.Delete | InotifyMask.DeleteSelf | InotifyMask.AddMask; - if ((filters & NotifyFilters.Attributes) != 0) - mask |= InotifyMask.Attrib; - - if ((filters & NotifyFilters.Security) != 0) - mask |= InotifyMask.Attrib; - - if ((filters & NotifyFilters.Size) != 0) { - mask |= InotifyMask.Attrib; - mask |= InotifyMask.Modify; - } - - if ((filters & NotifyFilters.LastAccess) != 0) { - mask |= InotifyMask.Attrib; - mask |= InotifyMask.Access; - mask |= InotifyMask.Modify; - } - - if ((filters & NotifyFilters.LastWrite) != 0) { - mask |= InotifyMask.Attrib; - mask |= InotifyMask.Modify; - } - - if ((filters & NotifyFilters.FileName) != 0) { - mask |= InotifyMask.MovedFrom; - mask |= InotifyMask.MovedTo; - } - - if ((filters & NotifyFilters.DirectoryName) != 0) { - mask |= InotifyMask.MovedFrom; - mask |= InotifyMask.MovedTo; - } - - return mask; - } - - static void StartMonitoringDirectory (InotifyData data, bool justcreated) - { - InotifyMask mask = GetMaskFromFilters (data.FSW.NotifyFilter); - int wd = AddDirectoryWatch (FD, data.Directory, mask); - if (wd == -1) { - int error = Marshal.GetLastWin32Error (); - if (error == 4) { // Too many open watches - string nr_watches = "(unknown)"; - try { - using (StreamReader reader = new StreamReader ("/proc/sys/fs/inotify/max_user_watches")) { - nr_watches = reader.ReadLine (); - } - } catch {} - - string msg = String.Format ("The per-user inotify watches limit of {0} has been reached. " + - "If you're experiencing problems with your application, increase that limit " + - "in /proc/sys/fs/inotify/max_user_watches.", nr_watches); - - throw new Win32Exception (error, msg); - } - throw new Win32Exception (error); - } - - FileSystemWatcher fsw = data.FSW; - data.Watch = wd; - - ParentInotifyData parent = (ParentInotifyData) watches[fsw]; - - if (parent.IncludeSubdirs) { - foreach (string directory in Directory.GetDirectories (data.Directory)) { - InotifyData fd = new InotifyData (); - fd.FSW = fsw; - fd.Directory = directory; - - if (justcreated) { - lock (fsw) { - RenamedEventArgs renamed = null; - if (fsw.Pattern.IsMatch (directory)) { - fsw.DispatchEvents (FileAction.Added, directory, ref renamed); - if (fsw.Waiting) { - fsw.Waiting = false; - System.Threading.Monitor.PulseAll (fsw); - } - } - } - } - - try { - StartMonitoringDirectory (fd, justcreated); - AppendRequestData (fd); - parent.children.Add(fd); - } catch {} // ignore errors and don't add directory. - } - } - - if (justcreated) { - foreach (string filename in Directory.GetFiles (data.Directory)) { - lock (fsw) { - RenamedEventArgs renamed = null; - if (fsw.Pattern.IsMatch (filename)) { - fsw.DispatchEvents (FileAction.Added, filename, ref renamed); - /* If a file has been created, then it has been written to */ - fsw.DispatchEvents (FileAction.Modified, filename, ref renamed); - - if (fsw.Waiting) { - fsw.Waiting = false; - System.Threading.Monitor.PulseAll(fsw); - } - } - } - } - } - } - - public void StopDispatching (object handle) - { - if (handle == null) - return; - var fsw = handle as FileSystemWatcher; - ParentInotifyData parent; - lock (this) { - parent = (ParentInotifyData) watches [fsw]; - if (parent == null) - return; - - if (RemoveRequestData (parent.data)) { - StopMonitoringDirectory (parent.data); - } - watches.Remove (fsw); - if (watches.Count == 0) { - stop = true; - IntPtr fd = FD; - FD = (IntPtr) (-1); - Close (fd); - } - - if (!parent.IncludeSubdirs) - return; - - foreach (InotifyData idata in parent.children) - { - if (RemoveRequestData (idata)) { - StopMonitoringDirectory (idata); - } - } - } - } - - static void StopMonitoringDirectory (InotifyData data) - { - RemoveWatch (FD, data.Watch); - } - - void Monitor () - { - byte [] buffer = new byte [4096]; - int nread; - while (!stop) { - nread = ReadFromFD (FD, buffer, (IntPtr) buffer.Length); - if (nread == -1) - continue; - - lock (this) { - ProcessEvents (buffer, nread); - - } - } - - lock (this) { - thread = null; - stop = false; - } - } - /* - struct inotify_event { - __s32 wd; - __u32 mask; - __u32 cookie; - __u32 len; // Includes any trailing null in 'name' - char name[0]; - }; - */ - - static int ReadEvent (byte [] source, int off, int size, out InotifyEvent evt) - { - evt = new InotifyEvent (); - if (size <= 0 || off > size - 16) { - return -1; - } - - int len; - if (BitConverter.IsLittleEndian) { - evt.WatchDescriptor = source [off] + (source [off + 1] << 8) + - (source [off + 2] << 16) + (source [off + 3] << 24); - evt.Mask = (InotifyMask) (source [off + 4] + (source [off + 5] << 8) + - (source [off + 6] << 16) + (source [off + 7] << 24)); - // Ignore Cookie -> +4 - len = source [off + 12] + (source [off + 13] << 8) + - (source [off + 14] << 16) + (source [off + 15] << 24); - } else { - evt.WatchDescriptor = source [off + 3] + (source [off + 2] << 8) + - (source [off + 1] << 16) + (source [off] << 24); - evt.Mask = (InotifyMask) (source [off + 7] + (source [off + 6] << 8) + - (source [off + 5] << 16) + (source [off + 4] << 24)); - // Ignore Cookie -> +4 - len = source [off + 15] + (source [off + 14] << 8) + - (source [off + 13] << 16) + (source [off + 12] << 24); - } - - if (len > 0) { - if (off > size - 16 - len) - return -1; - string name = Encoding.UTF8.GetString (source, off + 16, len); - evt.Name = name.Trim ('\0'); - } else { - evt.Name = null; - } - - return 16 + len; - } - - static IEnumerable GetEnumerator (object source) - { - if (source == null) - yield break; - - if (source is InotifyData) - yield return source; - - if (source is ArrayList) { - ArrayList list = (ArrayList) source; - for (int i = 0; i < list.Count; i++) - yield return list [i]; - } - } - - /* Interesting events: - * Modify - * Attrib - * MovedFrom - * MovedTo - * Create - * Delete - * DeleteSelf - */ - static InotifyMask Interesting = InotifyMask.Modify | InotifyMask.Attrib | InotifyMask.MovedFrom | - InotifyMask.MovedTo | InotifyMask.Create | InotifyMask.Delete | - InotifyMask.DeleteSelf; - - void ProcessEvents (byte [] buffer, int length) - { - ArrayList newdirs = null; - InotifyEvent evt; - int nread = 0; - RenamedEventArgs renamed = null; - while (length > nread) { - int bytes_read = ReadEvent (buffer, nread, length, out evt); - if (bytes_read <= 0) - break; - - nread += bytes_read; - - InotifyMask mask = evt.Mask; - bool is_directory = (mask & InotifyMask.Directory) != 0; - mask = (mask & Interesting); // Clear out all the bits that we don't need - if (mask == 0) - continue; - - foreach (InotifyData data in GetEnumerator (requests [evt.WatchDescriptor])) { - ParentInotifyData parent = (ParentInotifyData) watches[data.FSW]; - - if (data == null || parent.Enabled == false) - continue; - - string directory = data.Directory; - string filename = evt.Name; - if (filename == null) - filename = directory; - - FileSystemWatcher fsw = data.FSW; - FileAction action = 0; - if ((mask & (InotifyMask.Modify | InotifyMask.Attrib)) != 0) { - action = FileAction.Modified; - } else if ((mask & InotifyMask.Create) != 0) { - action = FileAction.Added; - } else if ((mask & InotifyMask.Delete) != 0) { - action = FileAction.Removed; - } else if ((mask & InotifyMask.DeleteSelf) != 0) { - if (data.Watch != parent.data.Watch) { - // To avoid duplicate events handle DeleteSelf only for the top level directory. - continue; - } - action = FileAction.Removed; - } else if ((mask & InotifyMask.MoveSelf) != 0) { - //action = FileAction.Removed; - continue; // Ignore this one - } else if ((mask & InotifyMask.MovedFrom) != 0) { - InotifyEvent to; - int i = ReadEvent (buffer, nread, length, out to); - if (i == -1 || (to.Mask & InotifyMask.MovedTo) == 0 || evt.WatchDescriptor != to.WatchDescriptor) { - action = FileAction.Removed; - } else { - nread += i; - action = FileAction.RenamedNewName; - renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, data.Directory, to.Name, evt.Name); - if (evt.Name != data.Directory && !fsw.Pattern.IsMatch (evt.Name)) - filename = to.Name; - } - } else if ((mask & InotifyMask.MovedTo) != 0) { - action = FileAction.Added; - } - if (fsw.IncludeSubdirectories) { - string full = fsw.FullPath; - string datadir = data.Directory; - if (datadir != full) { - int len = full.Length; - int slash = 1; - if (len > 1 && full [len - 1] == Path.DirectorySeparatorChar) - slash = 0; - string reldir = datadir.Substring (full.Length + slash); - datadir = Path.Combine (datadir, filename); - filename = Path.Combine (reldir, filename); - } else { - datadir = Path.Combine (full, filename); - } - - if (action == FileAction.Added && is_directory) { - if (newdirs == null) - newdirs = new ArrayList (2); - - InotifyData fd = new InotifyData (); - fd.FSW = fsw; - fd.Directory = datadir; - newdirs.Add (fd); - } - - if (action == FileAction.RenamedNewName && is_directory) { - string renamedOldFullPath = renamed.OldFullPath; - string renamedFullPath = renamed.FullPath; - int renamedOldFullPathLength = renamedOldFullPath.Length; - - foreach (InotifyData child in parent.children) { - - if (child.Directory.StartsWith (renamedOldFullPath - , StringComparison.Ordinal - )) { - child.Directory = renamedFullPath + - child.Directory.Substring (renamedOldFullPathLength); - } - } - } - } - - if (action == FileAction.Removed && filename == data.Directory) { - int idx = parent.children.IndexOf (data); - if (idx != -1) { - parent.children.RemoveAt (idx); - if (!fsw.Pattern.IsMatch (Path.GetFileName (filename))) { - continue; - } - } - } - - if (filename != data.Directory && !fsw.Pattern.IsMatch (Path.GetFileName (filename))) { - continue; - } - - lock (fsw) { - fsw.DispatchEvents (action, filename, ref renamed); - if (action == FileAction.RenamedNewName) - renamed = null; - if (fsw.Waiting) { - fsw.Waiting = false; - System.Threading.Monitor.PulseAll (fsw); - } - } - } - } - - if (newdirs != null) { - foreach (InotifyData newdir in newdirs) { - try { - StartMonitoringDirectory (newdir, true); - AppendRequestData (newdir); - ((ParentInotifyData) watches[newdir.FSW]).children.Add(newdir); - } catch {} // ignore the given directory - } - newdirs.Clear (); - } - } - - static int AddDirectoryWatch (IntPtr fd, string directory, InotifyMask mask) - { - mask |= InotifyMask.Directory; - return AddWatch (fd, directory, mask); - } - - public void Dispose (object handle) - { - // does nothing - } - - [DllImport ("libc", EntryPoint="close")] - internal extern static int Close (IntPtr fd); - - [DllImport ("libc", EntryPoint = "read")] - extern static int ReadFromFD (IntPtr fd, byte [] buffer, IntPtr length); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern static IntPtr GetInotifyInstance (); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern static int AddWatch (IntPtr fd, string name, InotifyMask mask); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern static IntPtr RemoveWatch (IntPtr fd, int wd); - } -} - diff --git a/mcs/class/System/System.Net.NetworkInformation/NetworkChange.cs b/mcs/class/System/System.Net.NetworkInformation/NetworkChange.cs index 8304ac82b4..0821210e7b 100644 --- a/mcs/class/System/System.Net.NetworkInformation/NetworkChange.cs +++ b/mcs/class/System/System.Net.NetworkInformation/NetworkChange.cs @@ -30,6 +30,7 @@ using System; using System.Net.Sockets; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; @@ -326,7 +327,7 @@ namespace System.Net.NetworkInformation { internal sealed class LinuxNetworkChange : INetworkChange { [Flags] - enum EventType { + enum EventType : int { Availability = 1 << 0, Address = 1 << 1, } @@ -485,20 +486,25 @@ namespace System.Net.NetworkInformation { } } -#if MONOTOUCH || MONODROID - const string LIBNAME = "__Internal"; -#else - const string LIBNAME = "MonoPosixHelper"; -#endif - - [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)] +#if MONODROID + [MethodImplAttribute(MethodImplOptions.InternalCall)] static extern IntPtr CreateNLSocket (); - [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)] + [MethodImplAttribute(MethodImplOptions.InternalCall)] static extern EventType ReadEvents (IntPtr sock, IntPtr buffer, int count, int size); - [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)] + [MethodImplAttribute(MethodImplOptions.InternalCall)] static extern IntPtr CloseNLSocket (IntPtr sock); +#else + [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)] + static extern IntPtr CreateNLSocket (); + + [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)] + static extern EventType ReadEvents (IntPtr sock, IntPtr buffer, int count, int size); + + [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)] + static extern IntPtr CloseNLSocket (IntPtr sock); +#endif } #endif diff --git a/mcs/class/System/System.Net.NetworkInformation/Win32IPAddressCollection.cs b/mcs/class/System/System.Net.NetworkInformation/Win32IPAddressCollection.cs index e22e7137d5..d5f565a165 100644 --- a/mcs/class/System/System.Net.NetworkInformation/Win32IPAddressCollection.cs +++ b/mcs/class/System/System.Net.NetworkInformation/Win32IPAddressCollection.cs @@ -79,6 +79,25 @@ namespace System.Net.NetworkInformation { return c; } + public static Win32IPAddressCollection FromSocketAddress (Win32_SOCKET_ADDRESS addr) + { + Win32IPAddressCollection c = new Win32IPAddressCollection (); + if (addr.Sockaddr != IntPtr.Zero) + c.InternalAdd (addr.GetIPAddress ()); + return c; + } + + public static Win32IPAddressCollection FromWinsServer (IntPtr ptr) + { + Win32IPAddressCollection c = new Win32IPAddressCollection (); + Win32_IP_ADAPTER_WINS_SERVER_ADDRESS a; + for (IntPtr p = ptr; p != IntPtr.Zero; p = a.Next) { + a = (Win32_IP_ADAPTER_WINS_SERVER_ADDRESS) Marshal.PtrToStructure (p, typeof (Win32_IP_ADAPTER_WINS_SERVER_ADDRESS)); + c.InternalAdd (a.Address.GetIPAddress ()); + } + return c; + } + void AddSubsequentlyString (IntPtr head) { Win32_IP_ADDR_STRING a; diff --git a/mcs/class/System/System.Net.NetworkInformation/Win32IPInterfaceProperties.cs b/mcs/class/System/System.Net.NetworkInformation/Win32IPInterfaceProperties.cs index 845fffebde..a9abd80037 100644 --- a/mcs/class/System/System.Net.NetworkInformation/Win32IPInterfaceProperties.cs +++ b/mcs/class/System/System.Net.NetworkInformation/Win32IPInterfaceProperties.cs @@ -44,13 +44,11 @@ namespace System.Net.NetworkInformation { public override IPv4InterfaceProperties GetIPv4Properties () { - Win32_IP_ADAPTER_INFO v4info = Win32NetworkInterface2.GetAdapterInfoByIndex (mib4.Index); - return new Win32IPv4InterfaceProperties (v4info, mib4); + return new Win32IPv4InterfaceProperties (addr, mib4); } public override IPv6InterfaceProperties GetIPv6Properties () { - Win32_IP_ADAPTER_INFO v6info = Win32NetworkInterface2.GetAdapterInfoByIndex (mib6.Index); return new Win32IPv6InterfaceProperties (mib6); } @@ -74,10 +72,9 @@ namespace System.Net.NetworkInformation { public override IPAddressCollection DhcpServerAddresses { get { - Win32_IP_ADAPTER_INFO v4info = Win32NetworkInterface2.GetAdapterInfoByIndex (mib4.Index); // FIXME: should ipv6 DhcpServer be considered? try { - return new Win32IPAddressCollection (v4info.DhcpServer); + return Win32IPAddressCollection.FromSocketAddress (addr.Dhcpv4Server); } catch (IndexOutOfRangeException) { return Win32IPAddressCollection.Empty; } @@ -96,28 +93,17 @@ namespace System.Net.NetworkInformation { get { var col = new GatewayIPAddressInformationCollection (); try { - Win32_IP_ADAPTER_INFO v4info = Win32NetworkInterface2.GetAdapterInfoByIndex (mib4.Index); // FIXME: should ipv6 DhcpServer be considered? - - var a = v4info.GatewayList; - if (!String.IsNullOrEmpty (a.IpAddress)) { - col.InternalAdd(new SystemGatewayIPAddressInformation(IPAddress.Parse (a.IpAddress))); - AddSubsequently (a.Next, col); + Win32_IP_ADAPTER_GATEWAY_ADDRESS a; + for (IntPtr p = addr.FirstGatewayAddress; p != IntPtr.Zero; p = a.Next) { + a = (Win32_IP_ADAPTER_GATEWAY_ADDRESS) Marshal.PtrToStructure (p, typeof (Win32_IP_ADAPTER_GATEWAY_ADDRESS)); + col.InternalAdd (new SystemGatewayIPAddressInformation (a.Address.GetIPAddress ())); } } catch (IndexOutOfRangeException) {} return col; } } - static void AddSubsequently (IntPtr head, GatewayIPAddressInformationCollection col) - { - Win32_IP_ADDR_STRING a; - for (IntPtr p = head; p != IntPtr.Zero; p = a.Next) { - a = (Win32_IP_ADDR_STRING) Marshal.PtrToStructure (p, typeof (Win32_IP_ADDR_STRING)); - col.InternalAdd (new SystemGatewayIPAddressInformation (IPAddress.Parse (a.IpAddress))); - } - } - public override bool IsDnsEnabled { get { return Win32NetworkInterface.FixedInfo.EnableDns != 0; } } @@ -147,7 +133,6 @@ namespace System.Net.NetworkInformation { public override UnicastIPAddressInformationCollection UnicastAddresses { get { try { - Win32_IP_ADAPTER_INFO ai = Win32NetworkInterface2.GetAdapterInfoByIndex (mib4.Index); // FIXME: should ipv6 DhcpServer be considered? return Win32FromUnicast (addr.FirstUnicastAddress); } catch (IndexOutOfRangeException) { @@ -170,9 +155,7 @@ namespace System.Net.NetworkInformation { public override IPAddressCollection WinsServersAddresses { get { try { - Win32_IP_ADAPTER_INFO v4info = Win32NetworkInterface2.GetAdapterInfoByIndex (mib4.Index); - // FIXME: should ipv6 DhcpServer be considered? - return new Win32IPAddressCollection (v4info.PrimaryWinsServer, v4info.SecondaryWinsServer); + return Win32IPAddressCollection.FromWinsServer (addr.FirstWinsServerAddress); } catch (IndexOutOfRangeException) { return Win32IPAddressCollection.Empty; } diff --git a/mcs/class/System/System.Net.NetworkInformation/Win32IPv4InterfaceProperties.cs b/mcs/class/System/System.Net.NetworkInformation/Win32IPv4InterfaceProperties.cs index 47f296f684..6f1b275dc4 100644 --- a/mcs/class/System/System.Net.NetworkInformation/Win32IPv4InterfaceProperties.cs +++ b/mcs/class/System/System.Net.NetworkInformation/Win32IPv4InterfaceProperties.cs @@ -36,13 +36,13 @@ namespace System.Net.NetworkInformation { [DllImport ("iphlpapi.dll")] static extern int GetPerAdapterInfo (int IfIndex, Win32_IP_PER_ADAPTER_INFO pPerAdapterInfo, ref int pOutBufLen); - Win32_IP_ADAPTER_INFO ainfo; + Win32_IP_ADAPTER_ADDRESSES addr; Win32_IP_PER_ADAPTER_INFO painfo; Win32_MIB_IFROW mib; - public Win32IPv4InterfaceProperties (Win32_IP_ADAPTER_INFO ainfo, Win32_MIB_IFROW mib) + public Win32IPv4InterfaceProperties (Win32_IP_ADAPTER_ADDRESSES addr, Win32_MIB_IFROW mib) { - this.ainfo = ainfo; + this.addr = addr; this.mib = mib; // get per-adapter info. @@ -67,7 +67,7 @@ namespace System.Net.NetworkInformation { } public override bool IsDhcpEnabled { - get { return ainfo.DhcpEnabled != 0; } + get { return addr.DhcpEnabled; } } public override bool IsForwardingEnabled { @@ -80,7 +80,7 @@ namespace System.Net.NetworkInformation { } public override bool UsesWins { - get { return ainfo.HaveWins; } + get { return addr.FirstWinsServerAddress != IntPtr.Zero; } } } diff --git a/mcs/class/System/System.Net.NetworkInformation/Win32NetworkInterface.cs b/mcs/class/System/System.Net.NetworkInformation/Win32NetworkInterface.cs index 3f08393569..776206bcff 100644 --- a/mcs/class/System/System.Net.NetworkInformation/Win32NetworkInterface.cs +++ b/mcs/class/System/System.Net.NetworkInformation/Win32NetworkInterface.cs @@ -49,9 +49,12 @@ namespace System.Net.NetworkInformation { { IntPtr ptr = IntPtr.Zero; int len = 0; - GetAdaptersAddresses (0, 0, IntPtr.Zero, ptr, ref len); + uint flags = Win32_IP_ADAPTER_ADDRESSES.GAA_FLAG_INCLUDE_WINS_INFO | Win32_IP_ADAPTER_ADDRESSES.GAA_FLAG_INCLUDE_GATEWAYS; + GetAdaptersAddresses (0, flags, IntPtr.Zero, ptr, ref len); + if (Marshal.SizeOf (typeof (Win32_IP_ADAPTER_ADDRESSES)) > len) + throw new NetworkInformationException (); ptr = Marshal.AllocHGlobal(len); - int ret = GetAdaptersAddresses (0, 0, IntPtr.Zero, ptr, ref len); + int ret = GetAdaptersAddresses (0, flags, IntPtr.Zero, ptr, ref len); if (ret != 0) throw new NetworkInformationException (ret); @@ -105,14 +108,6 @@ namespace System.Net.NetworkInformation { [DllImport ("iphlpapi.dll", SetLastError = true)] static extern int GetIfEntry (ref Win32_MIB_IFROW row); - public static Win32_IP_ADAPTER_INFO GetAdapterInfoByIndex (int index) - { - foreach (Win32_IP_ADAPTER_INFO info in GetAdaptersInfo ()) - if (info.Index == index) - return info; - throw new IndexOutOfRangeException ("No adapter found for index " + index); - } - static Win32_IP_ADAPTER_INFO [] GetAdaptersInfo () { int len = 0; diff --git a/mcs/class/System/System.Net.NetworkInformation/Win32NetworkInterfaceMarshal.cs b/mcs/class/System/System.Net.NetworkInformation/Win32NetworkInterfaceMarshal.cs index f608446cc8..71656efce7 100644 --- a/mcs/class/System/System.Net.NetworkInformation/Win32NetworkInterfaceMarshal.cs +++ b/mcs/class/System/System.Net.NetworkInformation/Win32NetworkInterfaceMarshal.cs @@ -109,15 +109,37 @@ namespace System.Net.NetworkInformation public NetworkInterfaceType IfType; public OperationalStatus OperStatus; public int Ipv6IfIndex; - [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16 * 4)] + [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)] public uint [] ZoneIndices; + public IntPtr FirstPrefix; // to PIP_ADAPTER_PREFIX + public UInt64 TransmitLinkSpeed; + public UInt64 ReceiveLinkSpeed; + public IntPtr FirstWinsServerAddress; // to PIP_ADAPTER_WINS_SERVER_ADDRESS_LH + public IntPtr FirstGatewayAddress; // to PIP_ADAPTER_GATEWAY_ADDRESS_LH + public uint Ipv4Metric; + public uint Ipv6Metric; + public UInt64 Luid; + public Win32_SOCKET_ADDRESS Dhcpv4Server; + public uint CompartmentId; + public UInt64 NetworkGuid; + public int ConnectionType; + public int TunnelType; + public Win32_SOCKET_ADDRESS Dhcpv6Server; + [MarshalAs (UnmanagedType.ByValArray, SizeConst = MAX_DHCPV6_DUID_LENGTH)] + public byte [] Dhcpv6ClientDuid; + public ulong Dhcpv6ClientDuidLength; + public ulong Dhcpv6Iaid; + public IntPtr FirstDnsSuffix; // to PIP_ADAPTER_DNS_SUFFIX - // Note that Vista-only members and XP-SP1-only member are - // omitted. + //Flags For GetAdapterAddresses + public const int GAA_FLAG_INCLUDE_WINS_INFO = 0x0040; + public const int GAA_FLAG_INCLUDE_GATEWAYS = 0x0080; const int MAX_ADAPTER_ADDRESS_LENGTH = 8; + const int MAX_DHCPV6_DUID_LENGTH = 130; const int IP_ADAPTER_DDNS_ENABLED = 1; + const int IP_ADAPTER_DHCP_ENABLED = 4; const int IP_ADAPTER_RECEIVE_ONLY = 8; const int IP_ADAPTER_NO_MULTICAST = 0x10; @@ -125,6 +147,10 @@ namespace System.Net.NetworkInformation get { return (Flags & IP_ADAPTER_DDNS_ENABLED) != 0; } } + public bool DhcpEnabled { + get { return (Flags & IP_ADAPTER_DHCP_ENABLED) != 0; } + } + public bool IsReceiveOnly { get { return (Flags & IP_ADAPTER_RECEIVE_ONLY) != 0; } } @@ -255,6 +281,22 @@ namespace System.Net.NetworkInformation public Win32_SOCKET_ADDRESS Address; } + [StructLayout (LayoutKind.Sequential)] + struct Win32_IP_ADAPTER_GATEWAY_ADDRESS + { + public Win32LengthFlagsUnion LengthFlags; + public IntPtr Next; // to Win32_IP_ADAPTER_GATEWAY_ADDRESS + public Win32_SOCKET_ADDRESS Address; + } + + [StructLayout (LayoutKind.Sequential)] + struct Win32_IP_ADAPTER_WINS_SERVER_ADDRESS + { + public Win32LengthFlagsUnion LengthFlags; + public IntPtr Next; // to Win32_IP_ADAPTER_WINS_SERVER_ADDRESS + public Win32_SOCKET_ADDRESS Address; + } + [StructLayout (LayoutKind.Sequential)] struct Win32_IP_ADAPTER_UNICAST_ADDRESS { diff --git a/mcs/class/System/System.Net/WebResponseStream.cs b/mcs/class/System/System.Net/WebResponseStream.cs index 0d6508b9ea..c55b2014ee 100644 --- a/mcs/class/System/System.Net/WebResponseStream.cs +++ b/mcs/class/System/System.Net/WebResponseStream.cs @@ -400,6 +400,8 @@ namespace System.Net WebConnection.Debug ($"{ME} CLOSE #1: read_eof={read_eof} bufferedEntireContent={bufferedEntireContent}"); if (read_eof || bufferedEntireContent) { disposed = true; + innerStream?.Dispose (); + innerStream = null; Operation.Finish (true); } else { // If we have not read all the contents diff --git a/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2.cs b/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2.cs index f234f33b92..f6237b7e6a 100644 --- a/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2.cs +++ b/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2.cs @@ -68,61 +68,68 @@ namespace System.Security.Cryptography.X509Certificates { public X509Certificate2 (byte[] rawData) { - Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet); + // MONO: temporary hack until `X509CertificateImplApple` derives from + // `X509Certificate2Impl`. + if (rawData != null && rawData.Length != 0) { + using (var safePasswordHandle = new SafePasswordHandle ((string)null)) { + var impl = X509Helper.Import (rawData, safePasswordHandle, X509KeyStorageFlags.DefaultKeySet); + ImportHandle (impl); + } + } } public X509Certificate2 (byte[] rawData, string password) + : base (rawData, password) { - Import (rawData, password, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate2 (byte[] rawData, SecureString password) + : base (rawData, password) { - Import (rawData, password, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate2 (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) + : base (rawData, password, keyStorageFlags) { - Import (rawData, password, keyStorageFlags); } public X509Certificate2 (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) + : base (rawData, password, keyStorageFlags) { - Import (rawData, password, keyStorageFlags); } public X509Certificate2 (string fileName) + : base (fileName) { - Import (fileName, String.Empty, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate2 (string fileName, string password) + : base (fileName, password) { - Import (fileName, password, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate2 (string fileName, SecureString password) + : base (fileName, password) { - Import (fileName, password, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate2 (string fileName, string password, X509KeyStorageFlags keyStorageFlags) + : base (fileName, password, keyStorageFlags) { - Import (fileName, password, keyStorageFlags); } public X509Certificate2 (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) + : base (fileName, password, keyStorageFlags) { - Import (fileName, password, keyStorageFlags); } public X509Certificate2 (IntPtr handle) : base (handle) { - throw new NotImplementedException (); + throw new PlatformNotSupportedException (); } public X509Certificate2 (X509Certificate certificate) - : base (SystemDependencyProvider.Instance.CertificateProvider.Import (certificate)) + : base (certificate) { } @@ -175,8 +182,10 @@ namespace System.Security.Cryptography.X509Certificates { public AsymmetricAlgorithm PrivateKey { get { return Impl.PrivateKey; } - set { Impl.PrivateKey = value; } - } + set { + throw new PlatformNotSupportedException (); + } + } public PublicKey PublicKey { get { return Impl.PublicKey; } @@ -216,46 +225,32 @@ namespace System.Security.Cryptography.X509Certificates { public override void Import (byte[] rawData) { - Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet); + base.Import (rawData); } - [MonoTODO ("missing KeyStorageFlags support")] public override void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { - Reset (); - using (var handle = new SafePasswordHandle (password)) { - var impl = SystemDependencyProvider.Instance.CertificateProvider.Import (rawData, handle, keyStorageFlags); - ImportHandle (impl); - } + base.Import (rawData, password, keyStorageFlags); } public override void Import (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { - Reset (); - using (var handle = new SafePasswordHandle (password)) { - var impl = SystemDependencyProvider.Instance.CertificateProvider.Import (rawData, handle, keyStorageFlags); - ImportHandle (impl); - } + base.Import (rawData, password, keyStorageFlags); } public override void Import (string fileName) { - byte[] rawData = File.ReadAllBytes (fileName); - Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet); + base.Import (fileName); } - [MonoTODO ("missing KeyStorageFlags support")] public override void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags) { - byte[] rawData = File.ReadAllBytes (fileName); - Import (rawData, password, keyStorageFlags); + base.Import (fileName, password, keyStorageFlags); } - [MonoTODO ("SecureString is incomplete")] public override void Import (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) { - byte[] rawData = File.ReadAllBytes (fileName); - Import (rawData, password, keyStorageFlags); + base.Import (fileName, password, keyStorageFlags); } [MonoTODO ("X509ContentType.SerializedCert is not supported")] diff --git a/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2Collection.cs b/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2Collection.cs index 02ff9b1a8b..dae611a04e 100644 --- a/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2Collection.cs +++ b/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2Collection.cs @@ -333,8 +333,7 @@ namespace System.Security.Cryptography.X509Certificates { public void Import (byte[] rawData) { // FIXME: can it import multiple certificates, e.g. a pkcs7 file ? - X509Certificate2 cert = new X509Certificate2 (); - cert.Import (rawData); + X509Certificate2 cert = new X509Certificate2 (rawData); Add (cert); } @@ -342,8 +341,7 @@ namespace System.Security.Cryptography.X509Certificates { public void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { // FIXME: can it import multiple certificates, e.g. a pkcs7 file ? - X509Certificate2 cert = new X509Certificate2 (); - cert.Import (rawData, password, keyStorageFlags); + X509Certificate2 cert = new X509Certificate2 (rawData, password, keyStorageFlags); Add (cert); } @@ -351,8 +349,7 @@ namespace System.Security.Cryptography.X509Certificates { public void Import (string fileName) { // FIXME: can it import multiple certificates, e.g. a pkcs7 file ? - X509Certificate2 cert = new X509Certificate2 (); - cert.Import (fileName); + X509Certificate2 cert = new X509Certificate2 (fileName); Add (cert); } @@ -360,8 +357,7 @@ namespace System.Security.Cryptography.X509Certificates { public void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags) { // FIXME: can it import multiple certificates, e.g. a pkcs7 file ? - X509Certificate2 cert = new X509Certificate2 (); - cert.Import (fileName, password, keyStorageFlags); + X509Certificate2 cert = new X509Certificate2 (fileName, password, keyStorageFlags); Add (cert); } diff --git a/mcs/class/System/System.Security.Cryptography.X509Certificates/X509ChainElement.cs b/mcs/class/System/System.Security.Cryptography.X509Certificates/X509ChainElement.cs index 8a8af6557c..63bcef6a47 100644 --- a/mcs/class/System/System.Security.Cryptography.X509Certificates/X509ChainElement.cs +++ b/mcs/class/System/System.Security.Cryptography.X509Certificates/X509ChainElement.cs @@ -29,8 +29,6 @@ #if SECURITY_DEP -using Mono.Security.X509; - namespace System.Security.Cryptography.X509Certificates { public class X509ChainElement { diff --git a/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Store.cs b/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Store.cs index 0b9ec4525b..72f76f1351 100644 --- a/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Store.cs +++ b/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Store.cs @@ -237,7 +237,7 @@ namespace System.Security.Cryptography.X509Certificates { foreach (MX.X509Certificate x in store.Certificates) { var cert2 = new X509Certificate2 (x.RawData); - cert2.PrivateKey = x.RSA; + cert2.Impl.PrivateKey = x.RSA; Certificates.Add (cert2); } } diff --git a/mcs/class/System/System_test.dll.sources b/mcs/class/System/System_test.dll.sources index 00be693eaf..d322e8ac2f 100644 --- a/mcs/class/System/System_test.dll.sources +++ b/mcs/class/System/System_test.dll.sources @@ -1,4 +1,5 @@ ../../test-helpers/NunitHelpers.cs +../../test-helpers/TestResourceHelper.cs Microsoft.CSharp/CodeGeneratorFromCompileUnitTest.cs Microsoft.CSharp/CodeGeneratorFromExpressionTest.cs Microsoft.CSharp/CodeGeneratorFromNamespaceTest.cs diff --git a/mcs/class/System/Test/System.ComponentModel/DefaultValueAttributeTest.cs b/mcs/class/System/Test/System.ComponentModel/DefaultValueAttributeTest.cs index 6eac761bfc..ae7cb694fb 100644 --- a/mcs/class/System/Test/System.ComponentModel/DefaultValueAttributeTest.cs +++ b/mcs/class/System/Test/System.ComponentModel/DefaultValueAttributeTest.cs @@ -26,6 +26,9 @@ using System; using System.ComponentModel; +#if !MOBILE && !XAMMAC_4_5 +using System.Drawing; +#endif using NUnit.Framework; namespace MonoTests.System.ComponentModel { @@ -58,5 +61,21 @@ namespace MonoTests.System.ComponentModel { Assert.AreEqual (1, dvat.GetHashCode (), "GetHashCode"); } + +#if !MOBILE && !XAMMAC_4_5 + [DefaultValue (typeof (Color), "Black")] + public Color Bar { get; set; } + + // https://github.com/mono/mono/issues/12362 + [Test] + public void Bug_12362 () + { + var prop = typeof (DefaultValueAttributeTest).GetProperty ("Bar"); + var attr = (DefaultValueAttribute)prop.GetCustomAttributes (true) [0]; + var value = attr.Value; + Assert.IsNotNull (value); + Assert.AreEqual (typeof (Color), value.GetType ()); + } +#endif } } diff --git a/mcs/class/System/Test/System.IO.Compression/DeflateStreamTest.cs b/mcs/class/System/Test/System.IO.Compression/DeflateStreamTest.cs index 9d54e0f601..f0c1f095a8 100644 --- a/mcs/class/System/Test/System.IO.Compression/DeflateStreamTest.cs +++ b/mcs/class/System/Test/System.IO.Compression/DeflateStreamTest.cs @@ -15,6 +15,8 @@ using System.IO; using System.IO.Compression; using System.Text; +using MonoTests.Helpers; + namespace MonoTests.System.IO.Compression { [TestFixture] @@ -467,7 +469,7 @@ namespace MonoTests.System.IO.Compression public void Bug44994_InflateByteByByte() { int byteCount = 0; - using (var fileStream = File.OpenRead(Path.Combine("Test", "compressed.bin"))) + using (var fileStream = File.OpenRead(TestResourceHelper.GetFullPathOfResource ("Test/compressed.bin"))) { using (var deflateStream = new DeflateStream(fileStream, CompressionMode.Decompress, false)) { diff --git a/mcs/class/System/Test/System.Net/HttpListenerBasicIdentityTest.cs b/mcs/class/System/Test/System.Net/HttpListenerBasicIdentityTest.cs index f998592aad..a6b196d071 100644 --- a/mcs/class/System/Test/System.Net/HttpListenerBasicIdentityTest.cs +++ b/mcs/class/System/Test/System.Net/HttpListenerBasicIdentityTest.cs @@ -37,7 +37,7 @@ namespace MonoTests.System.Net { [ExpectedException (typeof (ArgumentNullException))] public void Basic1 () { -#if MONOTOUCH_WATCH || __WATCHOS__ +#if MONOTOUCH_WATCH Assert.Ignore ("HttpListenerBasicIdentity is not supported on watchOS"); #endif HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity (null, null); @@ -46,7 +46,7 @@ namespace MonoTests.System.Net { [Test] public void Basic2 () { -#if MONOTOUCH_WATCH || __WATCHOS__ +#if MONOTOUCH_WATCH Assert.Ignore ("HttpListenerBasicIdentity is not supported on watchOS"); #endif HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity ("", null); @@ -59,7 +59,7 @@ namespace MonoTests.System.Net { [Test] public void Basic3 () { -#if MONOTOUCH_WATCH || __WATCHOS__ +#if MONOTOUCH_WATCH Assert.Ignore ("HttpListenerBasicIdentity is not supported on watchOS"); #endif HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity ("hey", null); @@ -72,7 +72,7 @@ namespace MonoTests.System.Net { [Test] public void Basic4 () { -#if MONOTOUCH_WATCH || __WATCHOS__ +#if MONOTOUCH_WATCH Assert.Ignore ("HttpListenerBasicIdentity is not supported on watchOS"); #endif HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity ("hey", "pass"); diff --git a/mcs/class/System/Test/System.Net/HttpWebRequestTest.cs.REMOVED.git-id b/mcs/class/System/Test/System.Net/HttpWebRequestTest.cs.REMOVED.git-id index 77d840e614..d0d8b70f46 100644 --- a/mcs/class/System/Test/System.Net/HttpWebRequestTest.cs.REMOVED.git-id +++ b/mcs/class/System/Test/System.Net/HttpWebRequestTest.cs.REMOVED.git-id @@ -1 +1 @@ -0e5e4fa3cc55421e0c4f859790f4f9db6af83d40 \ No newline at end of file +e002ba0f9d7349156f9fd25c0c9c7fc124a3b47a \ No newline at end of file diff --git a/mcs/class/System/Test/System.Security.Cryptography.X509Certificates/X509Cert20Test.cs b/mcs/class/System/Test/System.Security.Cryptography.X509Certificates/X509Cert20Test.cs index 75d04b12f7..5e097d7228 100644 --- a/mcs/class/System/Test/System.Security.Cryptography.X509Certificates/X509Cert20Test.cs +++ b/mcs/class/System/Test/System.Security.Cryptography.X509Certificates/X509Cert20Test.cs @@ -320,9 +320,6 @@ mgk3bWUV6ChegutbguiKrI/DbO7wPiDLxw== Assert.AreEqual ("System.Security.Cryptography.X509Certificates.X509Certificate", x.ToString (false), "ToString(false)"); Assert.IsTrue (x.Equals (x), "Equals(X509Certificate)"); Assert.IsTrue (x.Equals ((object) x), "Equals(object)"); - x.Reset (); - x.Import (cert1); - Assert.AreEqual ("02720006E8", x.GetSerialNumberString (), "GetSerialNumberString"); } [Test] @@ -456,7 +453,7 @@ mgk3bWUV6ChegutbguiKrI/DbO7wPiDLxw== #if !MOBILE [Test] - [ExpectedException (typeof (NullReferenceException))] + [ExpectedException (typeof (PlatformNotSupportedException))] public void GetObjectData_Null () { X509Certificate x = new X509Certificate (); @@ -465,6 +462,7 @@ mgk3bWUV6ChegutbguiKrI/DbO7wPiDLxw== } [Test] + [ExpectedException (typeof (PlatformNotSupportedException))] public void GetObjectData () { X509Certificate x = new X509Certificate (cert1); @@ -472,27 +470,22 @@ mgk3bWUV6ChegutbguiKrI/DbO7wPiDLxw== Assert.IsNotNull (s, "ISerializable"); SerializationInfo info = new SerializationInfo (typeof (X509Certificate), new FormatterConverter ()); s.GetObjectData (info, new StreamingContext (StreamingContextStates.All)); - Assert.AreEqual (1, info.MemberCount, "MemberCount"); - byte[] raw = (byte[]) info.GetValue ("RawData", typeof (byte[])); } #endif [Test] - [ExpectedException (typeof (NullReferenceException))] + [ExpectedException (typeof (PlatformNotSupportedException))] public void Ctor_Serialization_Null () { new X509Certificate (null, new StreamingContext (StreamingContextStates.All)); } [Test] + [ExpectedException (typeof (PlatformNotSupportedException))] public void Ctor_Serialization () { SerializationInfo info = new SerializationInfo (typeof (X509Certificate), new FormatterConverter ()); - info.AddValue ("RawData", cert1); - X509Certificate x = new X509Certificate (info, new StreamingContext (StreamingContextStates.All)); - Assert.AreEqual (cert1, x.GetRawCertData (), "GetRawCertData"); - // decoding is done too - Assert.AreEqual ("02720006E8", x.GetSerialNumberString (), "SerialNumber"); + new X509Certificate (info, new StreamingContext (StreamingContextStates.All)); } @@ -741,15 +734,6 @@ mgk3bWUV6ChegutbguiKrI/DbO7wPiDLxw== { new X509Certificate (farscape_pkcs7); } - - [Test] - [ExpectedException (typeof (CryptographicException))] - [Category ("MacNotWorking")] // SecCertificateCreateWithData does different things on 10.11 vs 10.12 with invalid certificates https://bugzilla.xamarin.com/show_bug.cgi?id=53689 - public void Pkcs7_Import () - { - X509Certificate x = new X509Certificate (); - x.Import (farscape_pkcs7); - } } } diff --git a/mcs/class/System/Test/System.Security.Cryptography.X509Certificates/X509Certificate2Test.cs.REMOVED.git-id b/mcs/class/System/Test/System.Security.Cryptography.X509Certificates/X509Certificate2Test.cs.REMOVED.git-id index f4a834896c..8f7b369860 100644 --- a/mcs/class/System/Test/System.Security.Cryptography.X509Certificates/X509Certificate2Test.cs.REMOVED.git-id +++ b/mcs/class/System/Test/System.Security.Cryptography.X509Certificates/X509Certificate2Test.cs.REMOVED.git-id @@ -1 +1 @@ -154d250723232cec39579047ce3ebd3ed2839f24 \ No newline at end of file +2ece09a6bcbc8bd2bc7fba916be03eb093a31b70 \ No newline at end of file diff --git a/mcs/class/System/Test/System/UriTest2.cs b/mcs/class/System/Test/System/UriTest2.cs index 85eb8c712c..8fccc8bab6 100644 --- a/mcs/class/System/Test/System/UriTest2.cs +++ b/mcs/class/System/Test/System/UriTest2.cs @@ -8,6 +8,8 @@ using System.Reflection; using System.Text; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System { // help bring Moonlight tests back to mono/mcs nunit @@ -108,7 +110,7 @@ namespace MonoTests.System [Ignore ("Tests needs to be updated for 2.0")] public void AbsoluteUriFromFile () { - FromResource ("test-uri-props.txt", null); + FromResource ("Test/System/test-uri-props.txt", null); } [Test] @@ -118,21 +120,19 @@ namespace MonoTests.System { if (Path.DirectorySeparatorChar == '\\') return; - FromResource ("test-uri-props-manual.txt", null); + FromResource ("Test/System/test-uri-props-manual.txt", null); } [Test] [Ignore ("Tests needs to be updated for 2.0")] public void RelativeUriFromFile () { - FromResource ("test-uri-relative-props.txt", new Uri ("http://www.go-mono.com")); + FromResource ("Test/System/test-uri-relative-props.txt", new Uri ("http://www.go-mono.com")); } private void FromResource (string res, Uri baseUri) { - Assembly a = Assembly.GetExecutingAssembly (); - Stream s = a.GetManifestResourceStream (res); - StreamReader sr = new StreamReader (s, Encoding.UTF8); + StreamReader sr = new StreamReader (TestResourceHelper.GetFullPathOfResource (res), Encoding.UTF8); while (sr.Peek () > 0) { sr.ReadLine (); // skip string uriString = sr.ReadLine (); diff --git a/mcs/class/System/Test/compressed.bin b/mcs/class/System/Test/compressed.bin new file mode 100644 index 0000000000..3098195f87 Binary files /dev/null and b/mcs/class/System/Test/compressed.bin differ diff --git a/mcs/class/System/mobile_System.dll.sources b/mcs/class/System/mobile_System.dll.sources index 665c31ae90..734c58b369 100644 --- a/mcs/class/System/mobile_System.dll.sources +++ b/mcs/class/System/mobile_System.dll.sources @@ -1,5 +1,6 @@ #include common.sources #include common_networking.sources +#include corefx.unix.sources ../../../external/corefx/src/Common/src/System/Net/ContextAwareResult.Unix.cs ../../../external/corefx/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.UnknownUnix.cs Internal.Cryptography/OidLookup.Managed.cs diff --git a/mcs/class/System/monodroid_System.dll.exclude.sources b/mcs/class/System/monodroid_System.dll.exclude.sources new file mode 100644 index 0000000000..7e8ef2c9ae --- /dev/null +++ b/mcs/class/System/monodroid_System.dll.exclude.sources @@ -0,0 +1 @@ +../../../external/corefx/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.UnknownUnix.cs diff --git a/mcs/class/System/monodroid_System.dll.sources b/mcs/class/System/monodroid_System.dll.sources index 35882f9032..a28f967b67 100644 --- a/mcs/class/System/monodroid_System.dll.sources +++ b/mcs/class/System/monodroid_System.dll.sources @@ -6,3 +6,16 @@ Mono.Btls/MonoBtlsX509LookupAndroid.cs ../../../external/corefx/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CompiledRegexRunner.cs ../../../external/corefx/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CompiledRegexRunnerFactory.cs ../../../external/corefx/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexLWCGCompiler.cs + +../../../external/corefx/src/Common/src/Interop/Linux/Interop.Libraries.cs +../../../external/corefx/src/Common/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs +../../../external/corefx/src/Common/src/Microsoft/Win32/SafeHandles/SafeDirectoryHandle.Unix.cs +../../../external/corefx/src/Common/src/Interop/Linux/System.Native/Interop.INotify.cs +../../../external/corefx/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Linux.cs +../../../external/corefx/src/Common/src/Interop/Unix/System.Native/Interop.OpenFlags.cs +../../../external/corefx/src/Common/src/Interop/Unix/System.Native/Interop.ReadDir.cs +../../../external/corefx/src/Common/src/Interop/Unix/System.Native/Interop.FLock.cs +../../../external/corefx/src/Common/src/Interop/Unix/System.Native/Interop.Stat.cs +../../../external/corefx/src/Common/src/Interop/Unix/System.Native/Interop.Poll.cs +../../../external/corefx/src/Common/src/Interop/Unix/System.Native/Interop.Open.cs +../../../external/corefx/src/Common/src/Interop/Unix/System.Native/Interop.Close.cs diff --git a/mcs/class/System/monotouch_System.dll.exclude.sources b/mcs/class/System/monotouch_System.dll.exclude.sources new file mode 100644 index 0000000000..7328c4dca7 --- /dev/null +++ b/mcs/class/System/monotouch_System.dll.exclude.sources @@ -0,0 +1,2 @@ +corefx/Unix/Interop.cs +corefx/Unix/Interop.Read.cs diff --git a/mcs/class/System/monotouch_tv_System.dll.exclude.sources b/mcs/class/System/monotouch_tv_System.dll.exclude.sources new file mode 100644 index 0000000000..a054966dd8 --- /dev/null +++ b/mcs/class/System/monotouch_tv_System.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_System.dll.exclude.sources diff --git a/mcs/class/System/monotouch_tv_System_test.dll.exclude.sources b/mcs/class/System/monotouch_tv_System_test.dll.exclude.sources new file mode 100644 index 0000000000..7263b4896b --- /dev/null +++ b/mcs/class/System/monotouch_tv_System_test.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_System_test.dll.exclude.sources diff --git a/mcs/class/System/monotouch_tv_System_xtest.dll.exclude.sources b/mcs/class/System/monotouch_tv_System_xtest.dll.exclude.sources new file mode 100644 index 0000000000..fde28e6e4b --- /dev/null +++ b/mcs/class/System/monotouch_tv_System_xtest.dll.exclude.sources @@ -0,0 +1,14 @@ +#include monotouch_System_xtest.dll.exclude.sources +../../../external/corefx/src/System.CodeDom/tests/CodeCollections/*.cs +../../../external/corefx/src/System.CodeDom/tests/CodeExpressions/*.cs +../../../external/corefx/src/System.CodeDom/tests/CodeObjects/*.cs +../../../external/corefx/src/System.CodeDom/tests/CodeStatements/*.cs +../../../external/corefx/src/System.CodeDom/tests/CodeTypeMembers/*.cs +../../../external/corefx/src/System.CodeDom/tests/Compiler/*.cs +../../../external/corefx/src/System.CodeDom/tests/Other/*.cs +../../../external/corefx/src/System.CodeDom/tests/Microsoft/CSharp/*.cs +../../../external/corefx/src/System.CodeDom/tests/Microsoft/VisualBasic/*.cs +../../../external/corefx/src/System.CodeDom/tests/*.cs +../../../external/corefx/src/System.IO.FileSystem.Watcher/tests/Utility/FileSystemWatcherTest.cs +../../../external/corefx/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.cs +../../../external/corefx/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.unit.cs diff --git a/mcs/class/System/monotouch_watch_System.dll.exclude.sources b/mcs/class/System/monotouch_watch_System.dll.exclude.sources index e0f6bbb13f..6dac986e5b 100644 --- a/mcs/class/System/monotouch_watch_System.dll.exclude.sources +++ b/mcs/class/System/monotouch_watch_System.dll.exclude.sources @@ -1,2 +1,3 @@ +#include monotouch_System.dll.exclude.sources #include common_networking.sources #include appletls.sources diff --git a/mcs/class/System/monotouch_watch_System.dll.sources b/mcs/class/System/monotouch_watch_System.dll.sources index 5ac8106c79..8ed3a4d14e 100644 --- a/mcs/class/System/monotouch_watch_System.dll.sources +++ b/mcs/class/System/monotouch_watch_System.dll.sources @@ -22,4 +22,22 @@ System.Net/HttpWebResponse.platformnotsupported.cs System.Net/ServicePoint.platformnotsupported.cs System.Net/ServicePointManager.platformnotsupported.cs System.Net.WebSockets/HttpListenerWebSocketContext.platformnotsupported.cs +../Mono.Security/Mono.Security/PKCS7.cs +../Mono.Security/Mono.Security.Cryptography/PKCS8.cs ../Mono.Security/Mono.Security.X509.Extensions/AuthorityKeyIdentifierExtension.cs +../Mono.Security/Mono.Security.X509/PKCS12.cs +../Mono.Security/Mono.Security.X509/X501Name.cs +../Mono.Security/Mono.Security.X509/X509Certificate.cs +../Mono.Security/Mono.Security.X509/X509CertificateCollection.cs +../Mono.Security/Mono.Security.X509/X509Chain.cs +../Mono.Security/Mono.Security.X509/X509ChainStatusFlags.cs +../Mono.Security/Mono.Security.X509/X509CRL.cs +../Mono.Security/Mono.Security.X509/X509Extension.cs +../Mono.Security/Mono.Security.X509/X509Extensions.cs +../Mono.Security/Mono.Security.X509/X509Store.cs +../Mono.Security/Mono.Security.X509/X509Stores.cs +../Mono.Security/Mono.Security.X509/X509StoreManager.cs +../Mono.Security/Mono.Security.X509/X520Attributes.cs +../Mono.Security/Mono.Security.X509.Extensions/BasicConstraintsExtension.cs +../Mono.Security/Mono.Security.X509.Extensions/KeyUsageExtension.cs +../Mono.Security/Mono.Security.X509.Extensions/SubjectKeyIdentifierExtension.cs diff --git a/mcs/class/System/monotouch_watch_System_test.dll.exclude.sources b/mcs/class/System/monotouch_watch_System_test.dll.exclude.sources new file mode 100644 index 0000000000..567cdc8336 --- /dev/null +++ b/mcs/class/System/monotouch_watch_System_test.dll.exclude.sources @@ -0,0 +1,2 @@ +#include monotouch_System_test.dll.exclude.sources +System.Net/HttpWebRequestTest.cs diff --git a/mcs/class/System/monotouch_watch_System_xtest.dll.exclude.sources b/mcs/class/System/monotouch_watch_System_xtest.dll.exclude.sources new file mode 100644 index 0000000000..fde28e6e4b --- /dev/null +++ b/mcs/class/System/monotouch_watch_System_xtest.dll.exclude.sources @@ -0,0 +1,14 @@ +#include monotouch_System_xtest.dll.exclude.sources +../../../external/corefx/src/System.CodeDom/tests/CodeCollections/*.cs +../../../external/corefx/src/System.CodeDom/tests/CodeExpressions/*.cs +../../../external/corefx/src/System.CodeDom/tests/CodeObjects/*.cs +../../../external/corefx/src/System.CodeDom/tests/CodeStatements/*.cs +../../../external/corefx/src/System.CodeDom/tests/CodeTypeMembers/*.cs +../../../external/corefx/src/System.CodeDom/tests/Compiler/*.cs +../../../external/corefx/src/System.CodeDom/tests/Other/*.cs +../../../external/corefx/src/System.CodeDom/tests/Microsoft/CSharp/*.cs +../../../external/corefx/src/System.CodeDom/tests/Microsoft/VisualBasic/*.cs +../../../external/corefx/src/System.CodeDom/tests/*.cs +../../../external/corefx/src/System.IO.FileSystem.Watcher/tests/Utility/FileSystemWatcherTest.cs +../../../external/corefx/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.cs +../../../external/corefx/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.unit.cs diff --git a/mcs/class/System/net_4_x_System.dll.sources b/mcs/class/System/net_4_x_System.dll.sources index 2023f0ba48..0a0a9c493d 100644 --- a/mcs/class/System/net_4_x_System.dll.sources +++ b/mcs/class/System/net_4_x_System.dll.sources @@ -139,7 +139,6 @@ System.IO/NullFileWatcher.cs System.IO/FileAction.cs System.IO/FileSystemWatcher.cs System.IO/IFileWatcher.cs -System.IO/InotifyWatcher.cs System.IO/KeventWatcher.cs System.IO/SearchPattern.cs diff --git a/mcs/class/WebMatrix.Data/Makefile b/mcs/class/WebMatrix.Data/Makefile index 781ebe75f4..d307728357 100644 --- a/mcs/class/WebMatrix.Data/Makefile +++ b/mcs/class/WebMatrix.Data/Makefile @@ -7,7 +7,10 @@ LIBRARY = WebMatrix.Data.dll LIB_REFS = System System.Data System.Core System.Configuration KEYFILE = ../mono.pub LIB_MCS_FLAGS = -TEST_MCS_FLAGS = +TEST_RESOURCE_FILES = Test/resources/testsqlite.db +TEST_MCS_FLAGS = $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) TEST_LIB_REFS = System System.Core System.Data Mono.Data.Sqlite Microsoft.CSharp +EXTRA_DISTFILES = $(TEST_RESOURCE_FILES) + include ../../build/library.make diff --git a/mcs/class/WebMatrix.Data/Test/WebMatrix.Data/DatabaseTests.cs b/mcs/class/WebMatrix.Data/Test/WebMatrix.Data/DatabaseTests.cs index a034e7ea02..41094b82e3 100644 --- a/mcs/class/WebMatrix.Data/Test/WebMatrix.Data/DatabaseTests.cs +++ b/mcs/class/WebMatrix.Data/Test/WebMatrix.Data/DatabaseTests.cs @@ -35,6 +35,8 @@ using WebMatrix.Data; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.WebMatrix.Data { [TestFixtureAttribute] @@ -46,7 +48,7 @@ namespace MonoTests.WebMatrix.Data [SetUp] public void Setup () { - dbPath = Path.Combine ("Test", "testsqlite.db"); + dbPath = TestResourceHelper.GetFullPathOfResource ("Test/resources/testsqlite.db"); database = Database.OpenConnectionString ("Data Source="+dbPath+";Version=3;", "Mono.Data.Sqlite"); } diff --git a/mcs/class/WebMatrix.Data/Test/resources/testsqlite.db b/mcs/class/WebMatrix.Data/Test/resources/testsqlite.db new file mode 100644 index 0000000000..06fd900473 Binary files /dev/null and b/mcs/class/WebMatrix.Data/Test/resources/testsqlite.db differ diff --git a/mcs/class/WebMatrix.Data/WebMatrix.Data_test.dll.sources b/mcs/class/WebMatrix.Data/WebMatrix.Data_test.dll.sources index 0d885863e4..bfe9f41b3b 100644 --- a/mcs/class/WebMatrix.Data/WebMatrix.Data_test.dll.sources +++ b/mcs/class/WebMatrix.Data/WebMatrix.Data_test.dll.sources @@ -1,4 +1,5 @@ ../../test-helpers/NunitHelpers.cs +../../test-helpers/TestResourceHelper.cs WebMatrix.Data/ConnectionEventArgsTests.cs WebMatrix.Data/DynamicRecordTests.cs ../WebMatrix.Data/DynamicRecord.cs diff --git a/mcs/class/corlib/LinkerDescriptor/mscorlib.xml b/mcs/class/corlib/LinkerDescriptor/mscorlib.xml index e0001bee05..25e78d55a1 100644 --- a/mcs/class/corlib/LinkerDescriptor/mscorlib.xml +++ b/mcs/class/corlib/LinkerDescriptor/mscorlib.xml @@ -230,7 +230,7 @@ - + @@ -322,9 +322,6 @@ - - - @@ -472,10 +469,7 @@ - - - - + @@ -554,11 +548,6 @@ - - - - - @@ -743,7 +732,7 @@ - + @@ -753,9 +742,6 @@ - - - diff --git a/mcs/class/corlib/Makefile b/mcs/class/corlib/Makefile index 86421f3a69..d25af03dfa 100644 --- a/mcs/class/corlib/Makefile +++ b/mcs/class/corlib/Makefile @@ -43,6 +43,7 @@ RESX_RESOURCE_STRING = \ ../../../external/corefx/src/System.Net.Requests/src/Resources/Strings.resx \ ../../../external/corefx/src/System.Net.Http/src/Resources/Strings.resx \ ../../../external/corefx/src/System.Numerics.Vectors/src/Resources/Strings.resx \ + ../../../external/corefx/src/System.Reflection.TypeExtensions/src/Resources/Strings.resx \ ../../../external/corefx/src/System.Runtime.Extensions/src/Resources/Strings.resx \ ../../../external/corefx/src/System.Runtime.InteropServices.RuntimeInformation/src/Resources/Strings.resx \ ../../../external/corefx/src/System.Runtime.Numerics/src/Resources/Strings.resx \ @@ -55,8 +56,8 @@ RESX_RESOURCE_STRING = \ ../../../external/corefx/src/System.Threading.Tasks.Parallel/src/Resources/Strings.resx \ ../../../external/corefx/src/System.ObjectModel/src/Resources/Strings.resx \ ../../../external/corert/src/System.Private.CoreLib/src/Resources/Strings.resx \ - ../../../external/corefx/src/System.Private.Uri/src/Resources/Strings.resx - + ../../../external/corefx/src/System.Private.Uri/src/Resources/Strings.resx \ + ../../../external/corefx/src/Microsoft.Win32.Registry/src/Resources/Strings.resx LIBRARY_COMPILE = $(BOOT_COMPILE) LIBRARY_INSTALL_DIR = $(mono_libdir)/mono/$(FRAMEWORK_VERSION) @@ -70,6 +71,8 @@ RESOURCE_STRINGS = ../referencesource/mscorlib/mscorlib.txt MODULE_DEPS = $(IL_REPLACE) endif +MODULE_DEPS += LinkerDescriptor/mscorlib.xml + RESOURCE_FILES = \ resources/charinfo.nlp \ resources/collation.core.bin \ @@ -122,7 +125,7 @@ ifdef MONO_FEATURE_APPLE_X509 LIB_MCS_FLAGS += -d:MONO_FEATURE_APPLE_X509 endif -COREFX_FLAGS := -d:BIT64 +COREFX_FLAGS := -d:BIT64,REGISTRY_ASSEMBLY WARNING_ABOUT_DISABLED_WARNING=1635 LOCAL_MCS_FLAGS = -unsafe -nostdlib -nowarn:612,618,3001,3002,3003,$(WARNING_ABOUT_DISABLED_WARNING) -d:INSIDE_CORLIB,MONO_CULTURE_DATA -d:LIBC $(REFERENCE_SOURCES_FLAGS) $(COREFX_FLAGS) @@ -132,6 +135,7 @@ TEST_LIB_REFS = System.Core System XTEST_LIB_REFS = System System.Core Facades/System.Threading.Tasks Facades/System.Text.RegularExpressions System.Numerics System.Runtime.CompilerServices.Unsafe XTEST_LIB_FLAGS = -d:netcoreapp -publicsign -keyfile:../mono.snk +XTEST_MCS_FLAGS = -resource:../../../external/corefx/src/System.Reflection/tests/Resources/ResourceTextFile.txt,ResourceTextFile.txt ifndef AOT_FRIENDLY_PROFILE ifneq ($(PROFILE),testing_aot_hybrid) @@ -171,6 +175,13 @@ CommonCrypto/%.g.cs: endif EXTRA_DISTFILES = \ + Test/resources/culture-*.cs \ + $(RESOURCE_FILES) \ + $(TEST_RESOURCE_FILES) \ + $(TEST_RESOURCES:.resources=.resx) \ + LinkerDescriptor/mscorlib_test.xml + +TEST_RESOURCE_FILES = \ Test/resources/MyResources.resources \ Test/resources/MyResources.de.resources \ Test/resources/Empty.resources \ @@ -179,11 +190,9 @@ EXTRA_DISTFILES = \ Test/resources/StreamTest.ja.resources \ Test/resources/bug81759.resources \ Test/resources/415628.bin \ - Test/resources/Fergie.GED \ - Test/resources/culture-*.cs \ - $(RESOURCE_FILES) \ - $(TEST_RESOURCES:.resources=.resx) \ - LinkerDescriptor/mscorlib_test.xml + Test/resources/Fergie.GED + +TEST_MCS_FLAGS += $(foreach r, $(TEST_RESOURCE_FILES), -resource:$(r),$(r)) TEST_RESX_RESOURCES = \ Test/resources/Resources.resources @@ -192,7 +201,7 @@ TEST_RESX_RESOURCES_SATELITE = \ Test/resources/Resources.es-ES.resources \ Test/resources/Resources.nn-NO.resources -CLEAN_FILES += $(TEST_RESX_RESOURCES) $(IL_REPLACE) +CLEAN_FILES += $(TEST_RESX_RESOURCES) $(TEST_RESX_RESOURCES_SATELITE) $(IL_REPLACE) include $(topdir)/build/library.make @@ -204,7 +213,7 @@ TEST_RESOURCES = $(TEST_RESX_RESOURCES) $(TEST_RESX_RESOURCES_SATELITE) satellite_assembly1 = $(test_lib_dir)/es-ES/$(patsubst %.dll,%.resources.dll,$(test_lib)) satellite_assembly2 = $(test_lib_dir)/nn-NO/$(patsubst %.dll,%.resources.dll,$(test_lib)) -$(test_lib_output): $(TEST_RESOURCES) $(satellite_assembly1) $(satellite_assembly2) | $(test_lib_dir) +$(test_lib_output): $(TEST_RESOURCES) $(satellite_assembly1) $(satellite_assembly2) $(test_lib_dir) $(satellite_assembly1): Test/resources/culture-es-ES.cs Test/resources/Resources.es-ES.resources @mkdir -p $(dir $@) diff --git a/mcs/class/corlib/Microsoft.Win32/RegistryHive.cs b/mcs/class/corlib/Microsoft.Win32/RegistryHive.cs deleted file mode 100644 index 922e78009e..0000000000 --- a/mcs/class/corlib/Microsoft.Win32/RegistryHive.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// Microsoft.Win32.RegistryHive.cs -// -// Author: -// Alexandre Pigolkine (pigolkine@gmx.de) - -// -// 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 System; -using System.Runtime.InteropServices; - -namespace Microsoft.Win32 -{ - - [Serializable] - [ComVisible (true)] - public enum RegistryHive - { - - ClassesRoot = -2147483648, - CurrentConfig = -2147483643, - CurrentUser = -2147483647, - DynData = -2147483642, - LocalMachine = -2147483646, - PerformanceData = -2147483644, - Users = -2147483645 - } - -} - diff --git a/mcs/class/corlib/Microsoft.Win32/RegistryKeyPermissionCheck.cs b/mcs/class/corlib/Microsoft.Win32/RegistryKeyPermissionCheck.cs deleted file mode 100644 index a1f95aacc2..0000000000 --- a/mcs/class/corlib/Microsoft.Win32/RegistryKeyPermissionCheck.cs +++ /dev/null @@ -1,38 +0,0 @@ -// -// Microsoft.Win32.RegistryKeyPermissionCheck.cs -// -// Author: -// Dick Porter (dick@ximian.com) - -// -// Copyright (C) 2007 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. -// - -namespace Microsoft.Win32 -{ - public enum RegistryKeyPermissionCheck - { - Default = 0, - ReadSubTree = 1, - ReadWriteSubTree = 2, - } -} diff --git a/mcs/class/corlib/Microsoft.Win32/RegistryOptions.cs b/mcs/class/corlib/Microsoft.Win32/RegistryOptions.cs deleted file mode 100644 index b7994b3257..0000000000 --- a/mcs/class/corlib/Microsoft.Win32/RegistryOptions.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// Microsoft.Win32.RegistryOptions.cs -// -// Copyright (C) 2010 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 System; -namespace Microsoft.Win32 { - [Flags] - [Serializable] - public enum RegistryOptions { - None, - Volatile - } -} - - diff --git a/mcs/class/corlib/Microsoft.Win32/RegistryValueKind.cs b/mcs/class/corlib/Microsoft.Win32/RegistryValueKind.cs deleted file mode 100644 index 8db4a861b5..0000000000 --- a/mcs/class/corlib/Microsoft.Win32/RegistryValueKind.cs +++ /dev/null @@ -1,44 +0,0 @@ -// -// Microsoft.Win32.RegistryValueKind.cs -// -// -// -// Copyright (C) 2006 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 System.Runtime.InteropServices; - -namespace Microsoft.Win32 -{ - [ComVisible (true)] - public enum RegistryValueKind { - Unknown, - String, - ExpandString, - Binary, - DWord, - MultiString = 7, - QWord = 11, - None = -1 - } -} - diff --git a/mcs/class/corlib/Microsoft.Win32/RegistryValueOptions.cs b/mcs/class/corlib/Microsoft.Win32/RegistryValueOptions.cs deleted file mode 100644 index 54f16378f3..0000000000 --- a/mcs/class/corlib/Microsoft.Win32/RegistryValueOptions.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// Microsoft.Win32.RegistryValueOptions.cs -// -// Author: -// Gert Driesen (drieseng@users.sourceforge.net) -// -// Copyright (C) 2006 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 System; - -namespace Microsoft.Win32 -{ - [Flags] - public enum RegistryValueOptions { - None, - DoNotExpandEnvironmentNames, - } -} - diff --git a/mcs/class/corlib/Microsoft.Win32/RegistryView.cs b/mcs/class/corlib/Microsoft.Win32/RegistryView.cs deleted file mode 100644 index 645b5c3eb4..0000000000 --- a/mcs/class/corlib/Microsoft.Win32/RegistryView.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// Microsoft.Win32.RegistryView.cs -// -// Copyright (C) 2010 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 System; -namespace Microsoft.Win32 { - [Serializable] - public enum RegistryView { - Default, - Registry64 = 0x100, - Registry32 = 0x200 - } -} - - diff --git a/mcs/class/corlib/Microsoft.Win32/UnixRegistryApi.cs b/mcs/class/corlib/Microsoft.Win32/UnixRegistryApi.cs index 3b9b0d4410..2865260707 100644 --- a/mcs/class/corlib/Microsoft.Win32/UnixRegistryApi.cs +++ b/mcs/class/corlib/Microsoft.Win32/UnixRegistryApi.cs @@ -1030,4 +1030,3 @@ namespace Microsoft.Win32 { } #endif // MOBILE - diff --git a/mcs/class/corlib/Mono/DependencyInjector.cs b/mcs/class/corlib/Mono/DependencyInjector.cs index 61e502e918..e30b26ff79 100644 --- a/mcs/class/corlib/Mono/DependencyInjector.cs +++ b/mcs/class/corlib/Mono/DependencyInjector.cs @@ -23,10 +23,10 @@ // 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 System; -#if !(MONOTOUCH || MONODROID) using System.Reflection; -#endif +using System.Runtime.CompilerServices; namespace Mono { @@ -45,13 +45,9 @@ namespace Mono if (systemDependency != null) return systemDependency; - // Not using `MOBILE` as a conditional here because we want to use this on full-aot. -#if !(MONOTOUCH || MONODROID) - // On Mobile, we initializes this during system startup. systemDependency = ReflectionLoad (); -#endif if (systemDependency == null) - throw new PlatformNotSupportedException ("Cannot get `ISystemDependencyProvider`."); + throw new PlatformNotSupportedException ($"Cannot find '{TypeName}' dependency"); return systemDependency; } @@ -67,22 +63,21 @@ namespace Mono } } -#if !(MONOTOUCH || MONODROID) - const string TypeName = "Mono.SystemDependencyProvider, " + Consts.AssemblySystem; + const string TypeName = "Mono.SystemDependencyProvider, System"; + [PreserveDependency ("get_Instance()", "Mono.SystemDependencyProvider", "System")] static ISystemDependencyProvider ReflectionLoad () { var type = Type.GetType (TypeName); if (type == null) return null; - var prop = type.GetProperty ("Instance", BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public); + var prop = type.GetProperty ("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly); if (prop == null) return null; - return (ISystemDependencyProvider)prop.GetValue (null); + return (ISystemDependencyProvider) prop.GetValue (null); } -#endif static object locker = new object (); static ISystemDependencyProvider systemDependency; diff --git a/mcs/class/corlib/Mono/MonoNativePlatform.cs b/mcs/class/corlib/Mono/MonoNativePlatform.cs new file mode 100644 index 0000000000..3159ac89a1 --- /dev/null +++ b/mcs/class/corlib/Mono/MonoNativePlatform.cs @@ -0,0 +1,86 @@ +// +// MonoNativePlatform.cs +// +// Author: +// Martin Baulig +// +// Copyright (c) 2018 Xamarin, 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. +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Mono +{ + /* + * The purpose of this class is to be used by test such as for instance + * the xamarin-macios test suite to examine and test the Mono.Native + * library. + */ + static class MonoNativePlatform + { + [DllImport ("System.Native")] + extern static int mono_native_get_platform_type (); + + public static MonoNativePlatformType GetPlatformType () + { + return (MonoNativePlatformType)mono_native_get_platform_type (); + } + + /* + * Test Suite Use Only. + */ + [MethodImpl (MethodImplOptions.InternalCall)] + extern static int IncrementInternalCounter (); + + [DllImport ("System.Native")] + extern static int mono_native_is_initialized (); + + [DllImport ("System.Native")] + extern static int mono_native_initialize (); + + /* + * This method is called by the xamarin-macios test suite + * to register the `IncrementInternalCounter` icall. + * + * It ensures that the native library can call + * `mono_add_internal_call_with_flags` and the mtouch and mmp + * tools can correctly deal with it. + */ + public static void Initialize () + { + mono_native_initialize (); + } + + public static bool IsInitialized () + { + return mono_native_is_initialized () != 0; + } + + /* + * Test Suite Use Only. + */ + internal static int TestInternalCounter () + { + // Atomically increments internal counter, for testing purposes only. + return IncrementInternalCounter (); + } + } +} diff --git a/mcs/class/corlib/System.Threading.Tasks/DecoupledTask.cs b/mcs/class/corlib/Mono/MonoNativePlatformType.cs similarity index 57% rename from mcs/class/corlib/System.Threading.Tasks/DecoupledTask.cs rename to mcs/class/corlib/Mono/MonoNativePlatformType.cs index f0e3d12ec2..3e20a5e7c3 100644 --- a/mcs/class/corlib/System.Threading.Tasks/DecoupledTask.cs +++ b/mcs/class/corlib/Mono/MonoNativePlatformType.cs @@ -1,10 +1,10 @@ // -// DecoupledTask.cs +// MonoNativePlatformType.cs // -// Authors: -// Marek Safar +// Author: +// Martin Baulig // -// Copyright 2013 Xamarin Inc (http://www.xamarin.com). +// Copyright (c) 2018 Xamarin, 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 @@ -23,51 +23,27 @@ // 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 System; - -namespace System.Threading.Tasks +namespace Mono { - // - // A proxy used to break direct dependency to TPL mostly useful for - // mobile profile - // - interface IDecoupledTask + // Keep in sync with mono/native/mono-native-platform-type.h + [Flags] + enum MonoNativePlatformType { - bool IsCompleted { get; } + MONO_NATIVE_PLATFORM_TYPE_UNKNOWN = 0, + MONO_NATIVE_PLATFORM_TYPE_MACOS = 1, + MONO_NATIVE_PLATFORM_TYPE_IOS = 2, + MONO_NATIVE_PLATFORM_TYPE_LINUX = 3, + + MONO_NATIVE_PLATFORM_TYPE_IPHONE = 0x100, + MONO_NATIVE_PLATFORM_TYPE_TV = 0x200, + MONO_NATIVE_PLATFORM_TYPE_WATCH = 0x400, + + MONO_NATIVE_PLATFORM_TYPE_COMPAT = 0x1000, + MONO_NATIVE_PLATFORM_TYPE_UNIFIED = 0x2000, + + MONO_NATIVE_PLATFORM_TYPE_SIMULATOR = 0x4000, + MONO_NATIVE_PLATFORM_TYPE_DEVICE = 0x8000 } - - sealed class DecoupledTask : IDecoupledTask - { - public DecoupledTask (Task task) - { - this.Task = task; - } - - public bool IsCompleted { - get { - return Task.IsCompleted; - } - } - - public Task Task { get; private set; } - } - - sealed class DecoupledTask : IDecoupledTask - { - public DecoupledTask (Task task) - { - this.Task = task; - } - - public bool IsCompleted { - get { - return Task.IsCompleted; - } - } - - public Task Task { get; private set; } - } } - diff --git a/mcs/class/corlib/Mono/Runtime.cs b/mcs/class/corlib/Mono/Runtime.cs index 6e0c9e3185..d4ca72d977 100644 --- a/mcs/class/corlib/Mono/Runtime.cs +++ b/mcs/class/corlib/Mono/Runtime.cs @@ -148,7 +148,7 @@ namespace Mono { } // All must be set except for configDir_str - static void EnableMicrosoftTelemetry (string appBundleID_str, string appSignature_str, string appVersion_str, string merpGUIPath_str, string eventType_str, string appPath_str) + static void EnableMicrosoftTelemetry (string appBundleID_str, string appSignature_str, string appVersion_str, string merpGUIPath_str, string eventType_str, string appPath_str, string configDir_str) { if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) { using (var appBundleID_chars = RuntimeMarshal.MarshalString (appBundleID_str)) @@ -157,14 +157,14 @@ namespace Mono { using (var merpGUIPath_chars = RuntimeMarshal.MarshalString (merpGUIPath_str)) using (var eventType_chars = RuntimeMarshal.MarshalString (eventType_str)) using (var appPath_chars = RuntimeMarshal.MarshalString (appPath_str)) + using (var configDir_chars = RuntimeMarshal.MarshalString (configDir_str)) { - EnableMicrosoftTelemetry_internal (appBundleID_chars.Value, appSignature_chars.Value, appVersion_chars.Value, merpGUIPath_chars.Value, eventType_chars.Value, appPath_chars.Value, IntPtr.Zero); + EnableMicrosoftTelemetry_internal (appBundleID_chars.Value, appSignature_chars.Value, appVersion_chars.Value, merpGUIPath_chars.Value, eventType_chars.Value, appPath_chars.Value, configDir_chars.Value); } } else { throw new PlatformNotSupportedException("Merp support is currently only supported on OSX."); } } - #endif [MethodImplAttribute (MethodImplOptions.InternalCall)] diff --git a/mcs/class/corlib/ReferenceSources/RuntimeType.cs b/mcs/class/corlib/ReferenceSources/RuntimeType.cs index 881474813e..fc0d54d91e 100644 --- a/mcs/class/corlib/ReferenceSources/RuntimeType.cs +++ b/mcs/class/corlib/ReferenceSources/RuntimeType.cs @@ -472,13 +472,13 @@ namespace System static extern Type MakeGenericType (Type gt, Type [] types); [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal extern IntPtr GetMethodsByName_native (IntPtr namePtr, BindingFlags bindingAttr, bool ignoreCase); + internal extern IntPtr GetMethodsByName_native (IntPtr namePtr, BindingFlags bindingAttr, MemberListType listType); - internal RuntimeMethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, RuntimeType reflectedType) + internal RuntimeMethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, MemberListType listType, RuntimeType reflectedType) { var refh = new RuntimeTypeHandle (reflectedType); using (var namePtr = new Mono.SafeStringMarshal (name)) - using (var h = new Mono.SafeGPtrArrayHandle (GetMethodsByName_native (namePtr.Value, bindingAttr, ignoreCase))) { + using (var h = new Mono.SafeGPtrArrayHandle (GetMethodsByName_native (namePtr.Value, bindingAttr, listType))) { var n = h.Length; var a = new RuntimeMethodInfo [n]; for (int i = 0; i < n; i++) { @@ -490,7 +490,7 @@ namespace System } [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern IntPtr GetPropertiesByName_native (IntPtr name, BindingFlags bindingAttr, bool icase); + extern IntPtr GetPropertiesByName_native (IntPtr name, BindingFlags bindingAttr, MemberListType listType); [MethodImplAttribute(MethodImplOptions.InternalCall)] extern IntPtr GetConstructors_native (BindingFlags bindingAttr); @@ -509,16 +509,16 @@ namespace System } } - RuntimePropertyInfo[] GetPropertiesByName (string name, BindingFlags bindingAttr, bool icase, RuntimeType reflectedType) + RuntimePropertyInfo[] GetPropertiesByName (string name, BindingFlags bindingAttr, MemberListType listType, RuntimeType reflectedType) { var refh = new RuntimeTypeHandle (reflectedType); using (var namePtr = new Mono.SafeStringMarshal (name)) - using (var h = new Mono.SafeGPtrArrayHandle (GetPropertiesByName_native (namePtr.Value, bindingAttr, icase))) { + using (var h = new Mono.SafeGPtrArrayHandle (GetPropertiesByName_native (namePtr.Value, bindingAttr, listType))) { var n = h.Length; var a = new RuntimePropertyInfo [n]; for (int i = 0; i < n; i++) { var ph = new Mono.RuntimePropertyHandle (h[i]); - a[i] = (RuntimePropertyInfo) PropertyInfo.GetPropertyFromHandle (ph, refh); + a[i] = (RuntimePropertyInfo) MonoProperty.GetPropertyFromHandle (ph, refh); } return a; } @@ -592,8 +592,10 @@ namespace System { AssemblyName assemblyname = new AssemblyName (); assemblyname.Name = "GetTypeFromCLSIDDummyAssembly"; - clsid_assemblybuilder = AppDomain.CurrentDomain.DefineDynamicAssembly ( - assemblyname, AssemblyBuilderAccess.Run); + /* Dynamically created assembly is marked internal to corlib to allow + __ComObject access for dynamic types. */ + clsid_assemblybuilder = new AssemblyBuilder (assemblyname, null, + AssemblyBuilderAccess.Run, true); } ModuleBuilder modulebuilder = clsid_assemblybuilder.DefineDynamicModule ( clsid.ToString ()); @@ -671,16 +673,16 @@ namespace System extern int GetGenericParameterPosition (); [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern IntPtr GetEvents_native (IntPtr name, BindingFlags bindingAttr); + extern IntPtr GetEvents_native (IntPtr name, BindingFlags bindingAttr, MemberListType listType); [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern IntPtr GetFields_native (IntPtr name, BindingFlags bindingAttr); + extern IntPtr GetFields_native (IntPtr name, BindingFlags bindingAttr, MemberListType listType); - RuntimeFieldInfo[] GetFields_internal (string name, BindingFlags bindingAttr, RuntimeType reflectedType) + RuntimeFieldInfo[] GetFields_internal (string name, BindingFlags bindingAttr, MemberListType listType, RuntimeType reflectedType) { var refh = new RuntimeTypeHandle (reflectedType); using (var namePtr = new Mono.SafeStringMarshal (name)) - using (var h = new Mono.SafeGPtrArrayHandle (GetFields_native (namePtr.Value, bindingAttr))) { + using (var h = new Mono.SafeGPtrArrayHandle (GetFields_native (namePtr.Value, bindingAttr, listType))) { int n = h.Length; var a = new RuntimeFieldInfo[n]; for (int i = 0; i < n; i++) { @@ -691,11 +693,11 @@ namespace System } } - RuntimeEventInfo[] GetEvents_internal (string name, BindingFlags bindingAttr, RuntimeType reflectedType) + RuntimeEventInfo[] GetEvents_internal (string name, BindingFlags bindingAttr, MemberListType listType, RuntimeType reflectedType) { var refh = new RuntimeTypeHandle (reflectedType); using (var namePtr = new Mono.SafeStringMarshal (name)) - using (var h = new Mono.SafeGPtrArrayHandle (GetEvents_native (namePtr.Value, bindingAttr))) { + using (var h = new Mono.SafeGPtrArrayHandle (GetEvents_native (namePtr.Value, bindingAttr, listType))) { int n = h.Length; var a = new RuntimeEventInfo[n]; for (int i = 0; i < n; i++) { @@ -710,15 +712,15 @@ namespace System public extern override Type[] GetInterfaces(); [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern IntPtr GetNestedTypes_native (IntPtr name, BindingFlags bindingAttr); + extern IntPtr GetNestedTypes_native (IntPtr name, BindingFlags bindingAttr, MemberListType listType); - RuntimeType[] GetNestedTypes_internal (string displayName, BindingFlags bindingAttr) + RuntimeType[] GetNestedTypes_internal (string displayName, BindingFlags bindingAttr, MemberListType listType) { string internalName = null; if (displayName != null) internalName = TypeIdentifiers.FromDisplay (displayName).InternalName; using (var namePtr = new Mono.SafeStringMarshal (internalName)) - using (var h = new Mono.SafeGPtrArrayHandle (GetNestedTypes_native (namePtr.Value, bindingAttr))) { + using (var h = new Mono.SafeGPtrArrayHandle (GetNestedTypes_native (namePtr.Value, bindingAttr, listType))) { int n = h.Length; var a = new RuntimeType [n]; for (int i = 0; i < n; i++) { @@ -798,6 +800,8 @@ namespace System } } + public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore (other); + public override bool IsSZArray { get { // TODO: intrinsic @@ -824,6 +828,5 @@ namespace System return RuntimeTypeHandle.IsSubclassOf (this, rtType); } - } } diff --git a/mcs/class/corlib/System.Configuration.Assemblies/AssemblyHashAlgorithm.cs b/mcs/class/corlib/System.Configuration.Assemblies/AssemblyHashAlgorithm.cs deleted file mode 100644 index ebac5f3d55..0000000000 --- a/mcs/class/corlib/System.Configuration.Assemblies/AssemblyHashAlgorithm.cs +++ /dev/null @@ -1,47 +0,0 @@ -// AssemblyHashAlgorithm.cs -// -// This code was automatically generated from -// ECMA CLI XML Library Specification. -// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] -// Created: Wed, 5 Sep 2001 06:38:03 UTC -// Source file: all.xml -// URL: http://devresource.hp.com/devresource/Docs/TechPapers/CSharp/all.xml -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004,2006 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 System.Runtime.InteropServices; - -namespace System.Configuration.Assemblies { - - [Serializable] - [ComVisible (true)] - public enum AssemblyHashAlgorithm { - None = 0, - MD5 = 32771, - SHA1 = 32772, - SHA256 = 32780, - SHA384 = 32781, - SHA512 = 32782, - } -} diff --git a/mcs/class/corlib/System.Configuration.Assemblies/AssemblyVersionCompatibility.cs b/mcs/class/corlib/System.Configuration.Assemblies/AssemblyVersionCompatibility.cs deleted file mode 100644 index 9e00f89046..0000000000 --- a/mcs/class/corlib/System.Configuration.Assemblies/AssemblyVersionCompatibility.cs +++ /dev/null @@ -1,44 +0,0 @@ -// AssemblyVersionCompatibility.cs -// -// This code was automatically generated from -// ECMA CLI XML Library Specification. -// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] -// Created: Wed, 5 Sep 2001 06:38:13 UTC -// Source file: all.xml -// URL: http://devresource.hp.com/devresource/Docs/TechPapers/CSharp/all.xml -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004, 2006 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 System.Runtime.InteropServices; - -namespace System.Configuration.Assemblies { - - [Serializable] - [ComVisible (true)] - public enum AssemblyVersionCompatibility { - SameMachine = 1, - SameProcess = 2, - SameDomain = 3 - } -} diff --git a/mcs/class/corlib/System.Diagnostics/StackTrace.cs b/mcs/class/corlib/System.Diagnostics/StackTrace.cs index 6add4df6fd..56e2aca4bf 100644 --- a/mcs/class/corlib/System.Diagnostics/StackTrace.cs +++ b/mcs/class/corlib/System.Diagnostics/StackTrace.cs @@ -185,8 +185,10 @@ namespace System.Diagnostics { return frames; var accum = new List (); - foreach (var t in captured_traces) - accum.AddRange(t.GetFrames ()); + foreach (var t in captured_traces) { + for (int i = 0; i < t.FrameCount; i++) + accum.Add (t.GetFrame (i)); + } accum.AddRange (frames); return accum.ToArray (); diff --git a/mcs/class/corlib/System.IO.IsolatedStorage/INormalizeForIsolatedStorage.cs b/mcs/class/corlib/System.IO.IsolatedStorage/INormalizeForIsolatedStorage.cs deleted file mode 100644 index 1d7093f993..0000000000 --- a/mcs/class/corlib/System.IO.IsolatedStorage/INormalizeForIsolatedStorage.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// System.IO.IsolatedStorage.INormalizeForIsolatedStorage -// -// author: -// Duco Fijma (duco@lorentz.xs4all.nl) -// -// (c) 2002 Duco Fijma -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.IO.IsolatedStorage { - - [ComVisible (true)] - public interface INormalizeForIsolatedStorage { - - object Normalize (); - - } -} - diff --git a/mcs/class/corlib/System.IO.IsolatedStorage/IsolatedStorageScope.cs b/mcs/class/corlib/System.IO.IsolatedStorage/IsolatedStorageScope.cs deleted file mode 100644 index 455a22997d..0000000000 --- a/mcs/class/corlib/System.IO.IsolatedStorage/IsolatedStorageScope.cs +++ /dev/null @@ -1,53 +0,0 @@ -// IsolatedStorageScope.cs -// -// This code was automatically generated from -// ECMA CLI XML Library Specification. -// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] -// Created: Wed, 5 Sep 2001 06:41:21 UTC -// Source file: all.xml -// URL: http://devresource.hp.com/devresource/Docs/TechPapers/CSharp/all.xml -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.IO.IsolatedStorage { - - [Flags] - [ComVisible (true)] - [Serializable] - public enum IsolatedStorageScope { - - None = 0, - User = 1, - Domain = 2, - Assembly = 4, - - // Documented in "C# In A Nutshell" - Roaming = 8, - - Machine = 16, - Application = 32 - } -} diff --git a/mcs/class/corlib/System.IO/DriveType.cs b/mcs/class/corlib/System.IO/DriveType.cs deleted file mode 100644 index e3d3189859..0000000000 --- a/mcs/class/corlib/System.IO/DriveType.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// Copyright (C) 2006 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 System; -using System.Text; -using System.Runtime.InteropServices; - -namespace System.IO { - - [ComVisible (true)] - [Serializable] - public enum DriveType { - CDRom = 5, - Fixed = 3, - Network = 4, - NoRootDirectory = 1, - Ram = 6, - Removable = 2, - Unknown = 0 - } -} diff --git a/mcs/class/corlib/System.IO/FileAccess.cs b/mcs/class/corlib/System.IO/FileAccess.cs deleted file mode 100644 index dce332d241..0000000000 --- a/mcs/class/corlib/System.IO/FileAccess.cs +++ /dev/null @@ -1,59 +0,0 @@ -// FileAccess.cs -// -// This code was automatically generated from -// ECMA CLI XML Library Specification. -// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] -// Created: Fri, 7 Sep 2001 16:32:20 UTC -// Source file: AllTypes.xml -// URL: http://msdn.microsoft.com/net/ecma/AllTypes.xml -// -// (C) 2001 Ximian, Inc. http://www.ximian.com - -// -// 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 System.Runtime.InteropServices; - -namespace System.IO { - - - /// - /// - [Flags] - [ComVisible (true)] - [Serializable] - public enum FileAccess : int { - - /// - /// - Read = 0x00000001, - - /// - /// - Write = 0x00000002, - - /// - /// - ReadWrite = Read | Write, - } // FileAccess - -} // System.IO diff --git a/mcs/class/corlib/System.IO/FileMode.cs b/mcs/class/corlib/System.IO/FileMode.cs deleted file mode 100644 index 0e3ac6a2df..0000000000 --- a/mcs/class/corlib/System.IO/FileMode.cs +++ /dev/null @@ -1,71 +0,0 @@ -// FileMode.cs -// -// This code was automatically generated from -// ECMA CLI XML Library Specification. -// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] -// Created: Fri, 7 Sep 2001 16:32:13 UTC -// Source file: AllTypes.xml -// URL: http://msdn.microsoft.com/net/ecma/AllTypes.xml -// -// (C) 2001 Ximian, Inc. http://www.ximian.com - -// -// 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 System.Runtime.InteropServices; - -namespace System.IO { - - - /// - /// - [ComVisible (true)] - [Serializable] - public enum FileMode { - - /// - /// - CreateNew = 1, - - /// - /// - Create = 2, - - /// - /// - Open = 3, - - /// - /// - OpenOrCreate = 4, - - /// - /// - Truncate = 5, - - /// - /// - Append = 6, - } // FileMode - -} // System.IO diff --git a/mcs/class/corlib/System.IO/FileOptions.cs b/mcs/class/corlib/System.IO/FileOptions.cs deleted file mode 100644 index 502974e7b0..0000000000 --- a/mcs/class/corlib/System.IO/FileOptions.cs +++ /dev/null @@ -1,57 +0,0 @@ -//------------------------------------------------------------------------------ -// -// System.IO.FileOptions.cs -// -// Author: Zoltan Varga (vargaz@gmail.com) -// -//------------------------------------------------------------------------------ - -// -// 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 System.Runtime.InteropServices; - -namespace System.IO -{ - [Flags] - [Serializable] - [ComVisible(true)] - public enum FileOptions - { - None = 0, - Encrypted = 0x4000, - DeleteOnClose = 0x4000000, - SequentialScan = 0x8000000, - RandomAccess = 0x10000000, - Asynchronous = 0x40000000, - WriteThrough = -2147483648 - // - // FileIsTemporary = 1 - // The above is an internal value used by Path.GetTempFile to - // get a file with 600 permissions, regardless of the umask - // settings. If a value "1" must be introduced here, update - // both metadata/w32file.c and Path.GetTempFile - // - } -} - diff --git a/mcs/class/corlib/System.IO/FileShare.cs b/mcs/class/corlib/System.IO/FileShare.cs deleted file mode 100644 index 4edab20e60..0000000000 --- a/mcs/class/corlib/System.IO/FileShare.cs +++ /dev/null @@ -1,55 +0,0 @@ -// FileShare.cs -// -// This code was automatically generated from -// ECMA CLI XML Library Specification. -// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] -// Created: Fri, 7 Sep 2001 16:32:26 UTC -// Source file: AllTypes.xml -// URL: http://msdn.microsoft.com/net/ecma/AllTypes.xml -// -// (C) 2001 Ximian, Inc. http://www.ximian.com - -// -// 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 System.Runtime.InteropServices; - -namespace System.IO { - - - /// - /// - [Flags] - [ComVisible (true)] - [Serializable] - public enum FileShare : int { - - None = 0, - Read = 1, - Write = 2, - ReadWrite = 3, - Delete = 4, - Inheritable = 16, - } // FileShare - -} // System.IO diff --git a/mcs/class/corlib/System.IO/SearchOption.cs b/mcs/class/corlib/System.IO/SearchOption.cs deleted file mode 100644 index 9c2bfd341c..0000000000 --- a/mcs/class/corlib/System.IO/SearchOption.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// System.IO.SearchOption -// -// Author: -// Zoltan Varga (vargaz@gmail.com) -// - -// -// Copyright (C) 2005 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 System.Runtime.InteropServices; - -namespace System.IO { - [ComVisible (true)] - [Serializable] - public - enum SearchOption { - TopDirectoryOnly = 0, - AllDirectories = 1 - } -} diff --git a/mcs/class/corlib/System.IO/SeekOrigin.cs b/mcs/class/corlib/System.IO/SeekOrigin.cs deleted file mode 100644 index 2c45f6d5bc..0000000000 --- a/mcs/class/corlib/System.IO/SeekOrigin.cs +++ /dev/null @@ -1,59 +0,0 @@ -// SeekOrigin.cs -// -// This code was automatically generated from -// ECMA CLI XML Library Specification. -// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] -// Created: Fri, 7 Sep 2001 16:32:32 UTC -// Source file: AllTypes.xml -// URL: http://msdn.microsoft.com/net/ecma/AllTypes.xml -// -// (C) 2001 Ximian, Inc. http://www.ximian.com - -// -// 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 System.Runtime.InteropServices; - -namespace System.IO { - - - /// - /// - [Serializable] - [ComVisible (true)] - public enum SeekOrigin : int { - - /// - /// - Begin = 0, - - /// - /// - Current = 1, - - /// - /// - End = 2, - } // SeekOrigin - -} // System.IO diff --git a/mcs/class/corlib/System.Reflection.Emit/ConstructorBuilder.cs b/mcs/class/corlib/System.Reflection.Emit/ConstructorBuilder.cs index 89e83c7f50..17d3ffd821 100644 --- a/mcs/class/corlib/System.Reflection.Emit/ConstructorBuilder.cs +++ b/mcs/class/corlib/System.Reflection.Emit/ConstructorBuilder.cs @@ -128,8 +128,7 @@ namespace System.Reflection.Emit { ParameterInfo [] retval = new ParameterInfo [parameters.Length]; for (int i = 0; i < parameters.Length; i++) - retval [i] = ParameterInfo.New (pinfo == null ? null - : pinfo [i + 1], parameters [i], this, i + 1); + retval [i] = MonoParameterInfo.New (pinfo?[i + 1], parameters [i], this, i + 1); return retval; } diff --git a/mcs/class/corlib/System.Reflection.Emit/ConstructorOnTypeBuilderInst.cs b/mcs/class/corlib/System.Reflection.Emit/ConstructorOnTypeBuilderInst.cs index 643e7272a3..932df2889d 100644 --- a/mcs/class/corlib/System.Reflection.Emit/ConstructorOnTypeBuilderInst.cs +++ b/mcs/class/corlib/System.Reflection.Emit/ConstructorOnTypeBuilderInst.cs @@ -121,14 +121,14 @@ namespace System.Reflection.Emit res = new ParameterInfo [cbuilder.parameters.Length]; for (int i = 0; i < cbuilder.parameters.Length; i++) { Type type = instantiation.InflateType (cbuilder.parameters [i]); - res [i] = ParameterInfo.New (cbuilder.pinfo == null ? null : cbuilder.pinfo [i], type, this, i + 1); + res [i] = MonoParameterInfo.New (cbuilder.pinfo?[i], type, this, i + 1); } } else { ParameterInfo[] parms = cb.GetParameters (); res = new ParameterInfo [parms.Length]; for (int i = 0; i < parms.Length; i++) { Type type = instantiation.InflateType (parms [i].ParameterType); - res [i] = ParameterInfo.New (parms [i], type, this, i + 1); + res [i] = MonoParameterInfo.New (parms [i], type, this, i + 1); } } return res; diff --git a/mcs/class/corlib/System.Reflection.Emit/DynamicMethod.cs b/mcs/class/corlib/System.Reflection.Emit/DynamicMethod.cs index 489a6b4909..d32a4a90ff 100644 --- a/mcs/class/corlib/System.Reflection.Emit/DynamicMethod.cs +++ b/mcs/class/corlib/System.Reflection.Emit/DynamicMethod.cs @@ -264,7 +264,7 @@ namespace System.Reflection.Emit { ParameterInfo[] retval = new ParameterInfo [parameters.Length]; for (int i = 0; i < parameters.Length; i++) { - retval [i] = ParameterInfo.New (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1); + retval [i] = MonoParameterInfo.New (pinfo?[i + 1], parameters [i], this, i + 1); } return retval; } diff --git a/mcs/class/corlib/System.Reflection.Emit/MethodBuilder.cs b/mcs/class/corlib/System.Reflection.Emit/MethodBuilder.cs index 38f81edca1..c24d4b4462 100644 --- a/mcs/class/corlib/System.Reflection.Emit/MethodBuilder.cs +++ b/mcs/class/corlib/System.Reflection.Emit/MethodBuilder.cs @@ -237,7 +237,7 @@ namespace System.Reflection.Emit ParameterInfo[] retval = new ParameterInfo [parameters.Length]; for (int i = 0; i < parameters.Length; i++) { - retval [i] = ParameterInfo.New (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1); + retval [i] = MonoParameterInfo.New (pinfo?[i + 1], parameters [i], this, i + 1); } return retval; } diff --git a/mcs/class/corlib/System.Reflection.Emit/OpCodeType.cs b/mcs/class/corlib/System.Reflection.Emit/OpCodeType.cs deleted file mode 100644 index c50e574bde..0000000000 --- a/mcs/class/corlib/System.Reflection.Emit/OpCodeType.cs +++ /dev/null @@ -1,76 +0,0 @@ -// OpCodeType.cs -// -// (C) 2001 Ximian, Inc. http://www.ximian.com - -// -// 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 System.Runtime.InteropServices; - -namespace System.Reflection.Emit { - - /// - /// Describes the types of MSIL instructions. - /// - [ComVisible (true)] - [Serializable] - public enum OpCodeType { - - /// - /// "Ignorable" instruction. - /// Such instruction are used to supply - /// additional information to particular - /// MSIL processor. - /// - [Obsolete ("This API has been deprecated.")] - Annotation = 0, - - /// - /// Denotes "shorthand" instruction. - /// Such instructions take less space - /// than their full-size equivalents - /// (ex. ldarg.0 vs. ldarg 0). - /// - Macro = 1, - - /// - /// Denotes instruction reserved for internal use. - /// - Nternal = 2, - - /// - /// Denotes instruction to deal with objects. - /// (ex. ldobj). - /// - Objmodel = 3, - - /// - /// - Prefix = 4, - - /// - /// - Primitive = 5 - } - -} diff --git a/mcs/class/corlib/System.Reflection.Emit/OperandType.cs b/mcs/class/corlib/System.Reflection.Emit/OperandType.cs deleted file mode 100644 index 4d823d33cb..0000000000 --- a/mcs/class/corlib/System.Reflection.Emit/OperandType.cs +++ /dev/null @@ -1,113 +0,0 @@ -// OperandType.cs -// -// (C) 2001 Ximian, Inc. http://www.ximian.com - -// -// 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 System.Runtime.InteropServices; - -namespace System.Reflection.Emit { - - /// - /// Describes the operand types of MSIL instructions. - /// - [ComVisible (true)] - [Serializable] - public enum OperandType { - - /// - /// - InlineBrTarget = 0, - - /// - /// - InlineField = 1, - - /// - /// - InlineI = 2, - - /// - /// - InlineI8 = 3, - - /// - /// - InlineMethod = 4, - - /// - /// - InlineNone = 5, - - /// - /// - [Obsolete ("This API has been deprecated.")] - InlinePhi = 6, - - /// - /// - InlineR = 7, - - /// - /// - InlineSig = 9, - - /// - /// - InlineString = 0x0A, - - /// - /// - InlineSwitch = 0x0B, - - /// - /// - InlineTok = 0x0C, - - /// - /// - InlineType = 0x0D, - - /// - /// - InlineVar = 0x0E, - - /// - /// - ShortInlineBrTarget = 0x0F, - - /// - /// - ShortInlineI = 0x10, - - /// - /// - ShortInlineR = 0x11, - - /// - /// - ShortInlineVar = 0x12 - } - -} diff --git a/mcs/class/corlib/System.Reflection.Emit/PackingSize.cs b/mcs/class/corlib/System.Reflection.Emit/PackingSize.cs deleted file mode 100644 index ad6be1d1d7..0000000000 --- a/mcs/class/corlib/System.Reflection.Emit/PackingSize.cs +++ /dev/null @@ -1,71 +0,0 @@ -// PackingSize.cs -// -// (C) 2001 Ximian, Inc. http://www.ximian.com - -// -// 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 System.Runtime.InteropServices; - -namespace System.Reflection.Emit { - - /// - /// Specifies the packing size (data alignment) of a type. - /// - [ComVisible (true)] - [Serializable] - public enum PackingSize { - - /// - /// The packing size is unspecified. - /// - Unspecified = 0, - - /// - /// - Size1 = 1, - - /// - /// - Size2 = 2, - - /// - /// - Size4 = 4, - - /// - /// - Size8 = 8, - - /// - /// - Size16 = 16, - - Size32 = 32, - - Size64 = 64, - - Size128 = 128 - } - -} diff --git a/mcs/class/corlib/System.Reflection.Emit/StackBehaviour.cs b/mcs/class/corlib/System.Reflection.Emit/StackBehaviour.cs deleted file mode 100644 index 524ea8d305..0000000000 --- a/mcs/class/corlib/System.Reflection.Emit/StackBehaviour.cs +++ /dev/null @@ -1,154 +0,0 @@ -// StackBehaviour.cs -// -// (C) 2001 Ximian, Inc. http://www.ximian.com - -// -// 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 System.Runtime.InteropServices; - -namespace System.Reflection.Emit { - - /// - /// Describes how values are pushed onto or popped off a stack. - /// - [ComVisible (true)] - [Serializable] - public enum StackBehaviour { - - /// - /// - Pop0 = 0, - - /// - /// - Pop1 = 1, - - /// - /// - Pop1_pop1 = 2, - - /// - /// - Popi = 3, - - /// - /// - Popi_pop1 = 4, - - /// - /// - Popi_popi = 5, - - /// - /// - Popi_popi8 = 6, - - /// - /// - Popi_popi_popi = 7, - - /// - /// - Popi_popr4 = 8, - - /// - /// - Popi_popr8 = 9, - - /// - /// - Popref = 0x0A, - - /// - /// - Popref_pop1 = 0x0B, - - /// - /// - Popref_popi = 0x0C, - - /// - /// - Popref_popi_popi = 0x0D, - - /// - /// - Popref_popi_popi8 = 0x0E, - - /// - /// - Popref_popi_popr4 = 0x0F, - - /// - /// - Popref_popi_popr8 = 0x10, - - /// - /// - Popref_popi_popref = 0x11, - - /// - /// - Push0 = 0x12, - - /// - /// - Push1 = 0x13, - - /// - /// - Push1_push1 = 0x14, - - /// - /// - Pushi = 0x15, - - /// - /// - Pushi8 = 0x16, - - /// - /// - Pushr4 = 0x17, - - /// - /// - Pushr8 = 0x18, - - /// - /// - Pushref = 0x19, - - /// - /// - Varpop = 0x1A, - - /// - /// - Varpush = 0x1B, - Popref_popi_pop1 = 0x1C - - } - -} diff --git a/mcs/class/corlib/System.Reflection/Binder.cs b/mcs/class/corlib/System.Reflection/Binder.cs index 2a5d9c00d8..23bc0b37e4 100644 --- a/mcs/class/corlib/System.Reflection/Binder.cs +++ b/mcs/class/corlib/System.Reflection/Binder.cs @@ -11,6 +11,6 @@ namespace System.Reflection { return false; } -#endif +#endif } } \ No newline at end of file diff --git a/mcs/class/corlib/System.Reflection/ConstructorInfo.cs b/mcs/class/corlib/System.Reflection/ConstructorInfo.cs deleted file mode 100644 index 65237fe796..0000000000 --- a/mcs/class/corlib/System.Reflection/ConstructorInfo.cs +++ /dev/null @@ -1,146 +0,0 @@ -// -// System.Reflection/ConstructorInfo.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Diagnostics; -using System.Globalization; -using System.Runtime.InteropServices; - -namespace System.Reflection { - - [ComVisible (true)] - [ComDefaultInterfaceAttribute (typeof (_ConstructorInfo))] - [Serializable] - [ClassInterface(ClassInterfaceType.None)] -#if MOBILE - public abstract class ConstructorInfo : MethodBase { -#else - public abstract class ConstructorInfo : MethodBase, _ConstructorInfo { -#endif - [ComVisible (true)] - public static readonly string ConstructorName = ".ctor"; - [ComVisible (true)] - public static readonly string TypeConstructorName = ".cctor"; - - protected ConstructorInfo() { - } - - [ComVisible (true)] - public override MemberTypes MemberType { - get {return MemberTypes.Constructor;} - } - - [DebuggerStepThrough] - [DebuggerHidden] - public object Invoke (object[] parameters) - { - return Invoke (BindingFlags.CreateInstance, null, parameters ?? EmptyArray.Value, null); - } - - public abstract object Invoke (BindingFlags invokeAttr, Binder binder, object[] parameters, - CultureInfo culture); - -#if !MOBILE - - void _ConstructorInfo.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException (); - } - - Type _ConstructorInfo.GetType () - { - // Required or object::GetType becomes virtual final - return base.GetType (); - } - - void _ConstructorInfo.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException (); - } - - void _ConstructorInfo.GetTypeInfoCount (out uint pcTInfo) - { - throw new NotImplementedException (); - } - - void _ConstructorInfo.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException (); - } - - object _ConstructorInfo.Invoke_2 (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) - { - return this.Invoke (obj, invokeAttr, binder, parameters, culture); - } - - object _ConstructorInfo.Invoke_3 (object obj, object[] parameters) - { - return base.Invoke (obj, parameters); - } - - object _ConstructorInfo.Invoke_4 (BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) - { - return this.Invoke (invokeAttr, binder, parameters, culture); - } - - object _ConstructorInfo.Invoke_5 (object[] parameters) - { - return this.Invoke (parameters); - } -#endif - - public override bool Equals (object obj) - { - return obj == (object) this; - } - - public override int GetHashCode () - { - return base.GetHashCode (); - } - - public static bool operator == (ConstructorInfo left, ConstructorInfo right) - { - if ((object)left == (object)right) - return true; - if ((object)left == null ^ (object)right == null) - return false; - return left.Equals (right); - } - - public static bool operator != (ConstructorInfo left, ConstructorInfo right) - { - if ((object)left == (object)right) - return false; - if ((object)left == null ^ (object)right == null) - return true; - return !left.Equals (right); - } - - } -} diff --git a/mcs/class/corlib/System.Reflection/CustomAttributeNamedArgument.cs b/mcs/class/corlib/System.Reflection/CustomAttributeNamedArgument.cs deleted file mode 100644 index 594c60a74a..0000000000 --- a/mcs/class/corlib/System.Reflection/CustomAttributeNamedArgument.cs +++ /dev/null @@ -1,105 +0,0 @@ -// -// System.Reflection/CustomAttributeNamedArgument.cs -// -// Author: -// Zoltan Varga (vargaz@gmail.com) -// Carlos Alberto Cortez (calberto.cortez@gmail.com) -// -// 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 System; -using System.Runtime.InteropServices; - -namespace System.Reflection { - - [ComVisible (true)] - [Serializable] - public struct CustomAttributeNamedArgument { - CustomAttributeTypedArgument typedArgument; - MemberInfo memberInfo; - - public - CustomAttributeNamedArgument (MemberInfo memberInfo, object value) - { - this.memberInfo = memberInfo; - this.typedArgument = (CustomAttributeTypedArgument) value; - } - - public CustomAttributeNamedArgument (MemberInfo memberInfo, CustomAttributeTypedArgument typedArgument) - { - this.memberInfo = memberInfo; - this.typedArgument = typedArgument; - } - - public MemberInfo MemberInfo { - get { - return memberInfo; - } - } - - public CustomAttributeTypedArgument TypedValue { - get { - return typedArgument; - } - } - - public bool IsField { - get { return memberInfo.MemberType == MemberTypes.Field; } - } - - public string MemberName { - get { return memberInfo.Name; } - } - - public override string ToString () - { - return memberInfo.Name + " = " + typedArgument.ToString (); - } - - public override bool Equals (object obj) - { - if (!(obj is CustomAttributeNamedArgument)) - return false; - CustomAttributeNamedArgument other = (CustomAttributeNamedArgument) obj; - return other.memberInfo == memberInfo && - typedArgument.Equals (other.typedArgument); - } - - public override int GetHashCode () - { - return (memberInfo.GetHashCode () << 16) + typedArgument.GetHashCode (); - } - - public static bool operator == (CustomAttributeNamedArgument left, CustomAttributeNamedArgument right) - { - return left.Equals (right); - } - - public static bool operator != (CustomAttributeNamedArgument left, CustomAttributeNamedArgument right) - { - return !left.Equals (right); - } - } - -} - diff --git a/mcs/class/corlib/System.Reflection/CustomAttributeTypedArgument.cs b/mcs/class/corlib/System.Reflection/CustomAttributeTypedArgument.cs deleted file mode 100644 index 88b551dcc1..0000000000 --- a/mcs/class/corlib/System.Reflection/CustomAttributeTypedArgument.cs +++ /dev/null @@ -1,125 +0,0 @@ -// -// System.Reflection/CustomAttributeTypedArgument.cs -// -// Author: -// Zoltan Varga (vargaz@gmail.com) -// Carlos Alberto Cortez (calberto.cortez@gmail.com) -// -// 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 System; -using System.Runtime.InteropServices; -using System.Collections.ObjectModel; - -namespace System.Reflection { - - [ComVisible (true)] - [Serializable] - public struct CustomAttributeTypedArgument { - Type argumentType; - object value; - - public - CustomAttributeTypedArgument (Type argumentType, object value) - { - if (argumentType == null) - throw new ArgumentNullException ("argumentType"); - - this.argumentType = argumentType; - this.value = value; - - // MS seems to convert arrays into a ReadOnlyCollection - if (value is Array) { - Array a = (Array)value; - - Type etype = a.GetType ().GetElementType (); - CustomAttributeTypedArgument[] new_value = new CustomAttributeTypedArgument [a.GetLength (0)]; - for (int i = 0; i < new_value.Length; ++i) - new_value [i] = new CustomAttributeTypedArgument (etype, a.GetValue (i)); - this.value = new ReadOnlyCollection (new_value); - } - } - - public CustomAttributeTypedArgument (object value) - { - if (value == null) - throw new ArgumentNullException ("value"); - - this.argumentType = value.GetType (); - this.value = value; - } - - public Type ArgumentType { - get { - return argumentType; - } - } - - public object Value { - get { - return value; - } - } - - public override string ToString () - { - string val = value != null ? value.ToString () : String.Empty; - if (argumentType == typeof (string)) - return "\"" + val + "\""; - if (argumentType == typeof (Type)) - return "typeof (" + val + ")"; - if (argumentType.IsEnum) - return "(" + argumentType.Name + ")" + val; - - return val; - } - - public override bool Equals (object obj) - { - if (!(obj is CustomAttributeTypedArgument)) - return false; - CustomAttributeTypedArgument other = (CustomAttributeTypedArgument) obj; - return other.argumentType == argumentType && - value != null ? value.Equals (other.value) : (object) other.value == null; - } - - public override int GetHashCode () - { - return (argumentType.GetHashCode () << 16) + (value != null ? value.GetHashCode () : 0); - } - - public static bool operator == (CustomAttributeTypedArgument left, CustomAttributeTypedArgument right) - { - return left.Equals (right); - } - - public static bool operator != (CustomAttributeTypedArgument left, CustomAttributeTypedArgument right) - { - return !left.Equals (right); - } - } - -} - - diff --git a/mcs/class/corlib/System.Reflection/EventInfo.cs b/mcs/class/corlib/System.Reflection/EventInfo.cs index 28a727924c..4c9be3ca14 100644 --- a/mcs/class/corlib/System.Reflection/EventInfo.cs +++ b/mcs/class/corlib/System.Reflection/EventInfo.cs @@ -33,51 +33,10 @@ using System.Runtime.InteropServices; namespace System.Reflection { - [ComVisible (true)] - [ComDefaultInterfaceAttribute (typeof (_EventInfo))] [Serializable] - [ClassInterface(ClassInterfaceType.None)] - [StructLayout (LayoutKind.Sequential)] -#if MOBILE - public abstract class EventInfo : MemberInfo { -#else - public abstract class EventInfo : MemberInfo, _EventInfo { -#endif + public abstract partial class EventInfo : MemberInfo { AddEventAdapter cached_add_event; - public abstract EventAttributes Attributes {get;} - - public - virtual - Type EventHandlerType { - get { - ParameterInfo[] p; - MethodInfo add = GetAddMethod (true); - p = add.GetParametersInternal (); - if (p.Length > 0) { - Type t = p [0].ParameterType; - /* is it alwasys the first arg? - if (!t.IsSubclassOf (typeof (System.Delegate))) - throw new Exception ("no delegate in event");*/ - return t; - } - - return null; - } - } - - public - virtual - bool IsMulticast {get {return true;}} - public bool IsSpecialName {get {return (Attributes & EventAttributes.SpecialName ) != 0;}} - public override MemberTypes MemberType { - get {return MemberTypes.Event;} - } - - protected EventInfo() { - } - - [DebuggerHidden] [DebuggerStepThrough] public @@ -112,97 +71,6 @@ namespace System.Reflection { #endif } - public MethodInfo GetAddMethod() { - return GetAddMethod (false); - } - public abstract MethodInfo GetAddMethod(bool nonPublic); - public MethodInfo GetRaiseMethod() { - return GetRaiseMethod (false); - } - public abstract MethodInfo GetRaiseMethod( bool nonPublic); - public MethodInfo GetRemoveMethod() { - return GetRemoveMethod (false); - } - public abstract MethodInfo GetRemoveMethod( bool nonPublic); - - public virtual MethodInfo[] GetOtherMethods (bool nonPublic) { - // implemented by the derived class - return EmptyArray.Value; - } - - public MethodInfo[] GetOtherMethods () { - return GetOtherMethods (false); - } - - [DebuggerHidden] - [DebuggerStepThrough] - public - virtual - void RemoveEventHandler (object target, Delegate handler) - { - MethodInfo remove = GetRemoveMethod (); - if (remove == null) - throw new InvalidOperationException ("Cannot remove a handler to an event that doesn't have a visible remove method"); - - remove.Invoke (target, new object [] {handler}); - } - - public override bool Equals (object obj) - { - return obj == (object) this; - } - - public override int GetHashCode () - { - return base.GetHashCode (); - } - - public static bool operator == (EventInfo left, EventInfo right) - { - if ((object)left == (object)right) - return true; - if ((object)left == null ^ (object)right == null) - return false; - return left.Equals (right); - } - - public static bool operator != (EventInfo left, EventInfo right) - { - if ((object)left == (object)right) - return false; - if ((object)left == null ^ (object)right == null) - return true; - return !left.Equals (right); - } - -#if !MOBILE - void _EventInfo.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException (); - } - - Type _EventInfo.GetType () - { - // Required or object::GetType becomes virtual final - return base.GetType (); - } - - void _EventInfo.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException (); - } - - void _EventInfo.GetTypeInfoCount (out uint pcTInfo) - { - throw new NotImplementedException (); - } - - void _EventInfo.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException (); - } -#endif - delegate void AddEventAdapter (object _this, Delegate dele); // this optimization cause problems with full AOT @@ -220,6 +88,8 @@ namespace System.Reflection { throw new TargetException ("Cannot add a handler to a non static event with a null target"); if (!(obj is T)) throw new TargetException ("Object doesn't match target"); + if (!(dele is D)) + throw new ArgumentException ($"Object of type {dele.GetType ()} cannot be converted to type {typeof (D)}."); addEvent ((T)obj, (D)dele); } @@ -269,16 +139,6 @@ namespace System.Reflection { } #endif - public virtual MethodInfo AddMethod { - get { return GetAddMethod (true); } - } - public virtual MethodInfo RaiseMethod { - get { return GetRaiseMethod (true); } - } - public virtual MethodInfo RemoveMethod { - get { return GetRemoveMethod (true); } - } - [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern EventInfo internal_from_handle_type (IntPtr event_handle, IntPtr type_handle); diff --git a/mcs/class/corlib/System.Reflection/FieldInfo.cs b/mcs/class/corlib/System.Reflection/FieldInfo.cs index 7c806b78f8..747b021c9b 100644 --- a/mcs/class/corlib/System.Reflection/FieldInfo.cs +++ b/mcs/class/corlib/System.Reflection/FieldInfo.cs @@ -35,113 +35,8 @@ using System.Runtime.InteropServices; namespace System.Reflection { - [ComVisible (true)] - [ComDefaultInterfaceAttribute (typeof (_FieldInfo))] [Serializable] - [ClassInterface(ClassInterfaceType.None)] -#if MOBILE - public abstract class FieldInfo : MemberInfo { -#else - public abstract class FieldInfo : MemberInfo, _FieldInfo { -#endif - public abstract FieldAttributes Attributes {get;} - public abstract RuntimeFieldHandle FieldHandle {get;} - - protected FieldInfo () {} - - public abstract Type FieldType { get; } - - public abstract object GetValue(object obj); - - public override MemberTypes MemberType { - get { return MemberTypes.Field;} - } - - public bool IsLiteral - { - get {return (Attributes & FieldAttributes.Literal) != 0;} - } - - public bool IsStatic - { - get {return (Attributes & FieldAttributes.Static) != 0;} - } - - public bool IsInitOnly - { - get {return (Attributes & FieldAttributes.InitOnly) != 0;} - } - public Boolean IsPublic - { - get - { - return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; - } - } - public Boolean IsPrivate - { - get - { - return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; - } - } - public Boolean IsFamily - { - get - { - return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; - } - } - public Boolean IsAssembly - { - get - { - return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; - } - } - public Boolean IsFamilyAndAssembly - { - get { - return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; - } - } - public Boolean IsFamilyOrAssembly - { - get - { - return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; - } - } - public Boolean IsPinvokeImpl - { - get - { - return (Attributes & FieldAttributes.PinvokeImpl) == FieldAttributes.PinvokeImpl; - } - } - public Boolean IsSpecialName - { - get - { - return (Attributes & FieldAttributes.SpecialName) == FieldAttributes.SpecialName; - } - } - public Boolean IsNotSerialized - { - get - { - return (Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized; - } - } - - public abstract void SetValue (object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture); - - [DebuggerHidden] - [DebuggerStepThrough] - public void SetValue (object obj, object value) - { - SetValue (obj, value, 0, null, null); - } + partial class FieldInfo : MemberInfo { [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern FieldInfo internal_from_handle_type (IntPtr field_handle, IntPtr type_handle); @@ -164,33 +59,11 @@ namespace System.Reflection { return fi; } - // - // Note: making this abstract imposes an implementation requirement - // on any class that derives from it. However, since it's also - // internal, that means only classes inside corlib can derive - // from FieldInfo. See - // - // errors/cs0534-4.cs errors/CS0534-4-lib.cs - // - // class/Microsoft.JScript/Microsoft.JScript/JSFieldInfo.cs - // internal virtual int GetFieldOffset () { throw new SystemException ("This method should not be called"); } - [CLSCompliant(false)] - public virtual object GetValueDirect (TypedReference obj) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); - } - - [CLSCompliant(false)] - public virtual void SetValueDirect (TypedReference obj, object value) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); - } - [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern MarshalAsAttribute get_marshal_info (); @@ -263,101 +136,5 @@ namespace System.Reflection { return attrsData; } - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern Type[] GetTypeModifiers (bool optional); - - public virtual Type[] GetOptionalCustomModifiers () { - Type[] types = GetTypeModifiers (true); - if (types == null) - return Type.EmptyTypes; - return types; - } - - public virtual Type[] GetRequiredCustomModifiers () { - Type[] types = GetTypeModifiers (false); - if (types == null) - return Type.EmptyTypes; - return types; - } - - public virtual object GetRawConstantValue () - { - throw new NotSupportedException ("This non-CLS method is not implemented."); - } - - - public override bool Equals (object obj) - { - return obj == (object) this; - } - - public override int GetHashCode () - { - return base.GetHashCode (); - } - - public static bool operator == (FieldInfo left, FieldInfo right) - { - if ((object)left == (object)right) - return true; - if ((object)left == null ^ (object)right == null) - return false; - return left.Equals (right); - } - - public static bool operator != (FieldInfo left, FieldInfo right) - { - if ((object)left == (object)right) - return false; - if ((object)left == null ^ (object)right == null) - return true; - return !left.Equals (right); - } - - public virtual bool IsSecurityCritical { - get { - throw new NotSupportedException (); - } - } - - public virtual bool IsSecuritySafeCritical { - get { - throw new NotSupportedException (); - } - } - - public virtual bool IsSecurityTransparent { - get { - throw new NotSupportedException (); - } - } - -#if !MOBILE - void _FieldInfo.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException (); - } - - Type _FieldInfo.GetType () - { - // Required or object::GetType becomes virtual final - return base.GetType (); - } - - void _FieldInfo.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException (); - } - - void _FieldInfo.GetTypeInfoCount (out uint pcTInfo) - { - throw new NotImplementedException (); - } - - void _FieldInfo.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException (); - } -#endif } } diff --git a/mcs/class/corlib/System.Reflection/ModuleResolveEventHandler.cs b/mcs/class/corlib/System.Reflection/ModuleResolveEventHandler.cs deleted file mode 100644 index fe02bcca0a..0000000000 --- a/mcs/class/corlib/System.Reflection/ModuleResolveEventHandler.cs +++ /dev/null @@ -1,42 +0,0 @@ -// -// System.Reflection.ModuleResolveEventHandler -// -// Authors: -// Gonzalo Paniagua Javier (gonzalo@ximian.com) -// -// (C) 2003 Ximian, Inc (http://www.ximian.com) -// - -// -// 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 System; -using System.Runtime.InteropServices; - -namespace System.Reflection -{ - [ComVisible (true)] - [Serializable] - public delegate Module ModuleResolveEventHandler (object sender, ResolveEventArgs e); -} - diff --git a/mcs/class/corlib/System.Reflection/MonoEvent.cs b/mcs/class/corlib/System.Reflection/MonoEvent.cs index 876de83bff..7067f2369b 100644 --- a/mcs/class/corlib/System.Reflection/MonoEvent.cs +++ b/mcs/class/corlib/System.Reflection/MonoEvent.cs @@ -209,5 +209,16 @@ namespace System.Reflection { public override IList GetCustomAttributesData () { return CustomAttributeData.GetCustomAttributes (this); } + + public override int MetadataToken { + get { + return get_metadata_token (this); + } + } + + public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore (other); + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + internal static extern int get_metadata_token (MonoEvent monoEvent); } } diff --git a/mcs/class/corlib/System.Reflection/MonoField.cs b/mcs/class/corlib/System.Reflection/MonoField.cs index ef2180fed0..f73ad7d5c9 100644 --- a/mcs/class/corlib/System.Reflection/MonoField.cs +++ b/mcs/class/corlib/System.Reflection/MonoField.cs @@ -318,5 +318,25 @@ namespace System.Reflection { get { return get_core_clr_security_level () == 1; } } #endif + + public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore (other); + + public override int MetadataToken { + get { + return get_metadata_token (this); + } + } + + [MethodImplAttribute (MethodImplOptions.InternalCall)] + internal static extern int get_metadata_token (MonoField monoField); + + [MethodImplAttribute (MethodImplOptions.InternalCall)] + extern Type[] GetTypeModifiers (bool optional); + + public override Type[] GetOptionalCustomModifiers () => GetCustomModifiers (true); + + public override Type[] GetRequiredCustomModifiers () => GetCustomModifiers (false); + + private Type[] GetCustomModifiers (bool optional) => GetTypeModifiers (optional) ?? Type.EmptyTypes; } } diff --git a/mcs/class/corlib/System.Reflection/MonoMethod.cs b/mcs/class/corlib/System.Reflection/MonoMethod.cs index e3e22863f6..b9b7f10e8f 100644 --- a/mcs/class/corlib/System.Reflection/MonoMethod.cs +++ b/mcs/class/corlib/System.Reflection/MonoMethod.cs @@ -33,6 +33,7 @@ using System.Collections.Generic; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using InteropServicesCallingConvention = System.Runtime.InteropServices.CallingConvention; using System.Runtime.Serialization; #if !FULL_AOT_RUNTIME using System.Reflection.Emit; @@ -106,9 +107,9 @@ namespace System.Reflection { static internal ParameterInfo GetReturnParameterInfo (MonoMethod method) { - return ParameterInfo.New (GetReturnType (method.mhandle), method, get_retval_marshal (method.mhandle)); + return MonoParameterInfo.New (GetReturnType (method.mhandle), method, get_retval_marshal (method.mhandle)); } - }; + } abstract class RuntimeMethodInfo : MethodInfo, ISerializable { @@ -143,7 +144,7 @@ namespace System.Reflection { sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format)); sbName.Append("("); - ParameterInfo.FormatParameters (sbName, GetParametersNoCopy (), CallingConvention, serialization); + MonoParameterInfo.FormatParameters (sbName, GetParametersNoCopy (), CallingConvention, serialization); sbName.Append(")"); return sbName.ToString(); @@ -220,6 +221,9 @@ namespace System.Reflection { [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern MonoMethod get_base_method (MonoMethod method, bool definition); + [MethodImplAttribute(MethodImplOptions.InternalCall)] + internal static extern int get_metadata_token (MonoMethod method); + public override MethodInfo GetBaseDefinition () { return get_base_method (this, true); @@ -246,6 +250,12 @@ namespace System.Reflection { return MonoMethodInfo.GetReturnParameterInfo (this); } } + + public override int MetadataToken { + get { + return get_metadata_token (this); + } + } public override MethodImplAttributes GetMethodImplementationFlags () { @@ -287,6 +297,15 @@ namespace System.Reflection { [DebuggerStepThrough] public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { + if (!IsStatic) { + if (!DeclaringType.IsInstanceOfType (obj)) { + if (obj == null) + throw new TargetException ("Non-static method requires a target."); + else + throw new TargetException ("Object does not match target type."); + } + } + if (binder == null) binder = Type.DefaultBinder; @@ -309,6 +328,8 @@ namespace System.Reflection { } catch (MethodAccessException) { throw; #endif + } catch (OverflowException) { + throw; } catch (Exception e) { throw new TargetInvocationException (e); } @@ -446,18 +467,96 @@ namespace System.Reflection { if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0) attrsData [count++] = new CustomAttributeData ((typeof (PreserveSigAttribute)).GetConstructor (Type.EmptyTypes)); - if ((info.attrs & MethodAttributes.PinvokeImpl) != 0) { - this.GetPInvoke (out PInvokeAttributes flags, out string entryPoint, out string dllName); - var ctorArgs = new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument(typeof(string), dllName) }; - attrsData [count++] = new CustomAttributeData ( - (typeof (FieldOffsetAttribute)).GetConstructor (new[] { typeof (string) }), - ctorArgs, - EmptyArray.Value); //FIXME Get named params - } + if ((info.attrs & MethodAttributes.PinvokeImpl) != 0) + attrsData [count++] = GetDllImportAttributeData (); return attrsData; } + private CustomAttributeData GetDllImportAttributeData () + { + if ((Attributes & MethodAttributes.PinvokeImpl) == 0) + return null; + + string entryPoint, dllName = null; + PInvokeAttributes flags = 0; + + GetPInvoke (out flags, out entryPoint, out dllName); + + CharSet charSet; + + switch (flags & PInvokeAttributes.CharSetMask) { + case PInvokeAttributes.CharSetNotSpec: + charSet = CharSet.None; + break; + case PInvokeAttributes.CharSetAnsi: + charSet = CharSet.Ansi; + break; + case PInvokeAttributes.CharSetUnicode: + charSet = CharSet.Unicode; + break; + case PInvokeAttributes.CharSetAuto: + charSet = CharSet.Auto; + break; + // Invalid: default to CharSet.None + default: + charSet = CharSet.None; + break; + } + + InteropServicesCallingConvention callingConvention; + + switch (flags & PInvokeAttributes.CallConvMask) { + case PInvokeAttributes.CallConvWinapi: + callingConvention = InteropServicesCallingConvention.Winapi; + break; + case PInvokeAttributes.CallConvCdecl: + callingConvention = InteropServicesCallingConvention.Cdecl; + break; + case PInvokeAttributes.CallConvStdcall: + callingConvention = InteropServicesCallingConvention.StdCall; + break; + case PInvokeAttributes.CallConvThiscall: + callingConvention = InteropServicesCallingConvention.ThisCall; + break; + case PInvokeAttributes.CallConvFastcall: + callingConvention = InteropServicesCallingConvention.FastCall; + break; + // Invalid: default to CallingConvention.Cdecl + default: + callingConvention = InteropServicesCallingConvention.Cdecl; + break; + } + + bool exactSpelling = (flags & PInvokeAttributes.NoMangle) != 0; + bool setLastError = (flags & PInvokeAttributes.SupportsLastError) != 0; + bool bestFitMapping = (flags & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitEnabled; + bool throwOnUnmappableChar = (flags & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharEnabled; + bool preserveSig = (GetMethodImplementationFlags () & MethodImplAttributes.PreserveSig) != 0; + + var ctorArgs = new CustomAttributeTypedArgument [] { + new CustomAttributeTypedArgument (typeof (string), dllName), + }; + + var attrType = typeof (DllImportAttribute); + + var namedArgs = new CustomAttributeNamedArgument [] { + new CustomAttributeNamedArgument (attrType.GetField ("EntryPoint"), entryPoint), + new CustomAttributeNamedArgument (attrType.GetField ("CharSet"), charSet), + new CustomAttributeNamedArgument (attrType.GetField ("ExactSpelling"), exactSpelling), + new CustomAttributeNamedArgument (attrType.GetField ("SetLastError"), setLastError), + new CustomAttributeNamedArgument (attrType.GetField ("PreserveSig"), preserveSig), + new CustomAttributeNamedArgument (attrType.GetField ("CallingConvention"), callingConvention), + new CustomAttributeNamedArgument (attrType.GetField ("BestFitMapping"), bestFitMapping), + new CustomAttributeNamedArgument (attrType.GetField ("ThrowOnUnmappableChar"), throwOnUnmappableChar) + }; + + return new CustomAttributeData ( + attrType.GetConstructor (new[] { typeof (string) }), + ctorArgs, + namedArgs); + } + public override MethodInfo MakeGenericMethod (Type [] methodInstantiation) { if (methodInstantiation == null) @@ -560,6 +659,8 @@ namespace System.Reflection { public override bool IsSecuritySafeCritical { get { return get_core_clr_security_level () == 1; } } + + public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore (other); } @@ -700,6 +801,8 @@ namespace System.Reflection { } catch (MethodAccessException) { throw; #endif + } catch (OverflowException) { + throw; } catch (Exception e) { throw new TargetInvocationException (e); } @@ -809,6 +912,8 @@ namespace System.Reflection { public extern int get_core_clr_security_level (); #endif + public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore (other); + public override bool IsSecurityTransparent { get { return get_core_clr_security_level () == 0; } } @@ -820,5 +925,14 @@ namespace System.Reflection { public override bool IsSecuritySafeCritical { get { return get_core_clr_security_level () == 1; } } + + public override int MetadataToken { + get { + return get_metadata_token (this); + } + } + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + internal static extern int get_metadata_token (MonoCMethod method); } } diff --git a/mcs/class/corlib/System.Reflection/MonoParameterInfo.cs b/mcs/class/corlib/System.Reflection/MonoParameterInfo.cs index e2fd19f13d..1c4590940a 100644 --- a/mcs/class/corlib/System.Reflection/MonoParameterInfo.cs +++ b/mcs/class/corlib/System.Reflection/MonoParameterInfo.cs @@ -48,7 +48,36 @@ namespace System.Reflection [Serializable] [ClassInterfaceAttribute (ClassInterfaceType.None)] [StructLayout (LayoutKind.Sequential)] - class MonoParameterInfo : RuntimeParameterInfo { + class MonoParameterInfo : RuntimeParameterInfo { + internal MarshalAsAttribute marshalAs; + + internal static void FormatParameters (StringBuilder sb, ParameterInfo[] p, CallingConventions callingConvention, bool serialization) + { + for (int i = 0; i < p.Length; ++i) { + if (i > 0) + sb.Append (", "); + + Type t = p[i].ParameterType; + + string typeName = t.FormatTypeName (serialization); + + // Legacy: Why use "ByRef" for by ref parameters? What language is this? + // VB uses "ByRef" but it should precede (not follow) the parameter name. + // Why don't we just use "&"? + if (t.IsByRef && !serialization) { + sb.Append (typeName.TrimEnd (new char[] { '&' })); + sb.Append (" ByRef"); + } else { + sb.Append (typeName); + } + } + + if ((callingConvention & CallingConventions.VarArgs) != 0) { + if (p.Length > 0) + sb.Append (", "); + sb.Append ("..."); + } + } #if !FULL_AOT_RUNTIME internal MonoParameterInfo (ParameterBuilder pb, Type type, MemberInfo member, int position) { @@ -87,8 +116,7 @@ namespace System.Reflection this.NameImpl = pinfo.Name; this.PositionImpl = pinfo.Position; this.AttrsImpl = pinfo.Attributes; - this.DefaultValueImpl = pinfo.GetDefaultValueImpl (); - //this.parent = pinfo; + this.DefaultValueImpl = GetDefaultValueImpl (pinfo); } /* to build a ParameterInfo for the return type of a method */ @@ -104,12 +132,12 @@ namespace System.Reflection public override object DefaultValue { get { - if (ClassImpl == typeof (Decimal)) { + if (ClassImpl == typeof (Decimal) || ClassImpl == typeof (Decimal?)) { /* default values for decimals are encoded using a custom attribute */ DecimalConstantAttribute[] attrs = (DecimalConstantAttribute[])GetCustomAttributes (typeof (DecimalConstantAttribute), false); if (attrs.Length > 0) return attrs [0].Value; - } else if (ClassImpl == typeof (DateTime)) { + } else if (ClassImpl == typeof (DateTime) || ClassImpl == typeof (DateTime?)) { /* default values for DateTime are encoded using a custom attribute */ DateTimeConstantAttribute[] attrs = (DateTimeConstantAttribute[])GetCustomAttributes (typeof (DateTimeConstantAttribute), false); if (attrs.Length > 0) @@ -160,6 +188,11 @@ namespace System.Reflection return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit); } + internal object GetDefaultValueImpl (ParameterInfo pinfo) + { + FieldInfo field = typeof (ParameterInfo).GetField ("DefaultValueImpl", BindingFlags.Instance | BindingFlags.NonPublic); + return field.GetValue (pinfo); + } public override @@ -171,6 +204,8 @@ namespace System.Reflection return CustomAttributeData.GetCustomAttributes (this); } + [MethodImplAttribute (MethodImplOptions.InternalCall)] + internal extern int GetMetadataToken (); public override @@ -181,6 +216,72 @@ namespace System.Reflection return types; } + internal object[] GetPseudoCustomAttributes () + { + int count = 0; + + if (IsIn) + count ++; + if (IsOut) + count ++; + if (IsOptional) + count ++; + if (marshalAs != null) + count ++; + + if (count == 0) + return null; + object[] attrs = new object [count]; + count = 0; + + if (IsIn) + attrs [count ++] = new InAttribute (); + if (IsOut) + attrs [count ++] = new OutAttribute (); + if (IsOptional) + attrs [count ++] = new OptionalAttribute (); + + if (marshalAs != null) + attrs [count ++] = marshalAs.Copy (); + + return attrs; + } + + internal CustomAttributeData[] GetPseudoCustomAttributesData () + { + int count = 0; + + if (IsIn) + count++; + if (IsOut) + count++; + if (IsOptional) + count++; + if (marshalAs != null) + count++; + + if (count == 0) + return null; + CustomAttributeData[] attrsData = new CustomAttributeData [count]; + count = 0; + + if (IsIn) + attrsData [count++] = new CustomAttributeData ((typeof (InAttribute)).GetConstructor (Type.EmptyTypes)); + if (IsOut) + attrsData [count++] = new CustomAttributeData ((typeof (OutAttribute)).GetConstructor (Type.EmptyTypes)); + if (IsOptional) + attrsData [count++] = new CustomAttributeData ((typeof (OptionalAttribute)).GetConstructor (Type.EmptyTypes)); + if (marshalAs != null) { + var ctorArgs = new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument (typeof (UnmanagedType), marshalAs.Value) }; + attrsData [count++] = new CustomAttributeData ( + (typeof (MarshalAsAttribute)).GetConstructor (new[] { typeof (UnmanagedType) }), + ctorArgs, + EmptyArray.Value);//FIXME Get named params + } + + return attrsData; + } + public override Type[] GetRequiredCustomModifiers () { @@ -202,5 +303,30 @@ namespace System.Reflection return true; } } + + [MethodImplAttribute (MethodImplOptions.InternalCall)] + internal extern Type[] GetTypeModifiers (bool optional); + +#if !FULL_AOT_RUNTIME + internal static ParameterInfo New (ParameterBuilder pb, Type type, MemberInfo member, int position) + { + return new MonoParameterInfo (pb, type, member, position); + } +#endif + + internal static ParameterInfo New (ParameterInfo pinfo, Type type, MemberInfo member, int position) + { + return new MonoParameterInfo (pinfo, type, member, position); + } + + internal static ParameterInfo New (ParameterInfo pinfo, MemberInfo member) + { + return new MonoParameterInfo (pinfo, member); + } + + internal static ParameterInfo New (Type type, MemberInfo member, MarshalAsAttribute marshalAs) + { + return new MonoParameterInfo (type, member, marshalAs); + } } } diff --git a/mcs/class/corlib/System.Reflection/MonoProperty.cs b/mcs/class/corlib/System.Reflection/MonoProperty.cs index 16f44ec583..4af9a23041 100644 --- a/mcs/class/corlib/System.Reflection/MonoProperty.cs +++ b/mcs/class/corlib/System.Reflection/MonoProperty.cs @@ -120,7 +120,7 @@ namespace System.Reflection { var pi = GetIndexParameters (); if (pi.Length > 0) { sbName.Append (" ["); - ParameterInfo.FormatParameters (sbName, pi, 0, serialization); + MonoParameterInfo.FormatParameters (sbName, pi, 0, serialization); sbName.Append ("]"); } @@ -274,7 +274,7 @@ namespace System.Reflection { var dest = new ParameterInfo [length]; for (int i = 0; i < length; ++i) { - dest [i] = ParameterInfo.New (src [i], this); + dest [i] = MonoParameterInfo.New (src [i], this); } return dest; } @@ -359,16 +359,7 @@ namespace System.Reflection { } getterType = getterDelegateType.MakeGenericType (typeVector); -#if MOBILE - // with Silverlight a coreclr failure (e.g. Transparent caller creating a delegate on a Critical method) - // would normally throw an ArgumentException, so we set throwOnBindFailure to false and check for a null - // delegate that we can transform into a MethodAccessException - getterDelegate = Delegate.CreateDelegate (getterType, method, false); - if (getterDelegate == null) - throw new MethodAccessException (); -#else getterDelegate = Delegate.CreateDelegate (getterType, method); -#endif adapterFrame = typeof (MonoProperty).GetMethod (frameName, BindingFlags.Static | BindingFlags.NonPublic); adapterFrame = adapterFrame.MakeGenericMethod (typeVector); return (GetterAdapter)Delegate.CreateDelegate (typeof (GetterAdapter), getterDelegate, adapterFrame, true); @@ -381,9 +372,9 @@ namespace System.Reflection { #if !FULL_AOT_RUNTIME if (cached_getter == null) { MethodInfo method = GetGetMethod (true); + if (method == null) + throw new ArgumentException ($"Get Method not found for '{Name}'"); if (!DeclaringType.IsValueType && !method.ContainsGenericParameters) { //FIXME find a way to build an invoke delegate for value types. - if (method == null) - throw new ArgumentException ("Get Method not found for '" + Name + "'"); cached_getter = CreateGetterDelegate (method); // The try-catch preserves the .Invoke () behaviour try { @@ -411,7 +402,7 @@ namespace System.Reflection { MethodInfo method = GetGetMethod (true); if (method == null) - throw new ArgumentException ("Get Method not found for '" + Name + "'"); + throw new ArgumentException ($"Get Method not found for '{Name}'"); try { if (index == null || index.Length == 0) @@ -462,5 +453,29 @@ namespace System.Reflection { public override IList GetCustomAttributesData () { return CustomAttributeData.GetCustomAttributes (this); } + + public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore (other); + + public override int MetadataToken { + get { + return get_metadata_token (this); + } + } + + [MethodImplAttribute (MethodImplOptions.InternalCall)] + internal static extern int get_metadata_token (MonoProperty monoProperty); + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private static extern PropertyInfo internal_from_handle_type (IntPtr event_handle, IntPtr type_handle); + + internal static PropertyInfo GetPropertyFromHandle (Mono.RuntimePropertyHandle handle, RuntimeTypeHandle reflectedType) + { + if (handle.Value == IntPtr.Zero) + throw new ArgumentException ("The handle is invalid."); + PropertyInfo pi = internal_from_handle_type (handle.Value, reflectedType.Value); + if (pi == null) + throw new ArgumentException ("The property handle and the type handle are incompatible."); + return pi; + } } } diff --git a/mcs/class/corlib/System.Reflection/ParameterInfo.cs b/mcs/class/corlib/System.Reflection/ParameterInfo.cs deleted file mode 100644 index 24674d04bb..0000000000 --- a/mcs/class/corlib/System.Reflection/ParameterInfo.cs +++ /dev/null @@ -1,317 +0,0 @@ -// System.Reflection.ParameterInfo -// -// Authors: -// Sean MacIsaac (macisaac@ximian.com) -// Marek Safar (marek.safar@gmail.com) -// -// (C) 2001 Ximian, Inc. -// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) -// Copyright 2013 Xamarin, Inc (http://www.xamarin.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. -// - -#if !FULL_AOT_RUNTIME -using System.Reflection.Emit; -#endif -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections.Generic; -using System.Text; -using System.Runtime.Serialization; - -namespace System.Reflection -{ - [ComVisible (true)] - [ComDefaultInterfaceAttribute (typeof (_ParameterInfo))] - [Serializable] - [ClassInterfaceAttribute (ClassInterfaceType.None)] - [StructLayout (LayoutKind.Sequential)] - public partial class ParameterInfo : ICustomAttributeProvider - -#if !MOBILE - , _ParameterInfo -#endif - - , IObjectReference - { - protected Type ClassImpl; - protected object DefaultValueImpl; - protected MemberInfo MemberImpl; - protected string NameImpl; - protected int PositionImpl; - protected ParameterAttributes AttrsImpl; - internal MarshalAsAttribute marshalAs; - - protected ParameterInfo () { - } - - public override string ToString() => ClassImpl.FormatTypeName() + " " + Name; - - internal static void FormatParameters (StringBuilder sb, ParameterInfo[] p, CallingConventions callingConvention, bool serialization) - { - for (int i = 0; i < p.Length; ++i) { - if (i > 0) - sb.Append (", "); - - Type t = p[i].ParameterType; - - string typeName = t.FormatTypeName (serialization); - - // Legacy: Why use "ByRef" for by ref parameters? What language is this? - // VB uses "ByRef" but it should precede (not follow) the parameter name. - // Why don't we just use "&"? - if (t.IsByRef && !serialization) { - sb.Append (typeName.TrimEnd (new char[] { '&' })); - sb.Append (" ByRef"); - } else { - sb.Append (typeName); - } - } - - if ((callingConvention & CallingConventions.VarArgs) != 0) { - if (p.Length > 0) - sb.Append (", "); - sb.Append ("..."); - } - } - - public virtual Type ParameterType { - get {return ClassImpl;} - } - public virtual ParameterAttributes Attributes { - get {return AttrsImpl;} - } - - public bool IsIn { - get { - return (Attributes & ParameterAttributes.In) != 0; - } - } -#if FEATURE_USE_LCID - public bool IsLcid { - get { - return (Attributes & ParameterAttributes.Lcid) != 0; - } - } -#endif - public bool IsOptional { - get { - return (Attributes & ParameterAttributes.Optional) != 0; - } - } - - public bool IsOut { - get { - return (Attributes & ParameterAttributes.Out) != 0; - } - } - - public bool IsRetval { - get { - return (Attributes & ParameterAttributes.Retval) != 0; - } - } - - public virtual MemberInfo Member { - get {return MemberImpl;} - } - - public virtual string Name { - get {return NameImpl;} - } - - public virtual int Position { - get {return PositionImpl;} - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern int GetMetadataToken (); - - internal object[] GetPseudoCustomAttributes () { - int count = 0; - - if (IsIn) - count ++; - if (IsOut) - count ++; - if (IsOptional) - count ++; - if (marshalAs != null) - count ++; - - if (count == 0) - return null; - object[] attrs = new object [count]; - count = 0; - - if (IsIn) - attrs [count ++] = new InAttribute (); - if (IsOptional) - attrs [count ++] = new OptionalAttribute (); - if (IsOut) - attrs [count ++] = new OutAttribute (); - - if (marshalAs != null) - attrs [count ++] = marshalAs.Copy (); - - return attrs; - } - - internal CustomAttributeData[] GetPseudoCustomAttributesData () - { - int count = 0; - - if (IsIn) - count++; - if (IsOut) - count++; - if (IsOptional) - count++; - if (marshalAs != null) - count++; - - if (count == 0) - return null; - CustomAttributeData[] attrsData = new CustomAttributeData [count]; - count = 0; - - if (IsIn) - attrsData [count++] = new CustomAttributeData ((typeof (InAttribute)).GetConstructor (Type.EmptyTypes)); - if (IsOptional) - attrsData [count++] = new CustomAttributeData ((typeof (OptionalAttribute)).GetConstructor (Type.EmptyTypes)); - if (IsOut) - attrsData [count++] = new CustomAttributeData ((typeof (OutAttribute)).GetConstructor (Type.EmptyTypes)); - if (marshalAs != null) { - var ctorArgs = new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument (typeof (UnmanagedType), marshalAs.Value) }; - attrsData [count++] = new CustomAttributeData ( - (typeof (MarshalAsAttribute)).GetConstructor (new[] { typeof( UnmanagedType) }), - ctorArgs, - EmptyArray.Value);//FIXME Get named params - } - - return attrsData; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern Type[] GetTypeModifiers (bool optional); - - internal object GetDefaultValueImpl () - { - return DefaultValueImpl; - } - - public virtual IEnumerable CustomAttributes { - get { return GetCustomAttributesData (); } - } - - public virtual bool HasDefaultValue { - get { throw new NotImplementedException (); } - } - -#if !MOBILE - void _ParameterInfo.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException (); - } - - void _ParameterInfo.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException (); - } - - void _ParameterInfo.GetTypeInfoCount (out uint pcTInfo) - { - throw new NotImplementedException (); - } - - void _ParameterInfo.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, - IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException (); - } -#endif - - public virtual object DefaultValue { - get { throw new NotImplementedException (); } - } - - public virtual object RawDefaultValue { - get { throw new NotImplementedException (); } - } - - public virtual int MetadataToken { - get { return 0x8000000; } - } - - public virtual object[] GetCustomAttributes (bool inherit) - { - return new object [0]; - } - - public virtual object[] GetCustomAttributes (Type attributeType, bool inherit) - { - return new object [0]; - } - - public object GetRealObject (StreamingContext context) - { - throw new NotImplementedException (); - } - - public virtual bool IsDefined( Type attributeType, bool inherit) { - return false; - } - - public virtual Type[] GetRequiredCustomModifiers () { - return new Type [0]; - } - - public virtual Type[] GetOptionalCustomModifiers () { - return new Type [0]; - } - - public virtual IList GetCustomAttributesData () { - throw new NotImplementedException (); - } - -#if !FULL_AOT_RUNTIME - internal static ParameterInfo New (ParameterBuilder pb, Type type, MemberInfo member, int position) - { - return new MonoParameterInfo (pb, type, member, position); - } -#endif - - internal static ParameterInfo New (ParameterInfo pinfo, Type type, MemberInfo member, int position) - { - return new MonoParameterInfo (pinfo, type, member, position); - } - - internal static ParameterInfo New (ParameterInfo pinfo, MemberInfo member) - { - return new MonoParameterInfo (pinfo, member); - } - - internal static ParameterInfo New (Type type, MemberInfo member, MarshalAsAttribute marshalAs) - { - return new MonoParameterInfo (type, member, marshalAs); - } - } -} diff --git a/mcs/class/corlib/System.Reflection/PropertyInfo.cs b/mcs/class/corlib/System.Reflection/PropertyInfo.cs deleted file mode 100644 index 9eeb9cc917..0000000000 --- a/mcs/class/corlib/System.Reflection/PropertyInfo.cs +++ /dev/null @@ -1,213 +0,0 @@ -// -// System.Reflection/PropertyInfo.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Diagnostics; -using System.Globalization; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; - -namespace System.Reflection { - - [ComVisible (true)] - [ComDefaultInterfaceAttribute (typeof (_PropertyInfo))] - [Serializable] - [ClassInterface(ClassInterfaceType.None)] -#if MOBILE - public abstract class PropertyInfo : MemberInfo { -#else - public abstract class PropertyInfo : MemberInfo, _PropertyInfo { -#endif - public abstract PropertyAttributes Attributes { get; } - public abstract bool CanRead { get; } - public abstract bool CanWrite { get; } - - public virtual MethodInfo GetMethod { - get { return GetGetMethod(true); } - } - - public virtual MethodInfo SetMethod { - get { return GetSetMethod(true); } - } - - public bool IsSpecialName { - get {return (Attributes & PropertyAttributes.SpecialName) != 0;} - } - - public override MemberTypes MemberType { - get {return MemberTypes.Property;} - } - public abstract Type PropertyType { get; } - - protected PropertyInfo () { } - - public MethodInfo[] GetAccessors () - { - return GetAccessors (false); - } - - public abstract MethodInfo[] GetAccessors (bool nonPublic); - - public MethodInfo GetGetMethod() - { - return GetGetMethod (false); - } - public abstract MethodInfo GetGetMethod(bool nonPublic); - - public abstract ParameterInfo[] GetIndexParameters(); - - public MethodInfo GetSetMethod() - { - return GetSetMethod (false); - } - - public abstract MethodInfo GetSetMethod (bool nonPublic); - - [DebuggerHidden] - [DebuggerStepThrough] - public virtual object GetValue (object obj, object[] index) - { - return GetValue(obj, BindingFlags.Default, null, index, null); - } - - [DebuggerHidden] - [DebuggerStepThrough] - public object GetValue (object obj) - { - return GetValue(obj, BindingFlags.Default, null, null, null); - } - - public abstract object GetValue (object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture); - - [DebuggerHidden] - [DebuggerStepThrough] - public virtual void SetValue (object obj, object value, object[] index) - { - SetValue (obj, value, BindingFlags.Default, null, index, null); - } - - [DebuggerHidden] - [DebuggerStepThrough] - public void SetValue (object obj, object value) - { - SetValue (obj, value, BindingFlags.Default, null, null, null); - } - - public abstract void SetValue (object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture); - - public virtual Type[] GetOptionalCustomModifiers () { - return Type.EmptyTypes; - } - - public virtual Type[] GetRequiredCustomModifiers () { - return Type.EmptyTypes; - } - - static NotImplementedException CreateNIE () - { - return new NotImplementedException (); - } - - public virtual object GetConstantValue () { - throw CreateNIE (); - } - - public virtual object GetRawConstantValue() { - throw CreateNIE (); - } - - public override bool Equals (object obj) - { - return obj == (object) this; - } - - public override int GetHashCode () - { - return base.GetHashCode (); - } - - public static bool operator == (PropertyInfo left, PropertyInfo right) - { - if ((object)left == (object)right) - return true; - if ((object)left == null ^ (object)right == null) - return false; - return left.Equals (right); - } - - public static bool operator != (PropertyInfo left, PropertyInfo right) - { - if ((object)left == (object)right) - return false; - if ((object)left == null ^ (object)right == null) - return true; - return !left.Equals (right); - } - -#if !MOBILE - void _PropertyInfo.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException (); - } - - Type _PropertyInfo.GetType () - { - // Required or object::GetType becomes virtual final - return base.GetType (); - } - - void _PropertyInfo.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException (); - } - - void _PropertyInfo.GetTypeInfoCount (out uint pcTInfo) - { - throw new NotImplementedException (); - } - - void _PropertyInfo.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException (); - } -#endif - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern PropertyInfo internal_from_handle_type (IntPtr event_handle, IntPtr type_handle); - - internal static PropertyInfo GetPropertyFromHandle (Mono.RuntimePropertyHandle handle, RuntimeTypeHandle reflectedType) - { - if (handle.Value == IntPtr.Zero) - throw new ArgumentException ("The handle is invalid."); - PropertyInfo pi = internal_from_handle_type (handle.Value, reflectedType.Value); - if (pi == null) - throw new ArgumentException ("The property handle and the type handle are incompatible."); - return pi; - } - } -} diff --git a/mcs/class/corlib/System.Runtime.CompilerServices/PreserveDependencyAttribute.cs b/mcs/class/corlib/System.Runtime.CompilerServices/PreserveDependencyAttribute.cs index d08dc4ce7d..e68473a63e 100644 --- a/mcs/class/corlib/System.Runtime.CompilerServices/PreserveDependencyAttribute.cs +++ b/mcs/class/corlib/System.Runtime.CompilerServices/PreserveDependencyAttribute.cs @@ -27,14 +27,20 @@ // namespace System.Runtime.CompilerServices { - [AttributeUsage (AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true)] + [AttributeUsage (AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Field, AllowMultiple = true)] /*public*/ sealed class PreserveDependencyAttribute : Attribute { - public PreserveDependencyAttribute (string metadataSignature) + public PreserveDependencyAttribute (string memberSignature) { } - public PreserveDependencyAttribute (string metadataSignature, string condition) + public PreserveDependencyAttribute (string memberSignature, string typeName) { } + + public PreserveDependencyAttribute (string memberSignature, string typeName, string assembly) + { + } + + public string Condition { get; set; } } } \ No newline at end of file diff --git a/mcs/class/corlib/System.Runtime.CompilerServices/Unsafe.cs b/mcs/class/corlib/System.Runtime.CompilerServices/Unsafe.cs index 1d9ff7a54a..56fdda2ef3 100644 --- a/mcs/class/corlib/System.Runtime.CompilerServices/Unsafe.cs +++ b/mcs/class/corlib/System.Runtime.CompilerServices/Unsafe.cs @@ -133,6 +133,15 @@ namespace System.Runtime.CompilerServices throw new NotImplementedException (); } + public static bool IsAddressGreaterThan(ref T left, ref T right) + { + throw new NotImplementedException (); + } + + public static bool IsAddressLessThan(ref T left, ref T right) + { + throw new NotImplementedException (); + } [MethodImpl (MethodImplOptions.AggressiveInlining)] unsafe internal static ref T AddByteOffset (ref T source, nuint byteOffset) diff --git a/mcs/class/corlib/System.Runtime.InteropServices.RuntimeInformation/RuntimeInformation.cs b/mcs/class/corlib/System.Runtime.InteropServices.RuntimeInformation/RuntimeInformation.cs index eda34460ff..7b11484ead 100644 --- a/mcs/class/corlib/System.Runtime.InteropServices.RuntimeInformation/RuntimeInformation.cs +++ b/mcs/class/corlib/System.Runtime.InteropServices.RuntimeInformation/RuntimeInformation.cs @@ -30,11 +30,19 @@ using System.IO; using System.Reflection; +using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices { public static class RuntimeInformation { + /* gets the runtime's arch from the value it uses for DllMap */ + static extern string RuntimeArchitecture + { + [MethodImpl (MethodImplOptions.InternalCall)] + get; + } + public static string FrameworkDescription { get { return "Mono " + Mono.Runtime.GetDisplayName (); @@ -75,8 +83,17 @@ namespace System.Runtime.InteropServices { get { - // TODO: very barebones implementation, doesn't respect ARM - return Environment.Is64BitOperatingSystem ? Architecture.X64 : Architecture.X86; + switch (RuntimeArchitecture) { + case "arm": + case "armv8": + return Environment.Is64BitOperatingSystem ? Architecture.Arm64 : Architecture.Arm; + case "x86": + case "x86-64": + // upstream only has these values; try to pretend we're x86 if nothing matches + // want more? bug: https://github.com/dotnet/corefx/issues/30706 + default: + return Environment.Is64BitOperatingSystem ? Architecture.X64 : Architecture.X86; + } } } @@ -84,8 +101,22 @@ namespace System.Runtime.InteropServices { get { - // TODO: very barebones implementation, doesn't respect ARM - return Environment.Is64BitProcess ? Architecture.X64 : Architecture.X86; + // we can use the runtime's compiled config options for DllMaps here + // process architecure for us is runtime architecture (OS is much harder) + // see for values: mono-config.c + switch (RuntimeArchitecture) { + case "x86": + return Architecture.X86; + case "x86-64": + return Architecture.X64; + case "arm": + return Architecture.Arm; + case "armv8": + return Architecture.Arm64; + // see comment in OSArchiteture default case + default: + return Environment.Is64BitProcess ? Architecture.X64 : Architecture.X86; + } } } } diff --git a/mcs/class/corlib/System.Runtime.InteropServices/GCHandleType.cs b/mcs/class/corlib/System.Runtime.InteropServices/GCHandleType.cs deleted file mode 100644 index 19007f4193..0000000000 --- a/mcs/class/corlib/System.Runtime.InteropServices/GCHandleType.cs +++ /dev/null @@ -1,46 +0,0 @@ -// GCHandleType.cs -// -// This code was automatically generated from -// ECMA CLI XML Library Specification. -// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] -// Created: Fri, 7 Sep 2001 16:33:42 UTC -// Source file: AllTypes.xml -// URL: http://msdn.microsoft.com/net/ecma/AllTypes.xml -// -// (C) 2001 Ximian, Inc. http://www.ximian.com - -// -// 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. -// - - -namespace System.Runtime.InteropServices { - - [ComVisible(true)] - [Serializable] - public enum GCHandleType { - Weak = 0, - WeakTrackResurrection = 1, - Normal = 2, - Pinned = 3, - } -} diff --git a/mcs/class/corlib/System.Runtime.InteropServices/Marshal.cs b/mcs/class/corlib/System.Runtime.InteropServices/Marshal.cs index 7eb79408ed..046281e1c6 100644 --- a/mcs/class/corlib/System.Runtime.InteropServices/Marshal.cs +++ b/mcs/class/corlib/System.Runtime.InteropServices/Marshal.cs @@ -1897,5 +1897,72 @@ namespace System.Runtime.InteropServices throw new NotSupportedException(); } #endif + + internal class MarshalerInstanceKeyComparer : IEqualityComparer<(Type, string)> { + public bool Equals ((Type, string) lhs, (Type, string) rhs) { + return lhs.CompareTo(rhs) == 0; + } + + public int GetHashCode ((Type, string) key) { + return key.GetHashCode (); + } + } + + internal static Dictionary<(Type, string), ICustomMarshaler> MarshalerInstanceCache; + internal static readonly object MarshalerInstanceCacheLock = new object (); + + internal static ICustomMarshaler GetCustomMarshalerInstance (Type type, string cookie) { + var key = (type, cookie); + + LazyInitializer.EnsureInitialized ( + ref MarshalerInstanceCache, + () => new Dictionary<(Type, string), ICustomMarshaler> (new MarshalerInstanceKeyComparer ()) + ); + + ICustomMarshaler result; + bool gotExistingInstance; + lock (MarshalerInstanceCacheLock) + gotExistingInstance = MarshalerInstanceCache.TryGetValue (key, out result); + + if (!gotExistingInstance) { + MonoMethod getInstanceMethod; + try { + getInstanceMethod = (MonoMethod)type.GetMethod ( + "GetInstance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod, + null, new Type[] { typeof(string) }, null + ); + } catch (AmbiguousMatchException) { + throw new ApplicationException ($"Custom marshaler '{type.FullName}' implements multiple static GetInstance methods that take a single string parameter."); + } + + if ((getInstanceMethod == null) || + (getInstanceMethod.ReturnType != typeof (ICustomMarshaler))) { + throw new ApplicationException ($"Custom marshaler '{type.FullName}' does not implement a static GetInstance method that takes a single string parameter and returns an ICustomMarshaler."); + } + + Exception exc; + try { + result = (ICustomMarshaler)getInstanceMethod.InternalInvoke (null, new object[] { cookie }, out exc); + } catch (Exception e) { + // FIXME: mscorlib's legacyUnhandledExceptionPolicy is apparently 1, + // so exceptions are thrown instead of being passed through the outparam + exc = e; + result = null; + } + + if (exc != null) { + var edi = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture (exc); + edi.Throw (); + } + + if (result == null) + throw new ApplicationException ($"A call to GetInstance() for custom marshaler '{type.FullName}' returned null, which is not allowed."); + + lock (MarshalerInstanceCacheLock) + MarshalerInstanceCache[key] = result; + } + + return result; + } } } diff --git a/mcs/class/corlib/System.Runtime.InteropServices/MarshalAsAttribute.cs b/mcs/class/corlib/System.Runtime.InteropServices/MarshalAsAttribute.cs index 2940358a58..745e2cb0f9 100644 --- a/mcs/class/corlib/System.Runtime.InteropServices/MarshalAsAttribute.cs +++ b/mcs/class/corlib/System.Runtime.InteropServices/MarshalAsAttribute.cs @@ -29,6 +29,7 @@ // using System; +using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices { @@ -44,6 +45,7 @@ namespace System.Runtime.InteropServices { public string MarshalType; [ComVisible(true)] + [PreserveDependency ("GetCustomMarshalerInstance", "System.Runtime.InteropServices.Marshal")] public Type MarshalTypeRef; public Type SafeArrayUserDefinedSubType; diff --git a/mcs/class/corlib/System.Runtime.Remoting/RemotingServices.cs b/mcs/class/corlib/System.Runtime.Remoting/RemotingServices.cs index 422302eaf0..37b06e040a 100644 --- a/mcs/class/corlib/System.Runtime.Remoting/RemotingServices.cs +++ b/mcs/class/corlib/System.Runtime.Remoting/RemotingServices.cs @@ -478,7 +478,7 @@ namespace System.Runtime.Remoting { const BindingFlags bfinst = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance; RuntimeType type = (RuntimeType) msg.MethodBase.DeclaringType; - return type.GetMethodsByName (msg.MethodName, bfinst, false, type).Length > 1; + return type.GetMethodsByName (msg.MethodName, bfinst, RuntimeType.MemberListType.CaseSensitive, type).Length > 1; } public static bool IsObjectOutOfAppDomain(object tp) diff --git a/mcs/class/corlib/System.Security.Cryptography.X509Certificates/X509Certificate.cs b/mcs/class/corlib/System.Security.Cryptography.X509Certificates/X509Certificate.cs index 084ebc13f6..4f806a7dde 100644 --- a/mcs/class/corlib/System.Security.Cryptography.X509Certificates/X509Certificate.cs +++ b/mcs/class/corlib/System.Security.Cryptography.X509Certificates/X509Certificate.cs @@ -38,7 +38,6 @@ using Internal.Cryptography; using Microsoft.Win32.SafeHandles; using Mono.Security; -using Mono.Security.Authenticode; namespace System.Security.Cryptography.X509Certificates { @@ -198,8 +197,7 @@ namespace System.Security.Cryptography.X509Certificates [System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Usage", "CA2229", Justification = "Public API has already shipped.")] public X509Certificate (SerializationInfo info, StreamingContext context) : this () { - byte[] raw = (byte[]) info.GetValue ("RawData", typeof (byte[])); - Import (raw, (string)null, X509KeyStorageFlags.DefaultKeySet); + throw new PlatformNotSupportedException (); } public static X509Certificate CreateFromCertFile (string filename) @@ -214,14 +212,12 @@ namespace System.Security.Cryptography.X509Certificates void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) { - if (!X509Helper.IsValid (impl)) - throw new NullReferenceException (); - // will throw a NRE if info is null (just like MS implementation) - info.AddValue ("RawData", impl.RawData); + throw new PlatformNotSupportedException (); } void IDeserializationCallback.OnDeserialization (object sender) { + throw new PlatformNotSupportedException (); } public IntPtr Handle { @@ -544,61 +540,40 @@ namespace System.Security.Cryptography.X509Certificates return sb.ToString (); } -#endregion - -#region Mono Implementation - - /* - /* CoreFX throws - /* throw new PlatformNotSupportedException(SR.NotSupported_ImmutableX509Certificate); - /* everywhere. - */ - [ComVisible (false)] public virtual void Import (byte[] rawData) { - Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet); + throw new PlatformNotSupportedException (SR.NotSupported_ImmutableX509Certificate); } [ComVisible (false)] public virtual void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { - Reset (); - using (var safePasswordHandle = new SafePasswordHandle (password)) - impl = X509Helper.Import (rawData, safePasswordHandle, keyStorageFlags); + throw new PlatformNotSupportedException (SR.NotSupported_ImmutableX509Certificate); } public virtual void Import (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { - using (var safePasswordHandle = new SafePasswordHandle (password)) - impl = X509Helper.Import (rawData, safePasswordHandle, keyStorageFlags); + throw new PlatformNotSupportedException (SR.NotSupported_ImmutableX509Certificate); } [ComVisible (false)] public virtual void Import (string fileName) { - Import (fileName, (string)null, X509KeyStorageFlags.DefaultKeySet); + throw new PlatformNotSupportedException (SR.NotSupported_ImmutableX509Certificate); } [ComVisible (false)] public virtual void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags) { - byte[] rawData = File.ReadAllBytes (fileName); - using (var safePasswordHandle = new SafePasswordHandle (password)) - impl = X509Helper.Import (rawData, safePasswordHandle, keyStorageFlags); + throw new PlatformNotSupportedException (SR.NotSupported_ImmutableX509Certificate); } public virtual void Import (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) { - byte[] rawData = File.ReadAllBytes (fileName); - using (var safePasswordHandle = new SafePasswordHandle (password)) - impl = X509Helper.Import (rawData, safePasswordHandle, keyStorageFlags); + throw new PlatformNotSupportedException (SR.NotSupported_ImmutableX509Certificate); } -#endregion - -#region CoreFX Implementation - internal DateTime GetNotAfter () { ThrowIfInvalid (); diff --git a/mcs/class/corlib/System.Security.Cryptography/CryptoConfig.Mobile.cs b/mcs/class/corlib/System.Security.Cryptography/CryptoConfig.Mobile.cs index 39b927e785..75269f74e7 100755 --- a/mcs/class/corlib/System.Security.Cryptography/CryptoConfig.Mobile.cs +++ b/mcs/class/corlib/System.Security.Cryptography/CryptoConfig.Mobile.cs @@ -39,6 +39,7 @@ using System.Runtime.InteropServices; using System.Security.Permissions; using System.Collections.Generic; +using System.Runtime.CompilerServices; namespace System.Security.Cryptography { @@ -57,6 +58,16 @@ namespace System.Security.Cryptography { return CreateFromName (name, null); } +#if MONOTOUCH || XAMMAC + [PreserveDependencyAttribute (".ctor()", "System.Security.Cryptography.AesManaged", "System.Core")] +#else + [PreserveDependencyAttribute (".ctor()", "System.Security.Cryptography.AesCryptoServiceProvider", "System.Core")] +#endif + [PreserveDependencyAttribute (".ctor()", "System.Security.Cryptography.X509Certificates.X509Chain", "System")] + [PreserveDependencyAttribute (".ctor()", "System.Security.Cryptography.X509Certificates.X509KeyUsageExtension", "System")] + [PreserveDependencyAttribute (".ctor()", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension", "System")] + [PreserveDependencyAttribute (".ctor()", "System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension", "System")] + [PreserveDependencyAttribute (".ctor()", "System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension", "System")] public static object CreateFromName (string name, params object[] args) { if (name == null) diff --git a/mcs/class/corlib/System.Security.Cryptography/ICspAsymmetricAlgorithm.cs b/mcs/class/corlib/System.Security.Cryptography/ICspAsymmetricAlgorithm.cs deleted file mode 100644 index 99520c88ad..0000000000 --- a/mcs/class/corlib/System.Security.Cryptography/ICspAsymmetricAlgorithm.cs +++ /dev/null @@ -1,45 +0,0 @@ -// -// ICspAsymmetricAlgorithm.cs: interface for CSP based asymmetric algorithm -// -// Author: -// Sebastien Pouliot (sebastien@ximian.com) -// -// (C) 2003 Motus Technologies Inc. (http://www.motus.com) -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Cryptography { - - [ComVisible (true)] - public interface ICspAsymmetricAlgorithm { - - byte[] ExportCspBlob (bool includePrivateParameters); - - void ImportCspBlob (byte[] rawData); - - CspKeyContainerInfo CspKeyContainerInfo { get; } - } -} - diff --git a/mcs/class/corlib/System.Security.Cryptography/KeyNumber.cs b/mcs/class/corlib/System.Security.Cryptography/KeyNumber.cs deleted file mode 100644 index d64bae58da..0000000000 --- a/mcs/class/corlib/System.Security.Cryptography/KeyNumber.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -// KeyNumber.cs: Key Number for CAPI containers -// -// Author: -// Sebastien Pouliot (sebastien@ximian.com) -// -// (C) 2003 Motus Technologies Inc. (http://www.motus.com) -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Cryptography { - - [ComVisible (true)] - [Serializable] - public enum KeyNumber { - Exchange = 1, - Signature = 2 - } -} diff --git a/mcs/class/corlib/System.Security.Permissions/FileDialogPermissionAccess.cs b/mcs/class/corlib/System.Security.Permissions/FileDialogPermissionAccess.cs deleted file mode 100644 index 4e94b5d12a..0000000000 --- a/mcs/class/corlib/System.Security.Permissions/FileDialogPermissionAccess.cs +++ /dev/null @@ -1,42 +0,0 @@ -// -// System.Security.Permissions.FileDialogPermissionAccess -// -// Author: Duncan Mak (duncan@ximian.com) -// -// (C) Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Permissions { - - [ComVisible (true)] - [Flags] - [Serializable] - public enum FileDialogPermissionAccess { - None = 0, - Open = 1, - Save = 2, - OpenSave = 3, - } -} diff --git a/mcs/class/corlib/System.Security.Permissions/HostProtectionResource.cs b/mcs/class/corlib/System.Security.Permissions/HostProtectionResource.cs deleted file mode 100644 index db5163ccef..0000000000 --- a/mcs/class/corlib/System.Security.Permissions/HostProtectionResource.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// System.Security.Permissions.HostProtectionResource enumeration -// -// Author: -// Sebastien Pouliot -// -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Permissions { - - [Flags] - [Serializable] - [ComVisible (true)] - public enum HostProtectionResource { - None = 0, - Synchronization = 1, - SharedState = 2, - ExternalProcessMgmt = 4, - SelfAffectingProcessMgmt = 8, - ExternalThreading = 16, - SelfAffectingThreading = 32, - SecurityInfrastructure = 64, - UI = 128, - MayLeakOnAbort = 256, - All = ExternalProcessMgmt | ExternalThreading | MayLeakOnAbort | SecurityInfrastructure | - SelfAffectingProcessMgmt | SelfAffectingThreading | SharedState | Synchronization | UI - } -} diff --git a/mcs/class/corlib/System.Security.Permissions/IUnrestrictedPermission.cs b/mcs/class/corlib/System.Security.Permissions/IUnrestrictedPermission.cs deleted file mode 100644 index f1dedde0f8..0000000000 --- a/mcs/class/corlib/System.Security.Permissions/IUnrestrictedPermission.cs +++ /dev/null @@ -1,38 +0,0 @@ -// -// System.Security.Permissions.IUnrestrictedPermission.cs -// -// Author: -// Nick Drochak(ndrochak@gol.com) -// -// (C) Nick Drochak -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Permissions { - - [ComVisible (true)] - public interface IUnrestrictedPermission { - bool IsUnrestricted (); - } -} diff --git a/mcs/class/corlib/System.Security.Permissions/IsolatedStorageContainment.cs b/mcs/class/corlib/System.Security.Permissions/IsolatedStorageContainment.cs deleted file mode 100644 index fd4b0d4153..0000000000 --- a/mcs/class/corlib/System.Security.Permissions/IsolatedStorageContainment.cs +++ /dev/null @@ -1,55 +0,0 @@ -// -// IsolatedStorageContainment.cs -// -// This code was automatically generated from -// ECMA CLI XML Library Specification. -// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] -// Created: Wed, 5 Sep 2001 06:41:57 UTC -// Source file: all.xml -// URL: http://devresource.hp.com/devresource/Docs/TechPapers/CSharp/all.xml -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Permissions { - - [Serializable] - [ComVisible (true)] - public enum IsolatedStorageContainment - { - None = 0x00, - DomainIsolationByUser = 0x10, - AssemblyIsolationByUser = 0x20, - DomainIsolationByRoamingUser = 0x50, - AssemblyIsolationByRoamingUser = 0x60, - AdministerIsolatedStorageByUser = 0x70, - UnrestrictedIsolatedStorage = 0xF0, - ApplicationIsolationByUser = 0x15, - DomainIsolationByMachine = 0x30, - AssemblyIsolationByMachine = 0x40, - ApplicationIsolationByMachine = 0x45, - ApplicationIsolationByRoamingUser = 0x65, - } -} diff --git a/mcs/class/corlib/System.Security.Permissions/PermissionState.cs b/mcs/class/corlib/System.Security.Permissions/PermissionState.cs deleted file mode 100644 index dae6d097e7..0000000000 --- a/mcs/class/corlib/System.Security.Permissions/PermissionState.cs +++ /dev/null @@ -1,44 +0,0 @@ -// PermissionState.cs -// -// This code was automatically generated from -// ECMA CLI XML Library Specification. -// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] -// Created: Wed, 5 Sep 2001 06:30:05 UTC -// Source file: AllTypes.xml -// URL: http://msdn.microsoft.com/net/ecma/AllTypes.xml -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Permissions { - - [ComVisible (true)] - [Serializable] - public enum PermissionState { - - Unrestricted = 1, - None = 0, - } -} diff --git a/mcs/class/corlib/System.Security.Permissions/ReflectionPermissionFlag.cs b/mcs/class/corlib/System.Security.Permissions/ReflectionPermissionFlag.cs deleted file mode 100644 index 438c65e094..0000000000 --- a/mcs/class/corlib/System.Security.Permissions/ReflectionPermissionFlag.cs +++ /dev/null @@ -1,57 +0,0 @@ -// System.Security.Permissions.ReflectionPermissionFlag.cs -// -// This code was automatically generated from -// ECMA CLI XML Library Specification. -// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] -// Created: Wed, 5 Sep 2001 06:31:14 UTC -// Source file: AllTypes.xml -// URL: http://msdn.microsoft.com/net/ecma/AllTypes.xml -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Permissions { - - [Flags] - [ComVisible (true)] - [Serializable] - public enum ReflectionPermissionFlag { - - NoFlags = 0x00000000, - - [Obsolete ("not used anymore")] - TypeInformation = 0x00000001, - - MemberAccess = 0x00000002, - [Obsolete] - ReflectionEmit = 0x4, - - [Obsolete] - AllFlags = TypeInformation | MemberAccess | ReflectionEmit, - - [ComVisible (false)] - RestrictedMemberAccess = 0x8 - } -} diff --git a/mcs/class/corlib/System.Security.Permissions/RegistryPermissionAccess.cs b/mcs/class/corlib/System.Security.Permissions/RegistryPermissionAccess.cs deleted file mode 100644 index db4b7eef6a..0000000000 --- a/mcs/class/corlib/System.Security.Permissions/RegistryPermissionAccess.cs +++ /dev/null @@ -1,48 +0,0 @@ -// RegistryPermissionAccess.cs -// -// This code was automatically generated from -// ECMA CLI XML Library Specification. -// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] -// Created: Wed, 5 Sep 2001 06:42:13 UTC -// Source file: all.xml -// URL: http://devresource.hp.com/devresource/Docs/TechPapers/CSharp/all.xml -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Permissions { - - [ComVisible (true)] - [Serializable] - [Flags] - public enum RegistryPermissionAccess { - - NoAccess = 0, - Read = 1, - Write = 2, - Create = 4, - AllAccess = 7, - } -} diff --git a/mcs/class/corlib/System.Security.Permissions/UIPermissionClipboard.cs b/mcs/class/corlib/System.Security.Permissions/UIPermissionClipboard.cs deleted file mode 100644 index 0d3918ed24..0000000000 --- a/mcs/class/corlib/System.Security.Permissions/UIPermissionClipboard.cs +++ /dev/null @@ -1,45 +0,0 @@ -// UIPermissionClipboard.cs -// -// This code was automatically generated from -// ECMA CLI XML Library Specification. -// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] -// Created: Wed, 5 Sep 2001 06:42:40 UTC -// Source file: all.xml -// URL: http://devresource.hp.com/devresource/Docs/TechPapers/CSharp/all.xml -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Permissions { - - [ComVisible (true)] - [Serializable] - public enum UIPermissionClipboard { - - NoClipboard = 0, - OwnClipboard = 1, - AllClipboard = 2, - } -} diff --git a/mcs/class/corlib/System.Security.Permissions/UIPermissionWindow.cs b/mcs/class/corlib/System.Security.Permissions/UIPermissionWindow.cs deleted file mode 100644 index e70fb042f6..0000000000 --- a/mcs/class/corlib/System.Security.Permissions/UIPermissionWindow.cs +++ /dev/null @@ -1,46 +0,0 @@ -// UIPermissionWindow.cs -// -// This code was automatically generated from -// ECMA CLI XML Library Specification. -// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] -// Created: Wed, 5 Sep 2001 06:42:30 UTC -// Source file: all.xml -// URL: http://devresource.hp.com/devresource/Docs/TechPapers/CSharp/all.xml -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Permissions { - - [ComVisible (true)] - [Serializable] - public enum UIPermissionWindow { - - NoWindows = 0, - SafeSubWindows = 1, - SafeTopLevelWindows = 2, - AllWindows = 3, - } -} diff --git a/mcs/class/corlib/System.Security.Policy/ApplicationVersionMatch.cs b/mcs/class/corlib/System.Security.Policy/ApplicationVersionMatch.cs deleted file mode 100644 index 08281026c1..0000000000 --- a/mcs/class/corlib/System.Security.Policy/ApplicationVersionMatch.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -// System.Security.Policy.ApplicationVersionMatch enumeration -// -// Author: -// Sebastien Pouliot -// -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Policy { - - [ComVisible (true)] - public enum ApplicationVersionMatch { - MatchExactVersion, - MatchAllVersions - } -} - diff --git a/mcs/class/corlib/System.Security.Policy/Evidence.cs b/mcs/class/corlib/System.Security.Policy/Evidence.cs index 66e6bec14e..a946ffb93b 100644 --- a/mcs/class/corlib/System.Security.Policy/Evidence.cs +++ b/mcs/class/corlib/System.Security.Policy/Evidence.cs @@ -37,8 +37,8 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Permissions; +using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; -using Mono.Security.Authenticode; namespace System.Security.Policy { @@ -260,16 +260,14 @@ namespace System.Security.Policy { // Authenticode(r) signed assemblies get a Publisher evidence if (IsAuthenticodePresent (a)) { - // Note: The certificate is part of the evidences even if it is not trusted! - // so we can't call X509Certificate.CreateFromSignedFile - AuthenticodeDeformatter ad = new AuthenticodeDeformatter (a.Location); - if (ad.SigningCertificate != null) { - X509Certificate x509 = new X509Certificate (ad.SigningCertificate.RawData); - if (x509.GetHashCode () != 0) { - e.AddHost (new Publisher (x509)); - } + try { + X509Certificate x509 = X509Certificate.CreateFromSignedFile (a.Location); + e.AddHost (new Publisher (x509)); + } + catch (CryptographicException) { } } + // assemblies loaded from the GAC also get a Gac evidence (new in Fx 2.0) if (a.GlobalAssemblyCache) { e.AddHost (new GacInstalled ()); diff --git a/mcs/class/corlib/System.Security.Policy/IIdentityPermissionFactory.cs b/mcs/class/corlib/System.Security.Policy/IIdentityPermissionFactory.cs deleted file mode 100644 index 64a77f9791..0000000000 --- a/mcs/class/corlib/System.Security.Policy/IIdentityPermissionFactory.cs +++ /dev/null @@ -1,38 +0,0 @@ -// -// System.Security.Policy.IIdentityPermissionFactory -// -// Nick Drochak (ndrochak@gol.com) -// -// (C) 2001 Nick Drochak -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Policy { - - [ComVisible (true)] - public interface IIdentityPermissionFactory { - - IPermission CreateIdentityPermission(Evidence evidence); - } -} diff --git a/mcs/class/corlib/System.Security.Policy/IMembershipCondition.cs b/mcs/class/corlib/System.Security.Policy/IMembershipCondition.cs deleted file mode 100644 index 34bb18a48f..0000000000 --- a/mcs/class/corlib/System.Security.Policy/IMembershipCondition.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// System.Security.Policy.IMembershipCondition.cs -// -// Nick Drochak (ndrochak@gol.com) -// -// (C) 2001 Nick Drochak -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Policy { - - [ComVisible (true)] - public interface IMembershipCondition : ISecurityEncodable, ISecurityPolicyEncodable { - - bool Check (Evidence evidence); - IMembershipCondition Copy (); - bool Equals (object obj); - string ToString (); - } -} diff --git a/mcs/class/corlib/System.Security.Policy/PolicyStatementAttribute.cs b/mcs/class/corlib/System.Security.Policy/PolicyStatementAttribute.cs deleted file mode 100644 index 12228129ba..0000000000 --- a/mcs/class/corlib/System.Security.Policy/PolicyStatementAttribute.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// System.Security.Policy.PolicyStatementAttribute -// -// Author: -// Nick Drochak (ndrochak@gol.com) -// -// (C) 2001 Nick Drochak -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Policy { - - [Flags] - [Serializable] - [ComVisible (true)] - public enum PolicyStatementAttribute { - Nothing = 0, - Exclusive = 1, - LevelFinal = 2, - All = 3 - } -} diff --git a/mcs/class/corlib/System.Security.Policy/Site.cs b/mcs/class/corlib/System.Security.Policy/Site.cs index 0c79eb8227..010a2bc5bf 100644 --- a/mcs/class/corlib/System.Security.Policy/Site.cs +++ b/mcs/class/corlib/System.Security.Policy/Site.cs @@ -53,10 +53,10 @@ namespace System.Security.Policy { throw new ArgumentException (Locale.GetText ("name is not valid")); origin_site = name; - } + } - public static Site CreateFromUrl (string url) - { + public static Site CreateFromUrl (string url) + { if (url == null) throw new ArgumentNullException ("url"); if (url.Length == 0) @@ -68,45 +68,45 @@ namespace System.Security.Policy { throw new ArgumentException (msg, "url"); } - return new Site (site); - } + return new Site (site); + } - public object Copy () - { - return new Site (origin_site); - } + public object Copy () + { + return new Site (origin_site); + } - public IPermission CreateIdentityPermission (Evidence evidence) - { - return new SiteIdentityPermission (origin_site); - } + public IPermission CreateIdentityPermission (Evidence evidence) + { + return new SiteIdentityPermission (origin_site); + } - public override bool Equals (object o) - { + public override bool Equals (object o) + { Site s = (o as System.Security.Policy.Site); if (s == null) return false; return (String.Compare (s.Name, origin_site, true, CultureInfo.InvariantCulture) == 0); - } + } - public override int GetHashCode () - { - return origin_site.GetHashCode (); - } + public override int GetHashCode () + { + return origin_site.GetHashCode (); + } - public override string ToString () - { + public override string ToString () + { SecurityElement element = new SecurityElement ("System.Security.Policy.Site"); element.AddAttribute ("version", "1"); element.AddChild (new SecurityElement ("Name", origin_site)); return element.ToString (); - } + } // properties - public string Name { - get { return origin_site; } - } + public string Name { + get { return origin_site; } + } // interface IBuiltInEvidence @@ -129,8 +129,8 @@ namespace System.Security.Policy { // internals - internal static bool IsValid (string name) - { + internal static bool IsValid (string name) + { if (name == String.Empty) return false; if ((name.Length == 1) && (name == ".")) // split would remove . @@ -154,8 +154,8 @@ namespace System.Security.Policy { return false; } } - return true; - } + return true; + } // no exception - we return null if a site couldn't be created // this is useful for creating the default evidence as the majority of URL will be local (file://) @@ -171,5 +171,5 @@ namespace System.Security.Policy { string site = uri.Host; return IsValid (site) ? site : null; } - } + } } diff --git a/mcs/class/corlib/System.Security.Principal/IIdentity.cs b/mcs/class/corlib/System.Security.Principal/IIdentity.cs deleted file mode 100644 index d18e3f4020..0000000000 --- a/mcs/class/corlib/System.Security.Principal/IIdentity.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -// System.Security.Principal.IIdentity.cs -// -// Author: -// Miguel de Icaza (miguel@ximian.com) -// -// (C) Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Principal { - - [ComVisible (true)] - public interface IIdentity { - - string AuthenticationType { - get; - } - - bool IsAuthenticated { - get; - } - - string Name { - get; - } - } -} diff --git a/mcs/class/corlib/System.Security.Principal/IPrincipal.cs b/mcs/class/corlib/System.Security.Principal/IPrincipal.cs deleted file mode 100644 index f10ee2cf16..0000000000 --- a/mcs/class/corlib/System.Security.Principal/IPrincipal.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// System.Security.Principal.IPrincipal.cs -// -// Author: -// Miguel de Icaza (miguel@ximian.com) -// -// (C) Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Principal { - - [ComVisible (true)] - public interface IPrincipal { - - IIdentity Identity { - get; - } - - bool IsInRole (string role); - } -} diff --git a/mcs/class/corlib/System.Security.Principal/PrincipalPolicy.cs b/mcs/class/corlib/System.Security.Principal/PrincipalPolicy.cs deleted file mode 100644 index 2bce6182d0..0000000000 --- a/mcs/class/corlib/System.Security.Principal/PrincipalPolicy.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// System.Security.Principal.PrincipalPolicy.cs -// -// Author: -// Miguel de Icaza (miguel@ximian.com) -// -// (C) Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Principal { - - [Serializable] - [ComVisible (true)] - public enum PrincipalPolicy { - UnauthenticatedPrincipal, - NoPrincipal, - WindowsPrincipal - } -} diff --git a/mcs/class/corlib/System.Security.Principal/TokenAccessLevels.cs b/mcs/class/corlib/System.Security.Principal/TokenAccessLevels.cs deleted file mode 100644 index 9628dcaa3d..0000000000 --- a/mcs/class/corlib/System.Security.Principal/TokenAccessLevels.cs +++ /dev/null @@ -1,53 +0,0 @@ -// -// System.Security.Principal.TokenAccessLevels flags -// -// Author: -// Sebastien Pouliot -// -// Copyright (C) 2005 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 System.Runtime.InteropServices; - -namespace System.Security.Principal { - - [Serializable] - [Flags] - [ComVisible (true)] - public enum TokenAccessLevels { - AssignPrimary = 1, - Duplicate = 2, - Impersonate = 4, - Query = 8, - QuerySource = 16, - AdjustPrivileges = 32, - AdjustGroups = 64, - AdjustDefault = 128, - AdjustSessionId = 256, - Read = 0x20008, - Write = 0x200E0, - AllAccess = 0xF01FF, - MaximumAllowed = 0x2000000 - } -} - diff --git a/mcs/class/corlib/System.Security.Principal/TokenImpersonationLevel.cs b/mcs/class/corlib/System.Security.Principal/TokenImpersonationLevel.cs deleted file mode 100644 index 763f1a5030..0000000000 --- a/mcs/class/corlib/System.Security.Principal/TokenImpersonationLevel.cs +++ /dev/null @@ -1,46 +0,0 @@ -// -// System.Security.Principal.TokenImpersonationLevel.cs -// -// Author: -// Tim Coleman (tim@timcoleman.com) -// -// Copyright (C) Tim Coleman, 2004 -// (C) Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security.Principal { - - [Serializable] - [ComVisible (true)] - public enum TokenImpersonationLevel { - Anonymous = 0x01, - Delegation = 0x04, - Identification = 0x02, - Impersonation = 0x03, - None = 0x00 - } -} - diff --git a/mcs/class/corlib/System.Security/IEvidenceFactory.cs b/mcs/class/corlib/System.Security/IEvidenceFactory.cs deleted file mode 100644 index b15cb9c5b4..0000000000 --- a/mcs/class/corlib/System.Security/IEvidenceFactory.cs +++ /dev/null @@ -1,37 +0,0 @@ -// System.Security.IEvidenceFactory -// -// Sean MacIsaac (macisaac@ximian.com) -// -// (C) Ximian, Inc. 2001 -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; -using System.Security.Policy; - -namespace System.Security { - - [ComVisible (true)] - public interface IEvidenceFactory { - Evidence Evidence { get; } - } -} diff --git a/mcs/class/corlib/System.Security/IPermission.cs b/mcs/class/corlib/System.Security/IPermission.cs deleted file mode 100644 index 09c99b0f81..0000000000 --- a/mcs/class/corlib/System.Security/IPermission.cs +++ /dev/null @@ -1,46 +0,0 @@ -// -// System.Security.IPermission.cs -// -// Author: -// Miguel de Icaza (miguel@ximian.com) -// -// (C) Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security { - - [ComVisible (true)] - public interface IPermission : ISecurityEncodable { - IPermission Copy (); - - void Demand (); - - IPermission Intersect (IPermission target); - - bool IsSubsetOf (IPermission target); - - IPermission Union (IPermission target); - } -} diff --git a/mcs/class/corlib/System.Security/ISecurityEncodable.cs b/mcs/class/corlib/System.Security/ISecurityEncodable.cs deleted file mode 100644 index 06fd6f9447..0000000000 --- a/mcs/class/corlib/System.Security/ISecurityEncodable.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// System.Security.ISecurityEncodable.cs -// -// Author: -// Miguel de Icaza (miguel@ximian.com) -// -// (C) Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security { - - [ComVisible (true)] - public interface ISecurityEncodable { - - void FromXml (SecurityElement e); - - SecurityElement ToXml (); - } -} diff --git a/mcs/class/corlib/System.Security/ISecurityPolicyEncodable.cs b/mcs/class/corlib/System.Security/ISecurityPolicyEncodable.cs deleted file mode 100644 index d2085ef8ef..0000000000 --- a/mcs/class/corlib/System.Security/ISecurityPolicyEncodable.cs +++ /dev/null @@ -1,42 +0,0 @@ -// -// System.Security.ISecurityPolicyEncodable.cs -// -// Author: -// Nick Drochak(ndrochak@gol.com) -// -// (C) Nick Drochak -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; -using System.Security.Policy; - -namespace System.Security { - - [ComVisible (true)] - public interface ISecurityPolicyEncodable { - - void FromXml (SecurityElement e, PolicyLevel level); - - SecurityElement ToXml (PolicyLevel level); - } -} diff --git a/mcs/class/corlib/System.Security/IStackWalk.cs b/mcs/class/corlib/System.Security/IStackWalk.cs deleted file mode 100644 index 1195a0993b..0000000000 --- a/mcs/class/corlib/System.Security/IStackWalk.cs +++ /dev/null @@ -1,45 +0,0 @@ -// -// System.Security.IStackWalk.cs -// -// Author: -// Miguel de Icaza (miguel@ximian.com) -// -// (C) Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security { - - [ComVisible (true)] - public interface IStackWalk { - - void Assert (); - - void Demand (); - - void Deny (); - - void PermitOnly (); - } -} diff --git a/mcs/class/corlib/System.Security/PolicyLevelType.cs b/mcs/class/corlib/System.Security/PolicyLevelType.cs deleted file mode 100644 index 24f583ec06..0000000000 --- a/mcs/class/corlib/System.Security/PolicyLevelType.cs +++ /dev/null @@ -1,42 +0,0 @@ -// -// System.Security.PolicyLevelType.cs -// -// Author: -// Nick Drochak(ndrochak@gol.com) -// -// (C) Nick Drochak -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security { - - [Serializable] - [ComVisible (true)] - public enum PolicyLevelType { - User = 0x0, - Machine, - Enterprise, - AppDomain, - } -} diff --git a/mcs/class/corlib/System.Security/SecurityZone.cs b/mcs/class/corlib/System.Security/SecurityZone.cs deleted file mode 100644 index 8ca1ce6202..0000000000 --- a/mcs/class/corlib/System.Security/SecurityZone.cs +++ /dev/null @@ -1,44 +0,0 @@ -// -// System.Security.SecurityZone.cs -// -// Author: -// Nick Drochak(ndrochak@gol.com) -// -// (C) Nick Drochak -// Copyright (C) 2004-2005 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 System.Runtime.InteropServices; - -namespace System.Security { - - [Serializable] - [ComVisible (true)] - public enum SecurityZone { - MyComputer = 0x0, - Intranet, - Trusted, - Internet, - Untrusted, - NoZone = -1, - } -} diff --git a/mcs/class/corlib/System.Security/VerificationException.cs b/mcs/class/corlib/System.Security/VerificationException.cs deleted file mode 100644 index 4e527a65a0..0000000000 --- a/mcs/class/corlib/System.Security/VerificationException.cs +++ /dev/null @@ -1,60 +0,0 @@ -// -// System.Security.VerificationException.cs -// -// Author: -// Nick Drochak(ndrochak@gol.com) -// -// (C) Nick Drochak -// Copyright (C) 2004-2005 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 System.Globalization; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; - -namespace System.Security { - - [Serializable] - [ComVisible (true)] - public class VerificationException : SystemException { - - // Constructors - public VerificationException () - { - } - - public VerificationException (string message) - : base (message) - { - } - - protected VerificationException (SerializationInfo info, StreamingContext context) - : base (info, context) - { - } - - public VerificationException (string message, Exception innerException) - : base (message, innerException) - { - } - } -} diff --git a/mcs/class/corlib/System.Security/XmlSyntaxException.cs b/mcs/class/corlib/System.Security/XmlSyntaxException.cs deleted file mode 100644 index 8bae8dde4b..0000000000 --- a/mcs/class/corlib/System.Security/XmlSyntaxException.cs +++ /dev/null @@ -1,70 +0,0 @@ -// -// System.Security.XmlSyntaxException.cs -// -// Author: -// Nick Drochak(ndrochak@gol.com) -// -// (C) Nick Drochak -// Copyright (C) 2004-2005 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 System.Globalization; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; - -namespace System.Security { - - [Serializable] - [ComVisible (true)] - public sealed class XmlSyntaxException : SystemException { - - // Constructors - public XmlSyntaxException () - { - } - - public XmlSyntaxException (int lineNumber) - : base (String.Format (Locale.GetText ("Invalid syntax on line {0}."), lineNumber)) - { - } - - public XmlSyntaxException (int lineNumber, string message) - : base (String.Format (Locale.GetText ("Invalid syntax on line {0} - {1}."), lineNumber, message)) - { - } - - public XmlSyntaxException (string message) - : base (message) - { - } - - public XmlSyntaxException (string message, Exception inner) - : base (message, inner) - { - } - - internal XmlSyntaxException (SerializationInfo info, StreamingContext context) - : base (info, context) - { - } - } -} diff --git a/mcs/class/corlib/System.Threading/NativeOverlapped.cs b/mcs/class/corlib/System.Threading/NativeOverlapped.cs deleted file mode 100644 index 161a2ad0a9..0000000000 --- a/mcs/class/corlib/System.Threading/NativeOverlapped.cs +++ /dev/null @@ -1,46 +0,0 @@ -// -// System.Threading.NativeOverlapped.cs -// -// Authors: -// Dick Porter (dick@ximian.com) -// Marek Safar (marek.safar@gmail.com) -// -// (C) Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// Copyright 2012 Xamarin 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. -// - -using System.Runtime.InteropServices; - -namespace System.Threading -{ - [ComVisible (true)] - public struct NativeOverlapped - { - public IntPtr InternalLow; - public IntPtr InternalHigh; - public int OffsetLow; - public int OffsetHigh; - public IntPtr EventHandle; - } -} - diff --git a/mcs/class/corlib/System.Threading/Thread.cs b/mcs/class/corlib/System.Threading/Thread.cs index 13731672a6..9e39ce4e90 100644 --- a/mcs/class/corlib/System.Threading/Thread.cs +++ b/mcs/class/corlib/System.Threading/Thread.cs @@ -71,7 +71,7 @@ namespace System.Threading { internal int _serialized_principal_version; private IntPtr appdomain_refs; private int interruption_requested; - private IntPtr synch_cs; + private IntPtr longlived; internal bool threadpool_thread; private bool thread_interrupt_requested; /* These are used from managed code */ diff --git a/mcs/class/corlib/System.Threading/Timer.cs b/mcs/class/corlib/System.Threading/Timer.cs index 25a446599d..368fa667ba 100644 --- a/mcs/class/corlib/System.Threading/Timer.cs +++ b/mcs/class/corlib/System.Threading/Timer.cs @@ -66,7 +66,7 @@ namespace System.Threading public sealed class Timer : MarshalByRefObject, IDisposable { - static readonly Scheduler scheduler = Scheduler.Instance; + static Scheduler scheduler => Scheduler.Instance; #region Timer instance fields TimerCallback callback; object state; @@ -223,7 +223,7 @@ namespace System.Threading } sealed class Scheduler { - static Scheduler instance; + static readonly Scheduler instance = new Scheduler (); SortedList list; #if WASM @@ -280,12 +280,6 @@ namespace System.Threading } #endif - - static Scheduler () - { - instance = new Scheduler (); - } - public static Scheduler Instance { get { return instance; } } diff --git a/mcs/class/corlib/System/BitConverter.cs b/mcs/class/corlib/System/BitConverter.cs new file mode 100644 index 0000000000..67aa078ede --- /dev/null +++ b/mcs/class/corlib/System/BitConverter.cs @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.CompilerServices; + +namespace System +{ + public static partial class BitConverter + { + [Intrinsic] + public static readonly bool IsLittleEndian; + + static BitConverter () + { + unsafe { + ushort i = 0x1234; + byte *b = (byte*)&i; + IsLittleEndian = (*b == 0x34); + } + } + } +} diff --git a/mcs/class/corlib/System/Delegate.cs b/mcs/class/corlib/System/Delegate.cs index 698d7cc0d6..dadeccaa71 100644 --- a/mcs/class/corlib/System/Delegate.cs +++ b/mcs/class/corlib/System/Delegate.cs @@ -229,7 +229,7 @@ namespace System } if (!argLengthMatch) { if (throwOnBindFailure) - throw new ArgumentException ("method argument length mismatch"); + throw new TargetParameterCountException ("Parameter count mismatch."); else return null; } diff --git a/mcs/class/corlib/System/MonoCustomAttrs.cs b/mcs/class/corlib/System/MonoCustomAttrs.cs index 7a6c06c268..15a4688d22 100644 --- a/mcs/class/corlib/System/MonoCustomAttrs.cs +++ b/mcs/class/corlib/System/MonoCustomAttrs.cs @@ -71,16 +71,15 @@ namespace System internal static object[] GetPseudoCustomAttributes (ICustomAttributeProvider obj, Type attributeType) { object[] pseudoAttrs = null; - /* FIXME: Add other types */ - if (obj is MonoMethod) - pseudoAttrs = ((MonoMethod)obj).GetPseudoCustomAttributes (); - else if (obj is FieldInfo) - pseudoAttrs = ((FieldInfo)obj).GetPseudoCustomAttributes (); - else if (obj is ParameterInfo) - pseudoAttrs = ((ParameterInfo)obj).GetPseudoCustomAttributes (); - else if (obj is Type) - pseudoAttrs = GetPseudoCustomAttributes (((Type)obj)); + if (obj is MonoMethod monoMethod) + pseudoAttrs = monoMethod.GetPseudoCustomAttributes (); + else if (obj is FieldInfo fieldInfo) + pseudoAttrs = fieldInfo.GetPseudoCustomAttributes (); + else if (obj is MonoParameterInfo monoParamInfo) + pseudoAttrs = monoParamInfo.GetPseudoCustomAttributes (); + else if (obj is Type t) + pseudoAttrs = GetPseudoCustomAttributes (t); if ((attributeType != null) && (pseudoAttrs != null)) { for (int i = 0; i < pseudoAttrs.Length; ++i) @@ -461,14 +460,14 @@ namespace System CustomAttributeData[] pseudoAttrsData = null; /* FIXME: Add other types */ - if (obj is MonoMethod) - pseudoAttrsData = ((MonoMethod)obj).GetPseudoCustomAttributesData (); - else if (obj is FieldInfo) - pseudoAttrsData = ((FieldInfo)obj).GetPseudoCustomAttributesData (); - else if (obj is ParameterInfo) - pseudoAttrsData = ((ParameterInfo)obj).GetPseudoCustomAttributesData (); - else if (obj is Type) - pseudoAttrsData = GetPseudoCustomAttributesData (((Type)obj)); + if (obj is MonoMethod monoMethod) + pseudoAttrsData = monoMethod.GetPseudoCustomAttributesData (); + else if (obj is FieldInfo fieldInfo) + pseudoAttrsData = fieldInfo.GetPseudoCustomAttributesData (); + else if (obj is MonoParameterInfo monoParamInfo) + pseudoAttrsData = monoParamInfo.GetPseudoCustomAttributesData (); + else if (obj is Type t) + pseudoAttrsData = GetPseudoCustomAttributesData (t); if ((attributeType != null) && (pseudoAttrsData != null)) { for (int i = 0; i < pseudoAttrsData.Length; ++i) { diff --git a/mcs/class/corlib/Test/Microsoft.Win32/RegistryKeyTest.cs.REMOVED.git-id b/mcs/class/corlib/Test/Microsoft.Win32/RegistryKeyTest.cs.REMOVED.git-id index 072259398c..1ba6ec9c32 100644 --- a/mcs/class/corlib/Test/Microsoft.Win32/RegistryKeyTest.cs.REMOVED.git-id +++ b/mcs/class/corlib/Test/Microsoft.Win32/RegistryKeyTest.cs.REMOVED.git-id @@ -1 +1 @@ -bef88b0c599515481b21854be4e0073c3fea3617 \ No newline at end of file +d5529557985b2dfc14eb9efc721ef19175f2d627 \ No newline at end of file diff --git a/mcs/class/corlib/Test/Mono/NativePlatformTest.cs b/mcs/class/corlib/Test/Mono/NativePlatformTest.cs new file mode 100644 index 0000000000..3e594b7ba9 --- /dev/null +++ b/mcs/class/corlib/Test/Mono/NativePlatformTest.cs @@ -0,0 +1,69 @@ +using System; +using System.Reflection; +using NUnit.Framework; +using Mono; + +namespace MonoTests.Mono +{ + [TestFixture] + public class NativePlatformTest + { +#if WIN_PLATFORM + [TestFixtureSetUp] + public void SetUp () + { + Assert.Ignore ("Mono.Native is not supported on this platform."); + } +#endif + + [Test] + public void PlatformType () + { + var type = MonoNativePlatform.GetPlatformType (); + Assert.That ((int)type, Is.GreaterThan (0), "platform type"); + } + + [Test] + public void TestInitialize () + { + MonoNativePlatform.Initialize (); + var initialized = MonoNativePlatform.IsInitialized (); + Assert.IsTrue (initialized, "MonoNativePlatform.IsInitialized()"); + } + + [Test] + public void TestReflectionInitialize () + { + var asm = typeof (string).Assembly; + var type = asm.GetType ("Mono.MonoNativePlatform"); + Assert.IsNotNull (type, "MonoNativePlatform"); + + var method = type.GetMethod ("Initialize", BindingFlags.Static | BindingFlags.Public); + Assert.IsNotNull (method, "MonoNativePlatform.Initialize"); + + var method2 = type.GetMethod ("IsInitialized", BindingFlags.Static | BindingFlags.Public); + Assert.IsNotNull (method2, "MonoNativePlatform.IsInitialized"); + + method.Invoke (null, null); + + var result = (bool)method2.Invoke (null, null); + Assert.IsTrue (result, "MonoNativePlatform.IsInitialized()"); + } + + [Test] + public void TestInternalCounter () + { + MonoNativePlatform.Initialize (); + + var asm = typeof (string).Assembly; + var type = asm.GetType ("Mono.MonoNativePlatform"); + Assert.IsNotNull (type, "MonoNativePlatform"); + + var method = type.GetMethod ("TestInternalCounter", BindingFlags.Static | BindingFlags.NonPublic); + Assert.IsNotNull (method, "MonoNativePlatform.TestInternalCounter"); + var result = method.Invoke (null, null); + + Assert.That (result, Is.GreaterThan (0), "MonoNativePlatform.TestInternalCounter()"); + } + } +} diff --git a/mcs/class/corlib/Test/System.Diagnostics/DebuggerTypeProxyAttribute.cs b/mcs/class/corlib/Test/System.Diagnostics/DebuggerTypeProxyAttribute.cs index bd3297d3cb..c560297134 100644 --- a/mcs/class/corlib/Test/System.Diagnostics/DebuggerTypeProxyAttribute.cs +++ b/mcs/class/corlib/Test/System.Diagnostics/DebuggerTypeProxyAttribute.cs @@ -1,5 +1,5 @@ // -// DecoupledTask.cs +// DebuggerTypeProxyAttribute.cs // // Authors: // Marek Safar diff --git a/mcs/class/corlib/Test/System.Diagnostics/StackFrameTest.cs b/mcs/class/corlib/Test/System.Diagnostics/StackFrameTest.cs index fda1185315..80702246d1 100644 --- a/mcs/class/corlib/Test/System.Diagnostics/StackFrameTest.cs +++ b/mcs/class/corlib/Test/System.Diagnostics/StackFrameTest.cs @@ -12,6 +12,7 @@ using System.Diagnostics; using System.Reflection; using NUnit.Framework; using System.Runtime.ExceptionServices; +using System.Threading.Tasks; namespace MonoTests.System.Diagnostics { @@ -181,7 +182,7 @@ namespace MonoTests.System.Diagnostics frame1.GetFileLineNumber (), "Line number (1)"); - Assert.AreEqual (135, + Assert.AreEqual (136, frame2.GetFileLineNumber (), "Line number (2)"); @@ -321,7 +322,7 @@ namespace MonoTests.System.Diagnostics frame1.GetFileLineNumber (), "Line number (1)"); - Assert.AreEqual (271, + Assert.AreEqual (272, frame2.GetFileLineNumber (), "Line number (2)"); } @@ -377,6 +378,47 @@ namespace MonoTests.System.Diagnostics } } + [Test] + // https://github.com/mono/mono/issues/12688 + public void GetFrames_AsynsCalls () + { + StartAsyncCalls ().Wait (); + } + + private async Task StartAsyncCalls () + { + try + { + await AsyncMethod1 (); + } + catch (Exception exception) + { + var stackTrace = new StackTrace (exception, true); + Assert.AreEqual (25, stackTrace.GetFrames ().Length); + } + } + + private async Task AsyncMethod1 () + { + return await AsyncMethod2 (); + } + + private async Task AsyncMethod2 () + { + return await AsyncMethod3 (); + } + + private async Task AsyncMethod3 () + { + return await AsyncMethod4 (); + } + + private async Task AsyncMethod4 () + { + await Task.Delay (10); + throw new Exception ("Test exception thrown!"); + } + /// /// Tests whether getting method associated with frame works. /// diff --git a/mcs/class/corlib/Test/System.Globalization/DaylightTimeTest.cs b/mcs/class/corlib/Test/System.Globalization/DaylightTimeTest.cs index 664249597e..e2c0f01f91 100644 --- a/mcs/class/corlib/Test/System.Globalization/DaylightTimeTest.cs +++ b/mcs/class/corlib/Test/System.Globalization/DaylightTimeTest.cs @@ -65,13 +65,12 @@ namespace MonoTests.System.Globalization { } static private byte[] serialized_daylighttime = { - 0x00, 0x01, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x01, 0x00, 0x00, 0x00, 0x21, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6D, 0x2E, 0x47, 0x6C, 0x6F, 0x62, - 0x61, 0x6C, 0x69, 0x7A, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2E, 0x44, 0x61, 0x79, 0x6C, 0x69, 0x67, 0x68, - 0x74, 0x54, 0x69, 0x6D, 0x65, 0x03, 0x00, 0x00, 0x00, 0x07, 0x6D, 0x5F, 0x73, 0x74, 0x61, 0x72, 0x74, - 0x05, 0x6D, 0x5F, 0x65, 0x6E, 0x64, 0x07, 0x6D, 0x5F, 0x64, 0x65, 0x6C, 0x74, 0x61, 0x00, 0x00, 0x00, - 0x0D, 0x0D, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x3F, 0x37, 0xF4, 0x75, 0x28, - 0xCA, 0x2B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x0B + 0x0, 0x1, 0x0, 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0xFF, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x1, 0x0, 0x0, + 0x0, 0x21, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6D, 0x2E, 0x47, 0x6C, 0x6F, 0x62, 0x61, 0x6C, 0x69, 0x7A, 0x61, + 0x74, 0x69, 0x6F, 0x6E, 0x2E, 0x44, 0x61, 0x79, 0x6C, 0x69, 0x67, 0x68, 0x74, 0x54, 0x69, 0x6D, 0x65, 0x3, + 0x0, 0x0, 0x0, 0x6, 0x5F, 0x73, 0x74, 0x61, 0x72, 0x74, 0x4, 0x5F, 0x65, 0x6E, 0x64, 0x6, 0x5F, 0x64, 0x65, + 0x6C, 0x74, 0x61, 0x0, 0x0, 0x0, 0xD, 0xD, 0xC, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3F, 0x37, + 0xF4, 0x75, 0x28, 0xCA, 0x2B, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0xB }; [Test] diff --git a/mcs/class/corlib/Test/System.IO/BinaryReaderTest.cs b/mcs/class/corlib/Test/System.IO/BinaryReaderTest.cs index aac304e5c7..8a7d183818 100644 --- a/mcs/class/corlib/Test/System.IO/BinaryReaderTest.cs +++ b/mcs/class/corlib/Test/System.IO/BinaryReaderTest.cs @@ -649,8 +649,10 @@ namespace MonoTests.System.IO Assert.AreEqual (1, reader.Read (), "test#03"); Assert.AreEqual (2, reader.PeekChar (), "test#03"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -687,8 +689,10 @@ namespace MonoTests.System.IO reader.Close (); reader.PeekChar (); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -706,8 +710,10 @@ namespace MonoTests.System.IO reader.Close (); reader.ReadBytes (1); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -727,8 +733,10 @@ namespace MonoTests.System.IO reader.Close (); Assert.AreEqual (null, reader.BaseStream, "test#03"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -767,8 +775,10 @@ namespace MonoTests.System.IO Assert.AreEqual (0, bytes [0], "test#10"); Assert.AreEqual (0, bytes [1], "test#11"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -804,8 +814,10 @@ namespace MonoTests.System.IO Assert.AreEqual (0, chars [0], "test#08"); Assert.AreEqual (0, chars [1], "test#09"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -827,8 +839,10 @@ namespace MonoTests.System.IO Assert.AreEqual (false, reader.ReadBoolean (), "test#04"); Assert.AreEqual (true, reader.ReadBoolean (), "test#05"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -848,8 +862,10 @@ namespace MonoTests.System.IO reader.ReadBoolean (); reader.ReadBoolean (); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -872,8 +888,10 @@ namespace MonoTests.System.IO Assert.AreEqual (0, reader.ReadByte (), "test#04"); Assert.AreEqual (13, reader.ReadByte (), "test#05"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -894,8 +912,10 @@ namespace MonoTests.System.IO reader.ReadByte (); reader.ReadByte (); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -925,8 +945,10 @@ namespace MonoTests.System.IO Assert.AreEqual (1, bytes.Length, "test#06"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -945,8 +967,10 @@ namespace MonoTests.System.IO reader = new BinaryReader (stream); reader.ReadBytes (-1); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -968,8 +992,10 @@ namespace MonoTests.System.IO Assert.AreEqual (0, reader.ReadChar (), "test#04"); Assert.AreEqual (13, reader.ReadChar (), "test#05"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -990,8 +1016,10 @@ namespace MonoTests.System.IO reader.ReadChar (); reader.ReadChar (); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1018,8 +1046,10 @@ namespace MonoTests.System.IO Assert.AreEqual (13, chars [0], "test#05"); Assert.AreEqual (1, chars.Length, "test#06"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1037,8 +1067,10 @@ namespace MonoTests.System.IO reader = new BinaryReader (stream); reader.ReadChars (-1); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1056,8 +1088,10 @@ namespace MonoTests.System.IO reader = new BinaryReader (stream); Assert.AreEqual (-18295873486192640, reader.ReadDecimal (), "test#01"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1071,8 +1105,10 @@ namespace MonoTests.System.IO reader.ReadDecimal (); reader.ReadDecimal (); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1085,8 +1121,10 @@ namespace MonoTests.System.IO Assert.AreEqual (1.8913127797311212E-307d, reader.ReadDouble (), "test#01"); Assert.AreEqual (1.2024538023802026E+111d, reader.ReadDouble (), "test#02"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1117,8 +1155,10 @@ namespace MonoTests.System.IO Assert.AreEqual (773, reader.ReadInt16 (), "test#03"); Assert.AreEqual (54, reader.ReadInt16 (), "test#04"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1132,8 +1172,10 @@ namespace MonoTests.System.IO reader.ReadInt16 (); reader.ReadInt16 (); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1146,8 +1188,10 @@ namespace MonoTests.System.IO Assert.AreEqual (723517761, reader.ReadInt32 (), "test#01"); Assert.AreEqual (3539717, reader.ReadInt32 (), "test#02"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1161,8 +1205,10 @@ namespace MonoTests.System.IO reader.ReadInt32 (); reader.ReadInt32 (); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1175,8 +1221,10 @@ namespace MonoTests.System.IO Assert.AreEqual (15202969475612993, reader.ReadInt64 (), "test#01"); Assert.AreEqual (2471354792417887522, reader.ReadInt64 (), "test#02"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1192,8 +1240,10 @@ namespace MonoTests.System.IO reader.ReadInt64 (); reader.ReadInt64 (); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1208,8 +1258,10 @@ namespace MonoTests.System.IO Assert.AreEqual (-56, reader.ReadSByte (), "test#02"); Assert.AreEqual (32, reader.ReadSByte (), "test#03"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1225,8 +1277,10 @@ namespace MonoTests.System.IO reader.ReadSByte (); reader.ReadSByte (); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1255,8 +1309,10 @@ namespace MonoTests.System.IO reader.ReadSingle (); reader.ReadSingle (); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } @@ -1275,8 +1331,10 @@ namespace MonoTests.System.IO Assert.AreEqual ("mo", reader.ReadString (), "test#02"); Assert.AreEqual ("o::", reader.ReadString (), "test#03"); } finally { - reader.Close (); - stream.Close (); + if (reader != null) + reader.Close (); + if (stream != null) + stream.Close (); } } diff --git a/mcs/class/corlib/Test/System.IO/FileTest.cs b/mcs/class/corlib/Test/System.IO/FileTest.cs index 943ad91c6b..bbc88cefe9 100644 --- a/mcs/class/corlib/Test/System.IO/FileTest.cs +++ b/mcs/class/corlib/Test/System.IO/FileTest.cs @@ -2774,7 +2774,7 @@ namespace MonoTests.System.IO public static extern int symlink (string oldpath, string newpath); [Test] -#if __TVOS__ +#if MONOTOUCH_TV [Ignore ("See bug #59239")] #endif public void SymLinkLoop () diff --git a/mcs/class/corlib/Test/System.IO/StreamReaderTest.cs b/mcs/class/corlib/Test/System.IO/StreamReaderTest.cs index f916c57a6a..ea336828a7 100644 --- a/mcs/class/corlib/Test/System.IO/StreamReaderTest.cs +++ b/mcs/class/corlib/Test/System.IO/StreamReaderTest.cs @@ -13,6 +13,8 @@ using System.Threading.Tasks; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.IO { [TestFixture] @@ -780,7 +782,7 @@ public class StreamReaderTest [Category ("MobileNotWorking")] public void EndOfBufferIsCR () { - using (StreamReader reader = new StreamReader ("Test/resources/Fergie.GED")) { + using (StreamReader reader = new StreamReader (TestResourceHelper.GetFullPathOfResource ("Test/resources/Fergie.GED"))) { string line; int count = 0; while ((line = reader.ReadLine ()) != null) { diff --git a/mcs/class/corlib/Test/System.Reflection/AssemblyTest.cs b/mcs/class/corlib/Test/System.Reflection/AssemblyTest.cs index 208318c173..2717b8541a 100644 --- a/mcs/class/corlib/Test/System.Reflection/AssemblyTest.cs +++ b/mcs/class/corlib/Test/System.Reflection/AssemblyTest.cs @@ -195,7 +195,7 @@ namespace MonoTests.System.Reflection // note: only available in default appdomain // http://weblogs.asp.net/asanto/archive/2003/09/08/26710.aspx // Not sure we should emulate this behavior. -#if __WATCHOS__ +#if MONOTOUCH_WATCH Assert.IsNull (Assembly.GetEntryAssembly (), "GetEntryAssembly"); Assert.IsTrue (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain"); #elif !MONODROID diff --git a/mcs/class/corlib/Test/System.Reflection/CustomAttributeDataTest.cs b/mcs/class/corlib/Test/System.Reflection/CustomAttributeDataTest.cs index 925b31e3cd..560c0a4f11 100644 --- a/mcs/class/corlib/Test/System.Reflection/CustomAttributeDataTest.cs +++ b/mcs/class/corlib/Test/System.Reflection/CustomAttributeDataTest.cs @@ -29,20 +29,60 @@ using NUnit.Framework; using System; +using System.Linq; using System.Reflection; using System.Collections.Generic; using System.Runtime.InteropServices; namespace MonoTests.System.Reflection { + enum Levels { one, two, three } + class Attr : Attribute { public Attr (byte[] arr) { } } + [AttributeUsage (AttributeTargets.Method)] + class TestAttrWithObjectCtorParam : Attribute { + object o; + public TestAttrWithObjectCtorParam (object o) => this.o = o; + } + + [AttributeUsage (AttributeTargets.Method)] + class TestAttrWithEnumCtorParam : Attribute { + Levels level; + public TestAttrWithEnumCtorParam (Levels level) => this.level = level; + } + + [AttributeUsage (AttributeTargets.Method)] + class TestAttrWithObjectArrayCtorParam : Attribute { + object[] o; + public TestAttrWithObjectArrayCtorParam (object[] o) => this.o = o; + } + + [AttributeUsage (AttributeTargets.Method)] + class TestAttrWithObjectArrayCtorParamAndParamsKeyword : Attribute { + object[] o; + public TestAttrWithObjectArrayCtorParamAndParamsKeyword (params object[] o) => this.o = o; + } + + [AttributeUsage (AttributeTargets.Method)] + class TestAttrWithObjectArrayCtorParams : Attribute { + object[] o1; + object[] o2; + public TestAttrWithObjectArrayCtorParams (object[] o1, params object[] o2) { + this.o1 = o1; + this.o2 = o2; + } + } + [TestFixture] public class CustomAttributeDataTest { + [DllImport ("libc")] + public static extern void pinvoke (); + [MarshalAs (UnmanagedType.LPStr)] [NonSerialized] public string fieldDecoratedWithPseudoCustomAttributes = "test"; @@ -51,6 +91,31 @@ namespace MonoTests.System.Reflection public void MethodWithAttr () { } + [TestAttrWithObjectCtorParam (Levels.two)] + public void MethodDecoratedWithAttribute1 () + { + } + + [TestAttrWithEnumCtorParam (Levels.two)] + public void MethodDecoratedWithAttribute2 () + { + } + + [TestAttrWithObjectArrayCtorParam (new object[] { Levels.one, Levels.two})] + public void MethodDecoratedWithAttribute3 () + { + } + + [TestAttrWithObjectArrayCtorParamAndParamsKeyword (Levels.one, Levels.two)] + public void MethodDecoratedWithAttribute4 () + { + } + + [TestAttrWithObjectArrayCtorParams (new object[] { Levels.one, Levels.two}, Levels.three, Levels.two)] + public void MethodDecoratedWithAttribute5 () + { + } + public void MethodWithParamDecoratedWithPseudoCustomAttributes ([Optional, In, Out, MarshalAs (UnmanagedType.LPStr)] String s) { } @@ -62,7 +127,6 @@ namespace MonoTests.System.Reflection } [Test] - [Category ("MobileNotWorking")] // #10263 public void Arrays () { IList cdata = CustomAttributeData.GetCustomAttributes (typeof (CustomAttributeDataTest).GetMethod ("MethodWithAttr")); Assert.AreEqual (1, cdata.Count); @@ -75,6 +139,78 @@ namespace MonoTests.System.Reflection Assert.AreEqual (typeof (byte), arr [1].ArgumentType); Assert.AreEqual (2, arr [1].Value); } + + [Test] + // https://github.com/mono/mono/issues/10951 + public void ObjectArrays () + { + CheckObjectArrayParam (nameof (MethodDecoratedWithAttribute3)); + CheckObjectArrayParam (nameof (MethodDecoratedWithAttribute4)); + } + + private void CheckObjectArrayParam (string methodName) + { + IList cdata = CustomAttributeData.GetCustomAttributes (typeof (CustomAttributeDataTest).GetMethod (methodName)); + Assert.AreEqual (1, cdata.Count, $"{methodName}#0"); + + CustomAttributeTypedArgument arg = cdata [0].ConstructorArguments [0]; + Assert.IsTrue (typeof (IList).IsAssignableFrom (arg.Value.GetType ()), $"{methodName}#1"); + + IList arr = (IList)arg.Value; + Assert.AreEqual (2, arr.Count, $"{methodName}#2"); + + Assert.AreEqual (typeof (Levels), arr [0].ArgumentType, $"{methodName}#3"); + Assert.IsTrue (arr [0].ArgumentType.GetTypeInfo().IsEnum, $"{methodName}#4"); + Assert.AreEqual (0, arr [0].Value, $"{methodName}#5"); + Assert.AreEqual (typeof (int), arr [0].Value.GetType (), $"{methodName}#6"); + + Assert.AreEqual (typeof (Levels), arr [1].ArgumentType, $"{methodName}#7"); + Assert.IsTrue (arr [1].ArgumentType.GetTypeInfo().IsEnum, $"{methodName}#8"); + Assert.AreEqual (1, arr [1].Value, $"{methodName}#9"); + Assert.AreEqual (typeof (int), arr [1].Value.GetType (), $"{methodName}#10"); + } + + [Test] + // https://github.com/mono/mono/issues/10951 + public void CheckObjectArrayParams () + { + string methodName = nameof (MethodDecoratedWithAttribute5); + IList cdata = CustomAttributeData.GetCustomAttributes (typeof (CustomAttributeDataTest).GetMethod (methodName)); + Assert.AreEqual (1, cdata.Count, $"{methodName}#0"); + Assert.AreEqual (2, cdata [0].ConstructorArguments.Count, $"{methodName}#00"); + + CustomAttributeTypedArgument arg = cdata [0].ConstructorArguments [0]; + Assert.IsTrue (typeof (IList).IsAssignableFrom (arg.Value.GetType ()), $"{methodName}#1"); + + IList arr = (IList)arg.Value; + Assert.AreEqual (2, arr.Count, $"{methodName}#2"); + + Assert.AreEqual (typeof (Levels), arr [0].ArgumentType, $"{methodName}#3"); + Assert.IsTrue (arr [0].ArgumentType.GetTypeInfo().IsEnum, $"{methodName}#4"); + Assert.AreEqual (0, arr [0].Value, $"{methodName}#5"); + Assert.AreEqual (typeof (int), arr [0].Value.GetType (), $"{methodName}#6"); + + Assert.AreEqual (typeof (Levels), arr [1].ArgumentType, $"{methodName}#7"); + Assert.IsTrue (arr [1].ArgumentType.GetTypeInfo().IsEnum, $"{methodName}#8"); + Assert.AreEqual (1, arr [1].Value, $"{methodName}#9"); + Assert.AreEqual (typeof (int), arr [1].Value.GetType (), $"{methodName}#10"); + + arg = cdata [0].ConstructorArguments [1]; + Assert.IsTrue (typeof (IList).IsAssignableFrom (arg.Value.GetType ()), $"{methodName}#11"); + + arr = (IList)arg.Value; + Assert.AreEqual (2, arr.Count, $"{methodName}#12"); + + Assert.AreEqual (typeof (Levels), arr [0].ArgumentType, $"{methodName}#13"); + Assert.IsTrue (arr [0].ArgumentType.GetTypeInfo().IsEnum, $"{methodName}#14"); + Assert.AreEqual (2, arr [0].Value, $"{methodName}#15"); + Assert.AreEqual (typeof (int), arr [0].Value.GetType (), $"{methodName}#16"); + + Assert.AreEqual (typeof (Levels), arr [1].ArgumentType, $"{methodName}#17"); + Assert.IsTrue (arr [1].ArgumentType.GetTypeInfo().IsEnum, $"{methodName}#18"); + Assert.AreEqual (1, arr [1].Value, $"{methodName}#19"); + Assert.AreEqual (typeof (int), arr [1].Value.GetType (), $"{methodName}#20"); + } [Test] public void ParameterIncludesPseudoCustomAttributesData () @@ -86,19 +222,19 @@ namespace MonoTests.System.Reflection Assert.AreEqual (4, customAttributesData.Count); var inAttributeData = customAttributesData [0]; - var optionalAttributeData = customAttributesData [1]; - var outAttributeData = customAttributesData [2]; + var outAttributeData = customAttributesData [1]; + var optionalAttributeData = customAttributesData [2]; var marshalAsAttributeData = customAttributesData [3]; var marshalAsAttributeCtorArg = marshalAsAttributeData.ConstructorArguments [0]; Assert.AreEqual (typeof (InAttribute), inAttributeData.AttributeType); - Assert.AreEqual (typeof (OptionalAttribute), optionalAttributeData.AttributeType); Assert.AreEqual (typeof (OutAttribute), outAttributeData.AttributeType); + Assert.AreEqual (typeof (OptionalAttribute), optionalAttributeData.AttributeType); Assert.AreEqual (typeof (MarshalAsAttribute), marshalAsAttributeData.AttributeType); Assert.AreEqual (typeof (UnmanagedType), marshalAsAttributeCtorArg.ArgumentType); - Assert.AreEqual (UnmanagedType.LPStr, marshalAsAttributeCtorArg.Value); + Assert.AreEqual ((int)UnmanagedType.LPStr, marshalAsAttributeCtorArg.Value); } [Test] @@ -116,7 +252,7 @@ namespace MonoTests.System.Reflection Assert.AreEqual (typeof (NonSerializedAttribute), nonSerializedAttributeData.AttributeType); Assert.AreEqual (typeof (MarshalAsAttribute), marshalAsAttributeData.AttributeType); Assert.AreEqual (typeof (UnmanagedType), marshalAsAttributeDataCtorArg.ArgumentType); - Assert.AreEqual (UnmanagedType.LPStr, marshalAsAttributeDataCtorArg.Value); + Assert.AreEqual ((int)UnmanagedType.LPStr, marshalAsAttributeDataCtorArg.Value); } [Test] @@ -131,7 +267,52 @@ namespace MonoTests.System.Reflection Assert.AreEqual (1, customAttributesData.Count); Assert.AreEqual (typeof (MarshalAsAttribute), marshalAsAttributeData.AttributeType); Assert.AreEqual (typeof (UnmanagedType), ctorArg.ArgumentType); - Assert.AreEqual (UnmanagedType.LPStr, ctorArg.Value); + Assert.AreEqual ((int)UnmanagedType.LPStr, ctorArg.Value); + } + + [Test] + // https://github.com/mono/mono/issues/10544 + public void MethodIncludesDllImportAttributeData () + { + var mi = typeof (CustomAttributeDataTest).FindMembers (MemberTypes.Method, BindingFlags.Static | BindingFlags.Public, (m, criteria) => m.Name == "pinvoke", null); + var data = ((MethodInfo)(mi[0])).CustomAttributes; + + Assert.AreEqual (2, data.Count ()); + + Assert.AreEqual (typeof (PreserveSigAttribute), data.First ().AttributeType); + + var dllImportAttributeData = data.Last (); + var ctorArg = dllImportAttributeData.ConstructorArguments [0]; + + Assert.AreEqual (typeof (DllImportAttribute), dllImportAttributeData.AttributeType); + Assert.AreEqual ("libc", ctorArg.Value); + } + + [Test] + // https://github.com/mono/mono/issues/10555 + public void CustomAttributeCtor_TakesEnumArg () + { + var method = GetMethod (nameof (MethodDecoratedWithAttribute1)); + var data = method.CustomAttributes; + var ctorArg = data.First ().ConstructorArguments [0]; + + Assert.AreEqual (typeof (Levels), ctorArg.ArgumentType); + Assert.AreEqual (1, ctorArg.Value); + Assert.AreEqual (typeof (int), ctorArg.Value.GetType ()); + + method = GetMethod (nameof (MethodDecoratedWithAttribute2)); + data = method.CustomAttributes; + ctorArg = data.First ().ConstructorArguments [0]; + + Assert.AreEqual (typeof (Levels), ctorArg.ArgumentType); + Assert.AreEqual (1, ctorArg.Value); + Assert.AreEqual (typeof (int), ctorArg.Value.GetType ()); + } + + private MethodInfo GetMethod (string methodName) + { + var mi = typeof (CustomAttributeDataTest).FindMembers (MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public, (m, criteria) => m.Name == methodName, null); + return (MethodInfo)(mi [0]); } } } diff --git a/mcs/class/corlib/Test/System.Reflection/EventInfoTest.cs b/mcs/class/corlib/Test/System.Reflection/EventInfoTest.cs index 311bf0f56a..faddd7b03f 100644 --- a/mcs/class/corlib/Test/System.Reflection/EventInfoTest.cs +++ b/mcs/class/corlib/Test/System.Reflection/EventInfoTest.cs @@ -123,6 +123,13 @@ namespace MonoTests.System.Reflection Assert.AreEqual (type.Module, ev.Module); } + [Test] + public void MetadataToken () + { + EventInfo ev = typeof (TestClass).GetEvent ("pub"); + Assert.IsTrue ((int)ev.MetadataToken > 0); + } + #pragma warning disable 67 public class PrivateEvent { diff --git a/mcs/class/corlib/Test/System.Reflection/FieldInfoTest.cs b/mcs/class/corlib/Test/System.Reflection/FieldInfoTest.cs index 2a73eecbac..d21482dd20 100644 --- a/mcs/class/corlib/Test/System.Reflection/FieldInfoTest.cs +++ b/mcs/class/corlib/Test/System.Reflection/FieldInfoTest.cs @@ -29,6 +29,7 @@ // using System; +using System.Globalization; using System.Threading; using System.Reflection; #if !MONOTOUCH && !FULL_AOT_RUNTIME @@ -224,6 +225,14 @@ namespace MonoTests.System.Reflection Assert.AreEqual (typeof (ObsoleteAttribute), attrs [0].GetType (), "#D10"); } + [Test] + public void MetadataToken () + { + Type type = typeof (FieldInfoTest); + FieldInfo field = type.GetField ("i"); + Assert.IsTrue ((int)field.MetadataToken > 0); + } + [Test] // GetFieldFromHandle (RuntimeFieldHandle) public void GetFieldFromHandle1_Handle_Zero () { @@ -1455,6 +1464,41 @@ namespace MonoTests.System.Reflection public const FieldInfoTest object_field = null; public int non_const_field; + class FieldInfoWrapper : FieldInfo + { + private FieldInfo fieldInfo; + + public FieldInfoWrapper (FieldInfo fieldInfo) + { + this.fieldInfo = fieldInfo; + } + + public override FieldAttributes Attributes => fieldInfo.Attributes; + public override Type DeclaringType => fieldInfo.DeclaringType; + public override RuntimeFieldHandle FieldHandle => fieldInfo.FieldHandle; + public override Type FieldType => fieldInfo.FieldType; + public override string Name => fieldInfo.Name; + public override Type ReflectedType => fieldInfo.ReflectedType; + + public override object[] GetCustomAttributes (bool inherit) => fieldInfo.GetCustomAttributes (inherit); + public override object[] GetCustomAttributes (Type attributeType, bool inherit) => fieldInfo.GetCustomAttributes (attributeType, inherit); + public override object GetValue (object obj) => fieldInfo.GetValue (obj); + public override bool IsDefined (Type attributeType, bool inherit) => fieldInfo.IsDefined (attributeType, inherit); + public override void SetValue (object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) => + fieldInfo.SetValue (obj, value, invokeAttr, binder, culture); + } + + [Test] + public void CustomFieldInfo () + { + var fieldInfoWrapper = new FieldInfoWrapper (GetType ().GetField (nameof (non_const_field))); + MethodInfo method = typeof (FieldInfoWrapper).GetMethod ("GetFieldOffset", BindingFlags.NonPublic | BindingFlags.Instance); + Assert.IsNotNull (method); + Assert.IsTrue (method.IsVirtual); + + var ex = Assert.Catch (() => method.Invoke (fieldInfoWrapper, new object[] {})); + Assert.IsTrue (ex.InnerException is SystemException); + } } // We do not refernece the field, that is expected diff --git a/mcs/class/corlib/Test/System.Reflection/ModuleTest.cs b/mcs/class/corlib/Test/System.Reflection/ModuleTest.cs index 3bb1af7f03..e45e4647db 100644 --- a/mcs/class/corlib/Test/System.Reflection/ModuleTest.cs +++ b/mcs/class/corlib/Test/System.Reflection/ModuleTest.cs @@ -317,6 +317,13 @@ public class ModuleTest Assert.AreEqual (method, res, "#1"); } + [Test] + public void ResolveInvalidMember () // https://github.com/mono/mono/issues/9604 + { + Module m = typeof (ModuleTest).Module; + Assert.Throws (() => m.ResolveMember(0x0A00F000)); + } + [Test] public void FindTypes () { diff --git a/mcs/class/corlib/Test/System.Reflection/ParameterInfoTest.cs b/mcs/class/corlib/Test/System.Reflection/ParameterInfoTest.cs index eee45b0b7b..8368512781 100644 --- a/mcs/class/corlib/Test/System.Reflection/ParameterInfoTest.cs +++ b/mcs/class/corlib/Test/System.Reflection/ParameterInfoTest.cs @@ -507,6 +507,26 @@ namespace MonoTests.System.Reflection Assert.AreEqual (expected, actual, "#1"); } + public class Dummy { + public void M1 (decimal? arg = 12.345M) { } + public void M2 ([Optional, DecimalConstant (1, 2, 3, 4, 5)] decimal? arg) { } + public void M3 (decimal? arg = null) { } + public void M4 ([Optional, DateTimeConstant (1L)] DateTime? arg) { } + public void M5 (DateTime? arg = null) { } + } + + [Test] + // https://github.com/mono/mono/issues/11303 + public void RawDefaultValue_Nullable () + { + var type = typeof (Dummy); + Assert.AreEqual (12.345M, type.GetMethod("M1").GetParameters () [0].RawDefaultValue); + Assert.AreEqual (new DecimalConstantAttribute (1, 2, 3, 4, 5).Value, type.GetMethod ("M2").GetParameters () [0].RawDefaultValue); + Assert.AreEqual (null, type.GetMethod ("M3").GetParameters () [0].RawDefaultValue); + Assert.AreEqual (new DateTime (1), type.GetMethod ("M4").GetParameters () [0].RawDefaultValue); + Assert.AreEqual (null, type.GetMethod ("M5").GetParameters () [0].RawDefaultValue); + } + [Test] public void ReturnParameter_IsDefined_False () { diff --git a/mcs/class/corlib/Test/System.Reflection/PropertyInfoTest.cs b/mcs/class/corlib/Test/System.Reflection/PropertyInfoTest.cs index 5163fef438..3ce24eb9c5 100644 --- a/mcs/class/corlib/Test/System.Reflection/PropertyInfoTest.cs +++ b/mcs/class/corlib/Test/System.Reflection/PropertyInfoTest.cs @@ -560,5 +560,12 @@ namespace MonoTests.System.Reflection Assert.AreEqual ("param", defaultParam.Name, "#1"); Assert.AreEqual ("test", defaultParam.DefaultValue, "#2"); } + + [Test] + public void MetadataToken () + { + PropertyInfo property = typeof (Base).GetProperty ("P"); + Assert.IsTrue ((int)property.MetadataToken > 0); + } } } diff --git a/mcs/class/corlib/Test/System.Resources/ResourceManagerTest.cs b/mcs/class/corlib/Test/System.Resources/ResourceManagerTest.cs index 9d2292bcfa..176191482a 100644 --- a/mcs/class/corlib/Test/System.Resources/ResourceManagerTest.cs +++ b/mcs/class/corlib/Test/System.Resources/ResourceManagerTest.cs @@ -41,6 +41,8 @@ using System.IO; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Resources { [TestFixture] @@ -350,7 +352,7 @@ namespace MonoTests.System.Resources public void CreateFileBasedResourceManager_BaseName_Resources () { ResourceManager rm = ResourceManager.CreateFileBasedResourceManager ( - "MyResources.resources", "Test/resources", null); + "MyResources.resources", TestResourceHelper.GetFullPathOfResource ("Test/resources"), null); try { rm.GetResourceSet (CultureInfo.InvariantCulture, true, true); Assert.Fail ("#1"); @@ -385,7 +387,7 @@ namespace MonoTests.System.Resources public void CreateFileBasedResourceManager_UsingResourceSet_Invalid () { ResourceManager rm = ResourceManager.CreateFileBasedResourceManager ( - "MyResources", "Test/resources", typeof (string)); + "MyResources", TestResourceHelper.GetFullPathOfResource ("Test/resources"), typeof (string)); Assert.IsNotNull (rm.BaseName, "#1"); Assert.AreEqual ("MyResources", rm.BaseName, "#2"); Assert.IsFalse (rm.IgnoreCase, "#3"); @@ -397,7 +399,7 @@ namespace MonoTests.System.Resources public void CreateFileBasedResourceManager_UsingResourceSet_Null () { ResourceManager rm = ResourceManager.CreateFileBasedResourceManager ( - "MyResources", "Test/resources", (Type) null); + "MyResources", TestResourceHelper.GetFullPathOfResource ("Test/resources"), (Type) null); Assert.IsNotNull (rm.BaseName, "#1"); Assert.AreEqual ("MyResources", rm.BaseName, "#2"); Assert.IsFalse (rm.IgnoreCase, "#3"); @@ -412,7 +414,7 @@ namespace MonoTests.System.Resources public void GetObject () { ResourceManager rm = ResourceManager. - CreateFileBasedResourceManager ("MyResources", "Test/resources", null); + CreateFileBasedResourceManager ("MyResources", TestResourceHelper.GetFullPathOfResource ("Test/resources"), null); Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; Assert.AreEqual ("Hello World", rm.GetObject ("HelloWorld"), "#A1"); @@ -474,7 +476,7 @@ namespace MonoTests.System.Resources { Thread.CurrentThread.CurrentUICulture = new CultureInfo ("de"); ResourceManager rm = ResourceManager. - CreateFileBasedResourceManager ("MyResources", "Test/resources", null); + CreateFileBasedResourceManager ("MyResources", TestResourceHelper.GetFullPathOfResource ("Test/resources"), null); ResourceSet rs = rm.GetResourceSet (new CultureInfo ("de"), true, true); rs.Dispose (); @@ -545,7 +547,7 @@ namespace MonoTests.System.Resources public void GetString () { ResourceManager rm = ResourceManager. - CreateFileBasedResourceManager ("MyResources", "Test/resources", null); + CreateFileBasedResourceManager ("MyResources", TestResourceHelper.GetFullPathOfResource ("Test/resources"), null); Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; Assert.AreEqual ("Hello World", rm.GetString ("HelloWorld"), "#A1"); @@ -607,7 +609,7 @@ namespace MonoTests.System.Resources public void GetString_ResourceSet_Disposed () { ResourceManager rm = ResourceManager. - CreateFileBasedResourceManager ("MyResources", "Test/resources", null); + CreateFileBasedResourceManager ("MyResources", TestResourceHelper.GetFullPathOfResource ("Test/resources"), null); ResourceSet rs = rm.GetResourceSet (new CultureInfo ("de"), true, true); rs.Dispose (); @@ -622,7 +624,7 @@ namespace MonoTests.System.Resources { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; ResourceManager rm = ResourceManager. - CreateFileBasedResourceManager ("StreamTest", "Test/resources", null); + CreateFileBasedResourceManager ("StreamTest", TestResourceHelper.GetFullPathOfResource ("Test/resources"), null); UnmanagedMemoryStream s = rm.GetStream ("test"); Assert.AreEqual (22, s.Length, "#A1"); Assert.AreEqual ("veritas vos liberabit\n", new StreamReader (s).ReadToEnd (), "#A2"); @@ -647,7 +649,7 @@ namespace MonoTests.System.Resources { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; ResourceManager rm = ResourceManager. - CreateFileBasedResourceManager ("StreamTest", "Test/resources", null); + CreateFileBasedResourceManager ("StreamTest", TestResourceHelper.GetFullPathOfResource ("Test/resources"), null); UnmanagedMemoryStream s = rm.GetStream ("test", new CultureInfo ("ja-JP")); Assert.AreEqual (22, s.Length, "#1"); Assert.AreEqual ("Veritas Vos Liberabit\n", new StreamReader (s).ReadToEnd (), "#2"); @@ -700,7 +702,7 @@ namespace MonoTests.System.Resources public void GetStream_Resource_DoesNotExist () { ResourceManager rm = ResourceManager. - CreateFileBasedResourceManager ("StreamTest", "Test/resources", null); + CreateFileBasedResourceManager ("StreamTest", TestResourceHelper.GetFullPathOfResource ("Test/resources"), null); Assert.IsNull (rm.GetStream ("HelloWorld")); rm.ReleaseAllResources (); } @@ -710,7 +712,7 @@ namespace MonoTests.System.Resources public void GetStream_Resource_NonStream () { ResourceManager rm = ResourceManager. - CreateFileBasedResourceManager ("MyResources", "Test/resources", null); + CreateFileBasedResourceManager ("MyResources", TestResourceHelper.GetFullPathOfResource ("Test/resources"), null); try { rm.GetStream ("HelloWorld", CultureInfo.InvariantCulture); @@ -730,7 +732,7 @@ namespace MonoTests.System.Resources public void GetStream_ResourceFile_DoesNotExist () { ResourceManager rm = ResourceManager. - CreateFileBasedResourceManager ("DoesNotExist", "Test/resources", null); + CreateFileBasedResourceManager ("DoesNotExist", TestResourceHelper.GetFullPathOfResource ("Test/resources"), null); try { rm.GetStream ("HelloWorld"); Assert.Fail ("#1"); @@ -750,7 +752,7 @@ namespace MonoTests.System.Resources { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; ResourceManager rm = ResourceManager. - CreateFileBasedResourceManager ("StreamTest", "Test/resources", null); + CreateFileBasedResourceManager ("StreamTest", TestResourceHelper.GetFullPathOfResource ("Test/resources"), null); ResourceSet rs = rm.GetResourceSet (new CultureInfo ("ja-JP"), true, true); rs.Dispose (); @@ -773,7 +775,7 @@ namespace MonoTests.System.Resources public void IgnoreCase () { ResourceManager rm = ResourceManager. - CreateFileBasedResourceManager ("MyResources", "Test/resources", null); + CreateFileBasedResourceManager ("MyResources", TestResourceHelper.GetFullPathOfResource ("Test/resources"), null); Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; Assert.IsFalse (rm.IgnoreCase, "#A1"); @@ -785,7 +787,6 @@ namespace MonoTests.System.Resources } [Test] - [Category ("SatelliteAssembliesNotWorking")] public void TestSatellites () { ResourceManager manager = new ResourceManager("Resources", GetType ().Assembly); diff --git a/mcs/class/corlib/Test/System.Resources/ResourceReaderTest.cs b/mcs/class/corlib/Test/System.Resources/ResourceReaderTest.cs index 55f00dd8be..2ec882d752 100644 --- a/mcs/class/corlib/Test/System.Resources/ResourceReaderTest.cs +++ b/mcs/class/corlib/Test/System.Resources/ResourceReaderTest.cs @@ -16,6 +16,8 @@ using System.Resources; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Resources { [TestFixture] @@ -28,9 +30,8 @@ namespace MonoTests.System.Resources [TestFixtureSetUp] public void FixtureSetUp () { - string base_path = Path.Combine (Directory.GetCurrentDirectory (), Path.Combine ("Test", "resources")); - m_ResourceFile = Path.Combine (base_path, "MyResources.resources"); - m_BadResourceFile = Path.Combine (base_path, "Empty.resources"); + m_ResourceFile = TestResourceHelper.GetFullPathOfResource ("Test/resources/MyResources.resources"); + m_BadResourceFile = TestResourceHelper.GetFullPathOfResource ("Test/resources/Empty.resources"); } [SetUp] @@ -231,7 +232,7 @@ namespace MonoTests.System.Resources [Category ("MobileNotWorking")] public void GetResourceDataNullName () { - ResourceReader r = new ResourceReader ("Test/resources/StreamTest.resources"); + ResourceReader r = new ResourceReader (TestResourceHelper.GetFullPathOfResource ("Test/resources/StreamTest.resources")); string type; byte [] bytes; @@ -257,7 +258,7 @@ namespace MonoTests.System.Resources byte [] t2 = new byte [] {0x0A, 0x73, 0x6F, 0x6D, 0x65, 0x73, 0x74, 0x72, 0x69, 0x6E, 0x67}; byte [] t3 = new byte [] {0x0E, 0x00, 0x00, 0x00, 0x73, 0x68, 0x61, 0x72, 0x64, 0x65, 0x6E, 0x66, 0x72, 0x65, 0x75, 0x64, 0x65, 0x0A}; - ResourceReader r = new ResourceReader ("Test/resources/StreamTest.resources"); + ResourceReader r = new ResourceReader (TestResourceHelper.GetFullPathOfResource ("Test/resources/StreamTest.resources")); Hashtable items = new Hashtable (); foreach (DictionaryEntry de in r) { string type; @@ -307,7 +308,7 @@ namespace MonoTests.System.Resources 0x68, 0x74, 0x00, 0x00, 0x08, 0x08, 0x02, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0B}; - ResourceReader r = new ResourceReader ("Test/resources/bug81759.resources"); + ResourceReader r = new ResourceReader (TestResourceHelper.GetFullPathOfResource ("Test/resources/bug81759.resources")); string type; byte [] bytes; r.GetResourceData ("imageList.ImageSize", out type, out bytes); diff --git a/mcs/class/corlib/Test/System.Resources/ResourceWriterTest.cs b/mcs/class/corlib/Test/System.Resources/ResourceWriterTest.cs index 3ba64bcf1e..c7d8e40026 100644 --- a/mcs/class/corlib/Test/System.Resources/ResourceWriterTest.cs +++ b/mcs/class/corlib/Test/System.Resources/ResourceWriterTest.cs @@ -16,6 +16,8 @@ using System.Text; using NUnit.Framework; +using MonoTests.Helpers; + namespace MonoTests.System.Resources { [TestFixture] @@ -356,11 +358,11 @@ namespace MonoTests.System.Resources stream.Write (buff, 0, buff.Length); stream.Position = 0; - ResourceWriter rw = new ResourceWriter ("Test/resources/AddResource_Stream.resources"); + ResourceWriter rw = new ResourceWriter (TestResourceHelper.GetFullPathOfResource ("Test/resources/AddResource_Stream.resources")); rw.AddResource ("Name", (object)stream); rw.Close (); - ResourceReader rr = new ResourceReader ("Test/resources/AddResource_Stream.resources"); + ResourceReader rr = new ResourceReader (TestResourceHelper.GetFullPathOfResource ("Test/resources/AddResource_Stream.resources")); IDictionaryEnumerator enumerator = rr.GetEnumerator (); // Get the first element @@ -587,7 +589,7 @@ namespace MonoTests.System.Resources { MemoryStream ms = new MemoryStream (); using (ResourceReader xr = new ResourceReader ( - "Test/resources/bug81759.resources")) { + TestResourceHelper.GetFullPathOfResource ("Test/resources/bug81759.resources"))) { ResourceWriter rw = new ResourceWriter (ms); foreach (DictionaryEntry de in xr) rw.AddResource ((string) de.Key, de.Value); diff --git a/mcs/class/corlib/Test/System.Runtime.Remoting/RemotingServicesTest.cs b/mcs/class/corlib/Test/System.Runtime.Remoting/RemotingServicesTest.cs index c35918edc4..a8b9424ab1 100644 --- a/mcs/class/corlib/Test/System.Runtime.Remoting/RemotingServicesTest.cs +++ b/mcs/class/corlib/Test/System.Runtime.Remoting/RemotingServicesTest.cs @@ -40,9 +40,8 @@ namespace MonoTests.System.Runtime.Remoting [Test] public void Bug46473 () // concurrent serialization/deserialization { - bool success = true; crossDomainSerializedObject = new CrossDomainSerializedObject(); - Task[] tasks = new Task [20]; + Task[] tasks = new Task [5]; for (int i = 0; i < tasks.Length; i++) { var assembly = Assembly.GetAssembly(typeof(AppDomainObject)); @@ -50,7 +49,7 @@ namespace MonoTests.System.Runtime.Remoting tasks [i] = Task.Factory.StartNew(() => AppDomainWithRemotingSerialization(assembly, name)); } - Assert.IsTrue (Task.WaitAll (tasks, 5000)); + Assert.IsTrue (Task.WaitAll (tasks, 20000)); } #endif } diff --git a/mcs/class/corlib/Test/System.Text/UTF8EncodingTest.cs b/mcs/class/corlib/Test/System.Text/UTF8EncodingTest.cs index 184900fbc2..8e47e53d13 100644 --- a/mcs/class/corlib/Test/System.Text/UTF8EncodingTest.cs +++ b/mcs/class/corlib/Test/System.Text/UTF8EncodingTest.cs @@ -19,6 +19,8 @@ using DecoderException = System.Text.DecoderFallbackException; using AssertType = NUnit.Framework.Assert; +using MonoTests.Helpers; + namespace MonoTests.System.Text { [TestFixture] @@ -1043,9 +1045,7 @@ namespace MonoTests.System.Text [Category ("MobileNotWorking")] public void Bug415628 () { - DirectoryInfo bcl_output_dir = Directory.GetParent (Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location)).Parent; - string namespace_dir = Path.Combine (bcl_output_dir.Parent.FullName, "corlib"); - using (var f = File.Open (Path.Combine (namespace_dir, "Test/resources/415628.bin"), FileMode.Open)) { + using (var f = File.Open (TestResourceHelper.GetFullPathOfResource ("Test/resources/415628.bin"), FileMode.Open)) { BinaryReader br = new BinaryReader (f); byte [] buf = br.ReadBytes (8000); Encoding.UTF8.GetString(buf); diff --git a/mcs/class/corlib/Test/System.Threading/ManualResetEventSlimTests.cs b/mcs/class/corlib/Test/System.Threading/ManualResetEventSlimTests.cs index b96903485f..5a21e54538 100644 --- a/mcs/class/corlib/Test/System.Threading/ManualResetEventSlimTests.cs +++ b/mcs/class/corlib/Test/System.Threading/ManualResetEventSlimTests.cs @@ -53,7 +53,7 @@ namespace MonoTests.System.Threading public void Constructor_Defaults () { Assert.IsFalse (mre.IsSet, "#1"); - Assert.AreEqual (Environment.ProcessorCount == 1 ? 1 : 10, mre.SpinCount, "#2"); + Assert.AreEqual (Environment.ProcessorCount == 1 ? 1 : 35, mre.SpinCount, "#2"); } [Test] diff --git a/mcs/class/corlib/Test/System.Threading/WaitHandleTest.cs b/mcs/class/corlib/Test/System.Threading/WaitHandleTest.cs index 8f5692efef..4d6a3eb9dd 100644 --- a/mcs/class/corlib/Test/System.Threading/WaitHandleTest.cs +++ b/mcs/class/corlib/Test/System.Threading/WaitHandleTest.cs @@ -409,7 +409,7 @@ namespace MonoTests.System.Threading { m.WaitOne (); }); thread1.Start (); - thread1.Join (1000); + Assert.IsTrue (thread1.Join (Timeout.Infinite), "thread1.Join"); try { m.WaitOne (); Assert.Fail ("Expected AbandonedMutexException"); @@ -421,7 +421,7 @@ namespace MonoTests.System.Threading { signalled = m.WaitOne (100); }); thread2.Start (); - thread2.Join (1000); + Assert.IsTrue (thread2.Join (Timeout.Infinite), "thread2.Join"); Assert.IsFalse (signalled); // Since this thread owns the Mutex releasing it shouldn't fail @@ -489,7 +489,7 @@ namespace MonoTests.System.Threading { m1.ReleaseMutex (); }); thread1.Start (); - thread1.Join (1000); + Assert.IsTrue (thread1.Join (Timeout.Infinite), "thread1.Join"); thread2.Start (); while (!mainProceed) { Thread.Sleep (10); @@ -502,7 +502,7 @@ namespace MonoTests.System.Threading { Assert.AreEqual (m2, e.Mutex); } finally { thread2Proceed = true; - thread2.Join (1000); + Assert.IsTrue (thread2.Join (Timeout.Infinite), "thread2.Join"); } // Current thread should own the second Mutex now @@ -511,7 +511,7 @@ namespace MonoTests.System.Threading { signalled = WaitHandle.WaitAny (new WaitHandle [] { m1, m2 }, 0); }); thread3.Start (); - thread3.Join (1000); + Assert.IsTrue (thread3.Join (Timeout.Infinite), "thread3.Join"); Assert.AreEqual (0, signalled); // Since this thread owns the second Mutex releasing it shouldn't fail @@ -540,7 +540,7 @@ namespace MonoTests.System.Threading { m1.WaitOne (); }); thread.Start (); - thread.Join (1000); + Assert.IsTrue (thread.Join (Timeout.Infinite), "thread.Join"); WaitHandle.WaitAll (new WaitHandle [] { m1, m2 }); } } @@ -652,7 +652,35 @@ namespace MonoTests.System.Threading { Assert.IsTrue (eventToSignal.WaitOne (), "#2"); } } + + // https://github.com/mono/mono/issues/9089 + // Duplication is ok for WaitAny, exception for WaitAll. + // System.DuplicateWaitObjectException: Duplicate objects in argument. + [Test] + public static void DuplicateWaitAny () + { + using (var a = new ManualResetEvent (true)) + { + var b = new ManualResetEvent [ ] { a, a }; + Assert.AreEqual (0, WaitHandle.WaitAny (b), "#1"); + } + } + + // https://github.com/mono/mono/issues/9089 + // Duplication is ok for WaitAny, exception for WaitAll. + // System.DuplicateWaitObjectException: Duplicate objects in argument. + [Test] + public static void DuplicateWaitAll () + { + using (var a = new ManualResetEvent (true)) + { + var b = new ManualResetEvent [ ] { a, a }; + try { + WaitHandle.WaitAll (b); + Assert.Fail ("Expected System.DuplicateWaitObjectException"); + } catch (DuplicateWaitObjectException) { + } + } + } } } - - diff --git a/mcs/class/corlib/Test/System/BitConverterTest.cs b/mcs/class/corlib/Test/System/BitConverterTest.cs index b69d81d535..3aae39b8aa 100644 --- a/mcs/class/corlib/Test/System/BitConverterTest.cs +++ b/mcs/class/corlib/Test/System/BitConverterTest.cs @@ -47,7 +47,7 @@ namespace MonoTests.System Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); - Assert.IsNull (ex.ParamName, "#B5"); + Assert.IsNotNull (ex.ParamName, "#B5"); } try { @@ -111,7 +111,7 @@ namespace MonoTests.System Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); - Assert.IsNull (ex.ParamName, "#B5"); + Assert.IsNotNull (ex.ParamName, "#B5"); } try { @@ -231,7 +231,7 @@ namespace MonoTests.System Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); - Assert.IsNull (ex.ParamName, "#B5"); + Assert.IsNotNull (ex.ParamName, "#B5"); } try { @@ -295,7 +295,7 @@ namespace MonoTests.System Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); - Assert.IsNull (ex.ParamName, "#B5"); + Assert.IsNotNull (ex.ParamName, "#B5"); } try { @@ -361,7 +361,7 @@ namespace MonoTests.System Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); - Assert.IsNull (ex.ParamName, "#B5"); + Assert.IsNotNull (ex.ParamName, "#B5"); } try { @@ -426,7 +426,7 @@ namespace MonoTests.System Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); - Assert.IsNull (ex.ParamName, "#B5"); + Assert.IsNotNull (ex.ParamName, "#B5"); } try { @@ -492,7 +492,7 @@ namespace MonoTests.System Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); - Assert.IsNull (ex.ParamName, "#B5"); + Assert.IsNotNull (ex.ParamName, "#B5"); } try { @@ -557,7 +557,7 @@ namespace MonoTests.System Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); - Assert.IsNull (ex.ParamName, "#B5"); + Assert.IsNotNull (ex.ParamName, "#B5"); } try { @@ -623,7 +623,7 @@ namespace MonoTests.System Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); - Assert.IsNull (ex.ParamName, "#B5"); + Assert.IsNotNull (ex.ParamName, "#B5"); } try { @@ -868,7 +868,7 @@ namespace MonoTests.System Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); - Assert.IsNull (ex.ParamName, "#5"); + Assert.IsNotNull (ex.ParamName, "#5"); } } diff --git a/mcs/class/corlib/Test/System/EnvironmentTest.cs b/mcs/class/corlib/Test/System/EnvironmentTest.cs index 8a6997699e..8abbe77add 100644 --- a/mcs/class/corlib/Test/System/EnvironmentTest.cs +++ b/mcs/class/corlib/Test/System/EnvironmentTest.cs @@ -156,7 +156,7 @@ namespace MonoTests.System public void GetCommandLineArgs () { string[] args = Environment.GetCommandLineArgs (); -#if !__WATCHOS__ +#if !MONOTOUCH_WATCH Assert.IsNotNull (args, "not null"); Assert.IsTrue (((args.Length > 0) && (args.Length < 256)), "reasonable"); Assert.IsNotNull (args [0], "application"); diff --git a/mcs/class/corlib/Test/System/MathTest.cs b/mcs/class/corlib/Test/System/MathTest.cs index f41b62c1df..6d3929dad8 100644 --- a/mcs/class/corlib/Test/System/MathTest.cs +++ b/mcs/class/corlib/Test/System/MathTest.cs @@ -499,7 +499,7 @@ namespace MonoTests.System Assert.IsTrue (double.IsNaN (Math.Pow ( double.NaN, double.NegativeInfinity)), "#2"); Assert.IsTrue (double.IsNaN (Math.Pow ( double.NaN, -2)), "#2"); Assert.IsTrue (double.IsNaN (Math.Pow ( double.NaN, -1)), "#3"); - Assert.IsTrue (double.IsNaN (Math.Pow ( double.NaN, 0)), "#4"); + Assert.IsFalse (double.IsNaN (Math.Pow ( double.NaN, 0)), "#4"); Assert.IsTrue (double.IsNaN (Math.Pow ( double.NaN, 1)), "#5"); Assert.IsTrue (double.IsNaN (Math.Pow ( double.NaN, 2)), "#6"); Assert.IsTrue (double.IsNaN (Math.Pow ( double.NaN, double.PositiveInfinity)), "#7"); @@ -507,7 +507,7 @@ namespace MonoTests.System Assert.IsTrue (double.IsNaN (Math.Pow ( -2, double.NaN)), "#9"); Assert.IsTrue (double.IsNaN (Math.Pow ( -1, double.NaN)), "#10"); Assert.IsTrue (double.IsNaN (Math.Pow ( 0, double.NaN)), "#11"); - Assert.IsTrue (double.IsNaN (Math.Pow ( 1, double.NaN)), "#12"); + Assert.IsFalse (double.IsNaN (Math.Pow ( 1, double.NaN)), "#12"); Assert.IsTrue (double.IsNaN (Math.Pow ( 2, double.NaN)), "#13"); Assert.IsTrue (double.IsNaN (Math.Pow (double.PositiveInfinity, double.NaN)), "#14"); @@ -527,8 +527,8 @@ namespace MonoTests.System Assert.IsTrue (double.IsNaN (Math.Pow (-1, 2.5)), "#19"); /* x = -1; y = NegativeInfinity or PositiveInfinity -> NaN */ - Assert.IsTrue (double.IsNaN (Math.Pow (-1, double.PositiveInfinity)), "#20"); - Assert.IsTrue (double.IsNaN (Math.Pow (-1, double.NegativeInfinity)), "#21"); + Assert.IsFalse (double.IsNaN (Math.Pow (-1, double.PositiveInfinity)), "#20"); + Assert.IsFalse (double.IsNaN (Math.Pow (-1, double.NegativeInfinity)), "#21"); /* -1 < x < 1; y = NegativeInfinity -> PositiveInfinity */ Assert.AreEqual (double.PositiveInfinity, Math.Pow (-0.5, double.NegativeInfinity), "#22"); @@ -856,11 +856,13 @@ namespace MonoTests.System { double a = 1.5D; double b = 2.5D; + double c = 0.5000000000000001; // https://github.com/mono/mono/issues/9989 Assert.AreEqual (2D, Math.Round (a), "#1"); Assert.AreEqual (2D, Math.Round (b), "#2"); - Assert.IsTrue (Double.MaxValue == Math.Round (Double.MaxValue), "#3"); - Assert.IsTrue (Double.MinValue == Math.Round (Double.MinValue), "#4"); + Assert.AreEqual (1D, Math.Round (c), "#3"); + Assert.IsTrue (Double.MaxValue == Math.Round (Double.MaxValue), "#4"); + Assert.IsTrue (Double.MinValue == Math.Round (Double.MinValue), "#5"); } [Test] diff --git a/mcs/class/corlib/Test/System/TypeTest.cs.REMOVED.git-id b/mcs/class/corlib/Test/System/TypeTest.cs.REMOVED.git-id index 3ee98174f5..244b9a6482 100644 --- a/mcs/class/corlib/Test/System/TypeTest.cs.REMOVED.git-id +++ b/mcs/class/corlib/Test/System/TypeTest.cs.REMOVED.git-id @@ -1 +1 @@ -80fe02b425454e3f5205fb0e48c932f6fbe95c5e \ No newline at end of file +798ab98b275858de38ea9093f694ac55c9a86318 \ No newline at end of file diff --git a/mcs/class/corlib/coreclr/Math.CoreCLR.cs b/mcs/class/corlib/coreclr/Math.CoreCLR.cs new file mode 100644 index 0000000000..f3538f6c8a --- /dev/null +++ b/mcs/class/corlib/coreclr/Math.CoreCLR.cs @@ -0,0 +1,97 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/*============================================================ +** +** +** +** Purpose: Some floating-point math operations +** +** +===========================================================*/ + +//This class contains only static members and doesn't require serialization. + +using System.Runtime.CompilerServices; + +namespace System +{ + public static partial class Math + { + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Abs(double value); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float Abs(float value); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Acos(double d); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Acosh(double d); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Asin(double d); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Asinh(double d); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Atan(double d); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Atan2(double y, double x); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Atanh(double d); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Cbrt(double d); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Ceiling(double a); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Cos(double d); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Cosh(double value); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Exp(double d); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Floor(double d); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Log(double d); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Log10(double d); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Pow(double x, double y); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Sin(double a); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Sinh(double value); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Sqrt(double d); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Tan(double a); + + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double Tanh(double value); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern double FMod(double x, double y); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern unsafe double ModF(double x, double* intptr); + } +} \ No newline at end of file diff --git a/mcs/class/corlib/coreclr/MemberInfo.cs b/mcs/class/corlib/coreclr/MemberInfo.cs new file mode 100644 index 0000000000..de8926b2e3 --- /dev/null +++ b/mcs/class/corlib/coreclr/MemberInfo.cs @@ -0,0 +1,26 @@ +namespace System.Reflection { + partial class MemberInfo { + internal virtual bool CacheEquals (object o) + { + throw new NotImplementedException (); + } + + internal bool HasSameMetadataDefinitionAsCore (MemberInfo other) where TOther : MemberInfo + { + if (other == null) + throw new ArgumentNullException (nameof (other)); + + // Ensure that "other" is a runtime-implemented MemberInfo. Do this check before calling any methods on it! + if (!(other is TOther)) + return false; + + if (MetadataToken != other.MetadataToken) + return false; + + if (!(Module.Equals (other.Module))) + return false; + + return true; + } + } +} \ No newline at end of file diff --git a/mcs/class/corlib/corefx/BinaryEnums.cs b/mcs/class/corlib/corefx/BinaryEnums.cs new file mode 100644 index 0000000000..840beeddbe --- /dev/null +++ b/mcs/class/corlib/corefx/BinaryEnums.cs @@ -0,0 +1,42 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.Serialization.Formatters; +using System.Runtime.Remoting; +using System.Runtime.Serialization; +using System; + +namespace System.Runtime.Serialization.Formatters.Binary +{ + [Serializable] + [Flags] + internal enum MessageEnum + { + NoArgs = 0x1, + ArgsInline = 0x2, + ArgsIsArray = 0x4, + ArgsInArray = 0x8, + NoContext = 0x10, + ContextInline = 0x20, + ContextInArray = 0x40, + MethodSignatureInArray = 0x80, + PropertyInArray = 0x100, + NoReturnValue = 0x200, + ReturnValueVoid = 0x400, + ReturnValueInline = 0x800, + ReturnValueInArray = 0x1000, + ExceptionInArray = 0x2000, + GenericMethod = 0x8000 + } + + [Serializable] + internal enum SoapAttributeType + { + None = 0x0, + SchemaType = 0x1, + Embedded = 0x2, + XmlElement = 0x4, + XmlAttribute = 0x8 + } +} \ No newline at end of file diff --git a/mcs/class/corlib/corefx/Interop.Libraries.Advapi32.cs b/mcs/class/corlib/corefx/Interop.Libraries.Advapi32.cs new file mode 100644 index 0000000000..32e759845b --- /dev/null +++ b/mcs/class/corlib/corefx/Interop.Libraries.Advapi32.cs @@ -0,0 +1,11 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +internal static partial class Interop +{ + internal static partial class Libraries + { + internal const string Advapi32 = "advapi32.dll"; + } +} diff --git a/mcs/class/corlib/corefx/Registry.cs b/mcs/class/corlib/corefx/Registry.cs new file mode 100644 index 0000000000..2f3dcd6cd5 --- /dev/null +++ b/mcs/class/corlib/corefx/Registry.cs @@ -0,0 +1,14 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +namespace Microsoft.Win32 +{ + partial class Registry + { + [Obsolete("Use PerformanceData instead")] + public static readonly RegistryKey DynData = RegistryKey.OpenBaseKey(RegistryHive.DynData, RegistryView.Default); + } +} \ No newline at end of file diff --git a/mcs/class/corlib/corefx/SR.cs.REMOVED.git-id b/mcs/class/corlib/corefx/SR.cs.REMOVED.git-id index 1f876cd065..0faf4f6e1a 100644 --- a/mcs/class/corlib/corefx/SR.cs.REMOVED.git-id +++ b/mcs/class/corlib/corefx/SR.cs.REMOVED.git-id @@ -1 +1 @@ -7d6c3d757b2553412e786d3044d3e3d62c801369 \ No newline at end of file +2198d9a8d7e614566f4b7cc49859d594b6827bfb \ No newline at end of file diff --git a/mcs/class/corlib/corefx/SR.missing.cs b/mcs/class/corlib/corefx/SR.missing.cs index b51991c2ac..133620404f 100644 --- a/mcs/class/corlib/corefx/SR.missing.cs +++ b/mcs/class/corlib/corefx/SR.missing.cs @@ -3,4 +3,24 @@ partial class SR public const string ArgumentOutOfRange_ConsoleKey = "Console key values must be between 0 and 255 inclusive."; public const string Arg_InvalidComObjectException = "Attempt has been made to use a COM object that does not have a backing class factory."; public const string Arg_MustBeNullTerminatedString = "The string must be null-terminated."; + public const string Arg_InvalidOleVariantTypeException = "Specified OLE variant was invalid."; + public const string Arg_SafeArrayRankMismatchException = "Specified array was not of the expected rank."; + public const string Arg_SafeArrayTypeMismatchException = "Specified array was not of the expected type."; + public const string TypeNotDelegate = "'Type '{0}' is not a delegate type. EventTokenTable may only be used with delegate types.'"; + public const string InvalidOperationException_ActorGraphCircular = "An Actor must not create a circular reference between itself (or one of its child Actors) and one of its parents."; + public const string InvalidOperation_ClaimCannotBeRemoved = "The Claim '{0}' was not able to be removed. It is either not part of this Identity or it is a Claim that is owned by the Principal that contains this Identity. For example, the Principal will own the Claim when creating a GenericPrincipal with roles. The roles will be exposed through the Identity that is passed in the constructor, but not actually owned by the Identity. Similar logic exists for a RolePrincipal."; + public const string PlatformNotSupported_Serialization = "This instance contains state that cannot be serialized and deserialized on this platform."; + public const string PrivilegeNotHeld_Default = "The process does not possess some privilege required for this operation."; + public const string PrivilegeNotHeld_Named = "The process does not possess the '{0}' privilege which is required for this operation."; + public const string CountdownEvent_Decrement_BelowZero = "CountdownEvent_Decrement_BelowZero"; + public const string CountdownEvent_Increment_AlreadyZero = "CountdownEvent_Increment_AlreadyZero"; + public const string CountdownEvent_Increment_AlreadyMax = "CountdownEvent_Increment_AlreadyMax"; + public const string ArrayWithOffsetOverflow = "ArrayWithOffsetOverflow"; + public const string Arg_NotIsomorphic = "Arg_NotIsomorphic"; + public const string StructArrayTooLarge = "StructArrayTooLarge"; + public const string IO_DriveNotFound = "IO_DriveNotFound"; + public const string Argument_MustSupplyParent = "Argument_MustSupplyParent"; + public const string Argument_MemberAndArray = "Argument_MemberAndArray"; + public const string Argument_MustSupplyContainer = "Argument_MustSupplyContainer"; + public const string Serialization_NoID = "Serialization_NoID"; } \ No newline at end of file diff --git a/mcs/class/corlib/corert/RuntimeAugments.cs b/mcs/class/corlib/corert/RuntimeAugments.cs index 64d7fbb800..c1dc3f3cb9 100644 --- a/mcs/class/corlib/corert/RuntimeAugments.cs +++ b/mcs/class/corlib/corert/RuntimeAugments.cs @@ -1,12 +1,22 @@ using System; +using System.Reflection; + +namespace Internal.Runtime.Augments { + partial class RuntimeAugments { + private static ReflectionExecutionDomainCallbacks s_reflectionExecutionDomainCallbacks = new ReflectionExecutionDomainCallbacks (); -namespace Internal.Runtime.Augments -{ - partial class RuntimeAugments - { public static void ReportUnhandledException (Exception exception) { throw exception; } + + internal static ReflectionExecutionDomainCallbacks Callbacks => s_reflectionExecutionDomainCallbacks; + } + + partial class ReflectionExecutionDomainCallbacks { + internal Exception CreateMissingMetadataException (Type attributeType) + { + return new MissingMetadataException (); + } } } \ No newline at end of file diff --git a/mcs/class/corlib/corert/RuntimeThread.cs b/mcs/class/corlib/corert/RuntimeThread.cs index 6ca08d787f..064aefed9d 100644 --- a/mcs/class/corlib/corert/RuntimeThread.cs +++ b/mcs/class/corlib/corert/RuntimeThread.cs @@ -5,6 +5,9 @@ namespace Internal.Runtime.Augments { sealed class RuntimeThread { + // Note: Magic number copied from CoreRT's RuntimeThread.cs. See the original source code for an explanation. + internal static readonly int OptimalMaxSpinWaitsPerSpinIteration = 64; + readonly Thread thread; RuntimeThread (Thread t) { thread = t; } @@ -26,6 +29,8 @@ namespace Internal.Runtime.Augments public void Start (object state) => thread.Start (state); + public static void Sleep(int millisecondsTimeout) => Thread.Sleep (millisecondsTimeout); + public static bool Yield () => Thread.Yield (); public static bool SpinWait (int iterations) diff --git a/mcs/class/corlib/corert/Type.cs b/mcs/class/corlib/corert/Type.cs new file mode 100644 index 0000000000..4096b6c527 --- /dev/null +++ b/mcs/class/corlib/corert/Type.cs @@ -0,0 +1,39 @@ +using System.Reflection; + +namespace System { + partial class Type { + internal const string DefaultTypeNameWhenMissingMetadata = "UnknownType"; + + internal string FullNameOrDefault { + get { + // First, see if Type.Name is available. If Type.Name is available, then we can be reasonably confident that it is safe to call Type.FullName. + // We'll still wrap the call in a try-catch as a failsafe. + if (InternalNameIfAvailable == null) + return DefaultTypeNameWhenMissingMetadata; + + try { + return FullName; + } catch (MissingMetadataException) { + return DefaultTypeNameWhenMissingMetadata; + } + } + } + + internal bool IsRuntimeImplemented () => true; + + internal virtual string InternalGetNameIfAvailable (ref Type rootCauseForFailure) => Name; + + internal string InternalNameIfAvailable { + get { + Type ignore = null; + return InternalGetNameIfAvailable (ref ignore); + } + } + + internal string NameOrDefault { + get { + return InternalNameIfAvailable ?? DefaultTypeNameWhenMissingMetadata; + } + } + } +} diff --git a/mcs/class/corlib/corlib.dll.sources.REMOVED.git-id b/mcs/class/corlib/corlib.dll.sources.REMOVED.git-id index 7b13bb3e05..be0c1dd604 100644 --- a/mcs/class/corlib/corlib.dll.sources.REMOVED.git-id +++ b/mcs/class/corlib/corlib.dll.sources.REMOVED.git-id @@ -1 +1 @@ -e5c031cc0f6c0a37baa8da70a39b05cd0d319050 \ No newline at end of file +434209ab0071fbc27efd9219f99f4dd3f9f3c5a5 \ No newline at end of file diff --git a/mcs/class/corlib/corlib_test.dll.sources b/mcs/class/corlib/corlib_test.dll.sources index c4ae45c780..915ed24058 100644 --- a/mcs/class/corlib/corlib_test.dll.sources +++ b/mcs/class/corlib/corlib_test.dll.sources @@ -1,6 +1,9 @@ Microsoft.Win32/RegistryKeyTest.cs Mono/DataConvertTest.cs ../Mono/DataConverter.cs +Mono/NativePlatformTest.cs +../Mono/MonoNativePlatform.cs +../Mono/MonoNativePlatformType.cs System/ActivatorTest.cs System/AppDomainManagerTest.cs System/AppDomainSetupTest.cs @@ -543,4 +546,5 @@ System.Threading/ThreadLocalTests.cs System.Threading/SpinLockTests.cs ../../../../mono/mini/TestHelpers.cs ../../test-helpers/NunitHelpers.cs +../../test-helpers/TestResourceHelper.cs System.Threading/ThreadPrincipalTests.cs diff --git a/mcs/class/corlib/corlib_xtest.dll.sources b/mcs/class/corlib/corlib_xtest.dll.sources index 459507c64f..9f970a8994 100644 --- a/mcs/class/corlib/corlib_xtest.dll.sources +++ b/mcs/class/corlib/corlib_xtest.dll.sources @@ -1,4 +1,6 @@ ../../../external/corefx/src/CoreFx.Private.TestUtilities/src/System/AssertExtensions.cs +../../../external/corefx/src/Common/tests/System/MockType.cs +../../../external/corefx/src/Common/tests/System/Reflection/MockParameterInfo.cs ../../../external/corefx/src/Common/tests/System/RandomExtensions.cs ../../../external/corefx/src/Common/tests/System/RandomDataGenerator.cs @@ -13,6 +15,12 @@ ../../../external/corefx/src/System.Reflection.Emit/tests/Utilities.cs +../../../external/corefx/src/System.Reflection/tests/Common.cs + +../../../external/corefx/src/System.Reflection/tests/*.cs:AssemblyTests.cs,AssemblyNameTests.cs,GetTypeTests.cs,MethodInfoTests.cs,ModuleTests.cs,TypeInfoTests.cs,TypeInfoTests.netcoreapp.cs,ParameterInfoTests.cs +../../../external/corefx/src/System.Reflection.Extensions/tests/Definitions/PropertyDefinitions.cs +../../../external/corefx/src/System.Reflection.Extensions/tests/*.cs + #TODO: audit the commented out tests and fix or disable #../../../external/corefx/src/System.Reflection.Emit/tests/AssemblyBuilderTests.cs @@ -149,6 +157,7 @@ ../../../external/corefx/src/System.Runtime/tests/System/String.SplitTests.cs ../../../external/corefx/src/System.Runtime/tests/System/NullableTests.cs ../../../external/corefx/src/System.Runtime/tests/System/Reflection/BindingFlagsDoNotWrap.netcoreapp.cs +../../../external/corefx/src/System.Runtime/tests/System/Reflection/CustomAttribute_Named_Typed_ArgumentTests.cs ../../../external/corefx/src/System.Runtime/tests/System/Text/*.cs ../../../external/corefx/src/System.Runtime/tests/System/Runtime/CompilerServices/*.cs:RuntimeHelpersTests.netcoreapp.cs,ConditionalWeakTableTests.netcoreapp.cs,ConditionalWeakTableTests.cs @@ -305,3 +314,12 @@ ../../../external/corefx/src/System.Runtime/tests/System/IO/*.cs:FileLoadException.InteropTests.cs,DirectoryNotFoundException.InteropTests.cs,FileNotFoundException.InteropTests.cs ../../../external/corefx/src/System.Runtime/tests/System/Text/*.cs ../../../external/corefx/src/System.Runtime/tests/System/Threading/*.cs:WaitHandleTests.cs + +# System.Runtime.Extensions +../../../external/corefx/src/System.Runtime.Extensions/tests/System/Math.cs +../../../external/corefx/src/System.Runtime.Extensions/tests/System/MathF.netcoreapp.cs +../../../external/corefx/src/System.Runtime.Extensions/tests/System/MathTests.netcoreapp.cs + +# System.Runtime.InteropServices +../../../external/corefx/src/System.Runtime.InteropServices/tests/System/Runtime/CompilerServices/*.cs +../../../external/corefx/src/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/*.cs:MarshalTests.cs,GCHandleTests.cs,SafeBufferTests.cs,ComEventsHelperTests.cs,RuntimeEnvironmentTests.cs,DispatchWrapperTests.cs,ArrayWithOffsetTests.cs,SetWin32ContextInIDispatchAttributeTests.cs,ComAwareEventInfoTests.cs,IDispatchImplAttributeTests.cs,ComAwareEventInfoTests.Windows.cs,MarshalTests.Windows.cs diff --git a/mcs/class/corlib/monotouch_tv_corlib_test.dll.exclude.sources b/mcs/class/corlib/monotouch_tv_corlib_test.dll.exclude.sources new file mode 100644 index 0000000000..444648b3e2 --- /dev/null +++ b/mcs/class/corlib/monotouch_tv_corlib_test.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_corlib_test.dll.exclude.sources diff --git a/mcs/class/corlib/monotouch_tv_corlib_xtest.dll.exclude.sources b/mcs/class/corlib/monotouch_tv_corlib_xtest.dll.exclude.sources new file mode 100644 index 0000000000..4770f4d1dc --- /dev/null +++ b/mcs/class/corlib/monotouch_tv_corlib_xtest.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_corlib_xtest.dll.exclude.sources diff --git a/mcs/class/corlib/monotouch_watch_corlib_test.dll.exclude.sources b/mcs/class/corlib/monotouch_watch_corlib_test.dll.exclude.sources new file mode 100644 index 0000000000..444648b3e2 --- /dev/null +++ b/mcs/class/corlib/monotouch_watch_corlib_test.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_corlib_test.dll.exclude.sources diff --git a/mcs/class/corlib/monotouch_watch_corlib_xtest.dll.exclude.sources b/mcs/class/corlib/monotouch_watch_corlib_xtest.dll.exclude.sources new file mode 100644 index 0000000000..4770f4d1dc --- /dev/null +++ b/mcs/class/corlib/monotouch_watch_corlib_xtest.dll.exclude.sources @@ -0,0 +1 @@ +#include monotouch_corlib_xtest.dll.exclude.sources diff --git a/mcs/class/corlib/testing_aot_full_corlib_test.dll.exclude.sources b/mcs/class/corlib/testing_aot_full_corlib_test.dll.exclude.sources index e17ad01699..5f14af5f27 100644 --- a/mcs/class/corlib/testing_aot_full_corlib_test.dll.exclude.sources +++ b/mcs/class/corlib/testing_aot_full_corlib_test.dll.exclude.sources @@ -1,3 +1,6 @@ +Mono/NativePlatformTest.cs +../Mono/MonoNativePlatform.cs +../Mono/MonoNativePlatformType.cs Microsoft.Win32/RegistryKeyTest.cs System.Diagnostics.Contracts/ContractAssertTest.cs System.Diagnostics.Contracts/ContractAssumeTest.cs diff --git a/mcs/class/corlib/wasm_corlib_test.dll.exclude.sources b/mcs/class/corlib/wasm_corlib_test.dll.exclude.sources index e17ad01699..5f14af5f27 100644 --- a/mcs/class/corlib/wasm_corlib_test.dll.exclude.sources +++ b/mcs/class/corlib/wasm_corlib_test.dll.exclude.sources @@ -1,3 +1,6 @@ +Mono/NativePlatformTest.cs +../Mono/MonoNativePlatform.cs +../Mono/MonoNativePlatformType.cs Microsoft.Win32/RegistryKeyTest.cs System.Diagnostics.Contracts/ContractAssertTest.cs System.Diagnostics.Contracts/ContractAssumeTest.cs diff --git a/mcs/class/corlib/win32_net_4_x_corlib.dll.exclude.sources b/mcs/class/corlib/win32_net_4_x_corlib.dll.exclude.sources index 4f014765c2..35559f4d09 100644 --- a/mcs/class/corlib/win32_net_4_x_corlib.dll.exclude.sources +++ b/mcs/class/corlib/win32_net_4_x_corlib.dll.exclude.sources @@ -6,4 +6,15 @@ corert/ThreadPoolBoundHandle.platformnotsupported.cs corefx/Interop.GetRandomBytes.Mono.cs corefx/Mono.SafePasswordHandle.Unix.cs ../../../external/corefx/src/System.Security.Cryptography.X509Certificates/src/Microsoft/Win32/SafeHandles/SafePasswordHandle.Unix.cs - +Mono/MonoNativePlatform.cs +Mono/MonoNativePlatformType.cs +Microsoft.Win32/IRegistryApi.cs +Microsoft.Win32/Registry.cs +Microsoft.Win32/RegistryKey.cs +Microsoft.Win32/Win32RegistryApi.cs +Microsoft.Win32/Win32ResultCode.cs +Microsoft.Win32/UnixRegistryApi.cs +System.Security.AccessControl/RegistryAccessRule.cs +System.Security.AccessControl/RegistryAuditRule.cs +System.Security.AccessControl/RegistrySecurity.cs +../referencesource/mscorlib/microsoft/win32/safehandles/saferegistryhandle.cs diff --git a/mcs/class/corlib/win32_net_4_x_corlib.dll.sources b/mcs/class/corlib/win32_net_4_x_corlib.dll.sources index 54b200a948..9b10a797c3 100644 --- a/mcs/class/corlib/win32_net_4_x_corlib.dll.sources +++ b/mcs/class/corlib/win32_net_4_x_corlib.dll.sources @@ -14,7 +14,7 @@ ../../../external/corert/src/Common/src/Interop/Windows/Interop.Libraries.cs -../../../external/corert/src/System.Private.CoreLib/shared/Interop/Windows/Interop.Errors.cs +../../../external/corefx/src/Common/src/Interop/Windows/Interop.Errors.cs ../../../external/corert/src/System.Private.CoreLib/shared/System/Threading/DeferredDisposableLifetime.cs @@ -34,4 +34,29 @@ corert/RuntimeImports.cs ../../../external/corefx/src/System.Security.Cryptography.X509Certificates/src/Microsoft/Win32/SafeHandles/SafePasswordHandle.Windows.cs corefx/Mono.SafePasswordHandle.Windows.cs - +../../../external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs +../../../external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs +corefx/Interop.Libraries.Advapi32.cs +../../../external/corefx/src/Microsoft.Win32.Registry/src/System/Security/AccessControl/RegistrySecurity.cs +../../../external/corefx/src/Microsoft.Win32.Registry/src/System/Security/AccessControl/RegistrySecurity.Windows.cs +../../../external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs +../../../external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs +../../../external/corefx/src/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs +corefx/Registry.cs +../../../external/corefx/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SECURITY_ATTRIBUTES.cs +../../../external/corefx/src/Common/src/Interop/Windows/Interop.BOOL.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegCloseKey.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegConnectRegistry.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegCreateKeyEx.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegDeleteKeyEx.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegDeleteValue.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegEnumKeyEx.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegEnumValue.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegFlushKey.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegisterServiceCtrlHandler.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegisterServiceCtrlHandlerEx.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegistryOptions.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegOpenKeyEx.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegQueryInfoKey.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegQueryValueEx.cs +../../../external/corefx/src/Common/src/Interop/Windows/advapi32/Interop.RegSetValueEx.cs diff --git a/mcs/class/corlib/win32_net_4_x_corlib_test.dll.exclude.sources b/mcs/class/corlib/win32_net_4_x_corlib_test.dll.exclude.sources new file mode 100644 index 0000000000..03980699b2 --- /dev/null +++ b/mcs/class/corlib/win32_net_4_x_corlib_test.dll.exclude.sources @@ -0,0 +1,2 @@ +#include testing_aot_full_corlib_test.dll.exclude.sources +Mono/NativePlatformTest.cs diff --git a/mcs/class/corlib/win32_net_4_x_corlib_test.dll.sources b/mcs/class/corlib/win32_net_4_x_corlib_test.dll.sources new file mode 100644 index 0000000000..011effe162 --- /dev/null +++ b/mcs/class/corlib/win32_net_4_x_corlib_test.dll.sources @@ -0,0 +1 @@ +#include corlib_test.dll.sources diff --git a/mcs/class/corlib/win32_net_4_x_corlib_xtest.dll.sources b/mcs/class/corlib/win32_net_4_x_corlib_xtest.dll.sources new file mode 100644 index 0000000000..1e78c54519 --- /dev/null +++ b/mcs/class/corlib/win32_net_4_x_corlib_xtest.dll.sources @@ -0,0 +1,9 @@ +#include corlib_xtest.dll.sources + +# Microsoft.Win32.Registry +../../../external/corefx/src/Microsoft.Win32.Registry/tests/RegistryTestsBase.cs +../../../external/corefx/src/Microsoft.Win32.Registry/tests/TestData.cs +#../../../external/corefx/src/Microsoft.Win32.Registry/tests/Helpers.cs +../../../external/corefx/src/Microsoft.Win32.Registry/tests/Registry/Registry_Fields.cs +../../../external/corefx/src/Microsoft.Win32.Registry/tests/Registry/Registry_SetValue_str_str_obj_valuekind.cs +../../../external/corefx/src/Microsoft.Win32.Registry/tests/RegistryKey/*.cs:RegistryKey_GetValue_str_obj_b.cs,RegistryKey_GetValue_CorruptData.cs,RegistryKey_GetValue_str.cs,RegistryKey_GetValue_str_obj.cs diff --git a/mcs/class/corlib/winaot_corlib.dll.exclude.sources b/mcs/class/corlib/winaot_corlib.dll.exclude.sources index 1e4ccd09cd..8e4ed59cb9 100644 --- a/mcs/class/corlib/winaot_corlib.dll.exclude.sources +++ b/mcs/class/corlib/winaot_corlib.dll.exclude.sources @@ -7,4 +7,13 @@ corert/ThreadPoolBoundHandle.platformnotsupported.cs corefx/Interop.GetRandomBytes.Mono.cs corefx/Mono.SafePasswordHandle.Unix.cs ../../../external/corefx/src/System.Security.Cryptography.X509Certificates/src/Microsoft/Win32/SafeHandles/SafePasswordHandle.Unix.cs - +Microsoft.Win32/IRegistryApi.cs +Microsoft.Win32/Registry.cs +Microsoft.Win32/RegistryKey.cs +Microsoft.Win32/Win32RegistryApi.cs +Microsoft.Win32/Win32ResultCode.cs +Microsoft.Win32/UnixRegistryApi.cs +System.Security.AccessControl/RegistryAccessRule.cs +System.Security.AccessControl/RegistryAuditRule.cs +System.Security.AccessControl/RegistrySecurity.cs +../referencesource/mscorlib/microsoft/win32/safehandles/saferegistryhandle.cs diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.InteropServices.dll b/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.InteropServices.dll deleted file mode 100644 index 35cf183d70..0000000000 Binary files a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.InteropServices.dll and /dev/null differ diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.dll b/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.dll deleted file mode 100644 index bc6b42e594..0000000000 Binary files a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.dll and /dev/null differ diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.dll b/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.dll deleted file mode 100644 index 9df009105a..0000000000 Binary files a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.dll and /dev/null differ diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Cecil.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Cecil.dll.REMOVED.git-id deleted file mode 100644 index 610d2262de..0000000000 --- a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Cecil.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -eb0997901e75ba5504d1b7755a7fa64f1d9209b9 \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Security.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Security.dll.REMOVED.git-id deleted file mode 100644 index 2f557d62c6..0000000000 --- a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Security.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -58c0087a3f5050b8dfd57c1efc4591a45330c748 \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Configuration.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Configuration.dll.REMOVED.git-id deleted file mode 100644 index ba5dd7c652..0000000000 --- a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Configuration.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -d14066172fb1b31d3ecc7834f33d86decbee7e4b \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Core.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Core.dll.REMOVED.git-id deleted file mode 100644 index 54574511e8..0000000000 --- a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Core.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -bda9900d9aa879780e77389c653cde3d893e2697 \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Numerics.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Numerics.dll.REMOVED.git-id deleted file mode 100644 index a70dc856a3..0000000000 --- a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Numerics.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -b2fbc4e31e37aaa1f90395e048c3486548d0fd4f \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.dll.REMOVED.git-id deleted file mode 100644 index d0be00e458..0000000000 --- a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -32753c579e227b6d1efce68693870b90d3aa0930 \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.dll.REMOVED.git-id deleted file mode 100644 index dc979adf94..0000000000 --- a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -01766890ba43b0839b5a18cb8a0ffd39579eb0af \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mcs.exe.REMOVED.git-id b/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mcs.exe.REMOVED.git-id deleted file mode 100644 index 38e5f139c7..0000000000 --- a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mcs.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3cf15af9f4dd78bada00c438ff69c15231357837 \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mscorlib.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mscorlib.dll.REMOVED.git-id deleted file mode 100644 index ae7c8ea56b..0000000000 --- a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mscorlib.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -00610ed248040b6bec71a3d6b9a65db6417b2c6f \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.Concurrent.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.Concurrent.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.Concurrent.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.Concurrent.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Debug.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Debug.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Debug.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Debug.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.FileVersionInfo.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.FileVersionInfo.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.FileVersionInfo.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.FileVersionInfo.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Tools.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Tools.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Tools.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Tools.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Dynamic.Runtime.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Dynamic.Runtime.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Dynamic.Runtime.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Dynamic.Runtime.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Globalization.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Globalization.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Globalization.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Globalization.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.Primitives.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.Primitives.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.Primitives.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.Primitives.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.Expressions.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.Expressions.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.Expressions.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.Expressions.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Extensions.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Extensions.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Extensions.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Extensions.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Primitives.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Primitives.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Primitives.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Primitives.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Resources.ResourceManager.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Resources.ResourceManager.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Resources.ResourceManager.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Resources.ResourceManager.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Extensions.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Extensions.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Extensions.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Extensions.dll diff --git a/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.InteropServices.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.InteropServices.dll new file mode 100644 index 0000000000..58d1df3676 Binary files /dev/null and b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.InteropServices.dll differ diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Numerics.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Numerics.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Numerics.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Numerics.dll diff --git a/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.dll new file mode 100644 index 0000000000..3f9a942a61 Binary files /dev/null and b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.dll differ diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Algorithms.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Algorithms.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Algorithms.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Algorithms.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Primitives.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Primitives.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Primitives.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Primitives.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.CodePages.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.CodePages.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.CodePages.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.CodePages.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.Extensions.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.Extensions.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.Extensions.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.Extensions.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.Parallel.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.Parallel.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.Parallel.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.Parallel.dll diff --git a/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.dll new file mode 100644 index 0000000000..bd94187f12 Binary files /dev/null and b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.dll differ diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.ValueTuple.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.ValueTuple.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.ValueTuple.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.ValueTuple.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.ReaderWriter.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.ReaderWriter.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.ReaderWriter.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.ReaderWriter.dll diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.XDocument.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.XDocument.dll similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.XDocument.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.XDocument.dll diff --git a/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Cecil.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Cecil.dll.REMOVED.git-id new file mode 100644 index 0000000000..be37de0f4c --- /dev/null +++ b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Cecil.dll.REMOVED.git-id @@ -0,0 +1 @@ +ac4040e2d669b15a51f36831721a799b30c9d9d8 \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Security.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Security.dll.REMOVED.git-id new file mode 100644 index 0000000000..5e60ced8e5 --- /dev/null +++ b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Security.dll.REMOVED.git-id @@ -0,0 +1 @@ +4f4391e937dcc54a4359d358a1c775bdef279ec8 \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Configuration.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Configuration.dll.REMOVED.git-id new file mode 100644 index 0000000000..47481af8c5 --- /dev/null +++ b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Configuration.dll.REMOVED.git-id @@ -0,0 +1 @@ +0a6705fab6968dae1904e86f6543c5f877d5a4a8 \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Core.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Core.dll.REMOVED.git-id new file mode 100644 index 0000000000..d1547c4f76 --- /dev/null +++ b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Core.dll.REMOVED.git-id @@ -0,0 +1 @@ +a03e85c37ce0d3d08fae6dea915d62fb4c71b5aa \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.IO.Compression.dll b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.IO.Compression.dll similarity index 99% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.IO.Compression.dll rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.IO.Compression.dll index 6f54cb8622..1cf8bbab36 100644 Binary files a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.IO.Compression.dll and b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.IO.Compression.dll differ diff --git a/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Numerics.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Numerics.dll.REMOVED.git-id new file mode 100644 index 0000000000..e1f1829359 --- /dev/null +++ b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Numerics.dll.REMOVED.git-id @@ -0,0 +1 @@ +32ddda617ddf4b5f8efd69a8440738ca362f1599 \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Security.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Security.dll.REMOVED.git-id similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Security.dll.REMOVED.git-id rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Security.dll.REMOVED.git-id diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.Linq.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.Linq.dll.REMOVED.git-id similarity index 100% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.Linq.dll.REMOVED.git-id rename to mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.Linq.dll.REMOVED.git-id diff --git a/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.dll.REMOVED.git-id new file mode 100644 index 0000000000..a5cfa9b947 --- /dev/null +++ b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.dll.REMOVED.git-id @@ -0,0 +1 @@ +5b76c9eff6ad5174965dbaae00f687535380c3a1 \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.dll.REMOVED.git-id new file mode 100644 index 0000000000..b1db618ee3 --- /dev/null +++ b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.dll.REMOVED.git-id @@ -0,0 +1 @@ +8df6f0bf6e9dca89d20ab916dc3c7b449bfbeb4b \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mcs.exe.REMOVED.git-id b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mcs.exe.REMOVED.git-id new file mode 100644 index 0000000000..2178bc4e51 --- /dev/null +++ b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mcs.exe.REMOVED.git-id @@ -0,0 +1 @@ +1d3ebea05d4f45721fc50683072d60048f65e461 \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mscorlib.dll.REMOVED.git-id b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mscorlib.dll.REMOVED.git-id new file mode 100644 index 0000000000..a6d2b3ab6d --- /dev/null +++ b/mcs/class/lib/monolite-linux/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mscorlib.dll.REMOVED.git-id @@ -0,0 +1 @@ +783746cb55609a3dee958691967fb240f9fe1146 \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.InteropServices.dll b/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.InteropServices.dll deleted file mode 100644 index 35cf183d70..0000000000 Binary files a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.InteropServices.dll and /dev/null differ diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.dll b/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.dll deleted file mode 100644 index bc6b42e594..0000000000 Binary files a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.dll and /dev/null differ diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.dll b/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.dll deleted file mode 100644 index 9df009105a..0000000000 Binary files a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.dll and /dev/null differ diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Cecil.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Cecil.dll.REMOVED.git-id deleted file mode 100644 index 610d2262de..0000000000 --- a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Cecil.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -eb0997901e75ba5504d1b7755a7fa64f1d9209b9 \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Security.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Security.dll.REMOVED.git-id deleted file mode 100644 index 2f557d62c6..0000000000 --- a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Security.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -58c0087a3f5050b8dfd57c1efc4591a45330c748 \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Configuration.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Configuration.dll.REMOVED.git-id deleted file mode 100644 index ba5dd7c652..0000000000 --- a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Configuration.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -d14066172fb1b31d3ecc7834f33d86decbee7e4b \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Core.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Core.dll.REMOVED.git-id deleted file mode 100644 index 54574511e8..0000000000 --- a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Core.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -bda9900d9aa879780e77389c653cde3d893e2697 \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Numerics.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Numerics.dll.REMOVED.git-id deleted file mode 100644 index a70dc856a3..0000000000 --- a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Numerics.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -b2fbc4e31e37aaa1f90395e048c3486548d0fd4f \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.dll.REMOVED.git-id deleted file mode 100644 index d0be00e458..0000000000 --- a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -32753c579e227b6d1efce68693870b90d3aa0930 \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.dll.REMOVED.git-id deleted file mode 100644 index dc979adf94..0000000000 --- a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -01766890ba43b0839b5a18cb8a0ffd39579eb0af \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mcs.exe.REMOVED.git-id b/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mcs.exe.REMOVED.git-id deleted file mode 100644 index 38e5f139c7..0000000000 --- a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mcs.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3cf15af9f4dd78bada00c438ff69c15231357837 \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mscorlib.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mscorlib.dll.REMOVED.git-id deleted file mode 100644 index ae7c8ea56b..0000000000 --- a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mscorlib.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -00610ed248040b6bec71a3d6b9a65db6417b2c6f \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.Concurrent.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.Concurrent.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.Concurrent.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.Concurrent.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Debug.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Debug.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Debug.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Debug.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.FileVersionInfo.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.FileVersionInfo.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.FileVersionInfo.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.FileVersionInfo.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Tools.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Tools.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Tools.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Tools.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Dynamic.Runtime.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Dynamic.Runtime.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Dynamic.Runtime.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Dynamic.Runtime.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Globalization.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Globalization.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Globalization.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Globalization.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.Primitives.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.Primitives.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.Primitives.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.Primitives.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.Expressions.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.Expressions.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.Expressions.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.Expressions.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Extensions.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Extensions.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Extensions.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Extensions.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Primitives.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Primitives.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Primitives.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Primitives.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Resources.ResourceManager.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Resources.ResourceManager.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Resources.ResourceManager.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Resources.ResourceManager.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Extensions.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Extensions.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Extensions.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Extensions.dll diff --git a/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.InteropServices.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.InteropServices.dll new file mode 100644 index 0000000000..58d1df3676 Binary files /dev/null and b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.InteropServices.dll differ diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Numerics.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Numerics.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Numerics.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Numerics.dll diff --git a/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.dll new file mode 100644 index 0000000000..3f9a942a61 Binary files /dev/null and b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.dll differ diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Algorithms.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Algorithms.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Algorithms.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Algorithms.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Primitives.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Primitives.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Primitives.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Primitives.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.CodePages.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.CodePages.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.CodePages.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.CodePages.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.Extensions.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.Extensions.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.Extensions.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.Extensions.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.Parallel.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.Parallel.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.Parallel.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.Parallel.dll diff --git a/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.dll new file mode 100644 index 0000000000..bd94187f12 Binary files /dev/null and b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.dll differ diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.ValueTuple.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.ValueTuple.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.ValueTuple.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.ValueTuple.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.ReaderWriter.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.ReaderWriter.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.ReaderWriter.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.ReaderWriter.dll diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.XDocument.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.XDocument.dll similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.XDocument.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.XDocument.dll diff --git a/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Cecil.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Cecil.dll.REMOVED.git-id new file mode 100644 index 0000000000..be37de0f4c --- /dev/null +++ b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Cecil.dll.REMOVED.git-id @@ -0,0 +1 @@ +ac4040e2d669b15a51f36831721a799b30c9d9d8 \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Security.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Security.dll.REMOVED.git-id new file mode 100644 index 0000000000..5e60ced8e5 --- /dev/null +++ b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Security.dll.REMOVED.git-id @@ -0,0 +1 @@ +4f4391e937dcc54a4359d358a1c775bdef279ec8 \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Configuration.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Configuration.dll.REMOVED.git-id new file mode 100644 index 0000000000..47481af8c5 --- /dev/null +++ b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Configuration.dll.REMOVED.git-id @@ -0,0 +1 @@ +0a6705fab6968dae1904e86f6543c5f877d5a4a8 \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Core.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Core.dll.REMOVED.git-id new file mode 100644 index 0000000000..d1547c4f76 --- /dev/null +++ b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Core.dll.REMOVED.git-id @@ -0,0 +1 @@ +a03e85c37ce0d3d08fae6dea915d62fb4c71b5aa \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.IO.Compression.dll b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.IO.Compression.dll similarity index 99% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.IO.Compression.dll rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.IO.Compression.dll index 6f54cb8622..1cf8bbab36 100644 Binary files a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.IO.Compression.dll and b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.IO.Compression.dll differ diff --git a/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Numerics.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Numerics.dll.REMOVED.git-id new file mode 100644 index 0000000000..e1f1829359 --- /dev/null +++ b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Numerics.dll.REMOVED.git-id @@ -0,0 +1 @@ +32ddda617ddf4b5f8efd69a8440738ca362f1599 \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Security.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Security.dll.REMOVED.git-id similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Security.dll.REMOVED.git-id rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Security.dll.REMOVED.git-id diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.Linq.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.Linq.dll.REMOVED.git-id similarity index 100% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.Linq.dll.REMOVED.git-id rename to mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.Linq.dll.REMOVED.git-id diff --git a/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.dll.REMOVED.git-id new file mode 100644 index 0000000000..a5cfa9b947 --- /dev/null +++ b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.dll.REMOVED.git-id @@ -0,0 +1 @@ +5b76c9eff6ad5174965dbaae00f687535380c3a1 \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.dll.REMOVED.git-id new file mode 100644 index 0000000000..b1db618ee3 --- /dev/null +++ b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.dll.REMOVED.git-id @@ -0,0 +1 @@ +8df6f0bf6e9dca89d20ab916dc3c7b449bfbeb4b \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mcs.exe.REMOVED.git-id b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mcs.exe.REMOVED.git-id new file mode 100644 index 0000000000..2178bc4e51 --- /dev/null +++ b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mcs.exe.REMOVED.git-id @@ -0,0 +1 @@ +1d3ebea05d4f45721fc50683072d60048f65e461 \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mscorlib.dll.REMOVED.git-id b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mscorlib.dll.REMOVED.git-id new file mode 100644 index 0000000000..a6d2b3ab6d --- /dev/null +++ b/mcs/class/lib/monolite-macos/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mscorlib.dll.REMOVED.git-id @@ -0,0 +1 @@ +783746cb55609a3dee958691967fb240f9fe1146 \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.InteropServices.dll b/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.InteropServices.dll deleted file mode 100644 index 35cf183d70..0000000000 Binary files a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.InteropServices.dll and /dev/null differ diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.dll b/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.dll deleted file mode 100644 index bc6b42e594..0000000000 Binary files a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.dll and /dev/null differ diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.dll b/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.dll deleted file mode 100644 index 9df009105a..0000000000 Binary files a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.dll and /dev/null differ diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Cecil.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Cecil.dll.REMOVED.git-id deleted file mode 100644 index 610d2262de..0000000000 --- a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Cecil.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -eb0997901e75ba5504d1b7755a7fa64f1d9209b9 \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Security.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Security.dll.REMOVED.git-id deleted file mode 100644 index 2f557d62c6..0000000000 --- a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Security.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -58c0087a3f5050b8dfd57c1efc4591a45330c748 \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Configuration.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Configuration.dll.REMOVED.git-id deleted file mode 100644 index ba5dd7c652..0000000000 --- a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Configuration.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -d14066172fb1b31d3ecc7834f33d86decbee7e4b \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Core.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Core.dll.REMOVED.git-id deleted file mode 100644 index 54574511e8..0000000000 --- a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Core.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -bda9900d9aa879780e77389c653cde3d893e2697 \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Numerics.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Numerics.dll.REMOVED.git-id deleted file mode 100644 index a70dc856a3..0000000000 --- a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Numerics.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -b2fbc4e31e37aaa1f90395e048c3486548d0fd4f \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.dll.REMOVED.git-id deleted file mode 100644 index d0be00e458..0000000000 --- a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -32753c579e227b6d1efce68693870b90d3aa0930 \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.dll.REMOVED.git-id deleted file mode 100644 index dc979adf94..0000000000 --- a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -01766890ba43b0839b5a18cb8a0ffd39579eb0af \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mcs.exe.REMOVED.git-id b/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mcs.exe.REMOVED.git-id deleted file mode 100644 index 38e5f139c7..0000000000 --- a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mcs.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3cf15af9f4dd78bada00c438ff69c15231357837 \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mscorlib.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mscorlib.dll.REMOVED.git-id deleted file mode 100644 index ae7c8ea56b..0000000000 --- a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mscorlib.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -00610ed248040b6bec71a3d6b9a65db6417b2c6f \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.Concurrent.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.Concurrent.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.Concurrent.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.Concurrent.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Debug.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Debug.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Debug.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Debug.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.FileVersionInfo.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.FileVersionInfo.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.FileVersionInfo.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.FileVersionInfo.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Tools.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Tools.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Tools.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Tools.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Dynamic.Runtime.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Dynamic.Runtime.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Dynamic.Runtime.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Dynamic.Runtime.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Globalization.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Globalization.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Globalization.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Globalization.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.Primitives.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.Primitives.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.Primitives.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.Primitives.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.Expressions.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.Expressions.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.Expressions.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.Expressions.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Extensions.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Extensions.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Extensions.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Extensions.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Primitives.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Primitives.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Primitives.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Primitives.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Resources.ResourceManager.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Resources.ResourceManager.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Resources.ResourceManager.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Resources.ResourceManager.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Extensions.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Extensions.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Extensions.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Extensions.dll diff --git a/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.InteropServices.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.InteropServices.dll new file mode 100644 index 0000000000..58d1df3676 Binary files /dev/null and b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.InteropServices.dll differ diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Numerics.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Numerics.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Numerics.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Numerics.dll diff --git a/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.dll new file mode 100644 index 0000000000..3f9a942a61 Binary files /dev/null and b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.dll differ diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Algorithms.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Algorithms.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Algorithms.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Algorithms.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Primitives.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Primitives.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Primitives.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Primitives.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.CodePages.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.CodePages.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.CodePages.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.CodePages.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.Extensions.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.Extensions.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.Extensions.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.Extensions.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.Parallel.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.Parallel.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.Parallel.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.Parallel.dll diff --git a/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.dll new file mode 100644 index 0000000000..bd94187f12 Binary files /dev/null and b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.dll differ diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.ValueTuple.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.ValueTuple.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.ValueTuple.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.ValueTuple.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.ReaderWriter.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.ReaderWriter.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.ReaderWriter.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.ReaderWriter.dll diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.XDocument.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.XDocument.dll similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.XDocument.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.XDocument.dll diff --git a/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Cecil.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Cecil.dll.REMOVED.git-id new file mode 100644 index 0000000000..be37de0f4c --- /dev/null +++ b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Cecil.dll.REMOVED.git-id @@ -0,0 +1 @@ +ac4040e2d669b15a51f36831721a799b30c9d9d8 \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Security.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Security.dll.REMOVED.git-id new file mode 100644 index 0000000000..5e60ced8e5 --- /dev/null +++ b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Security.dll.REMOVED.git-id @@ -0,0 +1 @@ +4f4391e937dcc54a4359d358a1c775bdef279ec8 \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Configuration.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Configuration.dll.REMOVED.git-id new file mode 100644 index 0000000000..47481af8c5 --- /dev/null +++ b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Configuration.dll.REMOVED.git-id @@ -0,0 +1 @@ +0a6705fab6968dae1904e86f6543c5f877d5a4a8 \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Core.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Core.dll.REMOVED.git-id new file mode 100644 index 0000000000..d1547c4f76 --- /dev/null +++ b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Core.dll.REMOVED.git-id @@ -0,0 +1 @@ +a03e85c37ce0d3d08fae6dea915d62fb4c71b5aa \ No newline at end of file diff --git a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.IO.Compression.dll b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.IO.Compression.dll similarity index 99% rename from mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.IO.Compression.dll rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.IO.Compression.dll index 6f54cb8622..1cf8bbab36 100644 Binary files a/mcs/class/lib/monolite-linux/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.IO.Compression.dll and b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.IO.Compression.dll differ diff --git a/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Numerics.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Numerics.dll.REMOVED.git-id new file mode 100644 index 0000000000..e1f1829359 --- /dev/null +++ b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Numerics.dll.REMOVED.git-id @@ -0,0 +1 @@ +32ddda617ddf4b5f8efd69a8440738ca362f1599 \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Security.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Security.dll.REMOVED.git-id similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Security.dll.REMOVED.git-id rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Security.dll.REMOVED.git-id diff --git a/mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.Linq.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.Linq.dll.REMOVED.git-id similarity index 100% rename from mcs/class/lib/monolite-unix/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.Linq.dll.REMOVED.git-id rename to mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.Linq.dll.REMOVED.git-id diff --git a/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.dll.REMOVED.git-id new file mode 100644 index 0000000000..a5cfa9b947 --- /dev/null +++ b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.dll.REMOVED.git-id @@ -0,0 +1 @@ +5b76c9eff6ad5174965dbaae00f687535380c3a1 \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.dll.REMOVED.git-id new file mode 100644 index 0000000000..b1db618ee3 --- /dev/null +++ b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.dll.REMOVED.git-id @@ -0,0 +1 @@ +8df6f0bf6e9dca89d20ab916dc3c7b449bfbeb4b \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mcs.exe.REMOVED.git-id b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mcs.exe.REMOVED.git-id new file mode 100644 index 0000000000..2178bc4e51 --- /dev/null +++ b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mcs.exe.REMOVED.git-id @@ -0,0 +1 @@ +1d3ebea05d4f45721fc50683072d60048f65e461 \ No newline at end of file diff --git a/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mscorlib.dll.REMOVED.git-id b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mscorlib.dll.REMOVED.git-id new file mode 100644 index 0000000000..a6d2b3ab6d --- /dev/null +++ b/mcs/class/lib/monolite-unix/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mscorlib.dll.REMOVED.git-id @@ -0,0 +1 @@ +783746cb55609a3dee958691967fb240f9fe1146 \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.InteropServices.dll b/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.InteropServices.dll deleted file mode 100644 index 35cf183d70..0000000000 Binary files a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.InteropServices.dll and /dev/null differ diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.dll b/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.dll deleted file mode 100644 index bc6b42e594..0000000000 Binary files a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.dll and /dev/null differ diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.dll b/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.dll deleted file mode 100644 index 9df009105a..0000000000 Binary files a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.dll and /dev/null differ diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Cecil.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Cecil.dll.REMOVED.git-id deleted file mode 100644 index 610d2262de..0000000000 --- a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Cecil.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -eb0997901e75ba5504d1b7755a7fa64f1d9209b9 \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Security.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Security.dll.REMOVED.git-id deleted file mode 100644 index 2f557d62c6..0000000000 --- a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Mono.Security.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -58c0087a3f5050b8dfd57c1efc4591a45330c748 \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Configuration.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Configuration.dll.REMOVED.git-id deleted file mode 100644 index ba5dd7c652..0000000000 --- a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Configuration.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -d14066172fb1b31d3ecc7834f33d86decbee7e4b \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Core.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Core.dll.REMOVED.git-id deleted file mode 100644 index 54574511e8..0000000000 --- a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Core.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -bda9900d9aa879780e77389c653cde3d893e2697 \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Numerics.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Numerics.dll.REMOVED.git-id deleted file mode 100644 index a70dc856a3..0000000000 --- a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Numerics.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -b2fbc4e31e37aaa1f90395e048c3486548d0fd4f \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Security.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Security.dll.REMOVED.git-id deleted file mode 100644 index 05d64a9760..0000000000 --- a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Security.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -8df5821845e0e3dc5e8fbb3b055aa5b226c107f1 \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.dll.REMOVED.git-id deleted file mode 100644 index d0be00e458..0000000000 --- a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -32753c579e227b6d1efce68693870b90d3aa0930 \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.dll.REMOVED.git-id deleted file mode 100644 index dc979adf94..0000000000 --- a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -01766890ba43b0839b5a18cb8a0ffd39579eb0af \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mcs.exe.REMOVED.git-id b/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mcs.exe.REMOVED.git-id deleted file mode 100644 index 38e5f139c7..0000000000 --- a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mcs.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3cf15af9f4dd78bada00c438ff69c15231357837 \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mscorlib.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mscorlib.dll.REMOVED.git-id deleted file mode 100644 index ae7c8ea56b..0000000000 --- a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/mscorlib.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -00610ed248040b6bec71a3d6b9a65db6417b2c6f \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.Concurrent.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.Concurrent.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.Concurrent.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.Concurrent.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Collections.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Collections.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Debug.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Debug.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Debug.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Debug.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.FileVersionInfo.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.FileVersionInfo.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.FileVersionInfo.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.FileVersionInfo.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Tools.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Tools.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Diagnostics.Tools.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Diagnostics.Tools.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Dynamic.Runtime.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Dynamic.Runtime.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Dynamic.Runtime.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Dynamic.Runtime.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Globalization.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Globalization.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Globalization.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Globalization.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.Primitives.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.Primitives.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.Primitives.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.Primitives.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.FileSystem.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.FileSystem.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.IO.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.IO.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.Expressions.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.Expressions.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.Expressions.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.Expressions.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Linq.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Linq.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Extensions.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Extensions.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Extensions.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Extensions.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Primitives.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Primitives.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.Primitives.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.Primitives.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Reflection.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Reflection.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Resources.ResourceManager.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Resources.ResourceManager.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Resources.ResourceManager.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Resources.ResourceManager.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Extensions.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Extensions.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Extensions.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Extensions.dll diff --git a/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.InteropServices.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.InteropServices.dll new file mode 100644 index 0000000000..58d1df3676 Binary files /dev/null and b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.InteropServices.dll differ diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Numerics.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Numerics.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Runtime.Numerics.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.Numerics.dll diff --git a/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.dll new file mode 100644 index 0000000000..3f9a942a61 Binary files /dev/null and b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Runtime.dll differ diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Algorithms.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Algorithms.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Algorithms.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Algorithms.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Primitives.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Primitives.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Security.Cryptography.Primitives.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Security.Cryptography.Primitives.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.CodePages.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.CodePages.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.CodePages.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.CodePages.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.Extensions.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.Extensions.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.Extensions.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.Extensions.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Text.Encoding.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Text.Encoding.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.Parallel.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.Parallel.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.Tasks.Parallel.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.Parallel.dll diff --git a/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.dll new file mode 100644 index 0000000000..bd94187f12 Binary files /dev/null and b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.Tasks.dll differ diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Threading.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Threading.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.ValueTuple.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.ValueTuple.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.ValueTuple.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.ValueTuple.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.ReaderWriter.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.ReaderWriter.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.ReaderWriter.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.ReaderWriter.dll diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.XDocument.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.XDocument.dll similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/Facades/System.Xml.XDocument.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Facades/System.Xml.XDocument.dll diff --git a/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Cecil.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Cecil.dll.REMOVED.git-id new file mode 100644 index 0000000000..be37de0f4c --- /dev/null +++ b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Cecil.dll.REMOVED.git-id @@ -0,0 +1 @@ +ac4040e2d669b15a51f36831721a799b30c9d9d8 \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Security.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Security.dll.REMOVED.git-id new file mode 100644 index 0000000000..5e60ced8e5 --- /dev/null +++ b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/Mono.Security.dll.REMOVED.git-id @@ -0,0 +1 @@ +4f4391e937dcc54a4359d358a1c775bdef279ec8 \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Configuration.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Configuration.dll.REMOVED.git-id new file mode 100644 index 0000000000..47481af8c5 --- /dev/null +++ b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Configuration.dll.REMOVED.git-id @@ -0,0 +1 @@ +0a6705fab6968dae1904e86f6543c5f877d5a4a8 \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Core.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Core.dll.REMOVED.git-id new file mode 100644 index 0000000000..d1547c4f76 --- /dev/null +++ b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Core.dll.REMOVED.git-id @@ -0,0 +1 @@ +a03e85c37ce0d3d08fae6dea915d62fb4c71b5aa \ No newline at end of file diff --git a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.IO.Compression.dll b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.IO.Compression.dll similarity index 99% rename from mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.IO.Compression.dll rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.IO.Compression.dll index 6f54cb8622..1cf8bbab36 100644 Binary files a/mcs/class/lib/monolite-macos/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.IO.Compression.dll and b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.IO.Compression.dll differ diff --git a/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Numerics.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Numerics.dll.REMOVED.git-id new file mode 100644 index 0000000000..e1f1829359 --- /dev/null +++ b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Numerics.dll.REMOVED.git-id @@ -0,0 +1 @@ +32ddda617ddf4b5f8efd69a8440738ca362f1599 \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Security.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Security.dll.REMOVED.git-id new file mode 100644 index 0000000000..123f8ebaac --- /dev/null +++ b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Security.dll.REMOVED.git-id @@ -0,0 +1 @@ +7924d993323ee2fdb0e3b7755c997a1ddba2df38 \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.Linq.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.Linq.dll.REMOVED.git-id similarity index 100% rename from mcs/class/lib/monolite-win32/179F7FD7-9CE8-424E-84AF-0DF5B0B8B469/System.Xml.Linq.dll.REMOVED.git-id rename to mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.Linq.dll.REMOVED.git-id diff --git a/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.dll.REMOVED.git-id new file mode 100644 index 0000000000..a5cfa9b947 --- /dev/null +++ b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.Xml.dll.REMOVED.git-id @@ -0,0 +1 @@ +5b76c9eff6ad5174965dbaae00f687535380c3a1 \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.dll.REMOVED.git-id new file mode 100644 index 0000000000..b1db618ee3 --- /dev/null +++ b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/System.dll.REMOVED.git-id @@ -0,0 +1 @@ +8df6f0bf6e9dca89d20ab916dc3c7b449bfbeb4b \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mcs.exe.REMOVED.git-id b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mcs.exe.REMOVED.git-id new file mode 100644 index 0000000000..2178bc4e51 --- /dev/null +++ b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mcs.exe.REMOVED.git-id @@ -0,0 +1 @@ +1d3ebea05d4f45721fc50683072d60048f65e461 \ No newline at end of file diff --git a/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mscorlib.dll.REMOVED.git-id b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mscorlib.dll.REMOVED.git-id new file mode 100644 index 0000000000..a6d2b3ab6d --- /dev/null +++ b/mcs/class/lib/monolite-win32/B886E13F-6276-4BE5-85F8-C6BF5EDBD200/mscorlib.dll.REMOVED.git-id @@ -0,0 +1 @@ +783746cb55609a3dee958691967fb240f9fe1146 \ No newline at end of file diff --git a/mcs/class/referencesource/System.ServiceModel/System/ServiceModel/SynchronizedKeyedCollection.cs b/mcs/class/referencesource/System.ServiceModel/System/ServiceModel/SynchronizedKeyedCollection.cs index a8db189c3b..5cf98137e7 100644 --- a/mcs/class/referencesource/System.ServiceModel/System/ServiceModel/SynchronizedKeyedCollection.cs +++ b/mcs/class/referencesource/System.ServiceModel/System/ServiceModel/SynchronizedKeyedCollection.cs @@ -236,7 +236,7 @@ namespace System.Collections.Generic { if (!(key != null)) { - Fx.Assert("key shouldn't be null!"); + //Fx.Assert("key shouldn't be null!"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key"); } if (this.dictionary != null) diff --git a/mcs/class/referencesource/System/compmod/system/componentmodel/TypeDescriptor.cs.REMOVED.git-id b/mcs/class/referencesource/System/compmod/system/componentmodel/TypeDescriptor.cs.REMOVED.git-id index c388a49870..59917705fd 100644 --- a/mcs/class/referencesource/System/compmod/system/componentmodel/TypeDescriptor.cs.REMOVED.git-id +++ b/mcs/class/referencesource/System/compmod/system/componentmodel/TypeDescriptor.cs.REMOVED.git-id @@ -1 +1 @@ -0783e121a8b8058a221c9497594d8d4597e24dda \ No newline at end of file +bef650013df46600cafccdc6151fb84c89d9fe8b \ No newline at end of file diff --git a/mcs/class/referencesource/mscorlib/system/rttype.cs.REMOVED.git-id b/mcs/class/referencesource/mscorlib/system/rttype.cs.REMOVED.git-id index 39a99e6d7c..66964fc1df 100644 --- a/mcs/class/referencesource/mscorlib/system/rttype.cs.REMOVED.git-id +++ b/mcs/class/referencesource/mscorlib/system/rttype.cs.REMOVED.git-id @@ -1 +1 @@ -ebcc83472ef4e3dfabc85b0df748807dbb8103fd \ No newline at end of file +131a11060435d35ce6b010151023448480ab65f9 \ No newline at end of file diff --git a/mcs/class/referencesource/mscorlib/system/threading/CancellationTokenSource.cs b/mcs/class/referencesource/mscorlib/system/threading/CancellationTokenSource.cs index 8c4ef0216b..dedf07801e 100644 --- a/mcs/class/referencesource/mscorlib/system/threading/CancellationTokenSource.cs +++ b/mcs/class/referencesource/mscorlib/system/threading/CancellationTokenSource.cs @@ -716,7 +716,11 @@ namespace System.Threading // If a cancellation has since come in, we will try to undo the registration and run the callback ourselves. // (this avoids leaving the callback orphaned) +#if MONO + bool deregisterOccurred = registration.Unregister(); +#else bool deregisterOccurred = registration.TryDeregister(); +#endif if (!deregisterOccurred) { diff --git a/mcs/class/referencesource/mscorlib/system/threading/thread.cs b/mcs/class/referencesource/mscorlib/system/threading/thread.cs index 0c6462309f..f2f8346003 100644 --- a/mcs/class/referencesource/mscorlib/system/threading/thread.cs +++ b/mcs/class/referencesource/mscorlib/system/threading/thread.cs @@ -40,8 +40,10 @@ namespace System.Threading { internal class ThreadHelper { +#if !MONO [System.Security.SecuritySafeCritical] static ThreadHelper() {} +#endif Delegate _start; Object _startArg = null; diff --git a/mcs/class/referencesource/mscorlib/system/threading/threadpool.cs b/mcs/class/referencesource/mscorlib/system/threading/threadpool.cs index aaa517a33e..c1fc4e1dbd 100644 --- a/mcs/class/referencesource/mscorlib/system/threading/threadpool.cs +++ b/mcs/class/referencesource/mscorlib/system/threading/threadpool.cs @@ -78,6 +78,19 @@ namespace System.Threading internal static class ThreadPoolGlobals { +#if MONO + public const uint tpQuantum = 30U; + + public static int processorCount => Environment.ProcessorCount; + + public static bool tpHosted => ThreadPool.IsThreadPoolHosted(); + + public static volatile bool vmTpInitialized; + public static bool enableWorkerTracking; + + [SecurityCritical] + public static readonly ThreadPoolWorkQueue workQueue = new ThreadPoolWorkQueue(); +#else //Per-appDomain quantum (in ms) for which the thread keeps processing //requests in the current domain. public static uint tpQuantum = 30U; @@ -96,6 +109,7 @@ namespace System.Threading static ThreadPoolGlobals() { } +#endif } internal sealed class ThreadPoolWorkQueue @@ -1216,8 +1230,10 @@ namespace System.Threading internal sealed class QueueUserWorkItemCallback : IThreadPoolWorkItem { +#if !MONO [System.Security.SecuritySafeCritical] static QueueUserWorkItemCallback() {} +#endif private WaitCallback callback; private ExecutionContext context; diff --git a/mcs/class/referencesource/mscorlib/system/unityserializationholder.cs b/mcs/class/referencesource/mscorlib/system/unityserializationholder.cs index c4b9924fec..914c50e30a 100644 --- a/mcs/class/referencesource/mscorlib/system/unityserializationholder.cs +++ b/mcs/class/referencesource/mscorlib/system/unityserializationholder.cs @@ -96,7 +96,17 @@ namespace System { return type; } - + +#if MONO + internal static void GetUnitySerializationInfo(SerializationInfo info, int unityType) + { + info.SetType(typeof(UnitySerializationHolder)); + info.AddValue("Data", null, typeof(string)); + info.AddValue("UnityType", unityType); + info.AddValue("AssemblyName", string.Empty); + } +#endif + internal static void GetUnitySerializationInfo(SerializationInfo info, RuntimeType type) { if (type.GetRootElementType().IsGenericParameter) diff --git a/mcs/class/test-helpers/TestResourceHelper.cs b/mcs/class/test-helpers/TestResourceHelper.cs new file mode 100644 index 0000000000..9ed3c7309c --- /dev/null +++ b/mcs/class/test-helpers/TestResourceHelper.cs @@ -0,0 +1,85 @@ +// +// TestResourceHelper.cs +// +// Author: +// Alexander Köplinger (alkpli@microsoft.com) +// +// Copyright (C) Microsoft +// +// 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 System; +using System.Globalization; +using System.Reflection; +using System.IO; + +using NUnit.Framework; + +namespace MonoTests.Helpers +{ + public static class TestResourceHelper + { + static string tempFolder; + static Assembly currentAssembly; + + static TestResourceHelper () + { + // create temp directory for extracting all the test resources to disk + tempFolder = Path.Combine (Path.GetTempPath(), Path.GetRandomFileName ()); + Directory.CreateDirectory (tempFolder); + + currentAssembly = Assembly.GetExecutingAssembly (); + foreach (string resourceName in currentAssembly.GetManifestResourceNames ()) + { + // skip non-test assets + if (!resourceName.StartsWith ("Test/")) + continue; + + // persist the resource to disk + var stream = currentAssembly.GetManifestResourceStream (resourceName); + var resourcePath = Path.Combine (tempFolder, resourceName); + Directory.CreateDirectory (Path.GetDirectoryName (resourcePath)); + + using (var file = File.Create (resourcePath)) + { + stream.CopyTo (file); + } + } + + // delete the temp directory at the end of the test process + AppDomain.CurrentDomain.ProcessExit += (s,e) => + { + try { Directory.Delete (tempFolder, true); } + catch { } + }; + } + + public static string GetFullPathOfResource (string resourceName) + { + return Path.Combine (tempFolder, resourceName); + } + + public static Stream GetStreamOfResource (string resourceName) + { + return currentAssembly.GetManifestResourceStream (resourceName); + } + } +} \ No newline at end of file diff --git a/mcs/errors/Makefile b/mcs/errors/Makefile index b957556292..d230375169 100644 --- a/mcs/errors/Makefile +++ b/mcs/errors/Makefile @@ -34,7 +34,8 @@ TEST_SUPPORT_FILES = \ CS8009-lib.dll \ CSFriendAssembly-lib.dll \ dlls/first/CS1704-lib.dll \ - dlls/second/CS1704-lib.dll + dlls/second/CS1704-lib.dll \ + dlls/cs1703-2/System.dll -include $(mcs_topdir)/build/config.make @@ -46,14 +47,7 @@ ifdef VALID_PROFILE qcheck: run-mcs-tests -# again, run-test is when the tests actually happen, so -# don't compile on make test. - -test-local: - @: - -run-test-local: clean-local - $(MAKE) run-mcs-tests +run-test-local: test-local qcheck check: run-test-local @@ -66,8 +60,10 @@ TESTER_OPTIONS = -compiler-options:"-v --break-on-ice -d:NET_4_0;NET_4_5" COMPILER = $(topdir)/class/lib/$(PROFILE)/mcs.exe TESTER = MONO_RUNTIME='$(RUNTIME)' $(TEST_RUNTIME) $(TEST_RUNTIME_FLAGS) $(LOCAL_RUNTIME_FLAGS) $(topdir)/class/lib/$(PROFILE)/compiler-tester.exe -run-mcs-tests: $(TEST_SUPPORT_FILES) - $(TESTER) -mode:neg -files:$(TEST_PATTERN) -compiler:$(COMPILER) -issues:known-issues-$(PROFILE) -log:$(PROFILE).log $(TESTER_OPTIONS) $(TOPTIONS) +test-local: $(TEST_SUPPORT_FILES) + +run-mcs-tests: test-local + $(TESTER) -mode:neg -files:$(TEST_PATTERN) -compiler:$(COMPILER) -reference-dir:$(topdir)/class/lib/$(PROFILE) -issues:known-issues-$(PROFILE) -log:$(PROFILE).log $(TESTER_OPTIONS) $(TOPTIONS) endif @@ -108,13 +104,17 @@ dlls/second/CS1703-lib.dll: dlls/second/CS1703-lib.cs dlls/second/CS1705-lib.dll: dlls/second/CS1705-lib.cs $(CSCOMPILE) /r:$(topdir)/class/lib/$(PROFILE_DIRECTORY)/mscorlib.dll /target:library /warn:0 /publicsign /keyfile:key.snk /out:$@ $< -CS1701-lib.dll : CS1701-lib.cs +dlls/cs1703-2/System.dll: $(topdir)/../external/binary-reference-assemblies/v2.0/System.dll + mkdir -p $(dir $@) + cp $< $@ + +CS1701-lib.dll : CS1701-lib.cs dlls/first/CS1701-lib.dll $(CSCOMPILE) /r:$(topdir)/class/lib/$(PROFILE_DIRECTORY)/mscorlib.dll /target:library /warn:0 /r:dlls/first/CS1701-lib.dll /out:$@ $< -CS1702-lib.dll : CS1702-lib.cs +CS1702-lib.dll : CS1702-lib.cs dlls/first/CS1702-lib.dll $(CSCOMPILE) /r:$(topdir)/class/lib/$(PROFILE_DIRECTORY)/mscorlib.dll /target:library /warn:0 /r:dlls/first/CS1702-lib.dll /out:$@ $< -CS1705-lib.dll : CS1705-lib.cs +CS1705-lib.dll : CS1705-lib.cs dlls/first/CS1705-lib.dll $(CSCOMPILE) /r:$(topdir)/class/lib/$(PROFILE_DIRECTORY)/mscorlib.dll /target:library /warn:0 /r:dlls/first/CS1705-lib.dll /out:$@ $< CSFriendAssembly-lib.dll : CSFriendAssembly-lib.cs diff --git a/mcs/errors/cs1703-2.cs b/mcs/errors/cs1703-2.cs index 5269513cf8..783af2ca44 100644 --- a/mcs/errors/cs1703-2.cs +++ b/mcs/errors/cs1703-2.cs @@ -1,4 +1,3 @@ // CS1703: An assembly `System' with the same identity has already been imported. Consider removing one of the references // Line: 0 -// Compiler options: -r:../../external/binary-reference-assemblies/v2.0/System.dll - +// Compiler options: -r:dlls/cs1703-2/System.dll diff --git a/mcs/jay/jay.vcxproj b/mcs/jay/jay.vcxproj index 653bb388f7..3f8fc4aade 100644 --- a/mcs/jay/jay.vcxproj +++ b/mcs/jay/jay.vcxproj @@ -11,41 +11,44 @@ + Win32 {5D485D32-3B9F-4287-AB24-C8DA5B89F537} jay Win32Proj 8.1 - + Application MultiByte v140 - + Application MultiByte v140 + + true + Win32 + Win32 + - - - - - + + <_ProjectFileVersion>10.0.30319.1 - $(MONO_BUILD_DIR_PREFIX)$(Platform)\bin\$(Configuration)\ - $(MONO_BUILD_DIR_PREFIX)$(Platform)\obj\$(ProjectName)\$(Configuration)\ - true - $(MONO_BUILD_DIR_PREFIX)$(Platform)\bin\$(Configuration)\ - $(MONO_BUILD_DIR_PREFIX)$(Platform)\obj\$(ProjectName)\$(Configuration)\ + $(MONO_BUILD_DIR_PREFIX)$(Platform)\bin\$(Configuration)\ + $(MONO_BUILD_DIR_PREFIX)$(Platform)\obj\$(ProjectName)\$(Configuration)\ + true + $(MONO_BUILD_DIR_PREFIX)$(Platform)\bin\$(Configuration)\ + $(MONO_BUILD_DIR_PREFIX)$(Platform)\obj\$(ProjectName)\$(Configuration)\ - + Disabled SKEL_DIRECTORY=".";%(PreprocessorDefinitions) @@ -64,7 +67,7 @@ false - + SKEL_DIRECTORY=".";%(PreprocessorDefinitions) diff --git a/mcs/mcs/expression.cs.REMOVED.git-id b/mcs/mcs/expression.cs.REMOVED.git-id index 96c93b34ff..2fc38a3aef 100644 --- a/mcs/mcs/expression.cs.REMOVED.git-id +++ b/mcs/mcs/expression.cs.REMOVED.git-id @@ -1 +1 @@ -7c3407f06c501504e47e8717882177b23cc68795 \ No newline at end of file +fe2118084d0d5f82a8993a0f1a03c2865023bceb \ No newline at end of file diff --git a/mcs/mcs/mcs.csproj b/mcs/mcs/mcs.csproj index e43ab2a288..bf94aea3a2 100644 --- a/mcs/mcs/mcs.csproj +++ b/mcs/mcs/mcs.csproj @@ -17,10 +17,10 @@ mcs v4.6.2 - + false @@ -45,6 +45,7 @@ + @@ -198,10 +199,17 @@ {702AE2C0-71DD-4112-9A06-E4FABCA59986} false Never - False + false + + + jay + {5d485d32-3b9f-4287-ab24-c8da5b89f537} + false + Never + false - + @@ -211,6 +219,12 @@ + + + ResolveReferences + $(ProjectDir)\..\jay\jay -ct < $(ProjectDir)\..\jay\skeleton.cs $(ProjectDir)\cs-parser.jay > $(ProjectDir)\cs-parser.cs $(ProjectDir)\..\jay\jay.exe -ct < $(ProjectDir)\..\jay\skeleton.cs $(ProjectDir)\cs-parser.jay > $(ProjectDir)\cs-parser.cs diff --git a/mcs/mcs/settings.cs b/mcs/mcs/settings.cs index 6b763f15e1..976c9b6812 100644 --- a/mcs/mcs/settings.cs +++ b/mcs/mcs/settings.cs @@ -1271,6 +1271,7 @@ namespace Mono.CSharp { case "/highentropyva+": case "/highentropyva-": case "/link": + case "/sourcelink": case "/moduleassemblyname": case "/nowin32manifest": case "/pdb": diff --git a/mcs/nunit24/NUnitMocks/mocks/nunit.mocks.csproj b/mcs/nunit24/NUnitMocks/mocks/nunit.mocks.csproj index 87dd1312a7..ae0c86656d 100644 --- a/mcs/nunit24/NUnitMocks/mocks/nunit.mocks.csproj +++ b/mcs/nunit24/NUnitMocks/mocks/nunit.mocks.csproj @@ -17,10 +17,10 @@ nunit.mocks v4.6.2 - + false @@ -42,6 +42,7 @@ + @@ -57,7 +58,7 @@ - + @@ -67,4 +68,10 @@ + + + ResolveReferences + \ No newline at end of file diff --git a/mcs/tests/Makefile b/mcs/tests/Makefile index a90bdfbbfd..8ccc5172a1 100644 --- a/mcs/tests/Makefile +++ b/mcs/tests/Makefile @@ -1,5 +1,5 @@ # -# use make run-test PROFILE=net_2_0 +# use make run-test # thisdir = tests @@ -57,7 +57,14 @@ LOCAL_RUNTIME_FLAGS = --verify-all COMPILER = $(topdir)/class/lib/$(PROFILE)/mcs.exe TESTER = MONO_RUNTIME='$(RUNTIME)' $(TEST_RUNTIME) $(TEST_RUNTIME_FLAGS) $(LOCAL_RUNTIME_FLAGS) $(topdir)/class/lib/$(PROFILE)/compiler-tester.exe -TEST_ILS := $(wildcard *-lib.il) +TEST_IL := $(wildcard *-lib.il) dlls/test-883.il +TEST_CS := \ + dlls/test-679-2/test-679-lib-2.cs \ + dlls/test-679-1/test-679-lib.cs \ + dlls/test-939-common.cs \ + dlls/test-939-1/test-939-lib.cs \ + dlls/test-939-1/test-939-ref.cs \ + dlls/test-939-2/test-939-lib.cs build-compiler-lib: cd ../class/Mono.CSharp && $(MAKE) NO_DIR_CHECK=yes @@ -71,20 +78,15 @@ KNOWN_ISSUES = known-issues-$(PROFILE) endif qcheck2: - $(TESTER) -mode:pos -files:$(TEST_PATTERN) -compiler:$(COMPILER) -issues:$(KNOWN_ISSUES) -log:$(PROFILE).log -il:ver-il-$(PROFILE).xml $(DEFINES) $(TOPTIONS) + $(TESTER) -mode:pos -files:$(TEST_PATTERN) -compiler:$(COMPILER) -reference-dir:$(topdir)/class/lib/$(PROFILE) -issues:$(KNOWN_ISSUES) -log:$(PROFILE).log -il:ver-il-$(PROFILE).xml $(DEFINES) $(TOPTIONS) gen-mt-tests: - $(TESTER) -mode:nunit -files:'v2' -compiler:$(COMPILER) -issues:known-issues-mt -compiler-options:"-lib:$(topdir)/class/lib/monotouch projects/MonoTouch/ivt.cs" + $(TESTER) -mode:nunit -files:'v2' -compiler:$(COMPILER) -reference-dir:$(topdir)/class/lib/$(PROFILE) -issues:known-issues-mt -compiler-options:"-lib:$(topdir)/class/lib/monotouch projects/MonoTouch/ivt.cs" -TESTERVERBOSE=$(if $(V),-verbose,) +test-local: $(TEST_IL:.il=.dll) $(TEST_CS:.cs=.dll) -test-local: - @: - -compile-all: $(TEST_ILS:.il=.dll) - -run-test-local: compile-all setup qcheck +run-test-local: test-local qcheck check: run-test-local @@ -108,11 +110,23 @@ csproj-local: CSCOMPILE_UTIL = $(CSCOMPILE) -noconfig -nologo -r:$(topdir)/class/lib/$(PROFILE)/mscorlib.dll -setup: - $(CSCOMPILE_UTIL) -t:library dlls/test-679-2/test-679-lib-2.cs -out:dlls/test-679-2/test-679-lib-2.dll - $(CSCOMPILE_UTIL) -t:library dlls/test-679-1/test-679-lib.cs -r:dlls/test-679-2/test-679-lib-2.dll -out:dlls/test-679-1/test-679-lib.dll - $(CSCOMPILE_UTIL) -t:library dlls/test-939-common.cs -keyfile:key.snk -publicsign -out:dlls/test-939-common.dll - $(CSCOMPILE_UTIL) -t:library dlls/test-939-1/test-939-lib.cs -keyfile:key.snk -publicsign -out:dlls/test-939-1/test-939-lib.dll - $(CSCOMPILE_UTIL) -t:library dlls/test-939-1/test-939-ref.cs -r:dlls/test-939-1/test-939-lib.dll -keyfile:key.snk -publicsign -out:dlls/test-939-1/test-939-ref.dll - $(CSCOMPILE_UTIL) -t:library dlls/test-939-2/test-939-lib.cs -r:dlls/test-939-common.dll -keyfile:key.snk -publicsign -out:dlls/test-939-2/test-939-lib.dll +dlls/test-679-2/test-679-lib-2.dll: dlls/test-679-2/test-679-lib-2.cs + $(CSCOMPILE_UTIL) -t:library -out:$@ dlls/test-679-2/test-679-lib-2.cs + +dlls/test-679-1/test-679-lib.dll: dlls/test-679-1/test-679-lib.cs dlls/test-679-2/test-679-lib-2.dll + $(CSCOMPILE_UTIL) -t:library -out:$@ -r:dlls/test-679-2/test-679-lib-2.dll dlls/test-679-1/test-679-lib.cs + +dlls/test-939-common.dll: dlls/test-939-common.cs key.snk + $(CSCOMPILE_UTIL) -t:library -out:$@ dlls/test-939-common.cs -keyfile:key.snk -publicsign + +dlls/test-939-1/test-939-lib.dll: dlls/test-939-1/test-939-lib.cs key.snk + $(CSCOMPILE_UTIL) -t:library -out:$@ dlls/test-939-1/test-939-lib.cs -keyfile:key.snk -publicsign + +dlls/test-939-1/test-939-ref.dll: dlls/test-939-1/test-939-ref.cs dlls/test-939-1/test-939-lib.dll key.snk + $(CSCOMPILE_UTIL) -t:library -out:$@ dlls/test-939-1/test-939-ref.cs -r:dlls/test-939-1/test-939-lib.dll -keyfile:key.snk -publicsign + +dlls/test-939-2/test-939-lib.dll: dlls/test-939-2/test-939-lib.cs dlls/test-939-common.dll key.snk + $(CSCOMPILE_UTIL) -t:library -out:$@ dlls/test-939-2/test-939-lib.cs -r:dlls/test-939-common.dll -keyfile:key.snk -publicsign + +dlls/test-883.dll: dlls/test-883.il $(ILASM) -dll dlls/test-883.il diff --git a/mcs/tests/gtest-exmethod-23.cs b/mcs/tests/gtest-exmethod-23.cs index 936d89ee38..82fcc82c1c 100644 --- a/mcs/tests/gtest-exmethod-23.cs +++ b/mcs/tests/gtest-exmethod-23.cs @@ -1,4 +1,4 @@ -// Compiler options: -nostdlib -noconfig -r:mscorlib.dll -r:System.Core.dll -lib:../class/lib/net_4_x +// Compiler options: -nostdlib -noconfig -r:mscorlib.dll -r:System.Core.dll -lib:$REF_DIR public static class T { diff --git a/mcs/tests/test-695.cs b/mcs/tests/test-695.cs index 1db1225cf1..9f6465d3cd 100644 --- a/mcs/tests/test-695.cs +++ b/mcs/tests/test-695.cs @@ -1,4 +1,4 @@ -// Compiler options: -r:../class/lib/net_4_x/Mono.Cecil.dll +// Compiler options: -r:$REF_DIR/Mono.Cecil.dll using System; using System.IO; diff --git a/mcs/tests/test-814.cs b/mcs/tests/test-814.cs index d6a9e76dea..8003ad6509 100644 --- a/mcs/tests/test-814.cs +++ b/mcs/tests/test-814.cs @@ -1,4 +1,4 @@ -// Compiler options: -r:../class/lib/net_4_x/Mono.Cecil.dll +// Compiler options: -r:$REF_DIR/Mono.Cecil.dll using System; using Mono.Cecil; diff --git a/mcs/tests/test-937.cs b/mcs/tests/test-937.cs index b577d34e7f..cc30b15d8e 100644 --- a/mcs/tests/test-937.cs +++ b/mcs/tests/test-937.cs @@ -1,4 +1,4 @@ -// Compiler options: /noconfig /nostdlib -r:../class/lib/net_4_x/Facades/System.Runtime.dll -r:../class/lib/net_4_x/mscorlib.dll +// Compiler options: /noconfig /nostdlib -r:$REF_DIR/Facades/System.Runtime.dll -r:$REF_DIR/mscorlib.dll using System; diff --git a/mcs/tests/test-anon-123.cs b/mcs/tests/test-anon-123.cs index 91c72b45af..45aab27c0a 100644 --- a/mcs/tests/test-anon-123.cs +++ b/mcs/tests/test-anon-123.cs @@ -1,3 +1,4 @@ +// Compiler options: -langversion:latest // Cloning tests using System; @@ -103,7 +104,11 @@ public class C : B default: break; } - }); + }); + + Test (() => { + char ch = default; + }); var c = new C (); c.InstanceTests (); diff --git a/mcs/tests/test-async-76.cs b/mcs/tests/test-async-76.cs index 7012722bb9..b7e5da9ef3 100644 --- a/mcs/tests/test-async-76.cs +++ b/mcs/tests/test-async-76.cs @@ -1,4 +1,4 @@ -// Compiler options: -r:../class/lib/net_4_x/Mono.Cecil.dll +// Compiler options: -r:$REF_DIR/Mono.Cecil.dll using System; using System.Threading.Tasks; diff --git a/mcs/tests/ver-il-net_4_x.xml.REMOVED.git-id b/mcs/tests/ver-il-net_4_x.xml.REMOVED.git-id index fabcd342a0..5ca335746e 100644 --- a/mcs/tests/ver-il-net_4_x.xml.REMOVED.git-id +++ b/mcs/tests/ver-il-net_4_x.xml.REMOVED.git-id @@ -1 +1 @@ -40c2d585df3aa012f8646c4cc723ef60fa4ca87f \ No newline at end of file +9e9a70426862d1af22c9c9160cc29d1039dc8a8b \ No newline at end of file diff --git a/mcs/tools/Makefile b/mcs/tools/Makefile index b7a4dce3ee..e3782fc902 100644 --- a/mcs/tools/Makefile +++ b/mcs/tools/Makefile @@ -47,18 +47,19 @@ net_4_5_dirs := \ mdb2ppdb \ ikdasm \ mono-symbolicate \ - linker-analyzer + linker-analyzer \ + gacutil -build_SUBDIRS = resgen gacutil security culevel cil-stringreplacer commoncryptogenerator resx2sr linker cil-strip corcompare mono-api-diff mono-api-html -monodroid_tools_SUBDIRS = cil-strip linker-analyzer mkbundle mdoc mono-symbolicate +build_SUBDIRS = +build_PARALLEL_SUBDIRS := resgen gacutil security culevel commoncryptogenerator resx2sr linker cil-strip corcompare mono-api-diff mono-api-html +monodroid_tools_SUBDIRS = +monodroid_tools_PARALLEL_SUBDIRS = cil-strip linker-analyzer mkbundle mdoc mono-symbolicate monodroid_SUBDIRS = nunit-lite monotouch_SUBDIRS = nunit-lite -net_4_5_SUBDIRS = gacutil -net_4_x_SUBDIRS = gacutil -net_4_5_PARALLEL_SUBDIRS = $(net_4_5_dirs) +net_4_x_SUBDIRS = net_4_x_PARALLEL_SUBDIRS = $(net_4_5_dirs) -SUBDIRS = $(build_SUBDIRS) $(net_4_5_dirs) +DIST_SUBDIRS = $(net_4_5_dirs) cil-stringreplacer commoncryptogenerator resx2sr include ../build/rules.make diff --git a/mcs/tools/cil-strip/cilstrip.cs b/mcs/tools/cil-strip/cilstrip.cs index ec80b178ca..97cd4669ee 100644 --- a/mcs/tools/cil-strip/cilstrip.cs +++ b/mcs/tools/cil-strip/cilstrip.cs @@ -8,6 +8,7 @@ // using System; +using System.Collections.Generic; using System.Reflection; using Mono.Cecil; @@ -15,25 +16,32 @@ using Mono.Cecil; namespace Mono.CilStripper { class Program { - - static int Main (string [] args) + static bool quiet; + static int Main (string [] arguments) { + var args = new List (arguments); + if (args.Count > 0 && args [0] == "-q") { + quiet = true; + args.RemoveAt (0); + } Header (); - if (args.Length == 0) + if (args.Count == 0) Usage (); string file = args [0]; - string output = args.Length > 1 ? args [1] : file; + string output = args.Count > 1 ? args [1] : file; try { AssemblyDefinition assembly = AssemblyFactory.GetAssembly (file); StripAssembly (assembly, output); - if (file != output) - Console.WriteLine ("Assembly {0} stripped out into {1}", file, output); - else - Console.WriteLine ("Assembly {0} stripped", file); + if (!quiet) { + if (file != output) + Console.WriteLine ("Assembly {0} stripped out into {1}", file, output); + else + Console.WriteLine ("Assembly {0} stripped", file); + } return 0; } catch (TargetInvocationException tie) { Console.WriteLine ("Error: {0}", tie.InnerException); @@ -50,13 +58,16 @@ namespace Mono.CilStripper { static void Header () { + if (quiet) + return; Console.WriteLine ("Mono CIL Stripper"); Console.WriteLine (); } static void Usage () { - Console.WriteLine ("Usage: mono-cil-strip file [output]"); + Console.WriteLine ("Usage: mono-cil-strip [options] file [output]"); + Console.WriteLine (" -q Only output errors."); Environment.Exit (1); } } diff --git a/mcs/tools/compiler-tester/compiler-tester.cs b/mcs/tools/compiler-tester/compiler-tester.cs index 181028ddb4..2d66fa3b1a 100644 --- a/mcs/tools/compiler-tester/compiler-tester.cs +++ b/mcs/tools/compiler-tester/compiler-tester.cs @@ -423,18 +423,21 @@ namespace TestRunner { class Checker: MarshalByRefObject, IDisposable { protected ITester tester; - protected int success; protected int total; protected int ignored; protected int syntax_errors; string issue_file; StreamWriter log_file; + StreamWriter result_xml; protected string[] extra_compiler_options; + protected string reference_dir; // protected string[] compiler_options; // protected string[] dependencies; protected ArrayList tests = new ArrayList (); protected Hashtable test_hash = new Hashtable (); + protected Dictionary file_log_lines = new Dictionary (); + protected ArrayList succeeded = new ArrayList (); protected ArrayList regression = new ArrayList (); protected ArrayList know_issues = new ArrayList (); protected ArrayList ignore_list = new ArrayList (); @@ -464,6 +467,17 @@ namespace TestRunner { } } + public string ResultXml { + set { + this.result_xml = new StreamWriter (value, false); + } + } + + public string Name { + get; + set; + } + public bool Verbose { set { verbose = value; @@ -482,6 +496,12 @@ namespace TestRunner { } } + public string ReferenceDirectory { + set { + reference_dir = value; + } + } + protected virtual bool GetExtraOptions (string file, out string[] compiler_options, out string[] dependencies) { @@ -519,7 +539,7 @@ namespace TestRunner { if (index != -1) { compiler_options = line.Substring (index + options.Length).Trim().Split (' '); for (int i = 0; i < compiler_options.Length; i++) - compiler_options[i] = compiler_options[i].TrimStart (); + compiler_options[i] = compiler_options[i].TrimStart ().Replace ("$REF_DIR", reference_dir); } index = line.IndexOf (depends); if (index != -1) { @@ -536,6 +556,8 @@ namespace TestRunner { if (test_hash.Contains (filename)) return true; + file_log_lines.Add (filename, new StringBuilder ()); + if (verbose) Log (filename + "...\t"); @@ -641,8 +663,8 @@ namespace TestRunner { LogLine ("Done" + Environment.NewLine); float rate = 0; if (total > 0) - rate = (float) (success) / (float)total; - LogLine ("{0} test cases passed ({1:0.##%})", success, rate); + rate = (float) (succeeded.Count) / (float)total; + LogLine ("{0} test cases passed ({1:0.##%})", succeeded.Count, rate); if (syntax_errors > 0) LogLine ("{0} test(s) ignored because of wrong syntax !", syntax_errors); @@ -668,6 +690,72 @@ namespace TestRunner { } } + protected virtual void OutputResultXml () + { + if (result_xml == null) + return; + + var xmlWriter = new XmlTextWriter (result_xml); + xmlWriter.Formatting = Formatting.Indented; + + xmlWriter.WriteStartDocument (); + + xmlWriter.WriteStartElement ("assemblies"); + + xmlWriter.WriteStartElement ("assembly"); + + xmlWriter.WriteAttributeString ("name", Name); + xmlWriter.WriteAttributeString ("environment", $"compiler-tester-version: {Assembly.GetExecutingAssembly ().GetName ()}, clr-version: {Environment.Version}, os-version: {Environment.OSVersion}, platform: {Environment.OSVersion.Platform}, cwd: {Environment.CurrentDirectory}, machine-name: {Environment.MachineName}, user: {Environment.UserName}, user-domain: {Environment.UserDomainName}"); + xmlWriter.WriteAttributeString ("test-framework", "compiler-tester"); + xmlWriter.WriteAttributeString ("run-date", XmlConvert.ToString (DateTime.Now, "yyyy-MM-dd")); + xmlWriter.WriteAttributeString ("run-time", XmlConvert.ToString (DateTime.Now, "HH:mm:ss")); + + xmlWriter.WriteAttributeString ("total", (succeeded.Count + regression.Count).ToString ()); // ignore known issues and ignored tests for now, we care mostly about failures + xmlWriter.WriteAttributeString ("errors", 0.ToString ()); + xmlWriter.WriteAttributeString ("failed", (regression.Count).ToString ()); + xmlWriter.WriteAttributeString ("skipped", 0.ToString ()); + + xmlWriter.WriteAttributeString ("passed", succeeded.Count.ToString ()); + + xmlWriter.WriteStartElement ("collection"); + xmlWriter.WriteAttributeString ("name", "tests"); + + foreach (var t in succeeded) { + xmlWriter.WriteStartElement ("test"); + xmlWriter.WriteAttributeString ("name", Name + ".tests." + t); + xmlWriter.WriteAttributeString ("type", Name + ".tests"); + xmlWriter.WriteAttributeString ("method", t.ToString ()); + xmlWriter.WriteAttributeString ("result", "Pass"); + xmlWriter.WriteAttributeString ("time", "0"); + xmlWriter.WriteEndElement (); // test element + } + + foreach (var t in regression) { + xmlWriter.WriteStartElement ("test"); + xmlWriter.WriteAttributeString ("name", Name + ".tests." + t); + xmlWriter.WriteAttributeString ("type", Name + ".tests"); + xmlWriter.WriteAttributeString ("method", t.ToString ()); + xmlWriter.WriteAttributeString ("result", "Fail"); + xmlWriter.WriteAttributeString ("time", "0"); + + xmlWriter.WriteStartElement ("failure"); + xmlWriter.WriteAttributeString ("exception-type", "CompilerTesterException"); + xmlWriter.WriteStartElement ("message"); + xmlWriter.WriteCData (file_log_lines[(string)t].ToString ()); + xmlWriter.WriteEndElement (); // message element + xmlWriter.WriteEndElement(); // failure element + + xmlWriter.WriteEndElement(); // test element + } + + xmlWriter.WriteEndElement (); // collection + xmlWriter.WriteEndElement (); // assembly + xmlWriter.WriteEndElement (); // assemblies + xmlWriter.WriteEndDocument (); + xmlWriter.Flush (); + xmlWriter.Close (); + } + public int ResultCode { get { @@ -696,11 +784,24 @@ namespace TestRunner { log_file.WriteLine (msg, rest); } + protected void LogLineForFile (string file, string msg) + { + file_log_lines[file].AppendLine (msg); + LogLine (msg); + } + + protected void LogLineForFile (string file, string msg, params object [] rest) + { + file_log_lines[file].AppendLine (String.Format (msg, rest)); + LogLine (msg, rest); + } + public void LogFileLine (string file, string msg) { string s = verbose ? msg : file + "...\t" + msg; Console.WriteLine (s); + file_log_lines[file].AppendLine (s); if (log_file != null) log_file.WriteLine (s); } @@ -722,6 +823,7 @@ namespace TestRunner { public virtual void CleanUp () { PrintSummary (); + OutputResultXml (); } } @@ -1138,7 +1240,7 @@ namespace TestRunner { { switch (status) { case TestResult.Success: - success++; + succeeded.Add (file); if (know_issues.Contains (file)) { LogFileLine (file, "FIXED ISSUE"); return; @@ -1196,7 +1298,7 @@ namespace TestRunner { } if (extra != null) - LogLine ("{0}", extra); + LogLineForFile (file, "{0}", extra); if (!regression.Contains (file)) regression.Add (file); @@ -1377,12 +1479,12 @@ namespace TestRunner { CompilerError result_code = GetCompilerError (expected, tester.Output); if (HandleFailure (filename, result_code)) { - success++; + succeeded.Add (filename); return true; } if (result_code == CompilerError.Wrong) - LogLine (tester.Output); + LogLineForFile (filename, tester.Output); return false; } @@ -1494,8 +1596,8 @@ namespace TestRunner { } else { LogFileLine (file, "REGRESSION (CORRECT ERROR -> WRONG ERROR MESSAGE)"); - LogLine ("Exp: {0}", expected_message); - LogLine ("Was: {0}", error_message); + LogLineForFile (file, "Exp: {0}", expected_message); + LogLineForFile (file, "Was: {0}", error_message); } break; @@ -1626,10 +1728,14 @@ namespace TestRunner { checker.IssueFile = temp; if (GetOption ("log", args, true, out temp)) checker.LogFile = temp; + if (GetOption ("resultXml", args, true, out temp)) + checker.ResultXml = temp; if (GetOption ("verbose", args, false, out temp)) checker.Verbose = true; if (GetOption ("safe-execution", args, false, out temp)) checker.SafeExecution = true; + if (GetOption ("reference-dir", args, true, out temp)) + checker.ReferenceDirectory = temp; if (GetOption ("compiler-options", args, true, out temp)) { string[] extra = temp.Split (' '); checker.ExtraCompilerOptions = extra; @@ -1641,19 +1747,20 @@ namespace TestRunner { return 1; } - var files = new List (); + var files = new List (); + var test_directory = new DirectoryInfo ("."); switch (test_pattern) { case "v1": - files.AddRange (Directory.GetFiles (".", positive ? "test*.cs" : "cs*.cs")); + files.AddRange (test_directory.EnumerateFiles (positive ? "test*.cs" : "cs*.cs")); break; case "v2": - files.AddRange (Directory.GetFiles (".", positive ? "gtest*.cs" : "gcs*.cs")); + files.AddRange (test_directory.EnumerateFiles (positive ? "gtest*.cs" : "gcs*.cs")); goto case "v1"; case "v4": - files.AddRange (Directory.GetFiles (".", positive ? "dtest*.cs" : "dcs*.cs")); + files.AddRange (test_directory.EnumerateFiles (positive ? "dtest*.cs" : "dcs*.cs")); goto case "v2"; default: - files.AddRange (Directory.GetFiles (".", test_pattern)); + files.AddRange (test_directory.EnumerateFiles (test_pattern)); break; } @@ -1662,6 +1769,7 @@ namespace TestRunner { return 2; } + checker.Name = test_directory.Name; checker.Initialize (); /* files.Sort ((a, b) => { @@ -1676,8 +1784,8 @@ namespace TestRunner { return a.CompareTo (b); }); */ - foreach (string s in files) { - string filename = Path.GetFileName (s); + foreach (FileInfo s in files) { + string filename = s.Name; if (Char.IsUpper (filename, 0)) { // Windows hack continue; } @@ -1727,9 +1835,11 @@ namespace TestRunner { " \n" + " -compiler:FILE The file which will be used to compiler tests\n" + " -compiler-options:OPTIONS Add global compiler options\n" + + " -reference-dir:DIRECTORY Use this directory for $REF_DIR variable in tests\n" + " -il:IL-FILE XML file with expected IL details for each test\n" + " -issues:FILE The list of expected failures\n" + " -log:FILE Writes any output also to the file\n" + + " -resultXml:FILE Writes test result data in xUnit.net v2 format to the file\n" + " -help Lists all options\n" + " -mode:[pos|neg] Specifies compiler test mode\n" + " -safe-execution Runs compiled executables in separate app-domain\n" + diff --git a/mcs/tools/linker/Makefile b/mcs/tools/linker/Makefile index 75d950fc66..bb608c46a8 100644 --- a/mcs/tools/linker/Makefile +++ b/mcs/tools/linker/Makefile @@ -11,16 +11,17 @@ TEST_CASES := \ mscorlib/test-exception-01.cs \ mscorlib/test-locale-01.cs \ mscorlib/test-reflection-01.cs \ + mscorlib/test-reflection-02.cs \ mscorlib/test-string-01.cs \ mscorlib/test-string-02.cs \ mscorlib/test-string-03.cs \ mscorlib/test-task-01.cs \ +# mscorlib/test-marshaling.cs \ System/test-security.cs ifdef MOBILE_PROFILE TEST_CASES += \ -# Requires linker fix -# mscorlib/test-crypto-01.cs + mscorlib/test-crypto-01.cs endif ifndef AOT_FRIENDLY_PROFILE @@ -33,6 +34,8 @@ SIZE_TEST_CASES := TESTS_COMPILER = $(MCS) -nologo -noconfig -unsafe -debug:portable -r:$(topdir)/class/lib/$(PROFILE_DIRECTORY)/mscorlib.dll +MARSHALING_TEST_NATIVE = mscorlib/test-marshaling-native.so + check: compile-tests $(MAKE) run-tests @@ -41,14 +44,31 @@ compile-tests: $(TEST_CASES) $(SIZE_TEST_CASES) mscorlib/test-%.cs: $(TESTS_COMPILER) Tests/$@ /out:Tests/$(@:.cs=.exe) +$(MARSHALING_TEST_NATIVE): $(@:.so=.c) + $(CCOMPILE) Tests/$(@:.so=.c) -shared -o Tests/$@ + +mscorlib/test-marshaling.cs: $(MARSHALING_TEST_NATIVE) + $(TESTS_COMPILER) Tests/$@ /out:Tests/$(@:.cs=.exe) + System/test-%.cs: $(TESTS_COMPILER) -r:$(topdir)/class/lib/$(PROFILE_DIRECTORY)/System.dll Tests/$@ /out:Tests/$(@:.cs=.exe) run-tests: $(TEST_CASES:.cs=.exe) +LINKER_PROFILE_OPTIONS := + +# Should be in sync with runtime sdk flags +ifeq ($(PROFILE),monotouch) +LINKER_PROFILE_OPTIONS += --exclude-feature remoting --exclude-feature com +endif + +ifeq ($(PROFILE),wasm) +LINKER_PROFILE_OPTIONS += --exclude-feature remoting --exclude-feature com --exclude-feature sre +endif + LINKER_OUTPUT := illink-output-$(PROFILE_DIRECTORY) PROFILE_PATH = $(topdir)/class/lib/$(PROFILE_DIRECTORY) -LINKER = MONO_PATH=$(topdir)/class/lib/$(BUILD_TOOLS_PROFILE) $(RUNTIME) $(RUNTIME_FLAGS) $(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)/monolinker.exe -c link -out $(LINKER_OUTPUT) -b true -d $(PROFILE_PATH) +LINKER = MONO_PATH=$(topdir)/class/lib/$(BUILD_TOOLS_PROFILE) $(RUNTIME) $(RUNTIME_FLAGS) $(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)/monolinker.exe -c link -out $(LINKER_OUTPUT) -b true -d $(PROFILE_PATH) $(LINKER_PROFILE_OPTIONS) TEST_EXEC = MONO_PATH=$(LINKER_OUTPUT) $(RUNTIME) $(RUNTIME_FLAGS) --debug -O=-aot .NOTPARALLEL: @@ -61,6 +81,15 @@ System/test-%.exe mscorlib/test-%.exe: $(TEST_EXEC) $(LINKER_OUTPUT)/$(@F) @rm -rf $(LINKER_OUTPUT) +mscorlib/test-marshaling.exe: $(MARSHALING_TEST_NATIVE) + @rm -rf $(LINKER_OUTPUT) + @mkdir $(LINKER_OUTPUT) + @echo Testing $@ + $(LINKER) -a Tests/$@ + cp Tests/$(MARSHALING_TEST_NATIVE) $(LINKER_OUTPUT) + (cd $(LINKER_OUTPUT); MONO_PATH=. $(RUNTIME) $(RUNTIME_FLAGS) --debug -O=-aot ./$(@F)) + @rm -rf $(LINKER_OUTPUT) + BCL_ASSEMBLIES_CORE=mscorlib.dll System.dll System.Core.dll System.Xml.dll BCL_ASSEMBLIES=$(BCL_ASSEMBLIES_CORE) $(sort $(filter-out $(BCL_ASSEMBLIES_CORE), $(notdir $(wildcard $(PROFILE_PATH)/System.*.dll)) )) @@ -88,13 +117,15 @@ bcl-size-diff: $(Q) $(MAKE) bcl-size-current PROFILE=net_4_x || true $(Q) $(MAKE) bcl-size-current PROFILE=monotouch || true $(Q) $(MAKE) bcl-size-current PROFILE=monodroid || true + $(Q) $(MAKE) bcl-size-current PROFILE=wasm || true @echo "Checking size differences..." @mkdir -p sizediff $(Q) git diff HEAD "*.csv" > temp.patch $(Q) git show HEAD:./net_4_x-linked-size.csv > net_4_x-linked-size.old.csv $(Q) git show HEAD:./monotouch-linked-size.csv > monotouch-linked-size.old.csv $(Q) git show HEAD:./monodroid-linked-size.csv > monodroid-linked-size.old.csv - $(Q) sed -e "/@diffdata@/r temp.patch" -e "/@diffdata@/d" -e "/@olddata-net_4_x@/r net_4_x-linked-size.old.csv" -e "/@olddata-net_4_x@/d" -e "/@olddata-monotouch@/r monotouch-linked-size.old.csv" -e "/@olddata-monotouch@/d" -e "/@olddata-monodroid@/r monodroid-linked-size.old.csv" -e "/@olddata-monodroid@/d" -e "/@newdata-net_4_x@/r net_4_x-linked-size.csv" -e "/@newdata-net_4_x@/d" -e "/@newdata-monotouch@/r monotouch-linked-size.csv" -e "/@newdata-monotouch@/d" -e "/@newdata-monodroid@/r monodroid-linked-size.csv" -e "/@newdata-monodroid@/d" linked-size-diff.html.in > sizediff/index.html + $(Q) git show HEAD:./wasm-linked-size.csv > wasm-linked-size.old.csv + $(Q) sed -e "/@diffdata@/r temp.patch" -e "/@diffdata@/d" -e "/@olddata-net_4_x@/r net_4_x-linked-size.old.csv" -e "/@olddata-net_4_x@/d" -e "/@olddata-monotouch@/r monotouch-linked-size.old.csv" -e "/@olddata-monotouch@/d" -e "/@olddata-monodroid@/r monodroid-linked-size.old.csv" -e "/@olddata-monodroid@/d" -e "/@olddata-wasm@/r wasm-linked-size.old.csv" -e "/@olddata-wasm@/d" -e "/@newdata-net_4_x@/r net_4_x-linked-size.csv" -e "/@newdata-net_4_x@/d" -e "/@newdata-monotouch@/r monotouch-linked-size.csv" -e "/@newdata-monotouch@/d" -e "/@newdata-monodroid@/r monodroid-linked-size.csv" -e "/@newdata-monodroid@/d" -e "/@newdata-wasm@/r wasm-linked-size.csv" -e "/@newdata-wasm@/d" linked-size-diff.html.in > sizediff/index.html $(Q) if [ -s temp.patch ]; then echo "Error: Found BCL Linked Size differences, see mcs/tools/linker/sizediff/index.html."; rm -f temp.patch *.old.csv; exit 1; else echo "No differences found."; rm -f temp.patch *.old.csv; fi include ../../build/executable.make diff --git a/mcs/tools/linker/monolinker.exe.sources b/mcs/tools/linker/monolinker.exe.sources index bbec634d73..2ea74b8881 100644 --- a/mcs/tools/linker/monolinker.exe.sources +++ b/mcs/tools/linker/monolinker.exe.sources @@ -37,3 +37,4 @@ ../../../external/linker/linker/Linker.Steps/TypeMapStep.cs ../../../external/linker/linker/Linker.Steps/IStep.cs ../../../external/linker/linker/Linker.Steps/AddBypassNGenStep.cs +../../../external/linker/linker/Linker.Steps/PreserveDependencyLookupStep.cs diff --git a/mcs/tools/mkbundle/bundle-mono-api.inc b/mcs/tools/mkbundle/bundle-mono-api.inc index 1035d9a5a4..6af254ff09 100644 --- a/mcs/tools/mkbundle/bundle-mono-api.inc +++ b/mcs/tools/mkbundle/bundle-mono-api.inc @@ -18,7 +18,7 @@ typedef struct BundleMonoAPI { void (*mono_register_bundled_assemblies) (const MonoBundledAssembly **assemblies); void (*mono_register_config_for_assembly) (const char* assembly_name, const char* config_xml); - void (*mono_jit_set_aot_mode) (int mode); + void (*mono_jit_set_aot_mode) (MonoAotMode mode); void (*mono_aot_register_module) (void* aot_info); void (*mono_config_parse_memory) (const char *buffer); void (*mono_register_machine_config) (const char *config_xml); diff --git a/mcs/tools/mkbundle/mkbundle.cs b/mcs/tools/mkbundle/mkbundle.cs index e0e81d547b..fa4460f236 100755 --- a/mcs/tools/mkbundle/mkbundle.cs +++ b/mcs/tools/mkbundle/mkbundle.cs @@ -470,7 +470,7 @@ class MakeBundle { // Modern bundling starts here if (!custom_mode){ if (runtime != null){ - // Nothing to do here, the user has chosen to manually specify --runtime nad libraries + // Nothing to do here, the user has chosen to manually specify --runtime and libraries } else if (sdk_path != null) { VerifySdk (sdk_path); } else if (cross_target == "default" || cross_target == null){ @@ -655,15 +655,28 @@ class MakeBundle { class PackageMaker { Dictionary> locations = new Dictionary> (); - const int align = 4096; + int align = 4096; // first non-Windows alignment, saving on average 30K Stream package; - public PackageMaker (string output) + public PackageMaker (string runtime, string output) { package = File.Create (output, 128*1024); if (IsUnix){ File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000)); } + + Console.WriteLine ("Using runtime: " + runtime); + + // Probe for MZ signature to decide if we are targeting Windows, + // so we can optimize an average of 30K away on Unix. + using (Stream runtimeStream = File.OpenRead (runtime)) { + var runtimeBuffer = new byte [2]; + if (runtimeStream.Read (runtimeBuffer, 0, 2) == 2 + && runtimeBuffer [0] == (byte)'M' + && runtimeBuffer [1] == (byte)'Z') + align = 1 << 16; // first Windows alignment + } + AddFile (runtime); } public int AddFile (string fname) @@ -675,6 +688,7 @@ class MakeBundle { Console.WriteLine ("At {0:x} with input {1}", package.Position, fileStream.Length); fileStream.CopyTo (package); package.Position = package.Position + (align - (package.Position % align)); + align = 4096; // rest of alignment for all systems return (int) ret; } } @@ -688,14 +702,17 @@ class MakeBundle { public void AddString (string entry, string text) { + // FIXME Strings are over-aligned? var bytes = Encoding.UTF8.GetBytes (text); locations [entry] = Tuple.Create (package.Position, bytes.Length); package.Write (bytes, 0, bytes.Length); + package.WriteByte (0); package.Position = package.Position + (align - (package.Position % align)); } public void AddStringPair (string entry, string key, string value) { + // FIXME Strings are over-aligned? var kbytes = Encoding.UTF8.GetBytes (key); var vbytes = Encoding.UTF8.GetBytes (value); @@ -785,9 +802,7 @@ class MakeBundle { return false; } - var maker = new PackageMaker (output); - Console.WriteLine ("Using runtime: " + runtime); - maker.AddFile (runtime); + var maker = new PackageMaker (runtime, output); foreach (var url in files){ string fname = LocateFile (new Uri (url).LocalPath); @@ -884,6 +899,7 @@ typedef struct { template_stream.Dispose (); if (compress) { + tc.WriteLine ("#define USE_COMPRESSED_ASSEMBLY\n"); tc.WriteLine ("typedef struct _compressed_data {"); tc.WriteLine ("\tMonoBundledAssembly assembly;"); tc.WriteLine ("\tint compressed_size;"); @@ -973,7 +989,7 @@ typedef struct { FileStream cf = File.OpenRead (fname + ".config"); if (!quiet) Console.WriteLine (" config from: " + fname + ".config"); - tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded); + tc.WriteLine ("extern const char assembly_config_{0} [];", encoded); WriteSymbol (ts, "assembly_config_" + encoded, cf.Length); WriteBuffer (ts, cf, buffer); ts.WriteLine (); @@ -1044,7 +1060,8 @@ typedef struct { tc.WriteLine ("\textern const void *mono_aot_module_{0}_info;", asm); } - tc.WriteLine ("\nstatic void install_aot_modules (void) {\n"); + tc.WriteLine ("\n#ifndef USE_COMPRESSED_ASSEMBLY\n"); + tc.WriteLine ("static void install_aot_modules (void) {\n"); foreach (string asm in aot_names){ tc.WriteLine ("\tmono_api.mono_aot_register_module (mono_aot_module_{0}_info);\n", asm); } @@ -1066,6 +1083,7 @@ typedef struct { tc.WriteLine ("\tmono_api.mono_jit_set_aot_mode ({0});", enum_aot_mode); tc.WriteLine ("\n}\n"); + tc.WriteLine ("#endif\n"); tc.WriteLine ("static char *image_name = \"{0}\";", prog); diff --git a/mcs/tools/mkbundle/template_common.inc b/mcs/tools/mkbundle/template_common.inc index a0339ee5c5..ab0a9a77e4 100644 --- a/mcs/tools/mkbundle/template_common.inc +++ b/mcs/tools/mkbundle/template_common.inc @@ -18,6 +18,8 @@ void initialize_mono_api (const BundleMonoAPI *info) mono_api.mono_register_machine_config = info->mono_register_machine_config; } +#ifdef USE_COMPRESSED_ASSEMBLY + static int validate_api_pointer (const char *name, void *ptr) { @@ -47,6 +49,12 @@ validate_api_struct () exit (1); } +#ifdef USE_DEFAULT_MONO_API_STRUCT +// We don't export in jit.h +// So declare here, and get it from mono +void mono_aot_register_module (void *aot_info); +#endif // USE_DEFAULT_MONO_API_STRUCT + static void init_default_mono_api_struct () { @@ -59,3 +67,5 @@ init_default_mono_api_struct () mono_api.mono_register_machine_config = mono_register_machine_config; #endif // USE_DEFAULT_MONO_API_STRUCT } + +#endif diff --git a/mcs/tools/mono-api-html/ApiChange.cs b/mcs/tools/mono-api-html/ApiChange.cs index c104bfa3b4..73e083066a 100644 --- a/mcs/tools/mono-api-html/ApiChange.cs +++ b/mcs/tools/mono-api-html/ApiChange.cs @@ -69,9 +69,9 @@ namespace Mono.ApiTools { if (!change.HasIgnoredChanges) { var isField = source.Name.LocalName == "field"; if (isField) { - State.LogDebugMessage ($"Comparison resulting in no changes (src: {source.GetFieldAttributes ()} dst: {target.GetFieldAttributes ()}) :\n{source}\n{target}\n\n"); + State.LogDebugMessage ($"Comparison resulting in no changes (src: {source.GetFieldAttributes ()} dst: {target.GetFieldAttributes ()}) :{Environment.NewLine}{source}{Environment.NewLine}{target}{Environment.NewLine}{Environment.NewLine}"); } else { - State.LogDebugMessage ($"Comparison resulting in no changes (src: {source.GetMethodAttributes ()} dst: {target.GetMethodAttributes ()}) :\n{source}\n{target}\n\n"); + State.LogDebugMessage ($"Comparison resulting in no changes (src: {source.GetMethodAttributes ()} dst: {target.GetMethodAttributes ()}) :{Environment.NewLine}{source}{Environment.NewLine}{target}{Environment.NewLine}{Environment.NewLine}"); } } return; diff --git a/mcs/tools/mono-api-html/FieldComparer.cs b/mcs/tools/mono-api-html/FieldComparer.cs index 125324f5ed..92774974c0 100644 --- a/mcs/tools/mono-api-html/FieldComparer.cs +++ b/mcs/tools/mono-api-html/FieldComparer.cs @@ -56,9 +56,9 @@ namespace Mono.ApiTools { if (srcNotSerialized != tgtNotSerialized) { // this is not a breaking change, so only render it if it changed. if (srcNotSerialized) { - change.AppendRemoved ("[NonSerialized]\n"); + change.AppendRemoved ($"[NonSerialized]{Environment.NewLine}"); } else { - change.AppendAdded ("[NonSerialized]\n"); + change.AppendAdded ($"[NonSerialized]{Environment.NewLine}"); } } diff --git a/mcs/tools/mono-api-html/HtmlFormatter.cs b/mcs/tools/mono-api-html/HtmlFormatter.cs index a72252bd88..189f092dfc 100644 --- a/mcs/tools/mono-api-html/HtmlFormatter.cs +++ b/mcs/tools/mono-api-html/HtmlFormatter.cs @@ -235,7 +235,7 @@ namespace Mono.ApiTools { output.WriteLine ("

Removed value{0}:

", list.Count () > 1 ? "s" : String.Empty); output.WriteLine ("
");
 			} else {
-				output.WriteLine ("

Removed {0}:

\n", list.Count () > 1 ? member.GroupName : member.ElementName); + output.WriteLine ("

Removed {0}:

", list.Count () > 1 ? member.GroupName : member.ElementName); output.WriteLine ("
");
 			}
 			State.Indent++;
@@ -303,7 +303,7 @@ namespace Mono.ApiTools {
 		public override void Diff (TextWriter output, ApiChange apichange)
 		{
 			output.Write ("
", apichange.Breaking ? "data-is-breaking" : "data-is-non-breaking"); - foreach (var line in apichange.Member.ToString ().Split ('\n')) { + foreach (var line in apichange.Member.ToString ().Split (new[] { Environment.NewLine }, 0)) { output.Write ('\t'); output.WriteLine (line); } diff --git a/mcs/tools/mono-api-html/MarkdownFormatter.cs b/mcs/tools/mono-api-html/MarkdownFormatter.cs index fd9964c750..978b805532 100644 --- a/mcs/tools/mono-api-html/MarkdownFormatter.cs +++ b/mcs/tools/mono-api-html/MarkdownFormatter.cs @@ -191,7 +191,7 @@ namespace Mono.ApiTools { public override void Diff (TextWriter output, ApiChange apichange) { - foreach (var line in apichange.Member.ToString ().Split ('\n')) { + foreach (var line in apichange.Member.ToString ().Split (new[] { Environment.NewLine }, 0)) { if (line.Contains ("+++")) { output.WriteLine ("-{0}", Clean (line, "+++", "---")); output.WriteLine ("+{0}", Clean (line, "---", "+++")); diff --git a/mcs/tools/mono-symbolicate/Makefile b/mcs/tools/mono-symbolicate/Makefile index 58a81cfc75..02f40193c3 100644 --- a/mcs/tools/mono-symbolicate/Makefile +++ b/mcs/tools/mono-symbolicate/Makefile @@ -16,7 +16,7 @@ MONO = MONO_PATH="$(LIB_PATH)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(RUNTIME) - MSYM_DIR = $(OUT_DIR)/msymdir TEST_CS = Test/StackTraceDumper.cs -TEST_EXE = $(OUT_DIR)/StackTraceDumper.exe +TEST_EXE = StackTraceDumper.exe STACKTRACE_FILE = $(OUT_DIR)/stacktrace.out SYMBOLICATE_RAW_FILE = $(OUT_DIR)/symbolicate_raw.out SYMBOLICATE_RESULT_FILE = $(OUT_DIR)/symbolicate.result @@ -44,22 +44,31 @@ PREPARE_OUTDIR = @\ mkdir -p $(OUT_DIR); \ mkdir -p $(MSYM_DIR); -COMPILE = \ - $(CSCOMPILE) $(TEST_CS) -r:$(LIB_PATH)/mscorlib.dll -r:$(LIB_PATH)/System.Core.dll -warn:0 -out:$(TEST_EXE); \ +STORE_SYMBOLS = \ $(MONO) $(LIB_PATH)/$(PROGRAM) store-symbols $(MSYM_DIR) $(OUT_DIR); \ $(MONO) $(LIB_PATH)/$(PROGRAM) store-symbols $(MSYM_DIR) $(LIB_PATH); +COPY_TEST = @\ + cp $(TEST_EXE) $(OUT_DIR); \ + cp $(TEST_EXE:.exe=.pdb) $(OUT_DIR); + check: run-test AOT_SUPPORTED = $(shell $(MONO) --aot 2>&1 | grep -q "AOT compilation is not supported" && echo 0 || echo 1) +test-local: $(TEST_EXE) + +$(TEST_EXE): $(TEST_CS) + $(CSCOMPILE) $(TEST_CS) -r:$(LIB_PATH)/mscorlib.dll -r:$(LIB_PATH)/System.Core.dll -warn:0 -out:$(TEST_EXE) + run-test-local: run-test-without-aot run-test-with-aot run-test-with-aot-msym run-test-without-aot: OUT_DIR = Test/without_aot run-test-without-aot: all @echo "Checking $(TEST_EXE) without AOT in $(OUT_DIR)" $(PREPARE_OUTDIR) - $(COMPILE) + $(COPY_TEST) + $(STORE_SYMBOLS) $(CHECK_DIFF) run-test-with-aot: OUT_DIR = Test/with_aot @@ -67,8 +76,9 @@ run-test-with-aot: all ifeq ($(AOT_SUPPORTED), 1) @echo "Checking $(TEST_EXE) with AOT in $(OUT_DIR)" $(PREPARE_OUTDIR) - $(COMPILE) - @$(MONO) --aot $(TEST_EXE) > /dev/null + $(COPY_TEST) + $(STORE_SYMBOLS) + @$(MONO) --aot $(OUT_DIR)/$(TEST_EXE) > /dev/null $(CHECK_DIFF) endif @@ -77,7 +87,8 @@ run-test-with-aot-msym: all ifeq ($(AOT_SUPPORTED), 1) @echo "Checking $(TEST_EXE) with AOT (using .msym) in $(OUT_DIR)" $(PREPARE_OUTDIR) - $(COMPILE) - @$(MONO) --aot=msym-dir=$(MSYM_DIR) $(TEST_EXE) > /dev/null + $(COPY_TEST) + $(STORE_SYMBOLS) + @$(MONO) --aot=msym-dir=$(MSYM_DIR) $(OUT_DIR)/$(TEST_EXE) > /dev/null $(CHECK_DIFF) endif diff --git a/mcs/tools/xbuild/xbuild_test.make b/mcs/tools/xbuild/xbuild_test.make index d7488d6641..4c79f36e45 100644 --- a/mcs/tools/xbuild/xbuild_test.make +++ b/mcs/tools/xbuild/xbuild_test.make @@ -1,13 +1,13 @@ XBUILD_DATA_DIR=$(topdir)/tools/xbuild/data -XBUILD_PROFILE_DIR=$(topdir)/class/lib/$(PROFILE) +XBUILD_TESTING_DIR=$(topdir)/class/lib/net_4_x/tests/xbuild # makes xbuild look in the class/lib/$PROFILE build directories for targets etc export TESTING_MONO=a -export MSBuildExtensionsPath=$(XBUILD_DATA_DIR) -export XBUILD_FRAMEWORK_FOLDERS_PATH= $(topdir)/class/Microsoft.Build/xbuild-testing +export MSBuildExtensionsPath=$(XBUILD_TESTING_DIR)/extensions +export XBUILD_FRAMEWORK_FOLDERS_PATH=$(XBUILD_TESTING_DIR)/frameworks -test-local: copy-targets Test/test-config-file-$(PROFILE) -clean-local: clean-targets clean-test-config +test-local: copy-targets copy-data copy-frameworks Test/test-config-file-$(PROFILE) +clean-local: clean-targets clean-data clean-frameworks clean-test-config Test/test-config-file-$(PROFILE): $(XBUILD_DATA_DIR)/xbuild.exe.config_test.in sed -e 's/@ASM_VERSION@/$(XBUILD_ASSEMBLY_VERSION)/g' $(XBUILD_DATA_DIR)/xbuild.exe.config_test.in > Test/test-config-file-$(PROFILE) @@ -23,6 +23,14 @@ XBUILD_4_0_PROFILE_DIR=$(topdir)/class/lib/net_4_x XBUILD_12_0_PROFILE_DIR=$(topdir)/class/lib/xbuild_12 XBUILD_14_0_PROFILE_DIR=$(topdir)/class/lib/xbuild_14 +copy-data: + mkdir -p $(XBUILD_TESTING_DIR)/extensions + cp -R -L $(XBUILD_DATA_DIR)/. $(XBUILD_TESTING_DIR)/extensions + +copy-frameworks: + mkdir -p $(XBUILD_TESTING_DIR)/frameworks + cp -R -L $(topdir)/class/Microsoft.Build/xbuild-testing/. $(XBUILD_TESTING_DIR)/frameworks + copy-targets-4.0: cp $(XBUILD_DATA_DIR)/4.0/Microsoft.Common.targets $(XBUILD_4_0_PROFILE_DIR) cp $(XBUILD_DATA_DIR)/4.0/Microsoft.Common.tasks $(XBUILD_4_0_PROFILE_DIR) @@ -41,6 +49,12 @@ copy-targets-14.0: cp $(XBUILD_DATA_DIR)/14.0/Microsoft.CSharp.targets $(XBUILD_14_0_PROFILE_DIR) cp $(XBUILD_DATA_DIR)/Microsoft.VisualBasic.targets $(XBUILD_14_0_PROFILE_DIR) +clean-data: + rm -rf $(XBUILD_TESTING_DIR)/extensions + +clean-frameworks: + rm -rf $(XBUILD_TESTING_DIR)/frameworks + clean-targets-4.0: rm -f $(XBUILD_4_0_PROFILE_DIR)/Microsoft.Common.targets rm -f $(XBUILD_4_0_PROFILE_DIR)/Microsoft.Common.tasks diff --git a/mk/Makefile.in b/mk/Makefile.in index 949ec307a1..8d38bdb993 100644 --- a/mk/Makefile.in +++ b/mk/Makefile.in @@ -82,7 +82,8 @@ subdir = mk DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -151,6 +152,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -224,6 +226,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/Makefile.am b/mono/Makefile.am index 34ec9cd71f..b21df745e0 100644 --- a/mono/Makefile.am +++ b/mono/Makefile.am @@ -8,11 +8,15 @@ if BTLS btls_dirs = btls endif +if MONO_NATIVE +native_dirs = native +endif + if CROSS_COMPILING -SUBDIRS = $(btls_dirs) eglib arch utils cil $(sgen_dirs) metadata mini dis profiler +SUBDIRS = $(btls_dirs) eglib arch utils cil $(sgen_dirs) metadata mini dis profiler $(native_dirs) else if INSTALL_MONOTOUCH -SUBDIRS = $(btls_dirs) eglib arch utils $(sgen_dirs) metadata mini profiler +SUBDIRS = $(btls_dirs) eglib arch utils $(sgen_dirs) metadata mini profiler $(native_dirs) monotouch-do-build: @list='$(SUBDIRS)'; for subdir in $$list; do \ @@ -36,7 +40,7 @@ monotouch-do-clean: (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$target); \ done; else -SUBDIRS = $(btls_dirs) eglib arch utils cil $(sgen_dirs) metadata mini dis tests unit-tests benchmark profiler +SUBDIRS = $(btls_dirs) eglib arch utils cil $(sgen_dirs) metadata mini dis tests unit-tests benchmark profiler $(native_dirs) endif endif -DIST_SUBDIRS = btls eglib arch utils cil $(sgen_dirs) metadata mini dis tests unit-tests benchmark profiler +DIST_SUBDIRS = btls native eglib arch utils cil $(sgen_dirs) metadata mini dis tests unit-tests benchmark profiler diff --git a/mono/Makefile.in b/mono/Makefile.in index f88677cc0d..6bb0029d2e 100644 --- a/mono/Makefile.in +++ b/mono/Makefile.in @@ -82,7 +82,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(srcdir)/Makefile.am $(top_srcdir)/mkinstalldirs subdir = mono ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -210,6 +211,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -283,6 +285,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ @@ -408,10 +426,11 @@ top_srcdir = @top_srcdir@ MAKEFLAGS := $(MAKEFLAGS) --no-builtin-rules @SUPPORT_SGEN_TRUE@sgen_dirs = sgen @BTLS_TRUE@btls_dirs = btls -@CROSS_COMPILING_FALSE@@INSTALL_MONOTOUCH_FALSE@SUBDIRS = $(btls_dirs) eglib arch utils cil $(sgen_dirs) metadata mini dis tests unit-tests benchmark profiler -@CROSS_COMPILING_FALSE@@INSTALL_MONOTOUCH_TRUE@SUBDIRS = $(btls_dirs) eglib arch utils $(sgen_dirs) metadata mini profiler -@CROSS_COMPILING_TRUE@SUBDIRS = $(btls_dirs) eglib arch utils cil $(sgen_dirs) metadata mini dis profiler -DIST_SUBDIRS = btls eglib arch utils cil $(sgen_dirs) metadata mini dis tests unit-tests benchmark profiler +@MONO_NATIVE_TRUE@native_dirs = native +@CROSS_COMPILING_FALSE@@INSTALL_MONOTOUCH_FALSE@SUBDIRS = $(btls_dirs) eglib arch utils cil $(sgen_dirs) metadata mini dis tests unit-tests benchmark profiler $(native_dirs) +@CROSS_COMPILING_FALSE@@INSTALL_MONOTOUCH_TRUE@SUBDIRS = $(btls_dirs) eglib arch utils $(sgen_dirs) metadata mini profiler $(native_dirs) +@CROSS_COMPILING_TRUE@SUBDIRS = $(btls_dirs) eglib arch utils cil $(sgen_dirs) metadata mini dis profiler $(native_dirs) +DIST_SUBDIRS = btls native eglib arch utils cil $(sgen_dirs) metadata mini dis tests unit-tests benchmark profiler all: all-recursive .SUFFIXES: diff --git a/mono/arch/Makefile.in b/mono/arch/Makefile.in index ec67144012..a5554c50a6 100644 --- a/mono/arch/Makefile.in +++ b/mono/arch/Makefile.in @@ -82,7 +82,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(srcdir)/Makefile.am $(top_srcdir)/mkinstalldirs subdir = mono/arch ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -210,6 +211,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -283,6 +285,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/arch/amd64/Makefile.in b/mono/arch/amd64/Makefile.in index ec083ef701..b7085e5b11 100644 --- a/mono/arch/amd64/Makefile.in +++ b/mono/arch/amd64/Makefile.in @@ -82,7 +82,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(srcdir)/Makefile.am $(top_srcdir)/mkinstalldirs subdir = mono/arch/amd64 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -151,6 +152,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -224,6 +226,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/arch/amd64/amd64-codegen.h b/mono/arch/amd64/amd64-codegen.h index de9943b3ec..79aaa1c72a 100644 --- a/mono/arch/amd64/amd64-codegen.h +++ b/mono/arch/amd64/amd64-codegen.h @@ -767,6 +767,13 @@ typedef union { #define emit_sse_reg_reg_op4(inst,dreg,reg,op1,op2,op3,op4) emit_sse_reg_reg_op4_size ((inst), (dreg), (reg), (op1), (op2), (op3), (op4), 0) +#define emit_sse_reg_reg_op4_imm(inst,dreg,reg,op1,op2,op3,op4,imm) do { \ + amd64_codegen_pre(inst); \ + emit_sse_reg_reg_op4 ((inst), (dreg), (reg), (op1), (op2), (op3), (op4)); \ + x86_imm_emit8 ((inst), (imm)); \ + amd64_codegen_post(inst); \ +} while (0) + /* specific SSE opcode defines */ #define amd64_sse_xorpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst),(dreg),(reg), 0x66, 0x0f, 0x57) @@ -885,6 +892,7 @@ typedef union { #define amd64_sse_shufpd_reg_reg_imm(inst,dreg,reg,imm) emit_sse_reg_reg_imm((inst), (dreg), (reg), 0x66, 0x0f, 0xC6, (imm)) +#define amd64_sse_roundpd_reg_reg_imm(inst, dreg, reg, imm) emit_sse_reg_reg_op4_imm((inst), (dreg), (reg), 0x66, 0x0f, 0x3a, 0x09, (imm)) #define amd64_sse_addpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x58) @@ -1140,7 +1148,6 @@ typedef union { #define amd64_movhlps_reg_reg(inst,dreg,sreg) emit_sse_reg_reg_op2((inst), (dreg), (sreg), 0x0f, 0x12) - #define amd64_sse_movups_membase_reg(inst, basereg, disp, reg) emit_sse_membase_reg_op2((inst), (basereg), (disp), (reg), 0x0f, 0x11) #define amd64_sse_movups_reg_membase(inst, dreg, basereg, disp) emit_sse_reg_membase_op2((inst), (dreg), (basereg), (disp), 0x0f, 0x10) diff --git a/mono/arch/arm/Makefile.in b/mono/arch/arm/Makefile.in index eb96141e50..023b89e1fb 100644 --- a/mono/arch/arm/Makefile.in +++ b/mono/arch/arm/Makefile.in @@ -82,7 +82,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(srcdir)/Makefile.am $(top_srcdir)/mkinstalldirs subdir = mono/arch/arm ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -151,6 +152,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -224,6 +226,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/arch/arm/arm-codegen.h b/mono/arch/arm/arm-codegen.h index 879c932b6b..eb63f596fc 100644 --- a/mono/arch/arm/arm-codegen.h +++ b/mono/arch/arm/arm-codegen.h @@ -21,7 +21,7 @@ typedef unsigned int armword_t; void __inline _arm_emit(arminstr_t** p, arminstr_t i) {**p = i; (*p)++;} # define ARM_EMIT(p, i) _arm_emit((arminstr_t**)&p, (arminstr_t)(i)) #else -# define ARM_EMIT(p, i) do { arminstr_t *__ainstrp = (void*)(p); *__ainstrp = (arminstr_t)(i); (p) = (void*)(__ainstrp+1);} while (0) +# define ARM_EMIT(p, i) do { arminstr_t *__ainstrp = (arminstr_t*)(p); *__ainstrp = (arminstr_t)(i); (p) = g_cast ((void*)(__ainstrp+1));} while (0) #endif #if defined(_MSC_VER) && !defined(ARM_NOIASM) diff --git a/mono/arch/arm64/Makefile.in b/mono/arch/arm64/Makefile.in index c3814ac484..d921c9047d 100644 --- a/mono/arch/arm64/Makefile.in +++ b/mono/arch/arm64/Makefile.in @@ -82,7 +82,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(srcdir)/Makefile.am $(top_srcdir)/mkinstalldirs subdir = mono/arch/arm64 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -151,6 +152,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -224,6 +226,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/arch/mips/Makefile.in b/mono/arch/mips/Makefile.in index 10706dffe3..9e3f2bcefd 100644 --- a/mono/arch/mips/Makefile.in +++ b/mono/arch/mips/Makefile.in @@ -86,7 +86,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ noinst_PROGRAMS = test$(EXEEXT) subdir = mono/arch/mips ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -203,6 +204,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -276,6 +278,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/arch/ppc/Makefile.in b/mono/arch/ppc/Makefile.in index 26b4574a16..af79b7f3c7 100644 --- a/mono/arch/ppc/Makefile.in +++ b/mono/arch/ppc/Makefile.in @@ -82,7 +82,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(srcdir)/Makefile.am $(top_srcdir)/mkinstalldirs subdir = mono/arch/ppc ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -151,6 +152,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -224,6 +226,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/arch/ppc/ppc-codegen.h b/mono/arch/ppc/ppc-codegen.h index 98fed7525f..25b805a4a0 100644 --- a/mono/arch/ppc/ppc-codegen.h +++ b/mono/arch/ppc/ppc-codegen.h @@ -137,7 +137,7 @@ enum { /* Macros to load/store pointer sized quantities */ -#if defined(__mono_ppc64__) && !defined(__mono_ilp32__) +#if defined(__mono_ppc64__) && !defined(MONO_ARCH_ILP32) #define ppc_ldptr(c,D,d,A) ppc_ld ((c), (D), (d), (A)) #define ppc_ldptr_update(c,D,d,A) ppc_ldu ((c), (D), (d), (A)) diff --git a/mono/arch/s390x/Makefile.in b/mono/arch/s390x/Makefile.in index 4694a71879..8cebdef58c 100644 --- a/mono/arch/s390x/Makefile.in +++ b/mono/arch/s390x/Makefile.in @@ -84,7 +84,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(top_srcdir)/depcomp subdir = mono/arch/s390x ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -197,6 +198,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -270,6 +272,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/arch/s390x/s390x-codegen.h b/mono/arch/s390x/s390x-codegen.h index 49fc120f7d..12fdd2894e 100644 --- a/mono/arch/s390x/s390x-codegen.h +++ b/mono/arch/s390x/s390x-codegen.h @@ -1393,8 +1393,8 @@ typedef struct { #define s390_mlr(c, r1, r2) S390_RRE(c, 0xb996, r1, r2) #define s390_mr(c, r1, r2) S390_RR(c, 0x1c, r1, r2) #define s390_ms(c, r, x, b, d) S390_RX(c, 0x71, r, x, b, d) -#define s390_msfi(c, r, v) S390_RIL_1(c, 0xc20, r, v) -#define s390_msgfi(c, r, v) S390_RIL_1(c, 0xc21, r, v) +#define s390_msfi(c, r, v) S390_RIL_1(c, 0xc21, r, v) +#define s390_msgfi(c, r, v) S390_RIL_1(c, 0xc20, r, v) #define s390_msgfr(c, r1, r2) S390_RRE(c, 0xb91c, r1, r2) #define s390_msgr(c, r1, r2) S390_RRE(c, 0xb90c, r1, r2) #define s390_msgrkc(c, r1, r2, r3) S390_RRF_1(c, 0xb9ed, r1, r2, r3) diff --git a/mono/arch/sparc/Makefile.in b/mono/arch/sparc/Makefile.in index d2e21a7d30..d7803c40b0 100644 --- a/mono/arch/sparc/Makefile.in +++ b/mono/arch/sparc/Makefile.in @@ -82,7 +82,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(srcdir)/Makefile.am $(top_srcdir)/mkinstalldirs subdir = mono/arch/sparc ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -151,6 +152,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -224,6 +226,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/arch/x86/Makefile.in b/mono/arch/x86/Makefile.in index 2be4670c46..2f2ec798ef 100644 --- a/mono/arch/x86/Makefile.in +++ b/mono/arch/x86/Makefile.in @@ -82,7 +82,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(srcdir)/Makefile.am $(top_srcdir)/mkinstalldirs subdir = mono/arch/x86 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -151,6 +152,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -224,6 +226,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/benchmark/Makefile.in b/mono/benchmark/Makefile.in index 24dd95afdb..0aea881ff0 100644 --- a/mono/benchmark/Makefile.in +++ b/mono/benchmark/Makefile.in @@ -82,7 +82,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(srcdir)/Makefile.am $(top_srcdir)/mkinstalldirs subdir = mono/benchmark ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -151,6 +152,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -224,6 +226,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/btls/Makefile.in b/mono/btls/Makefile.in index 26a75ff9f8..b431c02fb2 100644 --- a/mono/btls/Makefile.in +++ b/mono/btls/Makefile.in @@ -82,7 +82,8 @@ subdir = mono/btls DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -151,6 +152,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -224,6 +226,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/cil/Makefile.in b/mono/cil/Makefile.in index e73d51c3d7..627c2ccc6f 100644 --- a/mono/cil/Makefile.in +++ b/mono/cil/Makefile.in @@ -83,7 +83,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(srcdir)/Makefile.am $(top_srcdir)/mkinstalldirs TODO subdir = mono/cil ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -181,6 +182,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -254,6 +256,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/dis/Makefile.am b/mono/dis/Makefile.am index 6b0b645306..d463f85387 100644 --- a/mono/dis/Makefile.am +++ b/mono/dis/Makefile.am @@ -22,6 +22,8 @@ runtime_lib= \ $(top_builddir)/mono/utils/libmonoutils.la \ $(glib_libs) +noinst_LIBRARIES = libmonodis.a + if DISABLE_EXECUTABLES bin_PROGRAMS = else @@ -29,10 +31,13 @@ if DISABLE_LIBRARIES bin_PROGRAMS = else bin_PROGRAMS = monodis +noinst_LIBRARIES += libmonodismain.a endif endif -noinst_LIBRARIES = libmonodis.a +CFLAGS := $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) +libmonodis_a_CFLAGS = $(CFLAGS) @CXX_ADD_CFLAGS@ +libmonodismain_a_CFLAGS = $(CFLAGS) @CXX_ADD_CFLAGS@ libmonodis_a_SOURCES = \ get.c \ @@ -42,7 +47,7 @@ libmonodis_a_SOURCES = \ util.c \ util.h -monodis_SOURCES = \ +libmonodismain_a_SOURCES = \ dump.c \ dump.h \ main.c \ @@ -50,7 +55,12 @@ monodis_SOURCES = \ declsec.c \ declsec.h +monodis_SOURCES = + monodis_LDADD = \ + libmonodismain_a-dump.$(OBJEXT) \ + libmonodismain_a-main.$(OBJEXT) \ + libmonodismain_a-declsec.$(OBJEXT) \ libmonodis.a \ $(runtime_lib) \ $(LLVM_LIBS) \ diff --git a/mono/dis/Makefile.in b/mono/dis/Makefile.in index 6cb0627e32..5fd9430ff8 100644 --- a/mono/dis/Makefile.in +++ b/mono/dis/Makefile.in @@ -84,9 +84,11 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(srcdir)/Makefile.am $(top_srcdir)/mkinstalldirs \ $(top_srcdir)/depcomp @DISABLE_EXECUTABLES_FALSE@@DISABLE_LIBRARIES_FALSE@bin_PROGRAMS = monodis$(EXEEXT) +@DISABLE_EXECUTABLES_FALSE@@DISABLE_LIBRARIES_FALSE@am__append_1 = libmonodismain.a subdir = mono/dis ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -106,12 +108,18 @@ am__v_AR_0 = @echo " AR " $@; am__v_AR_1 = libmonodis_a_AR = $(AR) $(ARFLAGS) libmonodis_a_LIBADD = -am_libmonodis_a_OBJECTS = get.$(OBJEXT) dis-cil.$(OBJEXT) \ - util.$(OBJEXT) +am_libmonodis_a_OBJECTS = libmonodis_a-get.$(OBJEXT) \ + libmonodis_a-dis-cil.$(OBJEXT) libmonodis_a-util.$(OBJEXT) libmonodis_a_OBJECTS = $(am_libmonodis_a_OBJECTS) +libmonodismain_a_AR = $(AR) $(ARFLAGS) +libmonodismain_a_LIBADD = +am_libmonodismain_a_OBJECTS = libmonodismain_a-dump.$(OBJEXT) \ + libmonodismain_a-main.$(OBJEXT) \ + libmonodismain_a-declsec.$(OBJEXT) +libmonodismain_a_OBJECTS = $(am_libmonodismain_a_OBJECTS) am__installdirs = "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)" PROGRAMS = $(bin_PROGRAMS) -am_monodis_OBJECTS = dump.$(OBJEXT) main.$(OBJEXT) declsec.$(OBJEXT) +am_monodis_OBJECTS = monodis_OBJECTS = $(am_monodis_OBJECTS) am__DEPENDENCIES_1 = @SUPPORT_SGEN_FALSE@am__DEPENDENCIES_2 = $(am__DEPENDENCIES_1) @@ -119,7 +127,10 @@ am__DEPENDENCIES_1 = @SUPPORT_SGEN_TRUE@ $(top_builddir)/mono/sgen/libmonosgen.la am__DEPENDENCIES_3 = $(metadata_lib) $(am__DEPENDENCIES_2) \ $(top_builddir)/mono/utils/libmonoutils.la $(glib_libs) -monodis_DEPENDENCIES = libmonodis.a $(am__DEPENDENCIES_3) $(glib_libs) +monodis_DEPENDENCIES = libmonodismain_a-dump.$(OBJEXT) \ + libmonodismain_a-main.$(OBJEXT) \ + libmonodismain_a-declsec.$(OBJEXT) libmonodis.a \ + $(am__DEPENDENCIES_3) $(glib_libs) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent @@ -157,8 +168,10 @@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = -SOURCES = $(libmonodis_a_SOURCES) $(monodis_SOURCES) -DIST_SOURCES = $(libmonodis_a_SOURCES) $(monodis_SOURCES) +SOURCES = $(libmonodis_a_SOURCES) $(libmonodismain_a_SOURCES) \ + $(monodis_SOURCES) +DIST_SOURCES = $(libmonodis_a_SOURCES) $(libmonodismain_a_SOURCES) \ + $(monodis_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ @@ -240,7 +253,7 @@ CCASDEPMODE = @CCASDEPMODE@ CCASFLAGS = @CCASFLAGS@ CCDEPMODE = @CCDEPMODE@ CC_FOR_BUILD = @CC_FOR_BUILD@ -CFLAGS = @CFLAGS@ +CFLAGS := $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) CFLAGS_FOR_BUILD = @CFLAGS_FOR_BUILD@ CMAKE = @CMAKE@ CPP = @CPP@ @@ -250,6 +263,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -323,6 +337,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ @@ -458,7 +488,9 @@ runtime_lib = \ $(top_builddir)/mono/utils/libmonoutils.la \ $(glib_libs) -noinst_LIBRARIES = libmonodis.a +noinst_LIBRARIES = libmonodis.a $(am__append_1) +libmonodis_a_CFLAGS = $(CFLAGS) @CXX_ADD_CFLAGS@ +libmonodismain_a_CFLAGS = $(CFLAGS) @CXX_ADD_CFLAGS@ libmonodis_a_SOURCES = \ get.c \ get.h \ @@ -467,7 +499,7 @@ libmonodis_a_SOURCES = \ util.c \ util.h -monodis_SOURCES = \ +libmonodismain_a_SOURCES = \ dump.c \ dump.h \ main.c \ @@ -475,7 +507,11 @@ monodis_SOURCES = \ declsec.c \ declsec.h +monodis_SOURCES = monodis_LDADD = \ + libmonodismain_a-dump.$(OBJEXT) \ + libmonodismain_a-main.$(OBJEXT) \ + libmonodismain_a-declsec.$(OBJEXT) \ libmonodis.a \ $(runtime_lib) \ $(LLVM_LIBS) \ @@ -528,6 +564,11 @@ libmonodis.a: $(libmonodis_a_OBJECTS) $(libmonodis_a_DEPENDENCIES) $(EXTRA_libmo $(AM_V_at)-rm -f libmonodis.a $(AM_V_AR)$(libmonodis_a_AR) libmonodis.a $(libmonodis_a_OBJECTS) $(libmonodis_a_LIBADD) $(AM_V_at)$(RANLIB) libmonodis.a + +libmonodismain.a: $(libmonodismain_a_OBJECTS) $(libmonodismain_a_DEPENDENCIES) $(EXTRA_libmonodismain_a_DEPENDENCIES) + $(AM_V_at)-rm -f libmonodismain.a + $(AM_V_AR)$(libmonodismain_a_AR) libmonodismain.a $(libmonodismain_a_OBJECTS) $(libmonodismain_a_LIBADD) + $(AM_V_at)$(RANLIB) libmonodismain.a install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ @@ -588,12 +629,12 @@ mostlyclean-compile: distclean-compile: -rm -f *.tab.c -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/declsec.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dis-cil.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dump.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/get.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/main.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/util.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmonodis_a-dis-cil.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmonodis_a-get.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmonodis_a-util.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmonodismain_a-declsec.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmonodismain_a-dump.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmonodismain_a-main.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @@ -619,6 +660,90 @@ distclean-compile: @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< +libmonodis_a-get.o: get.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodis_a_CFLAGS) $(CFLAGS) -MT libmonodis_a-get.o -MD -MP -MF $(DEPDIR)/libmonodis_a-get.Tpo -c -o libmonodis_a-get.o `test -f 'get.c' || echo '$(srcdir)/'`get.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmonodis_a-get.Tpo $(DEPDIR)/libmonodis_a-get.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='get.c' object='libmonodis_a-get.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodis_a_CFLAGS) $(CFLAGS) -c -o libmonodis_a-get.o `test -f 'get.c' || echo '$(srcdir)/'`get.c + +libmonodis_a-get.obj: get.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodis_a_CFLAGS) $(CFLAGS) -MT libmonodis_a-get.obj -MD -MP -MF $(DEPDIR)/libmonodis_a-get.Tpo -c -o libmonodis_a-get.obj `if test -f 'get.c'; then $(CYGPATH_W) 'get.c'; else $(CYGPATH_W) '$(srcdir)/get.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmonodis_a-get.Tpo $(DEPDIR)/libmonodis_a-get.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='get.c' object='libmonodis_a-get.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodis_a_CFLAGS) $(CFLAGS) -c -o libmonodis_a-get.obj `if test -f 'get.c'; then $(CYGPATH_W) 'get.c'; else $(CYGPATH_W) '$(srcdir)/get.c'; fi` + +libmonodis_a-dis-cil.o: dis-cil.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodis_a_CFLAGS) $(CFLAGS) -MT libmonodis_a-dis-cil.o -MD -MP -MF $(DEPDIR)/libmonodis_a-dis-cil.Tpo -c -o libmonodis_a-dis-cil.o `test -f 'dis-cil.c' || echo '$(srcdir)/'`dis-cil.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmonodis_a-dis-cil.Tpo $(DEPDIR)/libmonodis_a-dis-cil.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='dis-cil.c' object='libmonodis_a-dis-cil.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodis_a_CFLAGS) $(CFLAGS) -c -o libmonodis_a-dis-cil.o `test -f 'dis-cil.c' || echo '$(srcdir)/'`dis-cil.c + +libmonodis_a-dis-cil.obj: dis-cil.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodis_a_CFLAGS) $(CFLAGS) -MT libmonodis_a-dis-cil.obj -MD -MP -MF $(DEPDIR)/libmonodis_a-dis-cil.Tpo -c -o libmonodis_a-dis-cil.obj `if test -f 'dis-cil.c'; then $(CYGPATH_W) 'dis-cil.c'; else $(CYGPATH_W) '$(srcdir)/dis-cil.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmonodis_a-dis-cil.Tpo $(DEPDIR)/libmonodis_a-dis-cil.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='dis-cil.c' object='libmonodis_a-dis-cil.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodis_a_CFLAGS) $(CFLAGS) -c -o libmonodis_a-dis-cil.obj `if test -f 'dis-cil.c'; then $(CYGPATH_W) 'dis-cil.c'; else $(CYGPATH_W) '$(srcdir)/dis-cil.c'; fi` + +libmonodis_a-util.o: util.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodis_a_CFLAGS) $(CFLAGS) -MT libmonodis_a-util.o -MD -MP -MF $(DEPDIR)/libmonodis_a-util.Tpo -c -o libmonodis_a-util.o `test -f 'util.c' || echo '$(srcdir)/'`util.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmonodis_a-util.Tpo $(DEPDIR)/libmonodis_a-util.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='util.c' object='libmonodis_a-util.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodis_a_CFLAGS) $(CFLAGS) -c -o libmonodis_a-util.o `test -f 'util.c' || echo '$(srcdir)/'`util.c + +libmonodis_a-util.obj: util.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodis_a_CFLAGS) $(CFLAGS) -MT libmonodis_a-util.obj -MD -MP -MF $(DEPDIR)/libmonodis_a-util.Tpo -c -o libmonodis_a-util.obj `if test -f 'util.c'; then $(CYGPATH_W) 'util.c'; else $(CYGPATH_W) '$(srcdir)/util.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmonodis_a-util.Tpo $(DEPDIR)/libmonodis_a-util.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='util.c' object='libmonodis_a-util.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodis_a_CFLAGS) $(CFLAGS) -c -o libmonodis_a-util.obj `if test -f 'util.c'; then $(CYGPATH_W) 'util.c'; else $(CYGPATH_W) '$(srcdir)/util.c'; fi` + +libmonodismain_a-dump.o: dump.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodismain_a_CFLAGS) $(CFLAGS) -MT libmonodismain_a-dump.o -MD -MP -MF $(DEPDIR)/libmonodismain_a-dump.Tpo -c -o libmonodismain_a-dump.o `test -f 'dump.c' || echo '$(srcdir)/'`dump.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmonodismain_a-dump.Tpo $(DEPDIR)/libmonodismain_a-dump.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='dump.c' object='libmonodismain_a-dump.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodismain_a_CFLAGS) $(CFLAGS) -c -o libmonodismain_a-dump.o `test -f 'dump.c' || echo '$(srcdir)/'`dump.c + +libmonodismain_a-dump.obj: dump.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodismain_a_CFLAGS) $(CFLAGS) -MT libmonodismain_a-dump.obj -MD -MP -MF $(DEPDIR)/libmonodismain_a-dump.Tpo -c -o libmonodismain_a-dump.obj `if test -f 'dump.c'; then $(CYGPATH_W) 'dump.c'; else $(CYGPATH_W) '$(srcdir)/dump.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmonodismain_a-dump.Tpo $(DEPDIR)/libmonodismain_a-dump.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='dump.c' object='libmonodismain_a-dump.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodismain_a_CFLAGS) $(CFLAGS) -c -o libmonodismain_a-dump.obj `if test -f 'dump.c'; then $(CYGPATH_W) 'dump.c'; else $(CYGPATH_W) '$(srcdir)/dump.c'; fi` + +libmonodismain_a-main.o: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodismain_a_CFLAGS) $(CFLAGS) -MT libmonodismain_a-main.o -MD -MP -MF $(DEPDIR)/libmonodismain_a-main.Tpo -c -o libmonodismain_a-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmonodismain_a-main.Tpo $(DEPDIR)/libmonodismain_a-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='libmonodismain_a-main.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodismain_a_CFLAGS) $(CFLAGS) -c -o libmonodismain_a-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c + +libmonodismain_a-main.obj: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodismain_a_CFLAGS) $(CFLAGS) -MT libmonodismain_a-main.obj -MD -MP -MF $(DEPDIR)/libmonodismain_a-main.Tpo -c -o libmonodismain_a-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmonodismain_a-main.Tpo $(DEPDIR)/libmonodismain_a-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='libmonodismain_a-main.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodismain_a_CFLAGS) $(CFLAGS) -c -o libmonodismain_a-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` + +libmonodismain_a-declsec.o: declsec.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodismain_a_CFLAGS) $(CFLAGS) -MT libmonodismain_a-declsec.o -MD -MP -MF $(DEPDIR)/libmonodismain_a-declsec.Tpo -c -o libmonodismain_a-declsec.o `test -f 'declsec.c' || echo '$(srcdir)/'`declsec.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmonodismain_a-declsec.Tpo $(DEPDIR)/libmonodismain_a-declsec.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='declsec.c' object='libmonodismain_a-declsec.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodismain_a_CFLAGS) $(CFLAGS) -c -o libmonodismain_a-declsec.o `test -f 'declsec.c' || echo '$(srcdir)/'`declsec.c + +libmonodismain_a-declsec.obj: declsec.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodismain_a_CFLAGS) $(CFLAGS) -MT libmonodismain_a-declsec.obj -MD -MP -MF $(DEPDIR)/libmonodismain_a-declsec.Tpo -c -o libmonodismain_a-declsec.obj `if test -f 'declsec.c'; then $(CYGPATH_W) 'declsec.c'; else $(CYGPATH_W) '$(srcdir)/declsec.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmonodismain_a-declsec.Tpo $(DEPDIR)/libmonodismain_a-declsec.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='declsec.c' object='libmonodismain_a-declsec.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonodismain_a_CFLAGS) $(CFLAGS) -c -o libmonodismain_a-declsec.obj `if test -f 'declsec.c'; then $(CYGPATH_W) 'declsec.c'; else $(CYGPATH_W) '$(srcdir)/declsec.c'; fi` + mostlyclean-libtool: -rm -f *.lo diff --git a/mono/dis/declsec.c b/mono/dis/declsec.c index eb0f168850..5575ef37aa 100755 --- a/mono/dis/declsec.c +++ b/mono/dis/declsec.c @@ -16,6 +16,7 @@ #include "mono/metadata/metadata.h" #include "mono/metadata/mono-endian.h" #include "mono/utils/mono-compiler.h" +#include "mono/utils/mono-math.h" #include "declsec.h" #include "util.h" @@ -113,14 +114,13 @@ declsec_20_write_value (GString *str, char type, const char *value) return value + 8; case MONO_TYPE_R4: { float val; - int inf; readr4 (value, &val); - inf = dis_isinf (val); + const int inf = mono_isinf (val); if (inf == -1) g_string_append_printf (str, "0xFF800000"); /* negative infinity */ else if (inf == 1) g_string_append_printf (str, "0x7F800000"); /* positive infinity */ - else if (dis_isnan (val)) + else if (mono_isnan (val)) g_string_append_printf (str, "0xFFC00000"); /* NaN */ else g_string_append_printf (str, "%.8g", val); @@ -128,14 +128,13 @@ declsec_20_write_value (GString *str, char type, const char *value) } case MONO_TYPE_R8: { double val; - int inf; readr8 (value, &val); - inf = dis_isinf (val); + const int inf = mono_isinf (val); if (inf == -1) g_string_append_printf (str, "0xFFF00000000000000"); /* negative infinity */ else if (inf == 1) g_string_append_printf (str, "0x7FFF0000000000000"); /* positive infinity */ - else if (isnan (val)) + else if (mono_isnan (val)) g_string_append_printf (str, "0xFFF80000000000000"); /* NaN */ else g_string_append_printf (str, "%.17g", val); diff --git a/mono/dis/dis-cil.c b/mono/dis/dis-cil.c index cc385d04ff..ec2b518ccc 100755 --- a/mono/dis/dis-cil.c +++ b/mono/dis/dis-cil.c @@ -21,6 +21,7 @@ #include "mono/metadata/opcodes.h" #include "mono/metadata/class-internals.h" #include "mono/utils/mono-compiler.h" +#include "mono/utils/mono-math.h" #define CODE_INDENT g_assert (indent_level < 512); \ indent[indent_level*2] = ' '; \ @@ -165,14 +166,13 @@ disassemble_cil (MonoImage *m, MonoMethodHeader *mh, MonoGenericContainer *conta case MonoInlineR: { double r; - int inf; readr8 (ptr, &r); - inf = dis_isinf (r); + const int inf = mono_isinf (r); if (inf == -1) fprintf (output, "(00 00 00 00 00 00 f0 ff)"); /* negative infinity */ else if (inf == 1) fprintf (output, "(00 00 00 00 00 00 f0 7f)"); /* positive infinity */ - else if (dis_isnan (r)) + else if (mono_isnan (r)) fprintf (output, "(00 00 00 00 00 00 f8 ff)"); /* NaN */ else { char *str = stringify_double (r); @@ -272,16 +272,13 @@ disassemble_cil (MonoImage *m, MonoMethodHeader *mh, MonoGenericContainer *conta case MonoShortInlineR: { float f; - int inf; - readr4 (ptr, &f); - - inf = dis_isinf (f); + const int inf = mono_isinf (f); if (inf == -1) fprintf (output, "(00 00 80 ff)"); /* negative infinity */ else if (inf == 1) fprintf (output, "(00 00 80 7f)"); /* positive infinity */ - else if (dis_isnan (f)) + else if (mono_isnan (f)) fprintf (output, "(00 00 c0 ff)"); /* NaN */ else { char *str = stringify_double ((double) f); diff --git a/mono/dis/dump.c b/mono/dis/dump.c index b041dceee6..30f889bb3b 100755 --- a/mono/dis/dump.c +++ b/mono/dis/dump.c @@ -21,6 +21,7 @@ #include "mono/metadata/class-internals.h" #include "mono/utils/mono-compiler.h" #include "mono/utils/mono-error-internals.h" +#include "mono/utils/mono-math.h" void dump_table_assembly (MonoImage *m) @@ -866,14 +867,13 @@ handle_enum: break; case MONO_TYPE_R4: { float val; - int inf; readr4 (p, &val); - inf = dis_isinf (val); + const int inf = mono_isinf (val); if (inf == -1) g_string_append_printf (res, "(00 00 80 ff)"); /* negative infinity */ else if (inf == 1) g_string_append_printf (res, "(00 00 80 7f)"); /* positive infinity */ - else if (dis_isnan (val)) + else if (mono_isnan (val)) g_string_append_printf (res, "(00 00 c0 ff)"); /* NaN */ else g_string_append_printf (res, "%g", val); @@ -882,15 +882,13 @@ handle_enum: } case MONO_TYPE_R8: { double val; - int inf; - readr8 (p, &val); - inf = dis_isinf (val); + const int inf = mono_isinf (val); if (inf == -1) g_string_append_printf (res, "(00 00 00 00 00 00 f0 ff)"); /* negative infinity */ else if (inf == 1) g_string_append_printf (res, "(00 00 00 00 00 00 f0 7f)"); /* positive infinity */ - else if (isnan (val)) + else if (mono_isnan (val)) g_string_append_printf (res, "(00 00 00 00 00 00 f8 ff)"); /* NaN */ else g_string_append_printf (res, "%g", val); diff --git a/mono/dis/get.c.REMOVED.git-id b/mono/dis/get.c.REMOVED.git-id index 35de80bcd2..2e1f56e77c 100644 --- a/mono/dis/get.c.REMOVED.git-id +++ b/mono/dis/get.c.REMOVED.git-id @@ -1 +1 @@ -f5495454b6b075435d7b75cc325d036da4e958a7 \ No newline at end of file +fc0b067eaac5a220c0c615eff5d6b09ef238b2e1 \ No newline at end of file diff --git a/mono/dis/util.c b/mono/dis/util.c index 80b6ad4445..52583687a5 100755 --- a/mono/dis/util.c +++ b/mono/dis/util.c @@ -14,10 +14,7 @@ #include #include "util.h" #include "mono/utils/mono-compiler.h" - -#ifdef HAVE_IEEEFP_H -#include -#endif +#include "mono/utils/mono-math.h" /** * \param code code to lookup in table @@ -126,37 +123,3 @@ data_dump (const char *data, int len, const char* prefix) { g_string_append_printf (str, "\n"); return g_string_free (str, FALSE); } - -int -dis_isinf (double num) -{ -#ifdef HAVE_ISINF - return isinf (num); -#elif defined(HAVE_IEEEFP_H) - fpclass_t klass; - - klass = fpclass (num); - if (klass == FP_NINF) - return -1; - - if (klass == FP_PINF) - return 1; - - return 0; -#elif defined(HAVE__FINITE) - return _finite (num) ? 0 : 1; -#else -#error "Don't know how to implement isinf for this platform." -#endif -} - -int -dis_isnan (double num) -{ -#ifdef __MINGW32_VERSION -return _isnan (num); -#else -return isnan (num); -#endif -} - diff --git a/mono/dis/util.h b/mono/dis/util.h index d8ff7bfb12..0e1168b85a 100755 --- a/mono/dis/util.h +++ b/mono/dis/util.h @@ -7,6 +7,3 @@ const char *map (guint32 code, dis_map_t *table); const char *flags (guint32 code, dis_map_t *table); void hex_dump (const char *buffer, int base, int count); char* data_dump (const char *data, int len, const char* prefix); - -extern int dis_isinf (double num); -extern int dis_isnan (double num); diff --git a/mono/eglib/Makefile.am b/mono/eglib/Makefile.am index 6483c0e48c..ba10873171 100644 --- a/mono/eglib/Makefile.am +++ b/mono/eglib/Makefile.am @@ -3,6 +3,8 @@ include $(top_srcdir)/mk/common.mk # FIXME #SUBDIRS = test +DIST_SUBDIRS = test + noinst_LTLIBRARIES = libeglib.la AM_CFLAGS = $(WERROR_CFLAGS) @@ -53,6 +55,8 @@ libeglib_la_SOURCES = \ unicode-data.h \ $(os_files) +CFLAGS := $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) @CXX_ADD_CFLAGS@ + eglibdir=$(datadir)/mono-$(API_VER)/mono/eglib eglib_DATA = eglib-config.h diff --git a/mono/eglib/Makefile.in b/mono/eglib/Makefile.in index 26bb8ff139..5eeb6c346f 100644 --- a/mono/eglib/Makefile.in +++ b/mono/eglib/Makefile.in @@ -84,8 +84,10 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(srcdir)/Makefile.am $(top_srcdir)/mkinstalldirs \ $(srcdir)/eglib-config.h.in $(top_srcdir)/depcomp subdir = mono/eglib +SUBDIRS = ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -170,6 +172,14 @@ am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libeglib_la_SOURCES) DIST_SOURCES = $(am__libeglib_la_SOURCES_DIST) +RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ + ctags-recursive dvi-recursive html-recursive info-recursive \ + install-data-recursive install-dvi-recursive \ + install-exec-recursive install-html-recursive \ + install-info-recursive install-pdf-recursive \ + install-ps-recursive install-recursive installcheck-recursive \ + installdirs-recursive pdf-recursive ps-recursive \ + tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ @@ -204,6 +214,14 @@ am__uninstall_files_from_dir = { \ } am__installdirs = "$(DESTDIR)$(eglibdir)" DATA = $(eglib_DATA) +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +am__recursive_targets = \ + $(RECURSIVE_TARGETS) \ + $(RECURSIVE_CLEAN_TARGETS) \ + $(am__extra_recursive_targets) +AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ + distdir am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is @@ -224,6 +242,31 @@ am__define_uniq_tagged_files = \ ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ @@ -250,7 +293,7 @@ CCASDEPMODE = @CCASDEPMODE@ CCASFLAGS = @CCASFLAGS@ CCDEPMODE = @CCDEPMODE@ CC_FOR_BUILD = @CC_FOR_BUILD@ -CFLAGS = @CFLAGS@ +CFLAGS := $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) @CXX_ADD_CFLAGS@ CFLAGS_FOR_BUILD = @CFLAGS_FOR_BUILD@ CMAKE = @CMAKE@ CPP = @CPP@ @@ -260,6 +303,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -333,6 +377,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ @@ -459,6 +519,7 @@ MAKEFLAGS := $(MAKEFLAGS) --no-builtin-rules # FIXME #SUBDIRS = test +DIST_SUBDIRS = test noinst_LTLIBRARIES = libeglib.la AM_CFLAGS = $(WERROR_CFLAGS) win_files = \ @@ -512,7 +573,7 @@ AM_CPPFLAGS = -I$(srcdir) @HOST_ANDROID_TRUE@libeglib_la_LIBADD = -lm -llog MAINTAINERCLEANFILES = Makefile.in EXTRA_DIST = eglib-config.h.in $(win_files) $(unix_files) -all: all-am +all: all-recursive .SUFFIXES: .SUFFIXES: .c .lo .o .obj @@ -910,14 +971,61 @@ uninstall-eglibDATA: files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(eglibdir)'; $(am__uninstall_files_from_dir) +# This directory's subdirectories are mostly independent; you can cd +# into them and run 'make' without going through this Makefile. +# To change the values of 'make' variables: instead of editing Makefiles, +# (1) if the variable is set in 'config.status', edit 'config.status' +# (which will cause the Makefiles to be regenerated when you run 'make'); +# (2) otherwise, pass the desired values on the 'make' command line. +$(am__recursive_targets): + @fail=; \ + if $(am__make_keepgoing); then \ + failcom='fail=yes'; \ + else \ + failcom='exit 1'; \ + fi; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique -tags: tags-am +tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ @@ -930,7 +1038,7 @@ tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $$unique; \ fi; \ fi -ctags: ctags-am +ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) @@ -943,7 +1051,7 @@ GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" -cscopelist: cscopelist-am +cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ @@ -992,22 +1100,48 @@ distdir: $(DISTFILES) || exit 1; \ fi; \ done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + $(am__make_dryrun) \ + || test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done check-am: all-am -check: check-am +check: check-recursive all-am: Makefile $(LTLIBRARIES) $(DATA) -installdirs: +installdirs: installdirs-recursive +installdirs-am: for dir in "$(DESTDIR)$(eglibdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am -installcheck: installcheck-am +installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ @@ -1030,89 +1164,90 @@ maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) -clean: clean-am +clean: clean-recursive clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am -distclean: distclean-am +distclean: distclean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags -dvi: dvi-am +dvi: dvi-recursive dvi-am: -html: html-am +html: html-recursive html-am: -info: info-am +info: info-recursive info-am: install-data-am: install-eglibDATA -install-dvi: install-dvi-am +install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: -install-html: install-html-am +install-html: install-html-recursive install-html-am: -install-info: install-info-am +install-info: install-info-recursive install-info-am: install-man: -install-pdf: install-pdf-am +install-pdf: install-pdf-recursive install-pdf-am: -install-ps: install-ps-am +install-ps: install-ps-recursive install-ps-am: installcheck-am: -maintainer-clean: maintainer-clean-am +maintainer-clean: maintainer-clean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic -mostlyclean: mostlyclean-am +mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool -pdf: pdf-am +pdf: pdf-recursive pdf-am: -ps: ps-am +ps: ps-recursive ps-am: uninstall-am: uninstall-eglibDATA -.MAKE: install-am install-strip +.MAKE: $(am__recursive_targets) install-am install-strip -.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ - clean-libtool clean-noinstLTLIBRARIES cscopelist-am ctags \ - ctags-am distclean distclean-compile distclean-generic \ - distclean-libtool distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-dvi install-dvi-am install-eglibDATA \ - install-exec install-exec-am install-html install-html-am \ - install-info install-info-am install-man install-pdf \ - install-pdf-am install-ps install-ps-am install-strip \ - installcheck installcheck-am installdirs maintainer-clean \ +.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ + check-am clean clean-generic clean-libtool \ + clean-noinstLTLIBRARIES cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-eglibDATA install-exec install-exec-am \ + install-html install-html-am install-info install-info-am \ + install-man install-pdf install-pdf-am install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am uninstall-eglibDATA diff --git a/mono/eglib/eglib-config.hw b/mono/eglib/eglib-config.hw index 54b7a4ee7d..6ab297f9c1 100644 --- a/mono/eglib/eglib-config.hw +++ b/mono/eglib/eglib-config.hw @@ -45,8 +45,10 @@ typedef int pid_t; #define F_SETFD 1 #define FD_CLOEXEC 1 +#ifndef __cplusplus #undef inline #define inline __inline +#endif #define strtok_r strtok_s diff --git a/mono/eglib/eglib-remap.h b/mono/eglib/eglib-remap.h index 031d70e8c6..3b03784f04 100644 --- a/mono/eglib/eglib-remap.h +++ b/mono/eglib/eglib-remap.h @@ -1,3 +1,11 @@ +#undef g_malloc +#undef g_realloc +#undef g_malloc0 +#undef g_calloc +#undef g_try_malloc +#undef g_try_realloc +#undef g_memdup + #define g_array_append monoeg_g_array_append #define g_array_append_vals monoeg_g_array_append_vals #define g_array_free monoeg_g_array_free @@ -285,9 +293,7 @@ #define g_unichar_break_type monoeg_unichar_break_type #define g_unichar_isspace monoeg_unichar_isspace #define g_unichar_to_utf16 monoeg_unichar_to_utf16 -#define g_utf8_find_prev_char monoeg_utf8_find_prev_char #define g_utf8_get_char_validated monoeg_utf8_get_char_validated -#define g_utf8_prev_char monoeg_utf8_prev_char #define g_utf8_to_ucs4 monoeg_utf8_to_ucs4 @@ -295,3 +301,5 @@ #define g_log_set_default_handler monoeg_log_set_default_handler #define g_set_print_handler monoeg_set_print_handler #define g_set_printerr_handler monoeg_set_printerr_handler + +#define g_size_to_int monoeg_size_to_int diff --git a/mono/eglib/garray.c b/mono/eglib/garray.c index b9844f88a9..bc06511189 100644 --- a/mono/eglib/garray.c +++ b/mono/eglib/garray.c @@ -25,7 +25,7 @@ * 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 #include diff --git a/mono/eglib/gbytearray.c b/mono/eglib/gbytearray.c index f8231b4834..6bb3b74f2c 100644 --- a/mono/eglib/gbytearray.c +++ b/mono/eglib/gbytearray.c @@ -25,12 +25,12 @@ * 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 #include GByteArray * -g_byte_array_new () +g_byte_array_new (void) { return (GByteArray *) g_array_new (FALSE, TRUE, 1); } diff --git a/mono/eglib/gdate-unix.c b/mono/eglib/gdate-unix.c index 5573e0d357..0397d2b394 100644 --- a/mono/eglib/gdate-unix.c +++ b/mono/eglib/gdate-unix.c @@ -25,6 +25,7 @@ * 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 #include #include diff --git a/mono/eglib/gdate-win32.c b/mono/eglib/gdate-win32.c index b00e9b7bd3..b86894201f 100644 --- a/mono/eglib/gdate-win32.c +++ b/mono/eglib/gdate-win32.c @@ -25,6 +25,7 @@ * 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 #include diff --git a/mono/eglib/gdir-unix.c b/mono/eglib/gdir-unix.c index 5d1e66be93..7cbd6bf14d 100644 --- a/mono/eglib/gdir-unix.c +++ b/mono/eglib/gdir-unix.c @@ -25,6 +25,7 @@ * 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 #include #include diff --git a/mono/eglib/gdir-win32.c b/mono/eglib/gdir-win32.c index 53fd62f837..5683c49923 100644 --- a/mono/eglib/gdir-win32.c +++ b/mono/eglib/gdir-win32.c @@ -25,6 +25,7 @@ * 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 #include #include @@ -54,7 +55,7 @@ g_dir_open (const gchar *path, guint flags, GError **gerror) dir = g_new0 (GDir, 1); path_utf16 = u8to16 (path); - path_utf16_search = g_malloc ((wcslen((wchar_t *) path_utf16) + 3)*sizeof(gunichar2)); + path_utf16_search = g_malloc ((wcslen(path_utf16) + 3)*sizeof(gunichar2)); wcscpy (path_utf16_search, path_utf16); wcscat (path_utf16_search, L"\\*"); @@ -72,7 +73,7 @@ g_dir_open (const gchar *path, guint flags, GError **gerror) g_free (path_utf16_search); g_free (path_utf16); - while ((wcscmp ((wchar_t *) find_data.cFileName, L".") == 0) || (wcscmp ((wchar_t *) find_data.cFileName, L"..") == 0)) { + while ((wcscmp (find_data.cFileName, L".") == 0) || (wcscmp (find_data.cFileName, L"..") == 0)) { if (!FindNextFileW (dir->handle, &find_data)) { if (gerror) { gint err = errno; @@ -111,7 +112,7 @@ g_dir_read_name (GDir *dir) dir->next = NULL; return dir->current; } - } while ((wcscmp ((wchar_t *) find_data.cFileName, L".") == 0) || (wcscmp ((wchar_t *) find_data.cFileName, L"..") == 0)); + } while ((wcscmp (find_data.cFileName, L".") == 0) || (wcscmp (find_data.cFileName, L"..") == 0)); dir->next = u16to8 (find_data.cFileName); return dir->current; diff --git a/mono/eglib/gfile-unix.c b/mono/eglib/gfile-unix.c index 3aacf9fb44..0912076a53 100644 --- a/mono/eglib/gfile-unix.c +++ b/mono/eglib/gfile-unix.c @@ -80,7 +80,7 @@ g_file_test (const gchar *filename, GFileTest test) } gchar * -g_mkdtemp (char *tmp_template) +g_mkdtemp (char *temp) { /* * On systems without mkdtemp, use a reimplemented version @@ -90,21 +90,14 @@ g_mkdtemp (char *tmp_template) * present without redefining it. */ #if defined(HAVE_MKDTEMP) && !defined(_AIX) - char *template_copy = g_strdup (tmp_template); - - return mkdtemp (template_copy); + return mkdtemp (g_strdup (temp)); #else - char *template = g_strdup (tmp_template); + temp = mktemp (g_strdup (temp)); + /* 0700 is the mode specified in specs */ + if (temp && *temp && mkdir (temp, 0700) == 0) + return temp; - template = mktemp(template); - if (template && *template) { - /* 0700 is the mode specified in specs */ - if (mkdir (template, 0700) == 0){ - return template; - } - } - - g_free (template); + g_free (temp); return NULL; #endif } diff --git a/mono/eglib/ghashtable.c b/mono/eglib/ghashtable.c index badba202f5..93aa37acc3 100644 --- a/mono/eglib/ghashtable.c +++ b/mono/eglib/ghashtable.c @@ -25,9 +25,11 @@ * 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 #include #include +#include // Remove the cast macros and restore the rename macros. typedef struct _Slot Slot; @@ -656,7 +658,7 @@ g_int_hash (gconstpointer v1) gboolean g_str_equal (gconstpointer v1, gconstpointer v2) { - return strcmp (v1, v2) == 0; + return strcmp ((const char*)v1, (const char*)v2) == 0; } guint diff --git a/mono/eglib/giconv.c b/mono/eglib/giconv.c index fd13f59971..3f54abae45 100644 --- a/mono/eglib/giconv.c +++ b/mono/eglib/giconv.c @@ -22,11 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ - -#ifdef HAVE_CONFIG_H #include -#endif - #include #include #ifdef HAVE_ICONV_H @@ -51,7 +47,7 @@ struct _GIConv { Decoder decode; Encoder encode; gunichar c; -#ifdef HAVE_ICONV +#ifdef HAVE_LIBICONV iconv_t cd; #endif }; @@ -112,7 +108,7 @@ static struct { GIConv g_iconv_open (const char *to_charset, const char *from_charset) { -#ifdef HAVE_ICONV +#ifdef HAVE_LIBICONV iconv_t icd = (iconv_t) -1; #endif Decoder decoder = NULL; @@ -135,7 +131,7 @@ g_iconv_open (const char *to_charset, const char *from_charset) } if (!encoder || !decoder) { -#ifdef HAVE_ICONV +#ifdef HAVE_LIBICONV if ((icd = iconv_open (to_charset, from_charset)) == (iconv_t) -1) return (GIConv) -1; #else @@ -150,7 +146,7 @@ g_iconv_open (const char *to_charset, const char *from_charset) cd->encode = encoder; cd->c = -1; -#ifdef HAVE_ICONV +#ifdef HAVE_LIBICONV cd->cd = icd; #endif @@ -160,7 +156,7 @@ g_iconv_open (const char *to_charset, const char *from_charset) int g_iconv_close (GIConv cd) { -#ifdef HAVE_ICONV +#ifdef HAVE_LIBICONV if (cd->cd != (iconv_t) -1) iconv_close (cd->cd); #endif @@ -179,7 +175,7 @@ g_iconv (GIConv cd, gchar **inbytes, gsize *inbytesleft, gunichar c; int rc = 0; -#ifdef HAVE_ICONV +#ifdef HAVE_LIBICONV if (cd->cd != (iconv_t) -1) { /* Note: gsize may have a different size than size_t, so we need to remap inbytesleft and outbytesleft to size_t's. */ diff --git a/mono/eglib/glib.h b/mono/eglib/glib.h index 9d809225f0..a09f9b76fa 100644 --- a/mono/eglib/glib.h +++ b/mono/eglib/glib.h @@ -1,5 +1,22 @@ #ifndef __GLIB_H #define __GLIB_H + +// Ask stdint.h and inttypes.h for the full C99 features for CentOS 6 g++ 4.4, Android, etc. +// See for example: +// $HOME/android-toolchain/toolchains/armeabi-v7a-clang/sysroot/usr/include/inttypes.h +// $HOME/android-toolchain/toolchains/armeabi-v7a-clang/sysroot/usr/include/stdint.h +#ifdef __cplusplus +#ifndef __STDC_LIMIT_MACROS +#define __STDC_LIMIT_MACROS +#endif +#ifndef __STDC_CONSTANT_MACROS +#define __STDC_CONSTANT_MACROS +#endif +#ifndef __STDC_FORMAT_MACROS +#define __STDC_FORMAT_MACROS +#endif +#endif // __cplusplus + #include #include #include @@ -7,16 +24,13 @@ #include #include #include - - -#ifdef _MSC_VER -#pragma include_alias(, ) -#endif - #include #include - +#ifdef _MSC_VER +#include +#else #include +#endif // - Pointers should only be converted to or from pointer-sized integers. // - Any size integer can be converted to any other size integer. @@ -48,14 +62,110 @@ # define offsetof(s_name,n_name) (size_t)(char *)&(((s_name*)0)->m_name) #endif -#define __EGLIB_X11 1 - #ifdef __cplusplus #define G_BEGIN_DECLS extern "C" { #define G_END_DECLS } +#define G_EXTERN_C extern "C" #else -#define G_BEGIN_DECLS -#define G_END_DECLS +#define G_BEGIN_DECLS /* nothing */ +#define G_END_DECLS /* nothing */ +#define G_EXTERN_C /* nothing */ +#endif + +#ifdef __cplusplus + +#define g_cast monoeg_g_cast // in case not inlined (see eglib-remap.h) + +// g_cast converts void* to T*. +// e.g. #define malloc(x) (g_cast (malloc (x))) +// FIXME It used to do more. Rename? +struct g_cast +{ +private: + void * const x; +public: + explicit g_cast (void *y) : x(y) { } + // Lack of rvalue constructor inhibits ternary operator. + // Either don't use ternary, or cast each side. + // sa = (salen <= 128) ? g_alloca (salen) : g_malloc (salen); + // w32socket.c:1045:24: error: call to deleted constructor of 'monoeg_g_cast' + //g_cast (g_cast&& y) : x(y.x) { } + g_cast (g_cast&&) = delete; + g_cast () = delete; + g_cast (const g_cast&) = delete; + + template + operator TTo* () const + { + return (TTo*)x; + } +}; + +#else + +// FIXME? Parens are omitted to preserve prior meaning. +#define g_cast(x) x + +#endif + +#ifdef __cplusplus + +// G++4.4 breaks opeq below without this. +#if defined (__GNUC__) || defined (__clang__) +#define G_MAY_ALIAS __attribute__((__may_alias__)) +#else +#define G_MAY_ALIAS /* nothing */ +#endif + +// Provide for bit operations on enums, but not all integer operations. +// This alleviates a fair number of casts in porting C to C++. + +// Forward declare template with no generic implementation. +template struct g_size_to_int; + +// Template specializations. +template <> struct g_size_to_int<1> { typedef int8_t type; }; +template <> struct g_size_to_int<2> { typedef int16_t type; }; +template <> struct g_size_to_int<4> { typedef int32_t type; }; +template <> struct g_size_to_int<8> { typedef int64_t type; }; + +// g++4.4 does not accept: +//template +//using g_size_to_int_t = typename g_size_to_int ::type; +#define g_size_to_int_t(x) g_size_to_int ::type + +#define G_ENUM_BINOP(Enum, op, opeq) \ +inline Enum \ +operator op (Enum a, Enum b) \ +{ \ + typedef g_size_to_int_t (Enum) type; \ + return static_cast(static_cast(a) op b); \ +} \ + \ +inline Enum& \ +operator opeq (Enum& a, Enum b) \ +{ \ + typedef g_size_to_int_t (Enum) G_MAY_ALIAS type; \ + return (Enum&)((type&)a opeq b); \ +} \ + +#define G_ENUM_FUNCTIONS(Enum) \ +extern "C++" { /* in case within extern "C" */ \ +inline Enum \ +operator~ (Enum a) \ +{ \ + typedef g_size_to_int_t (Enum) type; \ + return static_cast(~static_cast(a)); \ +} \ + \ +G_ENUM_BINOP (Enum, |, |=) \ +G_ENUM_BINOP (Enum, &, &=) \ +G_ENUM_BINOP (Enum, ^, ^=) \ + \ +} /* extern "C++" */ + +#else +#define G_ENUM_FUNCTIONS(Enum) /* nothing */ #endif G_BEGIN_DECLS @@ -87,7 +197,14 @@ typedef float gfloat; typedef double gdouble; typedef int32_t gboolean; +#if defined (HOST_WIN32) || defined (_WIN32) +G_END_DECLS +#include +typedef wchar_t gunichar2; +G_BEGIN_DECLS +#else typedef guint16 gunichar2; +#endif typedef guint32 gunichar; /* @@ -151,10 +268,15 @@ typedef guint32 gunichar; /* * Allocation */ +G_EXTERN_C // Used by MonoPosixHelper or MonoSupportW, at least. void g_free (void *ptr); +G_EXTERN_C // Used by MonoPosixHelper or MonoSupportW, at least. gpointer g_realloc (gpointer obj, gsize size); +G_EXTERN_C // Used by MonoPosixHelper or MonoSupportW, at least. gpointer g_malloc (gsize x); +G_EXTERN_C // Used by MonoPosixHelper or MonoSupportW, at least. gpointer g_malloc0 (gsize x); +G_EXTERN_C // Used by profilers, at least. gpointer g_calloc (gsize n, gsize x); gpointer g_try_malloc (gsize x); gpointer g_try_realloc (gpointer obj, gsize size); @@ -164,9 +286,10 @@ gpointer g_try_realloc (gpointer obj, gsize size); #define g_newa(type,size) ((type *) alloca (sizeof (type) * (size))) #define g_memmove(dest,src,len) memmove (dest, src, len) -#define g_renew(struct_type, mem, n_structs) g_realloc (mem, sizeof (struct_type) * n_structs) -#define g_alloca(size) alloca (size) +#define g_renew(struct_type, mem, n_structs) ((struct_type*)g_realloc (mem, sizeof (struct_type) * n_structs)) +#define g_alloca(size) (g_cast (alloca (size))) +G_EXTERN_C // Used by libtest, at least. gpointer g_memdup (gconstpointer mem, guint byte_size); static inline gchar *g_strdup (const gchar *str) { if (str) { return (gchar*) g_memdup (str, (guint)strlen (str) + 1); } return NULL; } gchar **g_strdupv (gchar **str_array); @@ -192,7 +315,10 @@ typedef struct _GMemChunk GMemChunk; gboolean g_hasenv(const gchar *variable); gchar * g_getenv(const gchar *variable); + +G_EXTERN_C // sdks/wasm/driver.c is C and uses this gboolean g_setenv(const gchar *variable, const gchar *value, gboolean overwrite); + void g_unsetenv(const gchar *variable); gchar* g_win32_getlocale(void); @@ -223,6 +349,7 @@ void g_propagate_error (GError **dest, GError *src); /* * Strings utility */ +G_EXTERN_C // Used by libtest, at least. gchar *g_strdup_printf (const gchar *format, ...); gchar *g_strdup_vprintf (const gchar *format, va_list args); gchar *g_strndup (const gchar *str, gsize n); @@ -243,7 +370,7 @@ gchar *g_strchomp (gchar *str); void g_strdown (gchar *string); gchar *g_strnfill (gsize length, gchar fill_char); -gchar *g_strdelimit (gchar *string, const gchar *delimiters, gchar new_delimiter); +void g_strdelimit (char *string, char delimiter, char new_delimiter); gchar *g_strescape (const gchar *source, const gchar *exceptions); gchar *g_filename_to_uri (const gchar *filename, const gchar *hostname, GError **gerror); @@ -290,9 +417,6 @@ gboolean g_utf16_asciiz_equal (const gunichar2 *utf16, const char *ascii); #endif #define g_ascii_strdup strdup - -#define G_STR_DELIMITERS "_-|> <." - /* * String type */ @@ -452,22 +576,28 @@ struct _GHashTableIter gpointer dummy [8]; }; +G_EXTERN_C // Used by MonoPosixHelper or MonoSupportW, at least. GHashTable *g_hash_table_new (GHashFunc hash_func, GEqualFunc key_equal_func); GHashTable *g_hash_table_new_full (GHashFunc hash_func, GEqualFunc key_equal_func, GDestroyNotify key_destroy_func, GDestroyNotify value_destroy_func); +G_EXTERN_C // Used by MonoPosixHelper or MonoSupportW, at least. void g_hash_table_insert_replace (GHashTable *hash, gpointer key, gpointer value, gboolean replace); guint g_hash_table_size (GHashTable *hash); GList *g_hash_table_get_keys (GHashTable *hash); GList *g_hash_table_get_values (GHashTable *hash); +G_EXTERN_C // Used by MonoPosixHelper or MonoSupportW, at least. gpointer g_hash_table_lookup (GHashTable *hash, gconstpointer key); gboolean g_hash_table_lookup_extended (GHashTable *hash, gconstpointer key, gpointer *orig_key, gpointer *value); +G_EXTERN_C // Used by MonoPosixHelper or MonoSupportW, at least. void g_hash_table_foreach (GHashTable *hash, GHFunc func, gpointer user_data); gpointer g_hash_table_find (GHashTable *hash, GHRFunc predicate, gpointer user_data); +G_EXTERN_C // Used by MonoPosixHelper or MonoSupportW, at least. gboolean g_hash_table_remove (GHashTable *hash, gconstpointer key); gboolean g_hash_table_steal (GHashTable *hash, gconstpointer key); void g_hash_table_remove_all (GHashTable *hash); guint g_hash_table_foreach_remove (GHashTable *hash, GHRFunc func, gpointer user_data); guint g_hash_table_foreach_steal (GHashTable *hash, GHRFunc func, gpointer user_data); +G_EXTERN_C // Used by MonoPosixHelper or MonoSupportW, at least. void g_hash_table_destroy (GHashTable *hash); void g_hash_table_print_stats (GHashTable *table); @@ -479,7 +609,9 @@ guint g_spaced_primes_closest (guint x); #define g_hash_table_insert(h,k,v) g_hash_table_insert_replace ((h),(k),(v),FALSE) #define g_hash_table_replace(h,k,v) g_hash_table_insert_replace ((h),(k),(v),TRUE) +G_EXTERN_C // Used by MonoPosixHelper or MonoSupportW, at least. gboolean g_direct_equal (gconstpointer v1, gconstpointer v2); +G_EXTERN_C // Used by MonoPosixHelper or MonoSupportW, at least. guint g_direct_hash (gconstpointer v1); gboolean g_int_equal (gconstpointer v1, gconstpointer v2); guint g_int_hash (gconstpointer v1); @@ -523,6 +655,7 @@ void g_array_set_size (GArray *array, gint length); #define g_array_append_val(a,v) (g_array_append_vals((a),&(v),1)) #define g_array_insert_val(a,i,v) (g_array_insert_vals((a),(i),&(v),1)) #define g_array_index(a,t,i) *(t*)(((a)->data) + sizeof(t) * (i)) +//FIXME previous missing parens /* * QSort @@ -554,6 +687,7 @@ gpointer *g_ptr_array_free (GPtrArray *array, gboolean free_seg); void g_ptr_array_foreach (GPtrArray *array, GFunc func, gpointer user_data); guint g_ptr_array_capacity (GPtrArray *array); #define g_ptr_array_index(array,index) (array)->pdata[(index)] +//FIXME previous missing parens /* * Queues @@ -595,13 +729,17 @@ typedef enum { G_LOG_LEVEL_MASK = ~(G_LOG_FLAG_RECURSION | G_LOG_FLAG_FATAL) } GLogLevelFlags; +G_ENUM_FUNCTIONS (GLogLevelFlags) + void g_printv (const gchar *format, va_list args); void g_print (const gchar *format, ...); void g_printerr (const gchar *format, ...); GLogLevelFlags g_log_set_always_fatal (GLogLevelFlags fatal_mask); GLogLevelFlags g_log_set_fatal_mask (const gchar *log_domain, GLogLevelFlags fatal_mask); void g_logv (const gchar *log_domain, GLogLevelFlags log_level, const gchar *format, va_list args); +G_EXTERN_C // Used by MonoPosixHelper or MonoSupportW, at least. void g_log (const gchar *log_domain, GLogLevelFlags log_level, const gchar *format, ...); +G_EXTERN_C // Used by MonoPosixHelper or MonoSupportW, at least. void g_assertion_message (const gchar *format, ...) G_GNUC_NORETURN; const char * g_get_assertion_message (void); @@ -800,9 +938,11 @@ gchar *g_utf8_strdown (const gchar *str, gssize len); gint g_unichar_to_utf8 (gunichar c, gchar *outbuf); gunichar *g_utf8_to_ucs4_fast (const gchar *str, glong len, glong *items_written); gunichar *g_utf8_to_ucs4 (const gchar *str, glong len, glong *items_read, glong *items_written, GError **err); +G_EXTERN_C // Used by libtest, at least. gunichar2 *g_utf8_to_utf16 (const gchar *str, glong len, glong *items_read, glong *items_written, GError **err); gunichar2 *eg_utf8_to_utf16_with_nuls (const gchar *str, glong len, glong *items_read, glong *items_written, GError **err); gunichar2 *eg_wtf8_to_utf16 (const gchar *str, glong len, glong *items_read, glong *items_written, GError **err); +G_EXTERN_C // Used by libtest, at least. gchar *g_utf16_to_utf8 (const gunichar2 *str, glong len, glong *items_read, glong *items_written, GError **err); gunichar *g_utf16_to_ucs4 (const gunichar2 *str, glong len, glong *items_read, glong *items_written, GError **err); gchar *g_ucs4_to_utf8 (const gunichar *str, glong len, glong *items_read, glong *items_written, GError **err); @@ -930,6 +1070,7 @@ typedef enum { G_FILE_TEST_EXISTS = 1 << 4 } GFileTest; +G_ENUM_FUNCTIONS (GFileTest) gboolean g_file_set_contents (const gchar *filename, const gchar *contents, gssize length, GError **gerror); gboolean g_file_get_contents (const gchar *filename, gchar **contents, gsize *length, GError **gerror); @@ -1116,8 +1257,6 @@ extern const guchar g_utf8_jump_table[256]; gboolean g_utf8_validate (const gchar *str, gssize max_len, const gchar **end); gunichar g_utf8_get_char_validated (const gchar *str, gssize max_len); -gchar *g_utf8_find_prev_char (const char *str, const char *p); -gchar *g_utf8_prev_char (const char *str); #define g_utf8_next_char(p) ((p) + g_utf8_jump_table[(guchar)(*p)]) gunichar g_utf8_get_char (const gchar *src); glong g_utf8_strlen (const gchar *str, gssize max); @@ -1199,4 +1338,22 @@ glong g_utf8_pointer_to_offset (const gchar *str, const gchar *pos); G_END_DECLS -#endif +// For each allocator; i.e. returning gpointer that needs to be cast. +// Macros do not recurse, so naming function and macro the same is ok. +// However these are also already macros. +#undef g_malloc +#undef g_realloc +#undef g_malloc0 +#undef g_calloc +#undef g_try_malloc +#undef g_try_realloc +#undef g_memdup +#define g_malloc(x) (g_cast (monoeg_malloc (x))) +#define g_realloc(obj, size) (g_cast (monoeg_realloc ((obj), (size)))) +#define g_malloc0(x) (g_cast (monoeg_malloc0 (x))) +#define g_calloc(x, y) (g_cast (monoeg_g_calloc ((x), (y)))) +#define g_try_malloc(x) (g_cast (monoeg_try_malloc (x))) +#define g_try_realloc(obj, size) (g_cast (monoeg_try_realloc ((obj), (size)))) +#define g_memdup(mem, size) (g_cast (monoeg_g_memdup ((mem), (size)))) + +#endif // __GLIB_H diff --git a/mono/eglib/glist.c b/mono/eglib/glist.c index 882fda48ec..be473d9702 100644 --- a/mono/eglib/glist.c +++ b/mono/eglib/glist.c @@ -26,11 +26,12 @@ * * (C) 2006 Novell, Inc. */ +#include "config.h" #include #include GList* -g_list_alloc () +g_list_alloc (void) { return g_new0 (GList, 1); } diff --git a/mono/eglib/gmarkup.c b/mono/eglib/gmarkup.c index a91058a4e5..ab23d491a2 100644 --- a/mono/eglib/gmarkup.c +++ b/mono/eglib/gmarkup.c @@ -39,6 +39,7 @@ * 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 #include #include @@ -53,13 +54,13 @@ typedef enum { CLOSING_ELEMENT, COMMENT, SKIP_XML_DECLARATION -} ParseState; +} MonoGMarkupParseState; struct _GMarkupParseContext { GMarkupParser parser; gpointer user_data; GDestroyNotify user_data_dnotify; - ParseState state; + MonoGMarkupParseState state; /* Stores the name of the current element, so we can issue the end_element */ GSList *level; @@ -447,7 +448,7 @@ g_markup_parse_context_parse (GMarkupParseContext *context, goto fail; } - text = current->data; + text = (char*)current->data; if (context->parser.end_element != NULL){ context->parser.end_element (context, text, context->user_data, gerror); if (gerror != NULL && *gerror != NULL){ diff --git a/mono/eglib/gmem.c b/mono/eglib/gmem.c index fab72f6df0..11d117bb60 100644 --- a/mono/eglib/gmem.c +++ b/mono/eglib/gmem.c @@ -29,6 +29,11 @@ #include #include #include +#include // Remove the cast macros and restore the rename macros. +#undef malloc +#undef realloc +#undef free +#undef calloc #if defined (ENABLE_OVERRIDABLE_ALLOCATORS) @@ -123,7 +128,7 @@ gpointer g_calloc (gsize n, gsize x) gpointer ptr; if (!x || !n) return 0; - ptr = G_CALLOC_INTERNAL (n, x); + ptr = G_CALLOC_INTERNAL (n, x); if (ptr) return ptr; g_error ("Could not allocate %i (%i * %i) bytes", x*n, n, x); diff --git a/mono/eglib/gmisc-win32.c b/mono/eglib/gmisc-win32.c index 70d99bfb94..4d0d3ec2ce 100644 --- a/mono/eglib/gmisc-win32.c +++ b/mono/eglib/gmisc-win32.c @@ -133,7 +133,12 @@ g_get_known_folder_path (void) { gchar *folder_path = NULL; PWSTR profile_path = NULL; - HRESULT hr = SHGetKnownFolderPath (&FOLDERID_Profile, KF_FLAG_DEFAULT, NULL, &profile_path); +#ifdef __cplusplus + REFGUID folderid = FOLDERID_Profile; +#else + REFGUID folderid = &FOLDERID_Profile; +#endif + HRESULT hr = SHGetKnownFolderPath (folderid, KF_FLAG_DEFAULT, NULL, &profile_path); if (SUCCEEDED(hr)) { folder_path = u16to8 (profile_path); CoTaskMemFree (profile_path); @@ -170,8 +175,8 @@ g_get_home_dir (void) sprintf (home_dir, "%s%s", drive, path); } } - g_free (drive); - g_free (path); + g_free ((void*)drive); + g_free ((void*)path); } return home_dir; diff --git a/mono/eglib/gmodule.h b/mono/eglib/gmodule.h index ee89683f51..7976684f19 100644 --- a/mono/eglib/gmodule.h +++ b/mono/eglib/gmodule.h @@ -20,9 +20,14 @@ typedef enum { G_MODULE_BIND_LOCAL = 0x02, G_MODULE_BIND_MASK = 0x03 } GModuleFlags; + +G_ENUM_FUNCTIONS (GModuleFlags) + typedef struct _GModule GModule; +G_EXTERN_C // Used by libtest, at least. GModule *g_module_open (const gchar *file, GModuleFlags flags); +G_EXTERN_C // Used by libtest, at least. gboolean g_module_symbol (GModule *module, const gchar *symbol_name, gpointer *symbol); const gchar *g_module_error (void); diff --git a/mono/eglib/gpath.c b/mono/eglib/gpath.c index 713e768617..a5f07c18a2 100644 --- a/mono/eglib/gpath.c +++ b/mono/eglib/gpath.c @@ -97,9 +97,9 @@ strrchr_seperator (const gchar* filename) #endif char *p; - p = strrchr (filename, G_DIR_SEPARATOR); + p = (char*)strrchr (filename, G_DIR_SEPARATOR); #ifdef G_OS_WIN32 - p2 = strrchr (filename, '/'); + p2 = (char*)strrchr (filename, '/'); if (p2 > p) p = p2; #endif @@ -224,7 +224,7 @@ g_find_program_in_path (const gchar *program) char *save = NULL; #ifdef G_OS_WIN32 char *program_exe; - char *suffix_list[5] = {".exe",".cmd",".bat",".com",NULL}; + static char const * const suffix_list[5] = {".exe",".cmd",".bat",".com",NULL}; int listx; gboolean hasSuffix; #endif diff --git a/mono/eglib/gpattern.c b/mono/eglib/gpattern.c index 84861412e8..1bece4df77 100644 --- a/mono/eglib/gpattern.c +++ b/mono/eglib/gpattern.c @@ -25,6 +25,7 @@ * 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 #include #include diff --git a/mono/eglib/gptrarray.c b/mono/eglib/gptrarray.c index f77b5f0fcd..8d08729858 100644 --- a/mono/eglib/gptrarray.c +++ b/mono/eglib/gptrarray.c @@ -27,7 +27,7 @@ * 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 #include diff --git a/mono/eglib/gqsort.c b/mono/eglib/gqsort.c index 59bd453718..cbc9089d33 100644 --- a/mono/eglib/gqsort.c +++ b/mono/eglib/gqsort.c @@ -24,7 +24,7 @@ * 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 #include @@ -40,14 +40,14 @@ typedef struct _QSortStack { size_t count; } QSortStack; -#define QSORT_PUSH(sp, a, c) (sp->array = a, sp->count = c, sp++) -#define QSORT_POP(sp, a, c) (sp--, a = sp->array, c = sp->count) +#define QSORT_PUSH(sp, a, c) ((sp)->array = (char*)(a), (sp)->count = (c), (sp)++) +#define QSORT_POP(sp, a, c) ((sp)--, (a) = (sp)->array, (c) = (sp)->count) #define SWAPTYPE(TYPE, a, b) { \ - long __n = size / sizeof (TYPE); \ - register TYPE *__a = (TYPE *) (a); \ - register TYPE *__b = (TYPE *) (b); \ - register TYPE t; \ + gssize __n = size / sizeof (TYPE); \ + TYPE *__a = (TYPE *) (a); \ + TYPE *__b = (TYPE *) (b); \ + TYPE t; \ \ do { \ t = *__a; \ @@ -69,7 +69,7 @@ void g_qsort_with_data (gpointer base, size_t nmemb, size_t size, GCompareDataFunc compare, gpointer user_data) { QSortStack stack[STACK_SIZE], *sp; - register char *i, *k, *mid; + char *i, *k, *mid; size_t n, n1, n2; char *lo, *hi; int swaplong; diff --git a/mono/eglib/gqueue.c b/mono/eglib/gqueue.c index cd94e1f36d..f9bba47aee 100644 --- a/mono/eglib/gqueue.c +++ b/mono/eglib/gqueue.c @@ -27,7 +27,7 @@ * Copyright (c) 2006-2009 Novell, Inc. * */ - +#include "config.h" #include #include diff --git a/mono/eglib/gshell.c b/mono/eglib/gshell.c index 07b355b9d6..6839eee3fd 100644 --- a/mono/eglib/gshell.c +++ b/mono/eglib/gshell.c @@ -25,6 +25,7 @@ * 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 #include diff --git a/mono/eglib/gslist.c b/mono/eglib/gslist.c index 5baa297f73..1293564df1 100644 --- a/mono/eglib/gslist.c +++ b/mono/eglib/gslist.c @@ -26,7 +26,7 @@ * * (C) 2006 Novell, Inc. */ - +#include "config.h" #include #include diff --git a/mono/eglib/gstr.c b/mono/eglib/gstr.c index ad9a9f883c..3ba01a47f8 100644 --- a/mono/eglib/gstr.c +++ b/mono/eglib/gstr.c @@ -914,22 +914,17 @@ g_utf16_asciiz_equal (const gunichar2 *utf16, const char *ascii) } } -gchar * -g_strdelimit (gchar *string, const gchar *delimiters, gchar new_delimiter) +void +g_strdelimit (gchar *string, gchar delimiter, gchar new_delimiter) { gchar *ptr; - g_return_val_if_fail (string != NULL, NULL); - - if (delimiters == NULL) - delimiters = G_STR_DELIMITERS; + g_return_if_fail (string != NULL); for (ptr = string; *ptr; ptr++) { - if (strchr (delimiters, *ptr)) + if (delimiter == *ptr) *ptr = new_delimiter; } - - return string; } gsize diff --git a/mono/eglib/gstring.c b/mono/eglib/gstring.c index 70a51c8952..403b3ec416 100644 --- a/mono/eglib/gstring.c +++ b/mono/eglib/gstring.c @@ -26,6 +26,7 @@ * 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 #include diff --git a/mono/eglib/gtimer-unix.c b/mono/eglib/gtimer-unix.c index 085e2c17c8..e659d99840 100644 --- a/mono/eglib/gtimer-unix.c +++ b/mono/eglib/gtimer-unix.c @@ -25,6 +25,7 @@ * 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 #include diff --git a/mono/eglib/gtimer-win32.c b/mono/eglib/gtimer-win32.c index 07e802bda1..49940c488f 100644 --- a/mono/eglib/gtimer-win32.c +++ b/mono/eglib/gtimer-win32.c @@ -25,6 +25,7 @@ * 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 #include diff --git a/mono/eglib/gunicode.c b/mono/eglib/gunicode.c index 69d02cd963..b8db6b5abd 100644 --- a/mono/eglib/gunicode.c +++ b/mono/eglib/gunicode.c @@ -39,10 +39,8 @@ #include #include -#ifndef G_OS_WIN32 -# ifdef HAVE_LOCALCHARSET_H -# include -# endif +#if !defined (G_OS_WIN32) && HAVE_NL_LANGINFO +# include #endif const char *eg_my_charset; @@ -62,7 +60,7 @@ g_unichar_type (gunichar c) continue; if (unicode_category_ranges [i].end <= cp) continue; - return unicode_category [i] [cp - unicode_category_ranges [i].start]; + return (GUnicodeType)(unicode_category [i] [cp - unicode_category_ranges [i].start]); } /* @@ -88,7 +86,7 @@ g_unichar_type (gunichar c) /* since the argument is UTF-16, we cannot check beyond FFFF */ /* It should match any of above */ - return 0; + return (GUnicodeType)0; // G_UNICODE_CONTROL } GUnicodeBreakType @@ -208,8 +206,29 @@ g_get_charset (G_CONST_RETURN char **charset) { if (eg_my_charset == NULL) { /* These shouldn't be heap allocated */ -#if defined(HAVE_LOCALCHARSET_H) - eg_my_charset = locale_charset (); +#if HAVE_NL_LANGINFO + /* + * This function used used to use the "locale_charset" call in + * libiconv's libcharset library. However, this isn't always + * available on some systems, including ones with GNU libc. So, + * instead use a function that's a standard part of POSIX2008. + * + * nl_langinfo is in POSIX2008 and should be on any sane modern + * Unix. With a UTF-8 locale, it should return "UTF-8" - this + * has been verified with Ubuntu 18.04, FreeBSD 11, and i 7.3. + * + * The motivation for using locale_charset was likely due to + * the cruftiness of Unices back in ~2001; where you had to + * manually query environment variables, and the values were + * inconsistent between each other. Nowadays, if Linux, macOS, + * AIX/PASE, and FreeBSD can all return the same values for a + * UTF-8 locale, we can just use the value directly. + * + * It should be noted that by default, this function will give + * values for the "C" locale, unless `setlocale (LC_ALL, "")` + * is ran to init locales - driver.c in mini does this for us. + */ + eg_my_charset = nl_langinfo (CODESET); #else eg_my_charset = "UTF-8"; #endif diff --git a/mono/eglib/gutf8.c b/mono/eglib/gutf8.c index c4c9b912e7..ab6e190b91 100644 --- a/mono/eglib/gutf8.c +++ b/mono/eglib/gutf8.c @@ -7,7 +7,7 @@ * (C) 2006 Novell, Inc. * Copyright 2012 Xamarin Inc */ - +#include "config.h" #include #include @@ -286,28 +286,6 @@ g_utf8_get_char (const gchar *src) return u; } -gchar * -g_utf8_find_prev_char (const gchar *str, const gchar *p) -{ - while (p > str) { - p--; - if ((*p & 0xc0) != 0xb0) - return (gchar *)p; - } - return NULL; -} - -gchar * -g_utf8_prev_char (const gchar *str) -{ - const gchar *p = str; - do { - p--; - } while ((*p & 0xc0) == 0xb0); - - return (gchar *)p; -} - gchar * g_utf8_offset_to_pointer (const gchar *str, glong offset) { @@ -328,7 +306,7 @@ g_utf8_offset_to_pointer (const gchar *str, glong offset) // if we land in the middle of a character // walk to the beginning - while ((*jump & 0xc0) == 0xb0) + while ((*jump & 0xc0) == 0x80) jump --; // count how many characters we've actually walked diff --git a/mono/eglib/test/Makefile.am b/mono/eglib/test/Makefile.am new file mode 100644 index 0000000000..2e5b90d142 --- /dev/null +++ b/mono/eglib/test/Makefile.am @@ -0,0 +1,55 @@ +include $(top_srcdir)/mk/common.mk + +EXTRA_DIST = UTF-8.txt UTF-16BE.txt UTF-16LE.txt UTF-32BE.txt UTF-32LE.txt + +SOURCES = \ + enum.cpp \ + test.c \ + test.h \ + tests.h \ + driver.c \ + hashtable.c \ + string-util.c \ + string.c \ + slist.c \ + sizes.c \ + ptrarray.c \ + list.c \ + array.c \ + fake.c \ + path.c \ + queue.c \ + shell.c \ + spawn.c \ + timer.c \ + file.c \ + pattern.c \ + dir.c \ + markup.c \ + unicode.c \ + utf8.c \ + endian.c \ + module.c \ + memory.c + +test_eglib_SOURCES = $(SOURCES) + +GLIB_TEST_FLAGS_COMMON = -Wall -DEGLIB_TESTS=1 -D_FORTIFY_SOURCE=2 -I$(srcdir)/.. -I.. -DDRIVER_NAME=\"EGlib\" +CFLAGS += $(GLIB_TEST_FLAGS_COMMON) +CXXFLAGS += $(GLIB_TEST_FLAGS_COMMON) @CXXFLAGS_COMMON@ + +test_eglib_LDADD = ../libeglib.la $(LTLIBICONV) +assertf_LDADD = ../libeglib.la $(LTLIBICONV) + +# Something amiss with subdirs ordering? +../libeglib.la: ../goutput.c # etc + make -C .. $(@F) + +run-eglib: all + srcdir=`readlink -f $(srcdir)` ./test-eglib + +noinst_PROGRAMS = test-eglib assertf + +run-both: run-eglib + +MAINTAINERCLEANFILES = Makefile.in diff --git a/mono/eglib/test/Makefile.in b/mono/eglib/test/Makefile.in new file mode 100644 index 0000000000..380bcbe768 --- /dev/null +++ b/mono/eglib/test/Makefile.in @@ -0,0 +1,832 @@ +# Makefile.in generated by automake 1.14.1 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2013 Free Software Foundation, Inc. + +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +VPATH = @srcdir@ +am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +target_triplet = @target@ +DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ + $(srcdir)/Makefile.am $(top_srcdir)/mkinstalldirs \ + $(top_srcdir)/depcomp README +noinst_PROGRAMS = test-eglib$(EXEEXT) assertf$(EXEEXT) +subdir = mono/eglib/test +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ + $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ + $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ + $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ + $(top_srcdir)/m4/po.m4 $(top_srcdir)/m4/progtest.m4 \ + $(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +PROGRAMS = $(noinst_PROGRAMS) +assertf_SOURCES = assertf.c +assertf_OBJECTS = assertf.$(OBJEXT) +assertf_DEPENDENCIES = ../libeglib.la +AM_V_lt = $(am__v_lt_@AM_V@) +am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) +am__v_lt_0 = --silent +am__v_lt_1 = +am__objects_1 = enum.$(OBJEXT) test.$(OBJEXT) driver.$(OBJEXT) \ + hashtable.$(OBJEXT) string-util.$(OBJEXT) string.$(OBJEXT) \ + slist.$(OBJEXT) sizes.$(OBJEXT) ptrarray.$(OBJEXT) \ + list.$(OBJEXT) array.$(OBJEXT) fake.$(OBJEXT) path.$(OBJEXT) \ + queue.$(OBJEXT) shell.$(OBJEXT) spawn.$(OBJEXT) \ + timer.$(OBJEXT) file.$(OBJEXT) pattern.$(OBJEXT) dir.$(OBJEXT) \ + markup.$(OBJEXT) unicode.$(OBJEXT) utf8.$(OBJEXT) \ + endian.$(OBJEXT) module.$(OBJEXT) memory.$(OBJEXT) +am_test_eglib_OBJECTS = $(am__objects_1) +test_eglib_OBJECTS = $(am_test_eglib_OBJECTS) +test_eglib_DEPENDENCIES = ../libeglib.la +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/depcomp +am__depfiles_maybe = depfiles +am__mv = mv -f +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +AM_V_CC = $(am__v_CC_@AM_V@) +am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) +am__v_CC_0 = @echo " CC " $@; +am__v_CC_1 = +CCLD = $(CC) +LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(AM_LDFLAGS) $(LDFLAGS) -o $@ +AM_V_CCLD = $(am__v_CCLD_@AM_V@) +am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) +am__v_CCLD_0 = @echo " CCLD " $@; +am__v_CCLD_1 = +CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = +CXXLD = $(CXX) +CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ + $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = +DIST_SOURCES = assertf.c $(test_eglib_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AOT_BUILD_FLAGS = @AOT_BUILD_FLAGS@ +AOT_RUN_FLAGS = @AOT_RUN_FLAGS@ +API_VER = @API_VER@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BOEHM_DEFINES = @BOEHM_DEFINES@ +BREAKPOINT = @BREAKPOINT@ +BTLS_ARCH = @BTLS_ARCH@ +BTLS_CFLAGS = @BTLS_CFLAGS@ +BTLS_CMAKE_ARGS = @BTLS_CMAKE_ARGS@ +BTLS_PLATFORM = @BTLS_PLATFORM@ +BTLS_ROOT = @BTLS_ROOT@ +BUILD_EXEEXT = @BUILD_EXEEXT@ +CC = @CC@ +CCAS = @CCAS@ +CCASDEPMODE = @CCASDEPMODE@ +CCASFLAGS = @CCASFLAGS@ +CCDEPMODE = @CCDEPMODE@ +CC_FOR_BUILD = @CC_FOR_BUILD@ +CFLAGS = @CFLAGS@ $(GLIB_TEST_FLAGS_COMMON) +CFLAGS_FOR_BUILD = @CFLAGS_FOR_BUILD@ +CMAKE = @CMAKE@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CSC = @CSC@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ $(GLIB_TEST_FLAGS_COMMON) @CXXFLAGS_COMMON@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ +CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ +CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFAULT_PROFILE = @DEFAULT_PROFILE@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DOLT_BASH = @DOLT_BASH@ +DSYMUTIL = @DSYMUTIL@ +DTRACE = @DTRACE@ +DTRACEFLAGS = @DTRACEFLAGS@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +EXTERNAL_LLVM_CONFIG = @EXTERNAL_LLVM_CONFIG@ +FGREP = @FGREP@ +GDKX11 = @GDKX11@ +GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ +GLIB_CFLAGS = @GLIB_CFLAGS@ +GMSGFMT = @GMSGFMT@ +GMSGFMT_015 = @GMSGFMT_015@ +GNUC_NORETURN = @GNUC_NORETURN@ +GNUC_PRETTY = @GNUC_PRETTY@ +GNUC_UNUSED = @GNUC_UNUSED@ +GREP = @GREP@ +GSIZE = @GSIZE@ +GSIZE_FORMAT = @GSIZE_FORMAT@ +GSSIZE = @GSSIZE@ +GTKX11 = @GTKX11@ +HAVE_ALLOCA_H = @HAVE_ALLOCA_H@ +HAVE_MSGFMT = @HAVE_MSGFMT@ +HAVE_NINJA = @HAVE_NINJA@ +HAVE_UNISTD_H = @HAVE_UNISTD_H@ +HOST_CC = @HOST_CC@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INTL = @INTL@ +INVARIANT_AOT_OPTIONS = @INVARIANT_AOT_OPTIONS@ +JEMALLOC_AUTOCONF_FLAGS = @JEMALLOC_AUTOCONF_FLAGS@ +JEMALLOC_CFLAGS = @JEMALLOC_CFLAGS@ +JEMALLOC_CPPFLAGS = @JEMALLOC_CPPFLAGS@ +JEMALLOC_LDFLAGS = @JEMALLOC_LDFLAGS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBC = @LIBC@ +LIBGC_CPPFLAGS = @LIBGC_CPPFLAGS@ +LIBGC_LIBS = @LIBGC_LIBS@ +LIBGC_STATIC_LIBS = @LIBGC_STATIC_LIBS@ +LIBMONO_LA = @LIBMONO_LA@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LLVM_CODEGEN_LIBS = @LLVM_CODEGEN_LIBS@ +LN_S = @LN_S@ +LTCOMPILE = @LTCOMPILE@ +LTCXXCOMPILE = @LTCXXCOMPILE@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MONO_CORLIB_VERSION = @MONO_CORLIB_VERSION@ +MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ +MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ +MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ +MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ +MSGFMT = @MSGFMT@ +MSGFMT_015 = @MSGFMT_015@ +MSGMERGE = @MSGMERGE@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +ORDER = @ORDER@ +OS = @OS@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATHSEP = @PATHSEP@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PIDTYPE = @PIDTYPE@ +PKG_CONFIG = @PKG_CONFIG@ +PLATFORM_AOT_SUFFIX = @PLATFORM_AOT_SUFFIX@ +RANLIB = @RANLIB@ +SEARCHSEP = @SEARCHSEP@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SGEN_DEFINES = @SGEN_DEFINES@ +SHARED_CFLAGS = @SHARED_CFLAGS@ +SHELL = @SHELL@ +SIZEOF_VOID_P = @SIZEOF_VOID_P@ +SQLITE = @SQLITE@ +SQLITE3 = @SQLITE3@ +STRIP = @STRIP@ +TEST_PROFILE = @TEST_PROFILE@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +VTUNE_CFLAGS = @VTUNE_CFLAGS@ +VTUNE_LIBS = @VTUNE_LIBS@ +WERROR_CFLAGS = @WERROR_CFLAGS@ +X11 = @X11@ +XATTR_LIB = @XATTR_LIB@ +XGETTEXT = @XGETTEXT@ +XGETTEXT_015 = @XGETTEXT_015@ +XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ +XINERAMA = @XINERAMA@ +XMKMF = @XMKMF@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +arch_target = @arch_target@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +docs_dir = @docs_dir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +export_ldflags = @export_ldflags@ +extra_runtime_ldflags = @extra_runtime_ldflags@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +ikvm_native_dir = @ikvm_native_dir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +libgc_dir = @libgc_dir@ +libgdiplus_install_loc = @libgdiplus_install_loc@ +libgdiplus_loc = @libgdiplus_loc@ +libmono_cflags = @libmono_cflags@ +libmono_ldflags = @libmono_ldflags@ +libsuffix = @libsuffix@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mcs_topdir = @mcs_topdir@ +mcs_topdir_from_srcdir = @mcs_topdir_from_srcdir@ +mkdir_p = @mkdir_p@ +mono_build_root = @mono_build_root@ +mono_cfg_dir = @mono_cfg_dir@ +mono_runtime = @mono_runtime@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +reloc_libdir = @reloc_libdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +subdirs = @subdirs@ +sysconfdir = @sysconfdir@ +target = @target@ +target_alias = @target_alias@ +target_cpu = @target_cpu@ +target_os = @target_os@ +target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +MAKEFLAGS := $(MAKEFLAGS) --no-builtin-rules +EXTRA_DIST = UTF-8.txt UTF-16BE.txt UTF-16LE.txt UTF-32BE.txt UTF-32LE.txt +SOURCES = \ + enum.cpp \ + test.c \ + test.h \ + tests.h \ + driver.c \ + hashtable.c \ + string-util.c \ + string.c \ + slist.c \ + sizes.c \ + ptrarray.c \ + list.c \ + array.c \ + fake.c \ + path.c \ + queue.c \ + shell.c \ + spawn.c \ + timer.c \ + file.c \ + pattern.c \ + dir.c \ + markup.c \ + unicode.c \ + utf8.c \ + endian.c \ + module.c \ + memory.c + +test_eglib_SOURCES = $(SOURCES) +GLIB_TEST_FLAGS_COMMON = -Wall -DEGLIB_TESTS=1 -D_FORTIFY_SOURCE=2 -I$(srcdir)/.. -I.. -DDRIVER_NAME=\"EGlib\" +test_eglib_LDADD = ../libeglib.la $(LTLIBICONV) +assertf_LDADD = ../libeglib.la $(LTLIBICONV) +MAINTAINERCLEANFILES = Makefile.in +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .cpp .lo .o .obj +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_srcdir)/mk/common.mk $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign mono/eglib/test/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign mono/eglib/test/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; +$(top_srcdir)/mk/common.mk: + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +clean-noinstPROGRAMS: + @list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \ + echo " rm -f" $$list; \ + rm -f $$list || exit $$?; \ + test -n "$(EXEEXT)" || exit 0; \ + list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ + echo " rm -f" $$list; \ + rm -f $$list + +assertf$(EXEEXT): $(assertf_OBJECTS) $(assertf_DEPENDENCIES) $(EXTRA_assertf_DEPENDENCIES) + @rm -f assertf$(EXEEXT) + $(AM_V_CCLD)$(LINK) $(assertf_OBJECTS) $(assertf_LDADD) $(LIBS) + +test-eglib$(EXEEXT): $(test_eglib_OBJECTS) $(test_eglib_DEPENDENCIES) $(EXTRA_test_eglib_DEPENDENCIES) + @rm -f test-eglib$(EXEEXT) + $(AM_V_CXXLD)$(CXXLINK) $(test_eglib_OBJECTS) $(test_eglib_LDADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/array.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/assertf.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dir.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/driver.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/endian.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/enum.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fake.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/file.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hashtable.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/list.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/markup.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/memory.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/module.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/path.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pattern.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ptrarray.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/queue.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/shell.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sizes.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/slist.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spawn.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/string-util.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/string.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/timer.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/unicode.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/utf8.Po@am__quote@ + +.c.o: +@am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ +@am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< + +.c.obj: +@am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ +@am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` + +.c.lo: +@am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ +@am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ +@am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< + +.cpp.o: +@am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ +@am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ +@am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< + +.cpp.obj: +@am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ +@am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ +@am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` + +.cpp.lo: +@am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ +@am__fastdepCXX_TRUE@ $(LTCXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ +@am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ + here=`pwd`; \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(PROGRAMS) +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." + -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) +clean: clean-am + +clean-am: clean-generic clean-libtool clean-noinstPROGRAMS \ + mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: + +.MAKE: install-am install-strip + +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-libtool clean-noinstPROGRAMS cscopelist-am ctags \ + ctags-am distclean distclean-compile distclean-generic \ + distclean-libtool distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-dvi install-dvi-am install-exec \ + install-exec-am install-html install-html-am install-info \ + install-info-am install-man install-pdf install-pdf-am \ + install-ps install-ps-am install-strip installcheck \ + installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-compile \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + tags tags-am uninstall uninstall-am + + +# Something amiss with subdirs ordering? +../libeglib.la: ../goutput.c # etc + make -C .. $(@F) + +run-eglib: all + srcdir=`readlink -f $(srcdir)` ./test-eglib + +run-both: run-eglib + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/mono/eglib/test/README b/mono/eglib/test/README new file mode 100644 index 0000000000..7c28d03e95 --- /dev/null +++ b/mono/eglib/test/README @@ -0,0 +1,113 @@ +EGlib Unit Testing +=============================================================================== + + 1. Writing new tests + 2. Using the test driver + +=============================================================================== +1. Writing new tests +=============================================================================== + +Tests are easy to write, but must be grouped in to logical cases. For instance, +the GPtrArray group has a number of tests that cover the entire GPtrArray +implementation. + +These logical case groups should be in a single C file, and must have +three elements: + + #include + #include "test.h" + + ... + + ... + + static Test groupname_tests [] = { + {"groupname_test1", groupname_test1}, + {"groupname_test1", groupname_test2}, + {NULL, NULL} + }; + + DEFINE_TEST_GROUP_INIT(groupname_tests_init, groupname_tests) + +A test implementation should look like: + + RESULT groupname_test1() + { + + + if(test_failed) { + return FAILED("reason: %s", "this works like printf"); + } + + return OK; /* just NULL, but OK is cute */ + } + +Once a test group is written, it needs to be added to the groups table +in tests.h: + + DEFINE_TEST_GROUP_INIT_H(groupname_tests_init) // same as in impl + + static Group test_groups [] = { + ... + {"groupname", groupname_tests_init} + ... + }; + +=============================================================================== +2. Using the test driver +=============================================================================== + +When tests are written, they are rebuilt with make. Two programs will be +built: + + test-eglib: the test driver and tests linked against eglib + test-glib: the test driver and tests linked against system glib-2.0 + +Each driver program works exactly the same. Running test-eglib will run +the tests against eglib, and test-glib against glib-2.0. + +The test driver supports a few options to allow for performance measuring: + + --help show all options and available test groups + --time time the overall run and report it, even if --quiet is set + --quiet do not print test results, useful for timing + --iterations N run all or specified test groups N times + +Run "test-eglib --help" for more details. + +Example: run the ptrarray test group 100000 times and only print the time + it took to perform all iterations + + ./test-eglib -tqi 100000 ptrarray + +Example: show single iteration of test output for two groups + + ./test-eglib ptrarray hashtable + +Example: show test output of all available groups + + ./test-eglib + +The 'test-both' script can be used to run both test-eglib and test-glib +with the same options back to back: + + $ ./test-both -tqi 100000 ptrarray + EGlib Total Time: 1.1961s + GLib Total Time: 0.955957s + +test-both also has a nice --speed-compare mode that shows comparison +information about EGlib vs GLib. It can run all tests or specific tests +with a configurable number of iterations. --speed-compare mode always runs +the drivers with -qtni + +The syntax for --speed-compare is: + + ./test-both --speed-compare [ITERATIONS] [GROUPS...] + + $ ./test-both --speed-compare Runs all tests with default iterations + $ ./test-both --speed-compare 500 Runs all tests with 500 iterations + $ ./test-both --speed-compare ptrarray Runs ptrarray test with default + iterations + + diff --git a/mono/eglib/test/UTF-16BE.txt b/mono/eglib/test/UTF-16BE.txt new file mode 100644 index 0000000000..b7e494cb4d Binary files /dev/null and b/mono/eglib/test/UTF-16BE.txt differ diff --git a/mono/eglib/test/UTF-16LE.txt b/mono/eglib/test/UTF-16LE.txt new file mode 100644 index 0000000000..30fe7b0698 Binary files /dev/null and b/mono/eglib/test/UTF-16LE.txt differ diff --git a/mono/eglib/test/UTF-32BE.txt b/mono/eglib/test/UTF-32BE.txt new file mode 100644 index 0000000000..a1fd5437bd Binary files /dev/null and b/mono/eglib/test/UTF-32BE.txt differ diff --git a/mono/eglib/test/UTF-32LE.txt b/mono/eglib/test/UTF-32LE.txt new file mode 100644 index 0000000000..043afc9927 Binary files /dev/null and b/mono/eglib/test/UTF-32LE.txt differ diff --git a/mono/eglib/test/UTF-8.txt b/mono/eglib/test/UTF-8.txt new file mode 100644 index 0000000000..4363f27bd5 --- /dev/null +++ b/mono/eglib/test/UTF-8.txt @@ -0,0 +1,212 @@ + +UTF-8 encoded sample plain-text file +‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ + +Markus Kuhn [ˈmaʳkʊs kuːn] — 2002-07-25 + + +The ASCII compatible UTF-8 encoding used in this plain-text file +is defined in Unicode, ISO 10646-1, and RFC 2279. + + +Using Unicode/UTF-8, you can write in emails and source code things such as + +Mathematics and sciences: + + ∮ E⋅da = Q, n → ∞, ∑ f(i) = ∏ g(i), ⎧⎡⎛┌─────┐⎞⎤⎫ + ⎪⎢⎜│a²+b³ ⎟⎥⎪ + ∀x∈ℝ: ⌈x⌉ = −⌊−x⌋, α ∧ ¬β = ¬(¬α ∨ β), ⎪⎢⎜│───── ⎟⎥⎪ + ⎪⎢⎜⎷ c₈ ⎟⎥⎪ + ℕ ⊆ ℕ₀ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ, ⎨⎢⎜ ⎟⎥⎬ + ⎪⎢⎜ ∞ ⎟⎥⎪ + ⊥ < a ≠ b ≡ c ≤ d ≪ ⊤ ⇒ (⟦A⟧ ⇔ ⟪B⟫), ⎪⎢⎜ ⎲ ⎟⎥⎪ + ⎪⎢⎜ ⎳aⁱ-bⁱ⎟⎥⎪ + 2H₂ + O₂ ⇌ 2H₂O, R = 4.7 kΩ, ⌀ 200 mm ⎩⎣⎝i=1 ⎠⎦⎭ + +Linguistics and dictionaries: + + ði ıntəˈnæʃənəl fəˈnɛtık əsoʊsiˈeıʃn + Y [ˈʏpsilɔn], Yen [jɛn], Yoga [ˈjoːgɑ] + +APL: + + ((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈ + +Nicer typography in plain text files: + + ╔══════════════════════════════════════════╗ + ║ ║ + ║ • ‘single’ and “double” quotes ║ + ║ ║ + ║ • Curly apostrophes: “We’ve been here” ║ + ║ ║ + ║ • Latin-1 apostrophe and accents: '´` ║ + ║ ║ + ║ • ‚deutsche‘ „Anführungszeichen“ ║ + ║ ║ + ║ • †, ‡, ‰, •, 3–4, —, −5/+5, ™, … ║ + ║ ║ + ║ • ASCII safety test: 1lI|, 0OD, 8B ║ + ║ ╭─────────╮ ║ + ║ • the euro symbol: │ 14.95 € │ ║ + ║ ╰─────────╯ ║ + ╚══════════════════════════════════════════╝ + +Combining characters: + + STARGΛ̊TE SG-1, a = v̇ = r̈, a⃑ ⊥ b⃑ + +Greek (in Polytonic): + + The Greek anthem: + + Σὲ γνωρίζω ἀπὸ τὴν κόψη + τοῦ σπαθιοῦ τὴν τρομερή, + σὲ γνωρίζω ἀπὸ τὴν ὄψη + ποὺ μὲ βία μετράει τὴ γῆ. + + ᾿Απ᾿ τὰ κόκκαλα βγαλμένη + τῶν ῾Ελλήνων τὰ ἱερά + καὶ σὰν πρῶτα ἀνδρειωμένη + χαῖρε, ὦ χαῖρε, ᾿Ελευθεριά! + + From a speech of Demosthenes in the 4th century BC: + + Οὐχὶ ταὐτὰ παρίσταταί μοι γιγνώσκειν, ὦ ἄνδρες ᾿Αθηναῖοι, + ὅταν τ᾿ εἰς τὰ πράγματα ἀποβλέψω καὶ ὅταν πρὸς τοὺς + λόγους οὓς ἀκούω· τοὺς μὲν γὰρ λόγους περὶ τοῦ + τιμωρήσασθαι Φίλιππον ὁρῶ γιγνομένους, τὰ δὲ πράγματ᾿ + εἰς τοῦτο προήκοντα, ὥσθ᾿ ὅπως μὴ πεισόμεθ᾿ αὐτοὶ + πρότερον κακῶς σκέψασθαι δέον. οὐδέν οὖν ἄλλο μοι δοκοῦσιν + οἱ τὰ τοιαῦτα λέγοντες ἢ τὴν ὑπόθεσιν, περὶ ἧς βουλεύεσθαι, + οὐχὶ τὴν οὖσαν παριστάντες ὑμῖν ἁμαρτάνειν. ἐγὼ δέ, ὅτι μέν + ποτ᾿ ἐξῆν τῇ πόλει καὶ τὰ αὑτῆς ἔχειν ἀσφαλῶς καὶ Φίλιππον + τιμωρήσασθαι, καὶ μάλ᾿ ἀκριβῶς οἶδα· ἐπ᾿ ἐμοῦ γάρ, οὐ πάλαι + γέγονεν ταῦτ᾿ ἀμφότερα· νῦν μέντοι πέπεισμαι τοῦθ᾿ ἱκανὸν + προλαβεῖν ἡμῖν εἶναι τὴν πρώτην, ὅπως τοὺς συμμάχους + σώσομεν. ἐὰν γὰρ τοῦτο βεβαίως ὑπάρξῃ, τότε καὶ περὶ τοῦ + τίνα τιμωρήσεταί τις καὶ ὃν τρόπον ἐξέσται σκοπεῖν· πρὶν δὲ + τὴν ἀρχὴν ὀρθῶς ὑποθέσθαι, μάταιον ἡγοῦμαι περὶ τῆς + τελευτῆς ὁντινοῦν ποιεῖσθαι λόγον. + + Δημοσθένους, Γ´ ᾿Ολυνθιακὸς + +Georgian: + + From a Unicode conference invitation: + + გთხოვთ ახლავე გაიაროთ რეგისტრაცია Unicode-ის მეათე საერთაშორისო + კონფერენციაზე დასასწრებად, რომელიც გაიმართება 10-12 მარტს, + ქ. მაინცში, გერმანიაში. კონფერენცია შეჰკრებს ერთად მსოფლიოს + ექსპერტებს ისეთ დარგებში როგორიცაა ინტერნეტი და Unicode-ი, + ინტერნაციონალიზაცია და ლოკალიზაცია, Unicode-ის გამოყენება + ოპერაციულ სისტემებსა, და გამოყენებით პროგრამებში, შრიფტებში, + ტექსტების დამუშავებასა და მრავალენოვან კომპიუტერულ სისტემებში. + +Russian: + + From a Unicode conference invitation: + + Зарегистрируйтесь сейчас на Десятую Международную Конференцию по + Unicode, которая состоится 10-12 марта 1997 года в Майнце в Германии. + Конференция соберет широкий круг экспертов по вопросам глобального + Интернета и Unicode, локализации и интернационализации, воплощению и + применению Unicode в различных операционных системах и программных + приложениях, шрифтах, верстке и многоязычных компьютерных системах. + +Thai (UCS Level 2): + + Excerpt from a poetry on The Romance of The Three Kingdoms (a Chinese + classic 'San Gua'): + + [----------------------------|------------------------] + ๏ แผ่นดินฮั่นเสื่อมโทรมแสนสังเวช พระปกเกศกองบู๊กู้ขึ้นใหม่ + สิบสองกษัตริย์ก่อนหน้าแลถัดไป สององค์ไซร้โง่เขลาเบาปัญญา + ทรงนับถือขันทีเป็นที่พึ่ง บ้านเมืองจึงวิปริตเป็นนักหนา + โฮจิ๋นเรียกทัพทั่วหัวเมืองมา หมายจะฆ่ามดชั่วตัวสำคัญ + เหมือนขับไสไล่เสือจากเคหา รับหมาป่าเข้ามาเลยอาสัญ + ฝ่ายอ้องอุ้นยุแยกให้แตกกัน ใช้สาวนั้นเป็นชนวนชื่นชวนใจ + พลันลิฉุยกุยกีกลับก่อเหตุ ช่างอาเพศจริงหนาฟ้าร้องไห้ + ต้องรบราฆ่าฟันจนบรรลัย ฤๅหาใครค้ำชูกู้บรรลังก์ ฯ + + (The above is a two-column text. If combining characters are handled + correctly, the lines of the second column should be aligned with the + | character above.) + +Ethiopian: + + Proverbs in the Amharic language: + + ሰማይ አይታረስ ንጉሥ አይከሰስ። + ብላ ካለኝ እንደአባቴ በቆመጠኝ። + ጌጥ ያለቤቱ ቁምጥና ነው። + ደሀ በሕልሙ ቅቤ ባይጠጣ ንጣት በገደለው። + የአፍ ወለምታ በቅቤ አይታሽም። + አይጥ በበላ ዳዋ ተመታ። + ሲተረጉሙ ይደረግሙ። + ቀስ በቀስ፥ ዕንቁላል በእግሩ ይሄዳል። + ድር ቢያብር አንበሳ ያስር። + ሰው እንደቤቱ እንጅ እንደ ጉረቤቱ አይተዳደርም። + እግዜር የከፈተውን ጉሮሮ ሳይዘጋው አይድርም። + የጎረቤት ሌባ፥ ቢያዩት ይስቅ ባያዩት ያጠልቅ። + ሥራ ከመፍታት ልጄን ላፋታት። + ዓባይ ማደሪያ የለው፥ ግንድ ይዞ ይዞራል። + የእስላም አገሩ መካ የአሞራ አገሩ ዋርካ። + ተንጋሎ ቢተፉ ተመልሶ ባፉ። + ወዳጅህ ማር ቢሆን ጨርስህ አትላሰው። + እግርህን በፍራሽህ ልክ ዘርጋ። + +Runes: + + ᚻᛖ ᚳᚹᚫᚦ ᚦᚫᛏ ᚻᛖ ᛒᚢᛞᛖ ᚩᚾ ᚦᚫᛗ ᛚᚪᚾᛞᛖ ᚾᚩᚱᚦᚹᛖᚪᚱᛞᚢᛗ ᚹᛁᚦ ᚦᚪ ᚹᛖᛥᚫ + + (Old English, which transcribed into Latin reads 'He cwaeth that he + bude thaem lande northweardum with tha Westsae.' and means 'He said + that he lived in the northern land near the Western Sea.') + +Braille: + + ⡌⠁⠧⠑ ⠼⠁⠒ ⡍⠜⠇⠑⠹⠰⠎ ⡣⠕⠌ + + ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠙⠑⠁⠙⠒ ⠞⠕ ⠃⠑⠛⠔ ⠺⠊⠹⠲ ⡹⠻⠑ ⠊⠎ ⠝⠕ ⠙⠳⠃⠞ + ⠱⠁⠞⠑⠧⠻ ⠁⠃⠳⠞ ⠹⠁⠞⠲ ⡹⠑ ⠗⠑⠛⠊⠌⠻ ⠕⠋ ⠙⠊⠎ ⠃⠥⠗⠊⠁⠇ ⠺⠁⠎ + ⠎⠊⠛⠝⠫ ⠃⠹ ⠹⠑ ⠊⠇⠻⠛⠹⠍⠁⠝⠂ ⠹⠑ ⠊⠇⠻⠅⠂ ⠹⠑ ⠥⠝⠙⠻⠞⠁⠅⠻⠂ + ⠁⠝⠙ ⠹⠑ ⠡⠊⠑⠋ ⠍⠳⠗⠝⠻⠲ ⡎⠊⠗⠕⠕⠛⠑ ⠎⠊⠛⠝⠫ ⠊⠞⠲ ⡁⠝⠙ + ⡎⠊⠗⠕⠕⠛⠑⠰⠎ ⠝⠁⠍⠑ ⠺⠁⠎ ⠛⠕⠕⠙ ⠥⠏⠕⠝ ⠰⡡⠁⠝⠛⠑⠂ ⠋⠕⠗ ⠁⠝⠹⠹⠔⠛ ⠙⠑ + ⠡⠕⠎⠑ ⠞⠕ ⠏⠥⠞ ⠙⠊⠎ ⠙⠁⠝⠙ ⠞⠕⠲ + + ⡕⠇⠙ ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ + + ⡍⠔⠙⠖ ⡊ ⠙⠕⠝⠰⠞ ⠍⠑⠁⠝ ⠞⠕ ⠎⠁⠹ ⠹⠁⠞ ⡊ ⠅⠝⠪⠂ ⠕⠋ ⠍⠹ + ⠪⠝ ⠅⠝⠪⠇⠫⠛⠑⠂ ⠱⠁⠞ ⠹⠻⠑ ⠊⠎ ⠏⠜⠞⠊⠊⠥⠇⠜⠇⠹ ⠙⠑⠁⠙ ⠁⠃⠳⠞ + ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ ⡊ ⠍⠊⠣⠞ ⠙⠁⠧⠑ ⠃⠑⠲ ⠔⠊⠇⠔⠫⠂ ⠍⠹⠎⠑⠇⠋⠂ ⠞⠕ + ⠗⠑⠛⠜⠙ ⠁ ⠊⠕⠋⠋⠔⠤⠝⠁⠊⠇ ⠁⠎ ⠹⠑ ⠙⠑⠁⠙⠑⠌ ⠏⠊⠑⠊⠑ ⠕⠋ ⠊⠗⠕⠝⠍⠕⠝⠛⠻⠹ + ⠔ ⠹⠑ ⠞⠗⠁⠙⠑⠲ ⡃⠥⠞ ⠹⠑ ⠺⠊⠎⠙⠕⠍ ⠕⠋ ⠳⠗ ⠁⠝⠊⠑⠌⠕⠗⠎ + ⠊⠎ ⠔ ⠹⠑ ⠎⠊⠍⠊⠇⠑⠆ ⠁⠝⠙ ⠍⠹ ⠥⠝⠙⠁⠇⠇⠪⠫ ⠙⠁⠝⠙⠎ + ⠩⠁⠇⠇ ⠝⠕⠞ ⠙⠊⠌⠥⠗⠃ ⠊⠞⠂ ⠕⠗ ⠹⠑ ⡊⠳⠝⠞⠗⠹⠰⠎ ⠙⠕⠝⠑ ⠋⠕⠗⠲ ⡹⠳ + ⠺⠊⠇⠇ ⠹⠻⠑⠋⠕⠗⠑ ⠏⠻⠍⠊⠞ ⠍⠑ ⠞⠕ ⠗⠑⠏⠑⠁⠞⠂ ⠑⠍⠏⠙⠁⠞⠊⠊⠁⠇⠇⠹⠂ ⠹⠁⠞ + ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ + + (The first couple of paragraphs of "A Christmas Carol" by Dickens) + +Compact font selection example text: + + ABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789 + abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ + –—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвгд + ∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა + +Greetings in various languages: + + Hello world, Καλημέρα κόσμε, コンニチハ + +Box drawing alignment tests: █ + ▉ + ╔══╦══╗ ┌──┬──┐ ╭──┬──╮ ╭──┬──╮ ┏━━┳━━┓ ┎┒┏┑ ╷ ╻ ┏┯┓ ┌┰┐ ▊ ╱╲╱╲╳╳╳ + ║┌─╨─┐║ │╔═╧═╗│ │╒═╪═╕│ │╓─╁─╖│ ┃┌─╂─┐┃ ┗╃╄┙ ╶┼╴╺╋╸┠┼┨ ┝╋┥ ▋ ╲╱╲╱╳╳╳ + ║│╲ ╱│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╿ │┃ ┍╅╆┓ ╵ ╹ ┗┷┛ └┸┘ ▌ ╱╲╱╲╳╳╳ + ╠╡ ╳ ╞╣ ├╢ ╟┤ ├┼─┼─┼┤ ├╫─╂─╫┤ ┣┿╾┼╼┿┫ ┕┛┖┚ ┌┄┄┐ ╎ ┏┅┅┓ ┋ ▍ ╲╱╲╱╳╳╳ + ║│╱ ╲│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╽ │┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▎ + ║└─╥─┘║ │╚═╤═╝│ │╘═╪═╛│ │╙─╀─╜│ ┃└─╂─┘┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▏ + ╚══╩══╝ └──┴──┘ ╰──┴──╯ ╰──┴──╯ ┗━━┻━━┛ ▗▄▖▛▀▜ └╌╌┘ ╎ ┗╍╍┛ ┋ ▁▂▃▄▅▆▇█ + ▝▀▘▙▄▟ diff --git a/mono/eglib/test/array.c b/mono/eglib/test/array.c new file mode 100644 index 0000000000..20865dadbe --- /dev/null +++ b/mono/eglib/test/array.c @@ -0,0 +1,163 @@ +#include +#include +#include +#include "test.h" + +/* example from glib documentation */ +static RESULT +test_array_big (void) +{ + GArray *garray; + gint i; + + /* We create a new array to store gint values. + We don't want it zero-terminated or cleared to 0's. */ + garray = g_array_new (FALSE, FALSE, sizeof (gint)); + for (i = 0; i < 10000; i++) + g_array_append_val (garray, i); + + for (i = 0; i < 10000; i++) + if (g_array_index (garray, gint, i) != i) + return FAILED ("array value didn't match"); + + g_array_free (garray, TRUE); + + return NULL; +} + +static RESULT +test_array_index (void) +{ + GArray *array = g_array_new (FALSE, FALSE, sizeof (int)); + int v; + + v = 27; + g_array_append_val (array, v); + + if (27 != g_array_index (array, int, 0)) + return FAILED (""); + + g_array_free (array, TRUE); + + return NULL; +} + +static RESULT +test_array_append_zero_terminated (void) +{ + GArray *array = g_array_new (TRUE, FALSE, sizeof (int)); + int v; + + v = 27; + g_array_append_val (array, v); + + if (27 != g_array_index (array, int, 0)) + return FAILED ("g_array_append_val failed"); + + if (0 != g_array_index (array, int, 1)) + return FAILED ("zero_terminated didn't append a zero element"); + + g_array_free (array, TRUE); + + return NULL; +} + +static RESULT +test_array_append (void) +{ + GArray *array = g_array_new (FALSE, FALSE, sizeof (int)); + int v; + + if (0 != array->len) + return FAILED ("initial array length not zero"); + + v = 27; + + g_array_append_val (array, v); + + if (1 != array->len) + return FAILED ("array append failed"); + + g_array_free (array, TRUE); + + return NULL; +} + +static RESULT +test_array_insert_val (void) +{ + GArray *array = g_array_new (FALSE, FALSE, sizeof (gpointer)); + gpointer ptr0, ptr1, ptr2, ptr3; + + g_array_insert_val (array, 0, array); + + if (array != g_array_index (array, gpointer, 0)) + return FAILED ("1 The value in the array is incorrect"); + + g_array_insert_val (array, 1, array); + if (array != g_array_index (array, gpointer, 1)) + return FAILED ("2 The value in the array is incorrect"); + + g_array_insert_val (array, 2, array); + if (array != g_array_index (array, gpointer, 2)) + return FAILED ("3 The value in the array is incorrect"); + + g_array_free (array, TRUE); + array = g_array_new (FALSE, FALSE, sizeof (gpointer)); + ptr0 = array; + ptr1 = array + 1; + ptr2 = array + 2; + ptr3 = array + 3; + + g_array_insert_val (array, 0, ptr0); + g_array_insert_val (array, 1, ptr1); + g_array_insert_val (array, 2, ptr2); + g_array_insert_val (array, 1, ptr3); + if (ptr0 != g_array_index (array, gpointer, 0)) + return FAILED ("4 The value in the array is incorrect"); + if (ptr3 != g_array_index (array, gpointer, 1)) + return FAILED ("5 The value in the array is incorrect"); + if (ptr1 != g_array_index (array, gpointer, 2)) + return FAILED ("6 The value in the array is incorrect"); + if (ptr2 != g_array_index (array, gpointer, 3)) + return FAILED ("7 The value in the array is incorrect"); + + g_array_free (array, TRUE); + return NULL; +} + +static RESULT +test_array_remove (void) +{ + GArray *array = g_array_new (FALSE, FALSE, sizeof (int)); + int v[] = {30, 29, 28, 27, 26, 25}; + + g_array_append_vals (array, v, 6); + + if (6 != array->len) + return FAILED ("append_vals fail"); + + g_array_remove_index (array, 3); + + if (5 != array->len) + return FAILED ("remove_index failed to update length"); + + if (26 != g_array_index (array, int, 3)) + return FAILED ("remove_index failed to update the array"); + + g_array_free (array, TRUE); + + return NULL; +} + +static Test array_tests [] = { + {"big", test_array_big}, + {"append", test_array_append}, + {"insert_val", test_array_insert_val}, + {"index", test_array_index}, + {"remove", test_array_remove}, + {"append_zero_term", test_array_append_zero_terminated}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(array_tests_init, array_tests) diff --git a/mono/eglib/test/assertf.c b/mono/eglib/test/assertf.c new file mode 100644 index 0000000000..05484adb91 --- /dev/null +++ b/mono/eglib/test/assertf.c @@ -0,0 +1,20 @@ +/* This tests g_assertf. + +f is for format, like printf + +Previously one would say like: + if (!expr) + g_error(...) + +now: + g_assertf(expr, ...); +*/ + +#include "../glib.h" + +int main(int argc, char** argv) +{ + g_assertf(1, "", *(volatile char*)0); + g_assertf(0, "argc:%d, argv0:%s", argc, argv[0]); + return 0; +} diff --git a/mono/eglib/test/dir.c b/mono/eglib/test/dir.c new file mode 100644 index 0000000000..a3af1dffad --- /dev/null +++ b/mono/eglib/test/dir.c @@ -0,0 +1,64 @@ +#include +#include +#include +#include +#ifdef HAVE_UNISTD_H +#include +#endif +#ifdef G_OS_UNIX +#include +#endif +#include "test.h" + +/* This test is just to be used with valgrind */ +static RESULT +test_dir (void) +{ + GDir *dir; + GError *gerror; + const gchar *name; + + /* + dir = g_dir_open (NULL, 0, NULL); + */ + dir = g_dir_open ("", 0, NULL); + if (dir != NULL) + return FAILED ("1 Should be an error"); + + dir = g_dir_open ("", 9, NULL); + if (dir != NULL) + return FAILED ("2 Should be an error"); + + gerror = NULL; + dir = g_dir_open (".ljasdslakjd", 9, &gerror); + if (dir != NULL) + return FAILED ("3 opendir should fail"); + if (gerror == NULL) + return FAILED ("4 got no error"); + g_error_free (gerror); + gerror = NULL; + dir = g_dir_open (g_get_tmp_dir (), 9, &gerror); + if (dir == NULL) + return FAILED ("5 opendir should succeed"); + if (gerror != NULL) + return FAILED ("6 got an error"); + name = NULL; + name = g_dir_read_name (dir); + if (name == NULL) + return FAILED ("7 didn't read a file name"); + while ((name = g_dir_read_name (dir)) != NULL) { + if (strcmp (name, ".") == 0) + return FAILED (". directory found"); + if (strcmp (name, "..") == 0) + return FAILED (".. directory found"); + } + g_dir_close (dir); + return OK; +} + +static Test dir_tests [] = { + {"g_dir_*", test_dir}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(dir_tests_init, dir_tests) diff --git a/mono/eglib/test/driver.c b/mono/eglib/test/driver.c new file mode 100644 index 0000000000..7a732c2945 --- /dev/null +++ b/mono/eglib/test/driver.c @@ -0,0 +1,253 @@ +/* + * EGLib Unit Test Driver + * + * Author: + * Aaron Bockover (abockover@novell.com) + * + * (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 +#include "test.h" + +#ifndef DRIVER_EXTERNAL_TESTS +#include "tests.h" +#endif + +#include +#ifdef HAVE_GETOPT_H +#include +#endif + +#if defined(HAVE_UNISTD_H) +#include +#endif + +#ifndef DRIVER_NAME +#define DRIVER_NAME "EGlib" +#endif + +typedef struct _StringArray { + gchar **strings; + gint length; +} StringArray; + +static StringArray * +string_array_append(StringArray *array, gchar *string) +{ + if (array == NULL) { + array = g_new0(StringArray, 1); + array->length = 1; + array->strings = g_malloc(sizeof(gchar *) * 2); + } else { + array->length++; + array->strings = g_realloc(array->strings, sizeof(gchar *) + * (array->length + 1)); + } + + array->strings[array->length - 1] = string; + array->strings[array->length] = NULL; + + return array; +} + +gint global_passed = 0, global_tests = 0; + +static void +string_array_free(StringArray *array) +{ + g_free(array->strings); + g_free(array); +} + +static void print_help(char *s) +{ + gint i; + + printf("Usage: %s [OPTION]... [TESTGROUP]...\n\n", s); + printf("OPTIONS are:\n"); + printf(" -h, --help show this help\n"); + printf(" -t, --time time the tests\n"); + printf(" -i, --iterations number of times to run tests\n"); + printf(" -q, --quiet do not print test results; " + "final time always prints\n"); + printf(" -n, --no-labels print final time without labels, " + "nice for scripts\n"); + printf(" -d, --debug do not run tests, " + "debug the driver itself for valgrind\n\n"); + printf("TESTGROUPS available:\n"); + + for (i = 0; test_groups[i].name != NULL; i++) { + if (test_groups[i].handler != fake_tests_init) { + printf(" %s\n", test_groups[i].name); + } + } + + printf("\n"); +} + +#ifdef DRIVER_EXTERNAL_MAIN +gint run_tests_main(gint argc, gchar **argv) +#else +gint main(gint argc, gchar **argv) +#endif +{ + gint i, j, c, iterations = 1; + StringArray *tests_to_run = NULL; + gdouble time_start; + gboolean report_time = FALSE; + gboolean quiet = FALSE; + gboolean global_failure = FALSE; + gboolean no_final_time_labels = FALSE; + gboolean debug = FALSE; + +#if HAVE_GETOPT_H + static struct option long_options [] = { + {"help", no_argument, 0, 'h'}, + {"time", no_argument, 0, 't'}, + {"quiet", no_argument, 0, 'q'}, + {"iterations", required_argument, 0, 'i'}, + {"debug", no_argument, 0, 'd'}, + {"no-labels", no_argument, 0, 'n'}, + {0, 0, 0, 0} + }; + + while((c = getopt_long(argc, argv, "dhtqni:", long_options, NULL)) != -1) { switch(c) { + case 'h': + print_help(argv[0]); + return 1; + case 't': + report_time = TRUE; + break; + case 'i': + iterations = atoi(optarg); + break; + case 'q': + quiet = TRUE; + break; + case 'n': + no_final_time_labels = TRUE; + break; + case 'd': + debug = TRUE; + break; + } + } + + for (i = optind; i < argc; i++) { + if (argv[i][0] == '-') { + continue; + } + + tests_to_run = string_array_append(tests_to_run, argv[i]); + } +#endif + + time_start = get_timestamp(); + + for (j = 0; test_groups[j].name != NULL; j++) { + gboolean run = TRUE; + gchar *tests = NULL; + gchar *group = NULL; + + if (tests_to_run != NULL) { + gint k; + run = FALSE; + + for (k = 0; k < tests_to_run->length; k++) { + gchar *user = tests_to_run->strings[k]; + const gchar *table = test_groups[j].name; + size_t user_len = strlen(user); + size_t table_len = strlen(table); + + if (strncmp(user, table, table_len) == 0) { + if (user_len > table_len && user[table_len] != ':') { + break; + } + + run = TRUE; + group = tests_to_run->strings[k]; + break; + } + } + } + + if (run) { + gboolean passed; + gchar **split = NULL; + + if (debug && test_groups[j].handler != fake_tests_init) { + printf("Skipping %s, in driver debug mode\n", + test_groups[j].name); + continue; + } else if (!debug && test_groups[j].handler == fake_tests_init) { + continue; + } + + if (group != NULL) { + split = eg_strsplit(group, ":", -1); + if (split != NULL) { + gint m; + for (m = 0; split[m] != NULL; m++) { + if (m == 1) { + tests = strdup(split[m]); + break; + } + } + eg_strfreev(split); + } + } + + passed = run_group(&(test_groups[j]), + iterations, quiet, report_time, tests); + + if (tests != NULL) { + g_free(tests); + } + + if (!passed && !global_failure) { + global_failure = TRUE; + } + } + } + + if (!quiet) { + gdouble pass_percentage = ((gdouble)global_passed / (gdouble)global_tests) * 100.0; + printf("=============================\n"); + printf("Overall result: %s : %d / %d (%g%%)\n", global_failure ? "FAILED" : "OK", global_passed, global_tests, pass_percentage); + } + + if (report_time) { + gdouble duration = get_timestamp() - time_start; + if (no_final_time_labels) { + printf("%g\n", duration); + } else { + printf("%s Total Time: %g\n", DRIVER_NAME, duration); + } + } + + if (tests_to_run != NULL) { + string_array_free(tests_to_run); + } + + return global_tests - global_passed; +} diff --git a/mono/eglib/test/endian.c b/mono/eglib/test/endian.c new file mode 100644 index 0000000000..a238ca62e5 --- /dev/null +++ b/mono/eglib/test/endian.c @@ -0,0 +1,37 @@ +#include "test.h" + +static RESULT +test_swap (void) +{ + guint32 a = 0xabcdef01, res32; + guint64 b = (((guint64)a) << 32) | a, res64; + guint64 b_expect = (((guint64)0x1efcdab) << 32) | 0x01efcdab; + guint16 c = 0xabcd, res16; + + res32 = GUINT32_SWAP_LE_BE (a); + if (res32 != 0x01efcdab) + return FAILED ("GUINT32_SWAP_LE_BE returned 0x%x", res32); + res32 = GUINT32_SWAP_LE_BE (1); + if (res32 != 0x1000000) + return FAILED ("GUINT32_SWAP_LE_BE returned 0x%x", res32); + + res64 = GUINT64_SWAP_LE_BE(b); + if (res64 != b_expect) + return FAILED ("GUINT64_SWAP_LE_BE returned 0x%llx (had=0x%llx)", res64, b); + res16 = GUINT16_SWAP_LE_BE(c); + if (res16 != 0xcdab) + return FAILED ("GUINT16_SWAP_LE_BE returned 0x%x", (guint32) res16); + + return OK; +} + +/* + * test initialization + */ + +static Test endian_tests [] = { + {"swap", test_swap}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(endian_tests_init, endian_tests) diff --git a/mono/eglib/test/enum.cpp b/mono/eglib/test/enum.cpp new file mode 100644 index 0000000000..f007b195da --- /dev/null +++ b/mono/eglib/test/enum.cpp @@ -0,0 +1,67 @@ +#include "config.h" +#include "glib.h" + +typedef enum { + Black = 0, + Red = 1, + Blue = 2, + Purple = Red | Blue, // 3 + Green = 4, + Yellow = Red | Green, // 5 + White = 7, +} Color; + +G_ENUM_FUNCTIONS (Color) + +static void +test_enum1 (void) +{ + const Color green = Green; + const Color blue = Blue; + const Color red = Red; + const Color white = White; + const Color purple = Purple; + + g_assert ((red & blue) == Black); + g_assert ((red | blue | green) == White); + g_assert ((red | blue) == Purple); + g_assert ((white ^ purple) == green); + + Color c = Black; + Color c2 = Black; + c |= red; + g_assert (c == Red); + c ^= red; + g_assert (c == Black); + + c |= (c2 |= Red) | Blue; + g_assert (c == Purple); + g_assert (c2 == Red); + + c = c2 = Black; + c |= (c2 |= Red) |= Blue; + g_assert (c == Purple); + g_assert (c2 == Purple); + + c = red; + c &= red; + g_assert (c == Red); + c &= blue; + g_assert (c == Black); +} + +#include "test.h" + +static RESULT +test_enum (void) +{ + test_enum1 (); + return OK; +} + +const static Test enum_tests [2] = {{"test_enum", test_enum}}; + +extern "C" +{ +DEFINE_TEST_GROUP_INIT (enum_tests_init, enum_tests) +} diff --git a/mono/eglib/test/fake.c b/mono/eglib/test/fake.c new file mode 100644 index 0000000000..96e8554118 --- /dev/null +++ b/mono/eglib/test/fake.c @@ -0,0 +1,18 @@ +/* + * Fake test allows debugging of the driver itself + */ + +#include "test.h" + +static RESULT +test_fake (void) +{ + return OK; +} + +static Test fake_tests [] = { + {"fake", test_fake}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(fake_tests_init, fake_tests) diff --git a/mono/eglib/test/file.c b/mono/eglib/test/file.c new file mode 100644 index 0000000000..feb8d9b5a9 --- /dev/null +++ b/mono/eglib/test/file.c @@ -0,0 +1,226 @@ +#include +#include +#include +#include +#ifdef HAVE_UNISTD_H +#include +#endif +#include +#include "test.h" + +#ifdef G_OS_WIN32 +#include +#define close _close +#endif + +static RESULT +test_file_get_contents (void) +{ + GError *gerror; + gchar *content; + gboolean ret; + gsize length; +#ifdef G_OS_WIN32 + const gchar *filename = "c:\\Windows\\system.ini"; +#else + const gchar *filename = "/etc/hosts"; +#endif + + /* + filename != NULL + ret = g_file_get_contents (NULL, NULL, NULL, NULL); + contents != NULL + ret = g_file_get_contents ("", NULL, NULL, NULL); + error no such file and fails for 'error' not being null too + ret = g_file_get_contents ("", &content, NULL, &gerror); + */ + + gerror = NULL; + ret = g_file_get_contents ("", &content, NULL, &gerror); + if (ret) + return FAILED ("HAH!"); + if (gerror == NULL) + return FAILED ("Got nothing as error."); + if (content != NULL) + return FAILED ("Content is uninitialized"); + + g_error_free (gerror); + gerror = NULL; + ret = g_file_get_contents (filename, &content, &length, &gerror); + if (!ret) + return FAILED ("The error is %d %s\n", gerror->code, gerror->message); + if (gerror != NULL) + return FAILED ("Got an error returning TRUE"); + if (content == NULL) + return FAILED ("Content is NULL"); + if (strlen (content) != length) + return FAILED ("length is %d but the string is %d", length, strlen (content)); + g_free (content); + + return OK; +} + +static RESULT +test_open_tmp (void) +{ + GError *gerror; + gint fd; + gchar *name = GINT_TO_POINTER (-1); + + /* + * Okay, this works, but creates a .xxx file in /tmp on every run. Disabled. + * fd = g_file_open_tmp (NULL, NULL, NULL); + * if (fd < 0) + * return FAILED ("Default failed."); + * close (fd); + */ + gerror = NULL; + fd = g_file_open_tmp ("invalidtemplate", NULL, &gerror); + if (fd != -1) + return FAILED ("The template was invalid and accepted"); + if (gerror == NULL) + return FAILED ("No error returned."); + g_error_free (gerror); + + gerror = NULL; + fd = g_file_open_tmp ("i/nvalidtemplate", &name, &gerror); + if (fd != -1) + return FAILED ("The template was invalid and accepted"); + if (gerror == NULL) + return FAILED ("No error returned."); + if (name == NULL) + return FAILED ("'name' is not reset"); + g_error_free (gerror); + + gerror = NULL; + fd = g_file_open_tmp ("valid-XXXXXX", &name, &gerror); + if (fd == -1) + return FAILED ("This should be valid"); + if (gerror != NULL) + return FAILED ("No error returned."); + if (name == NULL) + return FAILED ("No name returned."); + close (fd); + unlink (name); + g_free (name); + return OK; +} + +static RESULT +test_file (void) +{ + gboolean res; + const gchar *tmp; + gchar *path; + +#ifndef G_OS_WIN32 /* FIXME */ + gchar *sympath; + gint ignored G_GNUC_UNUSED; +#endif + + res = g_file_test (NULL, 0); + if (res) + return FAILED ("Should return FALSE HERE"); + + res = g_file_test ("file.c", 0); + if (res) + return FAILED ("Should return FALSE HERE"); + + tmp = g_get_tmp_dir (); + res = g_file_test (tmp, G_FILE_TEST_EXISTS); + if (!res) + return FAILED ("tmp does not exist."); + res = g_file_test (tmp, G_FILE_TEST_IS_REGULAR); + if (res) + return FAILED ("tmp is regular"); + + res = g_file_test (tmp, G_FILE_TEST_IS_DIR); + if (!res) + return FAILED ("tmp is not a directory"); + res = g_file_test (tmp, G_FILE_TEST_IS_EXECUTABLE); + if (!res) + return FAILED ("tmp is not a executable"); + + res = g_file_test (tmp, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_SYMLINK); + if (!res) + return FAILED ("2 tmp does not exist."); + res = g_file_test (tmp, G_FILE_TEST_IS_REGULAR | G_FILE_TEST_IS_SYMLINK); + if (res) + return FAILED ("2 tmp is regular"); + + res = g_file_test (tmp, G_FILE_TEST_IS_DIR | G_FILE_TEST_IS_SYMLINK); + if (!res) + return FAILED ("2 tmp is not a directory"); + res = g_file_test (tmp, G_FILE_TEST_IS_EXECUTABLE | G_FILE_TEST_IS_SYMLINK); + if (!res) + return FAILED ("2 tmp is not a executable"); + + close (g_file_open_tmp (NULL, &path, NULL)); /* create an empty file */ + res = g_file_test (path, G_FILE_TEST_EXISTS); + if (!res) + return FAILED ("3 %s should exist", path); + res = g_file_test (path, G_FILE_TEST_IS_REGULAR); + /* This is strange. Empty file is reported as not existing! */ + if (!res) + return FAILED ("3 %s IS_REGULAR", path); + res = g_file_test (path, G_FILE_TEST_IS_DIR); + if (res) + return FAILED ("3 %s should not be a directory", path); + res = g_file_test (path, G_FILE_TEST_IS_EXECUTABLE); + if (res) + return FAILED ("3 %s should not be executable", path); + res = g_file_test (path, G_FILE_TEST_IS_SYMLINK); + if (res) + return FAILED ("3 %s should not be a symlink", path); + +#ifndef G_OS_WIN32 /* FIXME */ + sympath = g_strconcat (path, "-link", NULL); + ignored = symlink (path, sympath); + res = g_file_test (sympath, G_FILE_TEST_EXISTS); + if (!res) + return FAILED ("4 %s should not exist", sympath); + res = g_file_test (sympath, G_FILE_TEST_IS_REGULAR); + if (!res) + return FAILED ("4 %s should not be a regular file", sympath); + res = g_file_test (sympath, G_FILE_TEST_IS_DIR); + if (res) + return FAILED ("4 %s should not be a directory", sympath); + res = g_file_test (sympath, G_FILE_TEST_IS_EXECUTABLE); + if (res) + return FAILED ("4 %s should not be executable", sympath); + res = g_file_test (sympath, G_FILE_TEST_IS_SYMLINK); + if (!res) + return FAILED ("4 %s should be a symlink", sympath); + + unlink (path); + + res = g_file_test (sympath, G_FILE_TEST_EXISTS); + if (res) + return FAILED ("5 %s should exist", sympath); + res = g_file_test (sympath, G_FILE_TEST_IS_REGULAR); + if (res) + return FAILED ("5 %s should be a regular file", sympath); + res = g_file_test (sympath, G_FILE_TEST_IS_DIR); + if (res) + return FAILED ("5 %s should not be a directory", sympath); + res = g_file_test (sympath, G_FILE_TEST_IS_EXECUTABLE); + if (res) + return FAILED ("5 %s should not be executable", sympath); + res = g_file_test (sympath, G_FILE_TEST_IS_SYMLINK); + if (!res) + return FAILED ("5 %s should be a symlink", sympath); + unlink (sympath); + g_free (sympath); +#endif + g_free (path); + return OK; +} + +static Test file_tests [] = { + {"g_file_get_contents", test_file_get_contents}, + {"g_file_open_tmp", test_open_tmp}, + {"g_file_test", test_file}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(file_tests_init, file_tests) diff --git a/mono/eglib/test/hashtable.c b/mono/eglib/test/hashtable.c new file mode 100644 index 0000000000..94878f3fa8 --- /dev/null +++ b/mono/eglib/test/hashtable.c @@ -0,0 +1,182 @@ +#include +#include +#include +#include "test.h" + +int foreach_count = 0; +int foreach_fail = 0; + +static void +foreach (gpointer key, gpointer value, gpointer user_data) +{ + foreach_count++; + if (GPOINTER_TO_INT (user_data) != 'a') + foreach_fail = 1; +} + +static RESULT +hash_t1 (void) +{ + GHashTable *t = g_hash_table_new (g_str_hash, g_str_equal); + + foreach_count = 0; + foreach_fail = 0; + g_hash_table_insert (t, (char*)"hello", (char*)"world"); + g_hash_table_insert (t, (char*)"my", (char*)"god"); + + g_hash_table_foreach (t, foreach, GINT_TO_POINTER('a')); + if (foreach_count != 2) + return FAILED ("did not find all keys, got %d expected 2", foreach_count); + if (foreach_fail) + return FAILED("failed to pass the user-data to foreach"); + + if (!g_hash_table_remove (t, (char*)"my")) + return FAILED ("did not find known key"); + if (g_hash_table_size (t) != 1) + return FAILED ("unexpected size"); + g_hash_table_insert(t, (char*)"hello", (char*)"moon"); + if (strcmp (g_hash_table_lookup (t, (char*)"hello"), (char*)"moon") != 0) + return FAILED ("did not replace world with moon"); + + if (!g_hash_table_remove (t, (char*)"hello")) + return FAILED ("did not find known key"); + if (g_hash_table_size (t) != 0) + return FAILED ("unexpected size"); + g_hash_table_destroy (t); + + return OK; +} + +static RESULT +hash_t2 (void) +{ + return OK; +} + +static RESULT +hash_default (void) +{ + GHashTable *hash = g_hash_table_new (NULL, NULL); + + if (hash == NULL) + return FAILED ("g_hash_table_new should return a valid hash"); + + g_hash_table_destroy (hash); + return NULL; +} + +static RESULT +hash_null_lookup (void) +{ + GHashTable *hash = g_hash_table_new (NULL, NULL); + gpointer ok, ov; + + g_hash_table_insert (hash, NULL, GINT_TO_POINTER (1)); + g_hash_table_insert (hash, GINT_TO_POINTER(1), GINT_TO_POINTER(2)); + + if (!g_hash_table_lookup_extended (hash, NULL, &ok, &ov)) + return FAILED ("Did not find the NULL"); + if (ok != NULL) + return FAILED ("Incorrect key found"); + if (ov != GINT_TO_POINTER (1)) + return FAILED ("Got wrong value %p\n", ov); + + if (!g_hash_table_lookup_extended (hash, GINT_TO_POINTER(1), &ok, &ov)) + return FAILED ("Did not find the 1"); + if (ok != GINT_TO_POINTER(1)) + return FAILED ("Incorrect key found"); + if (ov != GINT_TO_POINTER (2)) + return FAILED ("Got wrong value %p\n", ov); + + g_hash_table_destroy (hash); + + return NULL; +} + +static void +counter (gpointer key, gpointer value, gpointer user_data) +{ + int *counter = (int *) user_data; + + (*counter)++; +} + +static RESULT +hash_grow (void) +{ + GHashTable *hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); + int i, count = 0; + + for (i = 0; i < 1000; i++) + g_hash_table_insert (hash, g_strdup_printf ("%d", i), g_strdup_printf ("x-%d", i)); + + for (i = 0; i < 1000; i++){ + char buffer [30]; + gpointer value; + + sprintf (buffer, "%d", i); + + value = g_hash_table_lookup (hash, buffer); + sprintf (buffer, "x-%d", i); + if (strcmp (value, buffer) != 0){ + return FAILED ("Failed to lookup the key %d, the value was %s\n", i, value); + } + } + + if (g_hash_table_size (hash) != 1000) + return FAILED ("Did not find 1000 elements on the hash, found %d\n", g_hash_table_size (hash)); + + /* Now do the manual count, lets not trust the internals */ + g_hash_table_foreach (hash, counter, &count); + if (count != 1000){ + return FAILED ("Foreach count is not 1000"); + } + + g_hash_table_destroy (hash); + return NULL; +} + +static RESULT +hash_iter (void) +{ +#if !defined(GLIB_MAJOR_VERSION) || GLIB_CHECK_VERSION(2, 16, 0) + GHashTable *hash = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, NULL); + GHashTableIter iter; + int i, sum, keys_sum, values_sum; + gpointer key, value; + + sum = 0; + for (i = 0; i < 1000; i++) { + sum += i; + g_hash_table_insert (hash, GUINT_TO_POINTER (i), GUINT_TO_POINTER (i)); + } + + keys_sum = values_sum = 0; + g_hash_table_iter_init (&iter, hash); + while (g_hash_table_iter_next (&iter, &key, &value)) { + if (key != value) + return FAILED ("key != value"); + keys_sum += GPOINTER_TO_UINT (key); + values_sum += GPOINTER_TO_UINT (value); + } + if (keys_sum != sum || values_sum != sum) + return FAILED ("Did not find all key-value pairs"); + g_hash_table_destroy (hash); + return NULL; +#else + /* GHashTableIter was added in glib 2.16 */ + return NULL; +#endif +} + +static Test hashtable_tests [] = { + {"t1", hash_t1}, + {"t2", hash_t2}, + {"grow", hash_grow}, + {"default", hash_default}, + {"null_lookup", hash_null_lookup}, + {"iter", hash_iter}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(hashtable_tests_init, hashtable_tests) diff --git a/mono/eglib/test/list.c b/mono/eglib/test/list.c new file mode 100644 index 0000000000..b428e2d8dd --- /dev/null +++ b/mono/eglib/test/list.c @@ -0,0 +1,437 @@ +#include +#include +#include +#include "test.h" + +static RESULT +test_list_length (void) +{ + GList *list = g_list_prepend (NULL, (char*)"foo"); + + if (g_list_length (list) != 1) + return FAILED ("length failed. #1"); + + list = g_list_prepend (list, (char*)"bar"); + if (g_list_length (list) != 2) + return FAILED ("length failed. #2"); + + list = g_list_append (list, (char*)"bar"); + if (g_list_length (list) != 3) + return FAILED ("length failed. #3"); + + g_list_free (list); + return NULL; +} + +static RESULT +test_list_nth (void) +{ + char *foo = (char*)"foo"; + char *bar = (char*)"bar"; + char *baz = (char*)"baz"; + GList *nth, *list; + list = g_list_prepend (NULL, baz); + list = g_list_prepend (list, bar); + list = g_list_prepend (list, foo); + + nth = g_list_nth (list, 0); + if (nth->data != foo) + return FAILED ("nth failed. #0"); + + nth = g_list_nth (list, 1); + if (nth->data != bar) + return FAILED ("nth failed. #1"); + + nth = g_list_nth (list, 2); + if (nth->data != baz) + return FAILED ("nth failed. #2"); + + nth = g_list_nth (list, 3); + if (nth) + return FAILED ("nth failed. #3: %s", nth->data); + + g_list_free (list); + return OK; +} + +static RESULT +test_list_index (void) +{ + int i; + char *foo = (char*)"foo"; + char *bar = (char*)"bar"; + char *baz = (char*)"baz"; + GList *list; + list = g_list_prepend (NULL, baz); + list = g_list_prepend (list, bar); + list = g_list_prepend (list, foo); + + i = g_list_index (list, foo); + if (i != 0) + return FAILED ("index failed. #0: %d", i); + + i = g_list_index (list, bar); + if (i != 1) + return FAILED ("index failed. #1: %d", i); + + i = g_list_index (list, baz); + if (i != 2) + return FAILED ("index failed. #2: %d", i); + + g_list_free (list); + return OK; +} + +static RESULT +test_list_append (void) +{ + GList *list = g_list_prepend (NULL, (char*)"first"); + if (g_list_length (list) != 1) + return FAILED ("Prepend failed"); + + list = g_list_append (list, (char*)"second"); + + if (g_list_length (list) != 2) + return FAILED ("Append failed"); + + g_list_free (list); + return OK; +} + +static RESULT +test_list_last (void) +{ + GList *foo = g_list_prepend (NULL, (char*)"foo"); + GList *bar = g_list_prepend (NULL, (char*)"bar"); + GList *last; + + foo = g_list_concat (foo, bar); + last = g_list_last (foo); + + if (last != bar) + return FAILED ("last failed. #1"); + + foo = g_list_concat (foo, g_list_prepend (NULL, (char*)"baz")); + foo = g_list_concat (foo, g_list_prepend (NULL, (char*)"quux")); + + last = g_list_last (foo); + if (strcmp ("quux", last->data)) + return FAILED ("last failed. #2"); + + g_list_free (foo); + + return OK; +} + +static RESULT +test_list_concat (void) +{ + GList *foo = g_list_prepend (NULL, (char*)"foo"); + GList *bar = g_list_prepend (NULL, (char*)"bar"); + GList *list = g_list_concat (foo, bar); + + if (g_list_length (list) != 2) + return FAILED ("Concat failed. #1"); + + if (strcmp (list->data, "foo")) + return FAILED ("Concat failed. #2"); + + if (strcmp (list->next->data, "bar")) + return FAILED ("Concat failed. #3"); + + if (g_list_first (list) != foo) + return FAILED ("Concat failed. #4"); + + if (g_list_last (list) != bar) + return FAILED ("Concat failed. #5"); + + g_list_free (list); + + return OK; +} + +static gint +compare (gconstpointer a, gconstpointer b) +{ + char *foo = (char *) a; + char *bar = (char *) b; + + if (strlen (foo) < strlen (bar)) + return -1; + + return 1; +} + +static RESULT +test_list_insert_sorted (void) +{ + GList *list = g_list_prepend (NULL, (char*)"a"); + list = g_list_append (list, (char*)"aaa"); + + /* insert at the middle */ + list = g_list_insert_sorted (list, (char*)"aa", compare); + if (strcmp ("aa", list->next->data)) + return FAILED ("insert_sorted failed. #1"); + + /* insert at the beginning */ + list = g_list_insert_sorted (list, (char*)"", compare); + if (strcmp ("", list->data)) + return FAILED ("insert_sorted failed. #2"); + + /* insert at the end */ + list = g_list_insert_sorted (list, (char*)"aaaa", compare); + if (strcmp ("aaaa", g_list_last (list)->data)) + return FAILED ("insert_sorted failed. #3"); + + g_list_free (list); + return OK; +} + +static RESULT +test_list_copy (void) +{ + int i, length; + GList *list, *copy; + list = g_list_prepend (NULL, (char*)"a"); + list = g_list_append (list, (char*)"aa"); + list = g_list_append (list, (char*)"aaa"); + list = g_list_append (list, (char*)"aaaa"); + + length = g_list_length (list); + copy = g_list_copy (list); + + for (i = 0; i < length; i++) + if (strcmp (g_list_nth (list, i)->data, + g_list_nth (copy, i)->data)) + return FAILED ("copy failed."); + + g_list_free (list); + g_list_free (copy); + return OK; +} + +static RESULT +test_list_reverse (void) +{ + guint i, length; + GList *list, *reverse; + list = g_list_prepend (NULL, (char*)"a"); + list = g_list_append (list, (char*)"aa"); + list = g_list_append (list, (char*)"aaa"); + list = g_list_append (list, (char*)"aaaa"); + + length = g_list_length (list); + reverse = g_list_reverse (g_list_copy (list)); + + if (g_list_length (reverse) != length) + return FAILED ("reverse failed #1"); + + for (i = 0; i < length; i++){ + guint j = length - i - 1; + if (strcmp (g_list_nth (list, i)->data, + g_list_nth (reverse, j)->data)) + return FAILED ("reverse failed. #2"); + } + + g_list_free (list); + g_list_free (reverse); + return OK; +} + +static RESULT +test_list_remove (void) +{ + GList *list = g_list_prepend (NULL, (char*)"three"); + char *one = (char*)"one"; + list = g_list_prepend (list, (char*)"two"); + list = g_list_prepend (list, one); + + list = g_list_remove (list, one); + + if (g_list_length (list) != 2) + return FAILED ("Remove failed"); + + if (strcmp ("two", list->data) != 0) + return FAILED ("Remove failed"); + + g_list_free (list); + return OK; +} + +static RESULT +test_list_remove_link (void) +{ + GList *foo = g_list_prepend (NULL, (char*)"a"); + GList *bar = g_list_prepend (NULL, (char*)"b"); + GList *baz = g_list_prepend (NULL, (char*)"c"); + GList *list = foo; + + foo = g_list_concat (foo, bar); + foo = g_list_concat (foo, baz); + + list = g_list_remove_link (list, bar); + + if (g_list_length (list) != 2) + return FAILED ("remove_link failed #1"); + + if (bar->next != NULL) + return FAILED ("remove_link failed #2"); + + g_list_free (list); + g_list_free (bar); + return OK; +} + +static RESULT +test_list_insert_before (void) +{ + GList *foo, *bar, *baz; + + foo = g_list_prepend (NULL, (char*)"foo"); + foo = g_list_insert_before (foo, NULL, (char*)"bar"); + bar = g_list_last (foo); + + if (strcmp (bar->data, (char*)"bar")) + return FAILED ("1"); + + baz = g_list_insert_before (foo, bar, (char*)"baz"); + if (foo != baz) + return FAILED ("2"); + + if (strcmp (g_list_nth_data (foo, 1), (char*)"baz")) + return FAILED ("3: %s", g_list_nth_data (foo, 1)); + + g_list_free (foo); + return OK; +} + +#define N_ELEMS 101 + +static int intcompare (gconstpointer p1, gconstpointer p2) +{ + return GPOINTER_TO_INT (p1) - GPOINTER_TO_INT (p2); +} + +static gboolean verify_sort (GList *list, int len) +{ + int prev; + + if (list->prev) + return FALSE; + + prev = GPOINTER_TO_INT (list->data); + len--; + for (list = list->next; list; list = list->next) { + int curr = GPOINTER_TO_INT (list->data); + if (prev > curr) + return FALSE; + prev = curr; + + if (!list->prev || list->prev->next != list) + return FALSE; + + if (len == 0) + return FALSE; + len--; + } + return len == 0; +} + +static RESULT +test_list_sort (void) +{ + int i, j, mul; + GList *list = NULL; + + for (i = 0; i < N_ELEMS; ++i) + list = g_list_prepend (list, GINT_TO_POINTER (i)); + list = g_list_sort (list, intcompare); + if (!verify_sort (list, N_ELEMS)) + return FAILED ("decreasing list"); + + g_list_free (list); + + list = NULL; + for (i = 0; i < N_ELEMS; ++i) + list = g_list_prepend (list, GINT_TO_POINTER (-i)); + list = g_list_sort (list, intcompare); + if (!verify_sort (list, N_ELEMS)) + return FAILED ("increasing list"); + + g_list_free (list); + + list = g_list_prepend (NULL, GINT_TO_POINTER (0)); + for (i = 1; i < N_ELEMS; ++i) { + list = g_list_prepend (list, GINT_TO_POINTER (i)); + list = g_list_prepend (list, GINT_TO_POINTER (-i)); + } + list = g_list_sort (list, intcompare); + if (!verify_sort (list, 2*N_ELEMS-1)) + return FAILED ("alternating list"); + + g_list_free (list); + + list = NULL; + mul = 1; + for (i = 1; i < N_ELEMS; ++i) { + mul = -mul; + for (j = 0; j < i; ++j) + list = g_list_prepend (list, GINT_TO_POINTER (mul * j)); + } + list = g_list_sort (list, intcompare); + if (!verify_sort (list, (N_ELEMS*N_ELEMS - N_ELEMS)/2)) + return FAILED ("wavering list"); + + g_list_free (list); + + return OK; +} + +static gint +find_custom (gconstpointer a, gconstpointer b) +{ + return(strcmp (a, b)); +} + +static RESULT +test_list_find_custom (void) +{ + GList *list = NULL, *found; + char *foo = (char*)"foo"; + char *bar = (char*)"bar"; + char *baz = (char*)"baz"; + + list = g_list_prepend (list, baz); + list = g_list_prepend (list, bar); + list = g_list_prepend (list, foo); + + found = g_list_find_custom (list, baz, find_custom); + + if (found == NULL) + return FAILED ("Find failed"); + + g_list_free (list); + + return OK; +} + +static Test list_tests [] = { + { "length", test_list_length}, + { "nth", test_list_nth}, + { "index", test_list_index}, + { "last", test_list_last}, + { "append", test_list_append}, + { "concat", test_list_concat}, + {"insert_sorted", test_list_insert_sorted}, + {"insert_before", test_list_insert_before}, + { "copy", test_list_copy}, + { "reverse", test_list_reverse}, + { "remove", test_list_remove}, + { "remove_link", test_list_remove_link}, + { "remove_link", test_list_remove_link}, + { "sort", test_list_sort}, + { "find_custom", test_list_find_custom}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(list_tests_init, list_tests) diff --git a/mono/eglib/test/markup.c b/mono/eglib/test/markup.c new file mode 100644 index 0000000000..b7700615a7 --- /dev/null +++ b/mono/eglib/test/markup.c @@ -0,0 +1,233 @@ +#include +#include +#include +#include "test.h" + +#define do_bad_test(s) do { char *r = markup_test (s); if (r == NULL) return FAILED ("Failed on test " # s); else g_free (r); } while (0) +#define do_ok_test(s) do { char *r = markup_test (s); if (r != NULL) return FAILED ("Could not parse valid " # s); } while (0) + +static char * +markup_test (const char *s) +{ + GMarkupParser *parser = g_new0 (GMarkupParser, 1); + GMarkupParseContext *context; + GError *gerror = NULL; + + context = g_markup_parse_context_new (parser, 0, 0, 0); + + g_markup_parse_context_parse (context, s, strlen (s), &gerror); + g_markup_parse_context_free (context); + + if (gerror != NULL){ + char *msg = g_strdup (gerror->message); + g_error_free (gerror); + + g_free (parser); + return msg; + } + g_free (parser); + return NULL; +} + +static RESULT +invalid_documents (void) +{ + /* These should fail */ + do_bad_test ("<1>"); + do_bad_test (""); + do_bad_test (""); + do_bad_test (""); + do_bad_test (""); + + return OK; +} + +static RESULT +valid_documents (void) +{ + /* These should fail */ + do_ok_test (""); + do_ok_test (""); + + return OK; +} + +/* + * This is a test for the kind of files that the code in mono/domain.c + * parses; This code comes from Mono + */ +typedef struct { + GSList *supported_runtimes; + char *required_runtime; + int configuration_count; + int startup_count; +} AppConfigInfo; + +static char * +get_attribute_value (const gchar **attribute_names, + const gchar **attribute_values, + const char *att_name) +{ + int n; + for (n=0; attribute_names[n] != NULL; n++) { + if (strcmp (attribute_names[n], att_name) == 0) + return g_strdup (attribute_values[n]); + } + return NULL; +} + +static void +start_element (GMarkupParseContext *context, + const gchar *element_name, + const gchar **attribute_names, + const gchar **attribute_values, + gpointer user_data, + GError **gerror) +{ + AppConfigInfo* app_config = (AppConfigInfo*) user_data; + + if (strcmp (element_name, "configuration") == 0) { + app_config->configuration_count++; + return; + } + if (strcmp (element_name, "startup") == 0) { + app_config->startup_count++; + return; + } + + if (app_config->configuration_count != 1 || app_config->startup_count != 1) + return; + + if (strcmp (element_name, "requiredRuntime") == 0) { + app_config->required_runtime = get_attribute_value (attribute_names, attribute_values, "version"); + } else if (strcmp (element_name, "supportedRuntime") == 0) { + char *version = get_attribute_value (attribute_names, attribute_values, "version"); + app_config->supported_runtimes = g_slist_append (app_config->supported_runtimes, version); + } +} + +static void +end_element (GMarkupParseContext *context, + const gchar *element_name, + gpointer user_data, + GError **gerror) +{ + AppConfigInfo* app_config = (AppConfigInfo*) user_data; + + if (strcmp (element_name, "configuration") == 0) { + app_config->configuration_count--; + } else if (strcmp (element_name, "startup") == 0) { + app_config->startup_count--; + } +} + +static const GMarkupParser +mono_parser = { + start_element, + end_element, + NULL, + NULL, + NULL +}; + +static AppConfigInfo * +domain_test (const char *text) +{ + AppConfigInfo *app_config = g_new0 (AppConfigInfo, 1); + GMarkupParseContext *context; + + context = g_markup_parse_context_new (&mono_parser, 0, app_config, NULL); + if (g_markup_parse_context_parse (context, text, strlen (text), NULL)) { + g_markup_parse_context_end_parse (context, NULL); + } + g_markup_parse_context_free (context); + + return app_config; +} + +static void +domain_free (AppConfigInfo *info) +{ + GSList *l; + if (info->required_runtime) + g_free (info->required_runtime); + for (l = info->supported_runtimes; l != NULL; l = l->next){ + g_free (l->data); + } + g_slist_free (info->supported_runtimes); + g_free (info); +} + +static RESULT +mono_domain (void) +{ + AppConfigInfo *info; + + info = domain_test (""); + if (info->required_runtime == NULL) + return FAILED ("No required runtime section"); + if (strcmp (info->required_runtime, "v1") != 0) + return FAILED ("Got a runtime version %s, expected v1", info->required_runtime); + domain_free (info); + + info = domain_test (""); + if (info->required_runtime == NULL) + return FAILED ("No required runtime section on auto-close section"); + if (strcmp (info->required_runtime, "v1") != 0) + return FAILED ("Got a runtime version %s, expected v1", info->required_runtime); + domain_free (info); + + info = domain_test (""); + if ((strcmp ((char*)info->supported_runtimes->data, "v1") == 0)){ + if (info->supported_runtimes->next == NULL) + return FAILED ("Expected 2 supported runtimes"); + + if ((strcmp ((char*)info->supported_runtimes->next->data, "v2") != 0)) + return FAILED ("Expected v1, v2, got %s", info->supported_runtimes->next->data); + if (info->supported_runtimes->next->next != NULL) + return FAILED ("Expected v1, v2, got more"); + } else + return FAILED ("Expected `v1', got %s", info->supported_runtimes->data); + domain_free (info); + + return NULL; +} + +static RESULT +mcs_config (void) +{ + return markup_test ("\r\n \r\n \r\n \r\n "); + +} + +static RESULT +xml_parse (void) +{ + return markup_test (""); +} + +static RESULT +machine_config (void) +{ + char *data; + gsize size; + + if (g_file_get_contents ("../../data/net_1_1/machine.config", &data, &size, NULL)){ + return markup_test (data); + } + printf ("Ignoring this test\n"); + return NULL; +} + +static Test markup_tests [] = { + {"invalid_documents", invalid_documents}, + {"good_documents", valid_documents}, + {"mono_domain", mono_domain}, + {"mcs_config", mcs_config}, + {"xml_parse", xml_parse}, + {"machine_config", machine_config}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(markup_tests_init, markup_tests) diff --git a/mono/eglib/test/memory.c b/mono/eglib/test/memory.c new file mode 100644 index 0000000000..3fed8ced19 --- /dev/null +++ b/mono/eglib/test/memory.c @@ -0,0 +1,38 @@ + +#include +#include "test.h" + +static RESULT +test_memory_zero_size_allocations (void) +{ + gpointer p; + + p = g_malloc (0); + if (p) + return FAILED ("Calling g_malloc with size zero should return NULL."); + + p = g_malloc0 (0); + if (p) + return FAILED ("Calling g_malloc0 with size zero should return NULL."); + + p = g_realloc (NULL, 0); + if (p) + return FAILED ("Calling g_realloc with size zero should return NULL."); + + p = g_new (int, 0); + if (p) + return FAILED ("Calling g_new with size zero should return NULL."); + + p = g_new0 (int, 0); + if (p) + return FAILED ("Calling g_new0 with size zero should return NULL."); + + return OK; +} + +static Test memory_tests [] = { + { "zero_size_allocations", test_memory_zero_size_allocations}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(memory_tests_init, memory_tests) diff --git a/mono/eglib/test/module.c b/mono/eglib/test/module.c new file mode 100644 index 0000000000..75000c55ee --- /dev/null +++ b/mono/eglib/test/module.c @@ -0,0 +1,65 @@ +#include +#include +#include +#include +#include +#ifdef HAVE_UNISTD_H +#include +#endif +#include "test.h" + +#if defined (G_OS_WIN32) +#define EXTERNAL_SYMBOL "GetProcAddress" +#else +#define EXTERNAL_SYMBOL "system" +#endif + +void G_MODULE_EXPORT +dummy_test_export (void); + +void G_MODULE_EXPORT +dummy_test_export (void) +{ +} + +/* test for g_module_open (NULL, ...) */ +static RESULT +test_module_symbol_null (void) +{ + gpointer proc = GINT_TO_POINTER (42); + + GModule *m = g_module_open (NULL, G_MODULE_BIND_LAZY); + + if (m == NULL) + return FAILED ("bind to main module failed. #0"); + + if (g_module_symbol (m, "__unlikely_\nexistent__", &proc)) + return FAILED ("non-existent symbol lookup failed. #1"); + + if (proc) + return FAILED ("non-existent symbol lookup failed. #2"); + + if (!g_module_symbol (m, EXTERNAL_SYMBOL, &proc)) + return FAILED ("external lookup failed. #3"); + + if (!proc) + return FAILED ("external lookup failed. #4"); + + if (!g_module_symbol (m, "dummy_test_export", &proc)) + return FAILED ("in-proc lookup failed. #5"); + + if (!proc) + return FAILED ("in-proc lookup failed. #6"); + + if (!g_module_close (m)) + return FAILED ("close failed. #7"); + + return OK; +} + +static Test module_tests [] = { + {"g_module_symbol_null", test_module_symbol_null}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(module_tests_init, module_tests) diff --git a/mono/eglib/test/path.c b/mono/eglib/test/path.c new file mode 100644 index 0000000000..20d4626863 --- /dev/null +++ b/mono/eglib/test/path.c @@ -0,0 +1,355 @@ +#include +#include +#include +#include +#ifdef HAVE_UNISTD_H +#include +#endif +#ifdef G_OS_UNIX +#include +#endif +#include "test.h" + +#ifdef G_OS_WIN32 +#include +#define chdir _chdir +#endif + +/* This test is just to be used with valgrind */ +static RESULT +test_buildpath (void) +{ + char *s; + const char *buffer = "var/private"; + const char *dir = "/"; + + s = g_build_path ("/", "hola///", "//mundo", NULL); + if (strcmp (s, "hola/mundo") != 0) + return FAILED ("1 Got wrong result, got: %s", s); + g_free (s); + + s = g_build_path ("/", "hola/", "/mundo", NULL); + if (strcmp (s, "hola/mundo") != 0) + return FAILED ("2 Got wrong result, got: %s", s); + g_free (s); + + s = g_build_path ("/", "hola/", "mundo", NULL); + if (strcmp (s, "hola/mundo") != 0) + return FAILED ("3 Got wrong result, got: %s", s); + g_free (s); + + s = g_build_path ("/", "hola", "/mundo", NULL); + if (strcmp (s, "hola/mundo") != 0) + return FAILED ("4 Got wrong result, got: %s", s); + g_free (s); + + s = g_build_path ("/", "/hello", "world/", NULL); + if (strcmp (s, "/hello/world/") != 0) + return FAILED ("5 Got wrong result, got: %s", s); + g_free (s); + + /* Now test multi-char-separators */ + s = g_build_path ("**", "hello", "world", NULL); + if (strcmp (s, "hello**world") != 0) + return FAILED ("6 Got wrong result, got: %s", s); + g_free (s); + + s = g_build_path ("**", "hello**", "world", NULL); + if (strcmp (s, "hello**world") != 0) + return FAILED ("7 Got wrong result, got: %s", s); + g_free (s); + + s = g_build_path ("**", "hello**", "**world", NULL); + if (strcmp (s, "hello**world") != 0) + return FAILED ("8 Got wrong result, got: %s", s); + g_free (s); + + s = g_build_path ("**", "hello**", "**world", NULL); + if (strcmp (s, "hello**world") != 0) + return FAILED ("9 Got wrong result, got: %s", s); + g_free (s); + + s = g_build_path ("1234567890", "hello", "world", NULL); + if (strcmp (s, "hello1234567890world") != 0) + return FAILED ("10 Got wrong result, got: %s", s); + g_free (s); + + s = g_build_path ("1234567890", "hello1234567890", "1234567890world", NULL); + if (strcmp (s, "hello1234567890world") != 0) + return FAILED ("11 Got wrong result, got: %s", s); + g_free (s); + + s = g_build_path ("1234567890", "hello12345678901234567890", "1234567890world", NULL); + if (strcmp (s, "hello1234567890world") != 0) + return FAILED ("12 Got wrong result, got: %s", s); + g_free (s); + + /* Multiple */ + s = g_build_path ("/", "a", "b", "c", "d", NULL); + if (strcmp (s, "a/b/c/d") != 0) + return FAILED ("13 Got wrong result, got: %s", s); + g_free (s); + + s = g_build_path ("/", "/a", "", "/c/", NULL); + if (strcmp (s, "/a/c/") != 0) + return FAILED ("14 Got wrong result, got: %s", s); + g_free (s); + + /* Null */ + s = g_build_path ("/", NULL, NULL); + if (s == NULL) + return FAILED ("must get a non-NULL return"); + if (s [0] != 0) + return FAILED ("must get an empty string"); + + // This is to test the regression introduced by Levi for the Windows support + // that code errouneously read below the allowed area (in this case dir [-1]). + // and caused all kinds of random errors. + dir = "//"; + dir++; + s = g_build_filename (dir, buffer, NULL); + if (s [0] != '/') + return FAILED ("Must have a '/' at the start"); + + g_free (s); + return OK; +} + +static RESULT +test_buildfname (void) +{ + char *s; + + s = g_build_filename ("a", "b", "c", "d", NULL); +#ifdef G_OS_WIN32 + if (strcmp (s, "a\\b\\c\\d") != 0) +#else + if (strcmp (s, "a/b/c/d") != 0) +#endif + return FAILED ("1 Got wrong result, got: %s", s); + g_free (s); + +#ifdef G_OS_WIN32 + s = g_build_filename ("C:\\", "a", NULL); + if (strcmp (s, "C:\\a") != 0) +#else + s = g_build_filename ("/", "a", NULL); + if (strcmp (s, "/a") != 0) +#endif + return FAILED ("1 Got wrong result, got: %s", s); + +#ifndef G_OS_WIN32 + s = g_build_filename ("/", "foo", "/bar", "tolo/", "/meo/", NULL); + if (strcmp (s, "/foo/bar/tolo/meo/") != 0) + return FAILED ("1 Got wrong result, got: %s", s); +#endif + + return OK; +} + +static char * +test_dirname (void) +{ + char *s; + +#ifdef G_OS_WIN32 + s = g_path_get_dirname ("c:\\home\\miguel"); + if (strcmp (s, "c:\\home") != 0) + return FAILED ("Expected c:\\home, got %s", s); + g_free (s); + + s = g_path_get_dirname ("c:/home/miguel"); + if (strcmp (s, "c:/home") != 0) + return FAILED ("Expected c:/home, got %s", s); + g_free (s); + + s = g_path_get_dirname ("c:\\home\\dingus\\"); + if (strcmp (s, "c:\\home\\dingus") != 0) + return FAILED ("Expected c:\\home\\dingus, got %s", s); + g_free (s); + + s = g_path_get_dirname ("dir.c"); + if (strcmp (s, ".") != 0) + return FAILED ("Expected `.', got %s", s); + g_free (s); + + s = g_path_get_dirname ("c:\\index.html"); + if (strcmp (s, "c:") != 0) + return FAILED ("Expected [c:], got [%s]", s); +#else + s = g_path_get_dirname ("/home/miguel"); + if (strcmp (s, "/home") != 0) + return FAILED ("Expected /home, got %s", s); + g_free (s); + + s = g_path_get_dirname ("/home/dingus/"); + if (strcmp (s, "/home/dingus") != 0) + return FAILED ("Expected /home/dingus, got %s", s); + g_free (s); + + s = g_path_get_dirname ("dir.c"); + if (strcmp (s, ".") != 0) + return FAILED ("Expected `.', got %s", s); + g_free (s); + + s = g_path_get_dirname ("/index.html"); + if (strcmp (s, "/") != 0) + return FAILED ("Expected [/], got [%s]", s); +#endif + return OK; +} + +static char * +test_basename (void) +{ + char *s; + +#ifdef G_OS_WIN32 + s = g_path_get_basename (""); + if (strcmp (s, ".") != 0) + return FAILED ("Expected `.', got %s", s); + g_free (s); + + s = g_path_get_basename ("c:\\home\\dingus\\"); + if (strcmp (s, "dingus") != 0) + return FAILED ("1 Expected dingus, got %s", s); + g_free (s); + + s = g_path_get_basename ("c:/home/dingus/"); + if (strcmp (s, "dingus") != 0) + return FAILED ("1 Expected dingus, got %s", s); + g_free (s); + + s = g_path_get_basename ("c:\\home\\dingus"); + if (strcmp (s, "dingus") != 0) + return FAILED ("2 Expected dingus, got %s", s); + g_free (s); + + s = g_path_get_basename ("c:/home/dingus"); + if (strcmp (s, "dingus") != 0) + return FAILED ("2 Expected dingus, got %s", s); + g_free (s); +#else + s = g_path_get_basename (""); + if (strcmp (s, ".") != 0) + return FAILED ("Expected `.', got %s", s); + g_free (s); + + s = g_path_get_basename ("/home/dingus/"); + if (strcmp (s, "dingus") != 0) + return FAILED ("1 Expected dingus, got %s", s); + g_free (s); + + s = g_path_get_basename ("/home/dingus"); + if (strcmp (s, "dingus") != 0) + return FAILED ("2 Expected dingus, got %s", s); + g_free (s); +#endif + return OK; +} + +static gchar * +test_ppath (void) +{ + char *s; +#ifdef G_OS_WIN32 + const gchar *searchfor = "explorer.exe"; +#else + const gchar *searchfor = "ls"; +#endif + s = g_find_program_in_path (searchfor); + if (s == NULL) + return FAILED ("No %s on this system?", searchfor); + g_free (s); + return OK; +} + +static gchar * +test_ppath2 (void) +{ + char *s; + const char *path = g_getenv ("PATH"); +#ifdef G_OS_WIN32 + const gchar *searchfor = "test_eglib.exe"; +#else + const gchar *searchfor = "test-eglib"; +#endif + + g_setenv ("PATH", "", TRUE); + s = g_find_program_in_path ("ls"); + if (s != NULL) { + g_setenv ("PATH", path, TRUE); + return FAILED ("Found something interesting here: %s", s); + } + g_free (s); + s = g_find_program_in_path (searchfor); + if (s == NULL) { + g_setenv ("PATH", path, TRUE); + return FAILED ("It should find '%s' in the current directory.", searchfor); + } + g_free (s); + g_setenv ("PATH", path, TRUE); + return OK; +} + +#ifndef DISABLE_FILESYSTEM_TESTS +static gchar * +test_cwd (void) +{ + char *dir = g_get_current_dir (); +#ifdef G_OS_WIN32 + const gchar *newdir = "C:\\Windows"; +#else + const gchar *newdir = "/bin"; +#endif + + if (dir == NULL) + return FAILED ("No current directory?"); + g_free (dir); + + if (chdir (newdir) == -1) + return FAILED ("No %s?", newdir); + + dir = g_get_current_dir (); + if (strcmp (dir, newdir) != 0) + return FAILED("Did not go to %s?", newdir); + g_free (dir); + + return OK; +} +#else +static gchar * +test_cwd (void) +{ + return OK; +} +#endif + +static gchar * +test_misc (void) +{ + const char *home = g_get_home_dir (); + const char *tmp = g_get_tmp_dir (); + + if (home == NULL) + return FAILED ("Where did my home go?"); + + if (tmp == NULL) + return FAILED ("Where did my /tmp go?"); + + return OK; +} + +static Test path_tests [] = { + {"g_build_filename", test_buildfname}, + {"g_buildpath", test_buildpath}, + {"g_path_get_dirname", test_dirname}, + {"g_path_get_basename", test_basename}, + {"g_find_program_in_path", test_ppath}, + {"g_find_program_in_path2", test_ppath2}, + {"test_cwd", test_cwd }, + {"test_misc", test_misc }, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(path_tests_init, path_tests) diff --git a/mono/eglib/test/pattern.c b/mono/eglib/test/pattern.c new file mode 100644 index 0000000000..d01e985b1c --- /dev/null +++ b/mono/eglib/test/pattern.c @@ -0,0 +1,59 @@ +#include +#include +#include +#include +#ifdef HAVE_UNISTD_H +#include +#endif +#include +#include "test.h" + +#define MATCH(pat,string,error_if,msg) \ + spec = g_pattern_spec_new (pat); \ + res = g_pattern_match_string (spec, string); \ + if (res == error_if) \ + return FAILED (msg " returned %s", res ? "TRUE" : "FALSE"); \ + g_pattern_spec_free (spec); + +#define TEST_MATCH(pat,string,n) MATCH (pat, string, FALSE, "MATCH " #n) +#define TEST_NO_MATCH(pat,string,n) MATCH (pat, string,TRUE, "NO_MATCH " #n) + +static RESULT +test_pattern_spec (void) +{ + GPatternSpec *spec; + gboolean res; + + /* spec = g_pattern_spec_new (NULL); */ + TEST_MATCH ("*", "hola", 1); + TEST_MATCH ("hola", "hola", 2); + TEST_MATCH ("????", "hola", 3); + TEST_MATCH ("???a", "hola", 4); + TEST_MATCH ("h??a", "hola", 5); + TEST_MATCH ("h??*", "hola", 6); + TEST_MATCH ("h*", "hola", 7); + TEST_MATCH ("*hola", "hola", 8); + TEST_MATCH ("*l*", "hola", 9); + TEST_MATCH ("h*??", "hola", 10); + TEST_MATCH ("h*???", "hola", 11); + TEST_MATCH ("?o??", "hola", 12); + TEST_MATCH ("*h*o*l*a*", "hola", 13); + TEST_MATCH ("h*o*l*a", "hola", 14); + TEST_MATCH ("h?*?", "hola", 15); + + TEST_NO_MATCH ("", "hola", 1); + TEST_NO_MATCH ("?????", "hola", 2); + TEST_NO_MATCH ("???", "hola", 3); + TEST_NO_MATCH ("*o", "hola", 4); + TEST_NO_MATCH ("h", "hola", 5); + TEST_NO_MATCH ("h*????", "hola", 6); + + return OK; +} + +static Test pattern_tests [] = { + {"g_pattern_spec*", test_pattern_spec}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(pattern_tests_init, pattern_tests) diff --git a/mono/eglib/test/ptrarray.c b/mono/eglib/test/ptrarray.c new file mode 100644 index 0000000000..51a1396f4c --- /dev/null +++ b/mono/eglib/test/ptrarray.c @@ -0,0 +1,360 @@ +#include +#include +#include "test.h" + +/* Redefine the private structure only to verify proper allocations */ +typedef struct _GPtrArrayPriv { + gpointer *pdata; + guint len; + guint size; +} GPtrArrayPriv; + +/* Don't add more than 32 items to this please */ +static const char *items [] = { + "Apples", "Oranges", "Plumbs", "Goats", "Snorps", "Grapes", + "Tickle", "Place", "Coffee", "Cookies", "Cake", "Cheese", + "Tseng", "Holiday", "Avenue", "Smashing", "Water", "Toilet", + NULL +}; + +static GPtrArray *ptrarray_alloc_and_fill(guint *item_count) +{ + GPtrArray *array = g_ptr_array_new(); + gint i; + + for(i = 0; items[i] != NULL; i++) { + g_ptr_array_add(array, (gpointer)items[i]); + } + + if (item_count != NULL) { + *item_count = i; + } + + return array; +} + +static guint guess_size(guint length) +{ + guint size = 1; + + while (size < length) { + size <<= 1; + } + + return size; +} + +static RESULT +ptrarray_alloc (void) +{ + GPtrArrayPriv *array; + guint i; + + array = (GPtrArrayPriv *)ptrarray_alloc_and_fill(&i); + + if (array->size != guess_size(array->len)) { + return FAILED("Size should be %d, but it is %d", + guess_size(array->len), array->size); + } + + if (array->len != i) { + return FAILED("Expected %d node(s) in the array", i); + } + + g_ptr_array_free((GPtrArray *)array, TRUE); + + return OK; +} + +static +RESULT ptrarray_for_iterate (void) +{ + GPtrArray *array = ptrarray_alloc_and_fill(NULL); + guint i; + + for (i = 0; i < array->len; i++) { + char *item = (char *)g_ptr_array_index(array, i); + if (item != items[i]) { + return FAILED( + "Expected item at %d to be %s, but it was %s", + i, items[i], item); + } + } + + g_ptr_array_free(array, TRUE); + + return OK; +} + +static gint foreach_iterate_index = 0; +static char *foreach_iterate_error = NULL; + +static void +foreach_callback (gpointer data, gpointer user_data) +{ + char *item = (char *)data; + const char *item_cmp = items[foreach_iterate_index++]; + + if (foreach_iterate_error != NULL) { + return; + } + + if (item != item_cmp) { + foreach_iterate_error = FAILED( + "Expected item at %d to be %s, but it was %s", + foreach_iterate_index - 1, item_cmp, item); + } +} + +static RESULT +ptrarray_foreach_iterate (void) +{ + GPtrArray *array = ptrarray_alloc_and_fill(NULL); + + foreach_iterate_index = 0; + foreach_iterate_error = NULL; + + g_ptr_array_foreach(array, foreach_callback, array); + + g_ptr_array_free(array, TRUE); + + return foreach_iterate_error; +} + +static RESULT +ptrarray_set_size (void) +{ + GPtrArray *array = g_ptr_array_new(); + guint i, grow_length = 50; + + g_ptr_array_add(array, (gpointer)items[0]); + g_ptr_array_add(array, (gpointer)items[1]); + g_ptr_array_set_size(array, grow_length); + + if (array->len != grow_length) { + return FAILED("Array length should be 50, it is %d", array->len); + } else if (array->pdata[0] != items[0]) { + return FAILED("Item 0 was overwritten, should be %s", items[0]); + } else if (array->pdata[1] != items[1]) { + return FAILED("Item 1 was overwritten, should be %s", items[1]); + } + + for (i = 2; i < array->len; i++) { + if (array->pdata[i] != NULL) { + return FAILED("Item %d is not NULL, it is %p", i, array->pdata[i]); + } + } + + g_ptr_array_free(array, TRUE); + + return OK; +} + +static RESULT +ptrarray_remove_index (void) +{ + GPtrArray *array; + guint i; + + array = ptrarray_alloc_and_fill(&i); + + g_ptr_array_remove_index(array, 0); + if (array->pdata[0] != items[1]) { + return FAILED("First item is not %s, it is %s", items[1], + array->pdata[0]); + } + + g_ptr_array_remove_index(array, array->len - 1); + + if (array->pdata[array->len - 1] != items[array->len]) { + return FAILED("Last item is not %s, it is %s", + items[array->len - 2], array->pdata[array->len - 1]); + } + + g_ptr_array_free(array, TRUE); + + return OK; +} + +static RESULT +ptrarray_remove_index_fast (void) +{ + GPtrArray *array; + guint i; + + array = ptrarray_alloc_and_fill(&i); + + g_ptr_array_remove_index_fast(array, 0); + if (array->pdata[0] != items[array->len]) { + return FAILED("First item is not %s, it is %s", items[array->len], + array->pdata[0]); + } + + g_ptr_array_remove_index_fast(array, array->len - 1); + if (array->pdata[array->len - 1] != items[array->len - 1]) { + return FAILED("Last item is not %s, it is %s", + items[array->len - 1], array->pdata[array->len - 1]); + } + + g_ptr_array_free(array, TRUE); + + return OK; +} + +static RESULT +ptrarray_remove (void) +{ + GPtrArray *array; + guint i; + + array = ptrarray_alloc_and_fill(&i); + + g_ptr_array_remove(array, (gpointer)items[7]); + + if (!g_ptr_array_remove(array, (gpointer)items[4])) { + return FAILED("Item %s not removed", items[4]); + } + + if (g_ptr_array_remove(array, (gpointer)items[4])) { + return FAILED("Item %s still in array after removal", items[4]); + } + + if (array->pdata[array->len - 1] != items[array->len + 1]) { + return FAILED("Last item in GPtrArray not correct"); + } + + g_ptr_array_free(array, TRUE); + + return OK; +} + +static gint +ptrarray_sort_compare (gconstpointer a, gconstpointer b) +{ + gchar *stra = *(gchar **) a; + gchar *strb = *(gchar **) b; + return strcmp(stra, strb); +} + +static RESULT +ptrarray_sort (void) +{ + GPtrArray *array = g_ptr_array_new(); + guint i; + static gchar * const letters [] = { (char*)"A", (char*)"B", (char*)"C", (char*)"D", (char*)"E" }; + + g_ptr_array_add(array, letters[0]); + g_ptr_array_add(array, letters[1]); + g_ptr_array_add(array, letters[2]); + g_ptr_array_add(array, letters[3]); + g_ptr_array_add(array, letters[4]); + + g_ptr_array_sort(array, ptrarray_sort_compare); + + for (i = 0; i < array->len; i++) { + if (array->pdata[i] != letters[i]) { + return FAILED("Array out of order, expected %s got %s at position %d", + letters [i], (gchar *) array->pdata [i], i); + } + } + + g_ptr_array_free(array, TRUE); + + return OK; +} + +static gint +ptrarray_sort_compare_with_data (gconstpointer a, gconstpointer b, gpointer user_data) +{ + gchar *stra = *(gchar **) a; + gchar *strb = *(gchar **) b; + + if (strcmp (user_data, "this is the data for qsort") != 0) + fprintf (stderr, "oops at compare with_data\n"); + + return strcmp(stra, strb); +} + +static RESULT +ptrarray_sort_with_data (void) +{ + GPtrArray *array = g_ptr_array_new(); + guint i; + static gchar * const letters [] = { (char*)"A", (char*)"B", (char*)"C", (char*)"D", (char*)"E" }; + + g_ptr_array_add(array, letters[4]); + g_ptr_array_add(array, letters[1]); + g_ptr_array_add(array, letters[2]); + g_ptr_array_add(array, letters[0]); + g_ptr_array_add(array, letters[3]); + + g_ptr_array_sort_with_data(array, ptrarray_sort_compare_with_data, (char*)"this is the data for qsort"); + + for (i = 0; i < array->len; i++) { + if (array->pdata[i] != letters[i]) { + return FAILED("Array out of order, expected %s got %s at position %d", + letters [i], (gchar *) array->pdata [i], i); + } + } + + g_ptr_array_free(array, TRUE); + + return OK; +} + +static RESULT +ptrarray_remove_fast (void) +{ + GPtrArray *array = g_ptr_array_new(); + static gchar * const letters [] = { (char*)"A", (char*)"B", (char*)"C", (char*)"D", (char*)"E" }; + + if (g_ptr_array_remove_fast (array, NULL)) + return FAILED ("Removing NULL succeeded"); + + g_ptr_array_add(array, letters[0]); + if (!g_ptr_array_remove_fast (array, letters[0]) || array->len != 0) + return FAILED ("Removing last element failed"); + + g_ptr_array_add(array, letters[0]); + g_ptr_array_add(array, letters[1]); + g_ptr_array_add(array, letters[2]); + g_ptr_array_add(array, letters[3]); + g_ptr_array_add(array, letters[4]); + + if (!g_ptr_array_remove_fast (array, letters[0]) || array->len != 4) + return FAILED ("Removing first element failed"); + + if (array->pdata [0] != letters [4]) + return FAILED ("First element wasn't replaced with last upon removal"); + + if (g_ptr_array_remove_fast (array, letters[0])) + return FAILED ("Succedeed removing a non-existing element"); + + if (!g_ptr_array_remove_fast (array, letters[3]) || array->len != 3) + return FAILED ("Failed removing \"D\""); + + if (!g_ptr_array_remove_fast (array, letters[1]) || array->len != 2) + return FAILED ("Failed removing \"B\""); + + if (array->pdata [0] != letters [4] || array->pdata [1] != letters [2]) + return FAILED ("Last two elements are wrong"); + g_ptr_array_free(array, TRUE); + + return OK; +} + +static Test ptrarray_tests [] = { + {"alloc", ptrarray_alloc}, + {"for_iterate", ptrarray_for_iterate}, + {"foreach_iterate", ptrarray_foreach_iterate}, + {"set_size", ptrarray_set_size}, + {"remove_index", ptrarray_remove_index}, + {"remove_index_fast", ptrarray_remove_index_fast}, + {"remove", ptrarray_remove}, + {"sort", ptrarray_sort}, + {"remove_fast", ptrarray_remove_fast}, + {"sort_with_data", ptrarray_sort_with_data}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(ptrarray_tests_init, ptrarray_tests) diff --git a/mono/eglib/test/queue.c b/mono/eglib/test/queue.c new file mode 100644 index 0000000000..200952199a --- /dev/null +++ b/mono/eglib/test/queue.c @@ -0,0 +1,183 @@ +#include +#include +#include +#include "test.h" + +static RESULT +test_queue_push (void) +{ + GQueue *queue = g_queue_new (); + + g_queue_push_head (queue, (char*)"foo"); + g_queue_push_head (queue, (char*)"bar"); + g_queue_push_head (queue, (char*)"baz"); + + if (queue->length != 3) + return FAILED ("push failed"); + + if (NULL != queue->head->prev) + return FAILED ("HEAD: prev is wrong"); + if (strcmp ("baz", queue->head->data)) + return FAILED ("HEAD: First element is wrong"); + if (strcmp ("bar", queue->head->next->data)) + return FAILED ("HEAD: Second element is wrong"); + if (strcmp ("foo", queue->head->next->next->data)) + return FAILED ("HEAD: Third element is wrong"); + if (NULL != queue->head->next->next->next) + return FAILED ("HEAD: End is wrong"); + + if (NULL != queue->tail->next) + return FAILED ("TAIL: next is wrong"); + if (strcmp ("foo", queue->tail->data)) + return FAILED ("TAIL: Third element is wrong"); + if (strcmp ("bar", queue->tail->prev->data)) + return FAILED ("TAIL: Second element is wrong"); + if (strcmp ("baz", queue->tail->prev->prev->data)) + return FAILED ("TAIL: First element is wrong"); + if (NULL != queue->tail->prev->prev->prev) + return FAILED ("TAIL: End is wrong"); + + g_queue_free (queue); + return OK; +} + +static RESULT +test_queue_push_tail (void) +{ + GQueue *queue = g_queue_new (); + + g_queue_push_tail (queue, (char*)"baz"); + g_queue_push_tail (queue, (char*)"bar"); + g_queue_push_tail (queue, (char*)"foo"); + + if (queue->length != 3) + return FAILED ("push failed"); + + if (NULL != queue->head->prev) + return FAILED ("HEAD: prev is wrong"); + if (strcmp ("baz", queue->head->data)) + return FAILED ("HEAD: First element is wrong"); + if (strcmp ("bar", queue->head->next->data)) + return FAILED ("HEAD: Second element is wrong"); + if (strcmp ("foo", queue->head->next->next->data)) + return FAILED ("HEAD: Third element is wrong"); + if (NULL != queue->head->next->next->next) + return FAILED ("HEAD: End is wrong"); + + if (NULL != queue->tail->next) + return FAILED ("TAIL: next is wrong"); + if (strcmp ("foo", queue->tail->data)) + return FAILED ("TAIL: Third element is wrong"); + if (strcmp ("bar", queue->tail->prev->data)) + return FAILED ("TAIL: Second element is wrong"); + if (strcmp ("baz", queue->tail->prev->prev->data)) + return FAILED ("TAIL: First element is wrong"); + if (NULL != queue->tail->prev->prev->prev) + return FAILED ("TAIL: End is wrong"); + + g_queue_free (queue); + return OK; +} + +static RESULT +test_queue_pop (void) +{ + GQueue *queue = g_queue_new (); + gpointer data; + + g_queue_push_head (queue, (char*)"foo"); + g_queue_push_head (queue, (char*)"bar"); + g_queue_push_head (queue, (char*)"baz"); + + data = g_queue_pop_head (queue); + if (strcmp ("baz", data)) + return FAILED ("expect baz."); + + data = g_queue_pop_head (queue); + if (strcmp ("bar", data)) + return FAILED ("expect bar."); + + data = g_queue_pop_head (queue); + if (strcmp ("foo", data)) + return FAILED ("expect foo."); + + if (g_queue_is_empty (queue) == FALSE) + return FAILED ("expect is_empty."); + + if (queue->length != 0) + return FAILED ("expect 0 length ."); + + g_queue_push_head (queue, (char*)"foo"); + g_queue_push_head (queue, (char*)"bar"); + g_queue_push_head (queue, (char*)"baz"); + + g_queue_pop_head (queue); + + if (NULL != queue->head->prev) + return FAILED ("HEAD: prev is wrong"); + if (strcmp ("bar", queue->head->data)) + return FAILED ("HEAD: Second element is wrong"); + if (strcmp ("foo", queue->head->next->data)) + return FAILED ("HEAD: Third element is wrong"); + if (NULL != queue->head->next->next) + return FAILED ("HEAD: End is wrong"); + + if (NULL != queue->tail->next) + return FAILED ("TAIL: next is wrong"); + if (strcmp ("foo", queue->tail->data)) + return FAILED ("TAIL: Second element is wrong"); + if (strcmp ("bar", queue->tail->prev->data)) + return FAILED ("TAIL: First element is wrong"); + if (NULL != queue->tail->prev->prev) + return FAILED ("TAIL: End is wrong"); + + g_queue_free (queue); + return OK; +} + +static RESULT +test_queue_new (void) +{ + GQueue *queue = g_queue_new (); + + if (queue->length != 0) + return FAILED ("expect length == 0"); + + if (queue->head != NULL) + return FAILED ("expect head == NULL"); + + if (queue->tail != NULL) + return FAILED ("expect tail == NULL"); + + g_queue_free (queue); + return OK; +} + +static RESULT +test_queue_is_empty (void) +{ + GQueue *queue = g_queue_new (); + + if (g_queue_is_empty (queue) == FALSE) + return FAILED ("new queue should be empty"); + + g_queue_push_head (queue, (char*)"foo"); + + if (g_queue_is_empty (queue) == TRUE) + return FAILED ("expected TRUE"); + + g_queue_free (queue); + + return OK; +} + +static Test queue_tests [] = { + { "push", test_queue_push}, + {"push_tail", test_queue_push_tail}, + { "pop", test_queue_pop}, + { "new", test_queue_new}, + {"is_empty", test_queue_is_empty}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(queue_tests_init, queue_tests) diff --git a/mono/eglib/test/shell.c b/mono/eglib/test/shell.c new file mode 100644 index 0000000000..d464f98aed --- /dev/null +++ b/mono/eglib/test/shell.c @@ -0,0 +1,330 @@ +#include +#include +#include +#include "test.h" + +static RESULT +test_shell_argv1 (void) +{ + GError *gerror; + gint argc; + gchar **argv; + gboolean ret; + + /* The next line prints a critical error and returns FALSE + ret = g_shell_parse_argv (NULL, NULL, NULL, NULL); + */ + ret = g_shell_parse_argv ("", NULL, NULL, NULL); + if (ret) + return FAILED ("1. It should return FALSE"); + + ret = g_shell_parse_argv ("hola", NULL, NULL, NULL); + if (!ret) + return FAILED ("2. It should return TRUE"); + + argc = 0; + ret = g_shell_parse_argv ("hola", &argc, NULL, NULL); + if (!ret) + return FAILED ("3. It should return TRUE"); + if (argc != 1) + return FAILED ("4. argc was %d", argc); + + argc = 0; + ret = g_shell_parse_argv ("hola bola", &argc, NULL, NULL); + if (!ret) + return FAILED ("5. It should return TRUE"); + if (argc != 2) + return FAILED ("6. argc was %d", argc); + + argc = 0; + ret = g_shell_parse_argv ("hola bola", &argc, &argv, NULL); + if (!ret) + return FAILED ("7. It should return TRUE"); + if (argc != 2) + return FAILED ("8. argc was %d", argc); + if (strcmp (argv [0], "hola")) + return FAILED ("9. argv[0] was %s", argv [0]); + if (strcmp (argv [1], "bola")) + return FAILED ("10. argv[1] was %s", argv [1]); + + g_strfreev (argv); + argv = NULL; + argc = 0; + gerror = NULL; + ret = g_shell_parse_argv ("hola 'bola'", &argc, &argv, &gerror); + if (!ret) + return FAILED ("11. It should return TRUE"); + if (argc != 2) + return FAILED ("12. argc was %d expected 2", argc); + if (strcmp (argv [0], "hola")) + return FAILED ("13. argv[0] was %s", argv [0]); + if (strcmp (argv [1], "bola")) + return FAILED ("14. argv[1] was %s", argv [1]); + if (gerror != NULL) + return FAILED ("15. error is not null"); + + + g_strfreev (argv); + argv = NULL; + argc = 0; + gerror = NULL; + ret = g_shell_parse_argv ("hola '' 'bola'", &argc, &argv, &gerror); + if (!ret) + return FAILED ("16. It should return TRUE"); + if (argc != 3) + return FAILED ("17. argc was %d expected 3", argc); + if (strcmp (argv [0], "hola")) + return FAILED ("18. argv[0] was %s", argv [0]); + if (strcmp (argv [1], "")) + return FAILED ("19. argv[2] was %s", argv [1]); + if (strcmp (argv [2], "bola")) + return FAILED ("19. argv[2] was %s", argv [2]); + if (gerror != NULL) + return FAILED ("20. error is not null"); + + g_strfreev (argv); + argv = NULL; + argc = 0; + gerror = NULL; + ret = g_shell_parse_argv ("hola'' bola", &argc, &argv, &gerror); + if (!ret) + return FAILED ("21. It should return TRUE"); + if (argc != 2) + return FAILED ("22. argc was %d expected 2", argc); + if (strcmp (argv [0], "hola")) + return FAILED ("23. argv[0] was %s", argv [0]); + if (strcmp (argv [1], "bola")) + return FAILED ("24. argv[2] was %s", argv [1]); + if (gerror != NULL) + return FAILED ("25. error is not null"); + + return OK; +} + +static RESULT +test_shell_argv2 (void) +{ + GError *gerror; + gint argc; + gchar **argv; + gboolean ret; + + argv = NULL; + argc = 0; + gerror = NULL; + ret = g_shell_parse_argv ("hola \"bola\"", &argc, &argv, &gerror); + if (!ret) + return FAILED ("1. It should return TRUE"); + if (argc != 2) + return FAILED ("2. argc was %d expected 2", argc); + if (strcmp (argv [0], "hola")) + return FAILED ("3. argv[0] was %s", argv [0]); + if (strcmp (argv [1], "bola")) + return FAILED ("4. argv[1] was %s", argv [1]); + if (gerror != NULL) + return FAILED ("5. error is not null"); + + g_strfreev (argv); + argv = NULL; + argc = 0; + gerror = NULL; + ret = g_shell_parse_argv ("hola \"\" \"bola \"", &argc, &argv, &gerror); + if (!ret) + return FAILED ("6. It should return TRUE"); + if (argc != 3) + return FAILED ("7. argc was %d expected 3", argc); + if (strcmp (argv [0], "hola")) + return FAILED ("8. argv[0] was %s", argv [0]); + if (strcmp (argv [1], "")) + return FAILED ("9. argv[2] was %s", argv [1]); + if (strcmp (argv [2], "bola ")) + return FAILED ("10. argv[2] was %s", argv [2]); + if (gerror != NULL) + return FAILED ("11. error is not null"); + + g_strfreev (argv); + argv = NULL; + argc = 0; + gerror = NULL; + ret = g_shell_parse_argv ("hola\n\t \"\t\" \"bola \"", &argc, &argv, &gerror); + if (!ret) + return FAILED ("10. It should return TRUE"); + if (argc != 3) + return FAILED ("11. argc was %d expected 3", argc); + if (strcmp (argv [0], "hola")) + return FAILED ("12. argv[0] was %s", argv [0]); + if (strcmp (argv [1], "\t")) + return FAILED ("13. argv[2] was %s", argv [1]); + if (strcmp (argv [2], "bola ")) + return FAILED ("14. argv[2] was %s", argv [2]); + if (gerror != NULL) + return FAILED ("15. error is not null"); + + g_strfreev (argv); + argv = NULL; + argc = 0; + gerror = NULL; + ret = g_shell_parse_argv ("hola\n\t \\\n \"\t\" \"bola \"", &argc, &argv, &gerror); + if (!ret) + return FAILED ("16. It should return TRUE"); + if (argc != 3) + return FAILED ("17. argc was %d expected 3", argc); + if (strcmp (argv [0], "hola")) + return FAILED ("18. argv[0] was %s", argv [0]); + if (strcmp (argv [1], "\t")) + return FAILED ("19. argv[2] was %s", argv [1]); + if (strcmp (argv [2], "bola ")) + return FAILED ("20. argv[2] was %s", argv [2]); + if (gerror != NULL) + return FAILED ("21. error is not null"); + + g_strfreev (argv); + return OK; +} + +static RESULT +test_shell_argv3 (void) +{ + GError *gerror; + gint argc; + gchar **argv; + gboolean ret; + + argv = NULL; + argc = 0; + gerror = NULL; + ret = g_shell_parse_argv ("hola \"bola", &argc, &argv, &gerror); + if (ret) + return FAILED ("1. It should return FALSE"); + if (argc != 0) + return FAILED ("2. argc was %d expected 0", argc); + if (argv != NULL) + return FAILED ("3. argv[0] was %s", argv [0]); + if (gerror == NULL) + return FAILED ("4. error is null"); + + /* Text ended before matching quote was found for ". (The text was 'hola "bola') */ + g_error_free (gerror); + gerror = NULL; + ret = g_shell_parse_argv ("hola \\\"bola", &argc, &argv, &gerror); + if (!ret) + return FAILED ("5. It should return TRUE"); + if (argc != 2) + return FAILED ("6. argc was %d expected 2", argc); + if (strcmp (argv [0], "hola")) + return FAILED ("18. argv[0] was %s", argv [0]); + if (strcmp (argv [1], "\"bola")) + return FAILED ("18. argv[1] was %s", argv [1]); + if (gerror != NULL) + return FAILED ("8. error is not null"); + + g_strfreev (argv); + argv = NULL; + argc = 0; + ret = g_shell_parse_argv ("hola \"\n\\'bola\"", &argc, &argv, &gerror); + if (!ret) + return FAILED ("9. It should return TRUE. %s", gerror->message); + if (argc != 2) + return FAILED ("10. argc was %d expected 2", argc); + if (strcmp (argv [0], "hola")) + return FAILED ("11. argv[0] was %s", argv [0]); + if (strcmp (argv [1], "\n\\'bola")) + return FAILED ("12. argv[1] was %s", argv [1]); + if (gerror != NULL) + return FAILED ("13. error is not null"); + + g_strfreev (argv); + argv = NULL; + argc = 0; + return OK; +} + +// This was the 2.8 showstopper error +static RESULT +test_shell_argv4 (void) +{ + GError *gerror; + gint argc; + gchar **argv; + gboolean ret; + const char *str = "'/usr/bin/gnome-terminal' -e \"bash -c 'read -p \\\"Press any key to continue...\\\" -n1;'\""; + + argv = NULL; + argc = 0; + gerror = NULL; + ret = g_shell_parse_argv (str, &argc, &argv, &gerror); + if (!ret) + return FAILED ("1. It should return TRUE"); + if (argc != 3) + return FAILED ("2. argc was %d expected 3", argc); + if (argv == NULL) + return FAILED ("3. argv[0] was NULL"); + if (gerror != NULL) + return FAILED ("4. error was set"); + + if (strcmp (argv [0], "/usr/bin/gnome-terminal")) + return FAILED ("5. Expected /usr/bin/gnome-terminal got %s", argv [0]); + if (strcmp (argv [1], "-e")) + return FAILED ("6. Expected -e, got: %s", argv [1]); + if (strcmp (argv [2], "bash -c 'read -p \"Press any key to continue...\" -n1;'")) + return FAILED ("7. Got unexpected result: %s\n", argv [2]); + + return OK; +} + +// This is https://bugzilla.novell.com/show_bug.cgi?id=655896 +static RESULT +test_shell_argv5 (void) +{ + GError *gerror; + gint argc; + gchar **argv; + gboolean ret; + const char *str = "echo \"foo\",\"bar\""; + + argv = NULL; + argc = 0; + gerror = NULL; + ret = g_shell_parse_argv (str, &argc, &argv, &gerror); + if (!ret) + return FAILED ("1. It should return TRUE"); + if (argc != 2) + return FAILED ("2. argc was %d expected 2", argc); + if (argv == NULL) + return FAILED ("3. argv[0] was NULL"); + if (gerror != NULL) + return FAILED ("4. error was set"); + + if (strcmp (argv [0], "echo")) + return FAILED ("5. Expected echo got %s", argv [0]); + if (strcmp (argv [1], "foo,bar")) + return FAILED ("6. Expected foo,bar, got: %s", argv [1]); + + return OK; +} + +static RESULT +test_quote (void) +{ + if (strcmp (g_shell_quote ("foo"), "'foo'")) + return FAILED ("Should return 'foo'"); + + if (strcmp (g_shell_quote ("foo'bar"), "'foo'\\''bar'")) + return FAILED ("Should return 'foo'\\''bar'"); + + if (strcmp (g_shell_quote ("foo bar"), "'foo bar'")) + return FAILED ("Should return 'foo bar'"); + return OK; +} + +static Test shell_tests [] = { + {"test_shell_argv1", test_shell_argv1}, + {"test_shell_argv2", test_shell_argv2}, + {"test_shell_argv3", test_shell_argv3}, + {"test_shell_argv4", test_shell_argv4}, + {"test_shell_argv5", test_shell_argv5}, + {"g_shell_quote", test_quote}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(shell_tests_init, shell_tests) diff --git a/mono/eglib/test/sizes.c b/mono/eglib/test/sizes.c new file mode 100644 index 0000000000..1f3861fc99 --- /dev/null +++ b/mono/eglib/test/sizes.c @@ -0,0 +1,108 @@ +/* + * Tests to ensure that our type definitions are correct + * + * These depend on -Werror, -Wall being set to catch the build error. + */ +#include +#ifndef _MSC_VER +#include +#endif +#include +#include +#include "test.h" + +static RESULT +test_formats (void) +{ + char buffer [1024]; + gsize a = 1; + + sprintf (buffer, "%" G_GSIZE_FORMAT, a); + + return NULL; +} + +static RESULT +test_ptrconv (void) +{ + int iv, iv2; + unsigned int uv, uv2; + gpointer ptr; + + iv = G_MAXINT32; + ptr = GINT_TO_POINTER (iv); + iv2 = GPOINTER_TO_INT (ptr); + if (iv != iv2) + return FAILED ("int to pointer and back conversions fail %d != %d", iv, iv2); + + iv = G_MININT32; + ptr = GINT_TO_POINTER (iv); + iv2 = GPOINTER_TO_INT (ptr); + if (iv != iv2) + return FAILED ("int to pointer and back conversions fail %d != %d", iv, iv2); + + iv = 1; + ptr = GINT_TO_POINTER (iv); + iv2 = GPOINTER_TO_INT (ptr); + if (iv != iv2) + return FAILED ("int to pointer and back conversions fail %d != %d", iv, iv2); + + iv = -1; + ptr = GINT_TO_POINTER (iv); + iv2 = GPOINTER_TO_INT (ptr); + if (iv != iv2) + return FAILED ("int to pointer and back conversions fail %d != %d", iv, iv2); + + iv = 0; + ptr = GINT_TO_POINTER (iv); + iv2 = GPOINTER_TO_INT (ptr); + if (iv != iv2) + return FAILED ("int to pointer and back conversions fail %d != %d", iv, iv2); + + uv = 0; + ptr = GUINT_TO_POINTER (uv); + uv2 = GPOINTER_TO_UINT (ptr); + if (uv != uv2) + return FAILED ("uint to pointer and back conversions fail %u != %d", uv, uv2); + + uv = 1; + ptr = GUINT_TO_POINTER (uv); + uv2 = GPOINTER_TO_UINT (ptr); + if (uv != uv2) + return FAILED ("uint to pointer and back conversions fail %u != %d", uv, uv2); + + uv = UINT32_MAX; + ptr = GUINT_TO_POINTER (uv); + uv2 = GPOINTER_TO_UINT (ptr); + if (uv != uv2) + return FAILED ("uint to pointer and back conversions fail %u != %d", uv, uv2); + + return NULL; + +} + +typedef struct { + int a; + int b; +} my_struct; + +static RESULT +test_offset (void) +{ + if (G_STRUCT_OFFSET (my_struct, a) != 0) + return FAILED ("offset of a is not zero"); + + if (G_STRUCT_OFFSET (my_struct, b) != 4 && G_STRUCT_OFFSET (my_struct, b) != 8) + return FAILED ("offset of b is 4 or 8, macro might be busted"); + + return OK; +} + +static Test size_tests [] = { + {"formats", test_formats}, + {"ptrconv", test_ptrconv}, + {"g_struct_offset", test_offset}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(size_tests_init, size_tests) diff --git a/mono/eglib/test/slist.c b/mono/eglib/test/slist.c new file mode 100644 index 0000000000..b36a9a9c7b --- /dev/null +++ b/mono/eglib/test/slist.c @@ -0,0 +1,343 @@ +#include +#include +#include +#include "test.h" + +static RESULT +test_slist_nth (void) +{ + char *foo = (char*)"foo"; + char *bar = (char*)"bar"; + char *baz = (char*)"baz"; + GSList *nth, *list; + list = g_slist_prepend (NULL, baz); + list = g_slist_prepend (list, bar); + list = g_slist_prepend (list, foo); + + nth = g_slist_nth (list, 0); + if (nth->data != foo) + return FAILED ("nth failed. #0"); + + nth = g_slist_nth (list, 1); + if (nth->data != bar) + return FAILED ("nth failed. #1"); + + nth = g_slist_nth (list, 2); + if (nth->data != baz) + return FAILED ("nth failed. #2"); + + nth = g_slist_nth (list, 3); + if (nth) + return FAILED ("nth failed. #3: %s", nth->data); + + g_slist_free (list); + return OK; +} + +static RESULT +test_slist_index (void) +{ + int i; + char *foo = (char*)"foo"; + char *bar = (char*)"bar"; + char *baz = (char*)"baz"; + GSList *list; + list = g_slist_prepend (NULL, baz); + list = g_slist_prepend (list, bar); + list = g_slist_prepend (list, foo); + + i = g_slist_index (list, foo); + if (i != 0) + return FAILED ("index failed. #0: %d", i); + + i = g_slist_index (list, bar); + if (i != 1) + return FAILED ("index failed. #1: %d", i); + + i = g_slist_index (list, baz); + if (i != 2) + return FAILED ("index failed. #2: %d", i); + + g_slist_free (list); + return OK; +} + +static RESULT +test_slist_append (void) +{ + GSList *foo; + GSList *list = g_slist_append (NULL, (char*)"first"); + if (g_slist_length (list) != 1) + return FAILED ("append(null,...) failed"); + + foo = g_slist_append (list, (char*)"second"); + if (foo != list) + return FAILED ("changed list head on non-empty"); + + if (g_slist_length (list) != 2) + return FAILED ("Append failed"); + + g_slist_free (list); + return OK; +} + +static RESULT +test_slist_concat (void) +{ + GSList *foo = g_slist_prepend (NULL, (char*)"foo"); + GSList *bar = g_slist_prepend (NULL, (char*)"bar"); + + GSList *list = g_slist_concat (foo, bar); + + if (g_slist_length (list) != 2) + return FAILED ("Concat failed."); + + g_slist_free (list); + return OK; +} + +static RESULT +test_slist_find (void) +{ + GSList *list = g_slist_prepend (NULL, (char*)"three"); + GSList *found; + char *data; + + list = g_slist_prepend (list, (char*)"two"); + list = g_slist_prepend (list, (char*)"one"); + + data = (char*)"four"; + list = g_slist_append (list, data); + + found = g_slist_find (list, data); + + if (found->data != data) + return FAILED ("Find failed"); + + g_slist_free (list); + return OK; +} + +static gint +find_custom (gconstpointer a, gconstpointer b) +{ + return(strcmp (a, b)); +} + +static RESULT +test_slist_find_custom (void) +{ + GSList *list = NULL, *found; + char *foo = (char*)"foo"; + char *bar = (char*)"bar"; + char *baz = (char*)"baz"; + + list = g_slist_prepend (list, baz); + list = g_slist_prepend (list, bar); + list = g_slist_prepend (list, foo); + + found = g_slist_find_custom (list, baz, find_custom); + + if (found == NULL) + return FAILED ("Find failed"); + + g_slist_free (list); + + return OK; +} + +static RESULT +test_slist_remove (void) +{ + GSList *list = g_slist_prepend (NULL,(char*) "three"); + char *one = (char*)"one"; + list = g_slist_prepend (list, (char*)"two"); + list = g_slist_prepend (list, one); + + list = g_slist_remove (list, one); + + if (g_slist_length (list) != 2) + return FAILED ("Remove failed"); + + if (strcmp ("two", list->data) != 0) + return FAILED ("Remove failed"); + + g_slist_free (list); + return OK; +} + +static RESULT +test_slist_remove_link (void) +{ + GSList *foo = g_slist_prepend (NULL, (char*)"a"); + GSList *bar = g_slist_prepend (NULL, (char*)"b"); + GSList *baz = g_slist_prepend (NULL, (char*)"c"); + GSList *list = foo; + + foo = g_slist_concat (foo, bar); + foo = g_slist_concat (foo, baz); + + list = g_slist_remove_link (list, bar); + + if (g_slist_length (list) != 2) + return FAILED ("remove_link failed #1"); + + if (bar->next != NULL) + return FAILED ("remove_link failed #2"); + + g_slist_free (list); + g_slist_free (bar); + + return OK; +} + +static gint +compare (gconstpointer a, gconstpointer b) +{ + char *foo = (char *) a; + char *bar = (char *) b; + + if (strlen (foo) < strlen (bar)) + return -1; + + return 1; +} + +static RESULT +test_slist_insert_sorted (void) +{ + GSList *list = g_slist_prepend (NULL,(char*) "a"); + list = g_slist_append (list, (char*)"aaa"); + + /* insert at the middle */ + list = g_slist_insert_sorted (list, (char*)"aa", compare); + if (strcmp ("aa", list->next->data)) + return FAILED("insert_sorted failed #1"); + + /* insert at the beginning */ + list = g_slist_insert_sorted (list, (char*)"", compare); + if (strcmp ("", list->data)) + return FAILED ("insert_sorted failed #2"); + + /* insert at the end */ + list = g_slist_insert_sorted (list, (char*)"aaaa", compare); + if (strcmp ("aaaa", g_slist_last (list)->data)) + return FAILED ("insert_sorted failed #3"); + + g_slist_free (list); + return OK; +} + +static RESULT +test_slist_insert_before (void) +{ + GSList *foo, *bar, *baz; + + foo = g_slist_prepend (NULL, (char*)"foo"); + foo = g_slist_insert_before (foo, NULL, (char*)"bar"); + bar = g_slist_last (foo); + + if (strcmp (bar->data, "bar")) + return FAILED ("1"); + + baz = g_slist_insert_before (foo, bar, (char*)"baz"); + if (foo != baz) + return FAILED ("2"); + + if (strcmp (foo->next->data, "baz")) + return FAILED ("3: %s", foo->next->data); + + g_slist_free (foo); + return OK; +} + +#define N_ELEMS 100 + +static int intcompare (gconstpointer p1, gconstpointer p2) +{ + return GPOINTER_TO_INT (p1) - GPOINTER_TO_INT (p2); +} + +static gboolean verify_sort (GSList *list, int len) +{ + int prev = GPOINTER_TO_INT (list->data); + len--; + for (list = list->next; list; list = list->next) { + int curr = GPOINTER_TO_INT (list->data); + if (prev > curr) + return FALSE; + prev = curr; + + if (len == 0) + return FALSE; + len--; + } + return len == 0; +} + +static RESULT +test_slist_sort (void) +{ + int i, j, mul; + GSList *list = NULL; + + for (i = 0; i < N_ELEMS; ++i) + list = g_slist_prepend (list, GINT_TO_POINTER (i)); + list = g_slist_sort (list, intcompare); + if (!verify_sort (list, N_ELEMS)) + return FAILED ("decreasing list"); + + g_slist_free (list); + + list = NULL; + for (i = 0; i < N_ELEMS; ++i) + list = g_slist_prepend (list, GINT_TO_POINTER (-i)); + list = g_slist_sort (list, intcompare); + if (!verify_sort (list, N_ELEMS)) + return FAILED ("increasing list"); + + g_slist_free (list); + + list = g_slist_prepend (NULL, GINT_TO_POINTER (0)); + for (i = 1; i < N_ELEMS; ++i) { + list = g_slist_prepend (list, GINT_TO_POINTER (-i)); + list = g_slist_prepend (list, GINT_TO_POINTER (i)); + } + list = g_slist_sort (list, intcompare); + if (!verify_sort (list, 2*N_ELEMS-1)) + return FAILED ("alternating list"); + + g_slist_free (list); + + list = NULL; + mul = 1; + for (i = 1; i < N_ELEMS; ++i) { + mul = -mul; + for (j = 0; j < i; ++j) + list = g_slist_prepend (list, GINT_TO_POINTER (mul * j)); + } + list = g_slist_sort (list, intcompare); + if (!verify_sort (list, (N_ELEMS*N_ELEMS - N_ELEMS)/2)) + return FAILED ("wavering list"); + + g_slist_free (list); + + return OK; +} + +static Test slist_tests [] = { + {"nth", test_slist_nth}, + {"index", test_slist_index}, + {"append", test_slist_append}, + {"concat", test_slist_concat}, + {"find", test_slist_find}, + {"find_custom", test_slist_find_custom}, + {"remove", test_slist_remove}, + {"remove_link", test_slist_remove_link}, + {"insert_sorted", test_slist_insert_sorted}, + {"insert_before", test_slist_insert_before}, + {"sort", test_slist_sort}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(slist_tests_init, slist_tests) diff --git a/mono/eglib/test/spawn.c b/mono/eglib/test/spawn.c new file mode 100644 index 0000000000..82f14880f7 --- /dev/null +++ b/mono/eglib/test/spawn.c @@ -0,0 +1,80 @@ +#include +#include +#include +#include +#ifdef HAVE_UNISTD_H +#include +#endif +#include "test.h" + +#ifdef G_OS_WIN32 +#include +#define read _read +#define close _close +#endif + +static RESULT +test_spawn_sync (void) +{ + gchar *out; + gchar *err; + gint status = -1; + GError *gerror = NULL; + + if (!g_spawn_command_line_sync ("ls", &out, &err, &status, &gerror)) + return FAILED ("Error executing 'ls'"); + + if (status != 0) + return FAILED ("Status is %d", status); + + if (out == NULL || strlen (out) == 0) + return FAILED ("Didn't get any output from ls!?"); + + g_free (out); + g_free (err); + return OK; +} + +static RESULT +test_spawn_async (void) +{ + /* +gboolean +g_spawn_async_with_pipes (const gchar *working_directory, + gchar **argv, + gchar **envp, + GSpawnFlags flags, + GSpawnChildSetupFunc child_setup, + gpointer user_data, + GPid *child_pid, + gint *standard_input, + gint *standard_output, + gint *standard_error, + GError **gerror) */ + char *argv [15]; + int stdout_fd = -1; + char buffer [512]; + pid_t child_pid = 0; + + memset (argv, 0, 15 * sizeof (char *)); + argv [0] = (char*)"ls"; + if (!g_spawn_async_with_pipes (NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, &child_pid, NULL, &stdout_fd, NULL, NULL)) + return FAILED ("1 Failed to run ls"); + if (child_pid == 0) + return FAILED ("2 child pid not returned"); + if (stdout_fd == -1) + return FAILED ("3 out fd is -1"); + + while (read (stdout_fd, buffer, 512) > 0); + close (stdout_fd); + + return OK; +} + +static Test spawn_tests [] = { + {"g_shell_spawn_sync", test_spawn_sync}, + {"g_shell_spawn_async_with_pipes", test_spawn_async}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(spawn_tests_init, spawn_tests) diff --git a/mono/eglib/test/string-util.c b/mono/eglib/test/string-util.c new file mode 100644 index 0000000000..7b5b7af32c --- /dev/null +++ b/mono/eglib/test/string-util.c @@ -0,0 +1,707 @@ +#include +#include +#include +#include "test.h" + +/* This test is just to be used with valgrind */ +static RESULT +test_strfreev (void) +{ + gchar **array = g_new (gchar *, 4); + array [0] = g_strdup ("one"); + array [1] = g_strdup ("two"); + array [2] = g_strdup ("three"); + array [3] = NULL; + + g_strfreev (array); + g_strfreev (NULL); + + return OK; +} + +static RESULT +test_concat (void) +{ + gchar *x = g_strconcat ("Hello", ", ", "world", NULL); + if (strcmp (x, "Hello, world") != 0) + return FAILED("concat failed, got: %s", x); + g_free (x); + return OK; +} + +static RESULT +test_split (void) +{ + const gchar *to_split = "Hello world, how are we doing today?"; + gint i; + gchar **v; + + v= g_strsplit(to_split, " ", 0); + + if(v == NULL) { + return FAILED("split failed, got NULL vector (1)"); + } + + for(i = 0; v[i] != NULL; i++); + if(i != 7) { + return FAILED("split failed, expected 7 tokens, got %d", i); + } + + g_strfreev(v); + + v = g_strsplit(to_split, ":", -1); + if(v == NULL) { + return FAILED("split failed, got NULL vector (2)"); + } + + for(i = 0; v[i] != NULL; i++); + if(i != 1) { + return FAILED("split failed, expected 1 token, got %d", i); + } + + if(strcmp(v[0], to_split) != 0) { + return FAILED("expected vector[0] to be '%s' but it was '%s'", + to_split, v[0]); + } + g_strfreev(v); + + v = g_strsplit ("", ":", 0); + if (v == NULL) + return FAILED ("g_strsplit returned NULL"); + g_strfreev (v); + + v = g_strsplit ("/home/miguel/dingus", "/", 0); + if (v [0][0] != 0) + return FAILED ("Got a non-empty first element"); + g_strfreev (v); + + v = g_strsplit ("appdomain1, Version=0.0.0.0, Culture=neutral", ",", 4); + if (strcmp (v [0], "appdomain1") != 0) + return FAILED ("Invalid value"); + + if (strcmp (v [1], " Version=0.0.0.0") != 0) + return FAILED ("Invalid value"); + + if (strcmp (v [2], " Culture=neutral") != 0) + return FAILED ("Invalid value"); + + if (v [3] != NULL) + return FAILED ("Expected only 3 elements"); + + g_strfreev (v); + + v = g_strsplit ("abcXYdefXghiXYjklYmno", "XY", 4); + if (strcmp (v [0], "abc") != 0) + return FAILED ("Invalid value 0"); + + if (strcmp (v [1], "defXghi") != 0) + return FAILED ("Invalid value 1"); + + if (strcmp (v [2], "jklYmno") != 0) + return FAILED ("Invalid value 2"); + + if (v [3] != NULL) + return FAILED ("Expected only 3 elements (1)"); + + g_strfreev (v); + + v = g_strsplit ("abcXYdefXghiXYjklYmno", "XY", 2); + if (strcmp (v [0], "abc") != 0) + return FAILED ("Invalid value 3"); + + if (strcmp (v [1], "defXghiXYjklYmno") != 0) + return FAILED ("Invalid value 4"); + + if (v [2] != NULL) + return FAILED ("Expected only 2 elements (2)"); + + g_strfreev (v); + + v = g_strsplit ("abcXYdefXghiXYjklYmnoXY", "XY", 3); + if (strcmp (v [0], "abc") != 0) + return FAILED ("Invalid value 5"); + + if (strcmp (v [1], "defXghi") != 0) + return FAILED ("Invalid value 6"); + + if (strcmp (v [2], "jklYmnoXY") != 0) + return FAILED ("Invalid value 7"); + + if (v [3] != NULL) + return FAILED ("Expected only 3 elements (3)"); + + g_strfreev (v); + + v = g_strsplit ("abcXYXYXYdefXY", "XY", -1); + if (strcmp (v [0], "abc") != 0) + return FAILED ("Invalid value 8"); + + if (strcmp (v [1], "") != 0) + return FAILED ("Invalid value 9"); + + if (strcmp (v [2], "") != 0) + return FAILED ("Invalid value 10"); + + if (strcmp (v [3], "def") != 0) + return FAILED ("Invalid value 11"); + + if (strcmp (v [4], "") != 0) + return FAILED ("Invalid value 12"); + + if (v [5] != NULL) + return FAILED ("Expected only 5 elements (4)"); + + g_strfreev (v); + + v = g_strsplit ("XYXYXYabcXYdef", "XY", -1); + if (strcmp (v [0], "") != 0) + return FAILED ("Invalid value 13"); + + if (strcmp (v [1], "") != 0) + return FAILED ("Invalid value 14"); + + if (strcmp (v [2], "") != 0) + return FAILED ("Invalid value 15"); + + if (strcmp (v [3], "abc") != 0) + return FAILED ("Invalid value 16"); + + if (strcmp (v [4], "def") != 0) + return FAILED ("Invalid value 17"); + + if (v [5] != NULL) + return FAILED ("Expected only 5 elements (5)"); + + g_strfreev (v); + + v = g_strsplit ("value=", "=", 2); + if (strcmp (v [0], "value") != 0) + return FAILED ("Invalid value 18; expected 'value', got '%s'", v [0]); + if (strcmp (v [1], "") != 0) + return FAILED ("Invalid value 19; expected '', got '%s'", v [1]); + if (v [2] != NULL) + return FAILED ("Expected only 2 elements (6)"); + + g_strfreev (v); + + return OK; +} + +static RESULT +test_split_set (void) +{ + gchar **v; + + v = g_strsplit_set ("abcXYdefXghiXYjklYmno", "XY", 6); + if (strcmp (v [0], "abc") != 0) + return FAILED ("Invalid value 0"); + + if (strcmp (v [1], "") != 0) + return FAILED ("Invalid value 1"); + + if (strcmp (v [2], "def") != 0) + return FAILED ("Invalid value 2"); + + if (strcmp (v [3], "ghi") != 0) + return FAILED ("Invalid value 3"); + + if (strcmp (v [4], "") != 0) + return FAILED ("Invalid value 4"); + + if (strcmp (v [5], "jklYmno") != 0) + return FAILED ("Invalid value 5"); + + if (v [6] != NULL) + return FAILED ("Expected only 6 elements (1)"); + + g_strfreev (v); + + v = g_strsplit_set ("abcXYdefXghiXYjklYmno", "XY", 3); + if (strcmp (v [0], "abc") != 0) + return FAILED ("Invalid value 6"); + + if (strcmp (v [1], "") != 0) + return FAILED ("Invalid value 7"); + + if (strcmp (v [2], "defXghiXYjklYmno") != 0) + return FAILED ("Invalid value 8"); + + if (v [3] != NULL) + return FAILED ("Expected only 3 elements (2)"); + + g_strfreev (v); + + v = g_strsplit_set ("abcXdefYghiXjklYmnoX", "XY", 5); + if (strcmp (v [0], "abc") != 0) + return FAILED ("Invalid value 9"); + + if (strcmp (v [1], "def") != 0) + return FAILED ("Invalid value 10"); + + if (strcmp (v [2], "ghi") != 0) + return FAILED ("Invalid value 11"); + + if (strcmp (v [3], "jkl") != 0) + return FAILED ("Invalid value 12"); + + if (strcmp (v [4], "mnoX") != 0) + return FAILED ("Invalid value 13"); + + if (v [5] != NULL) + return FAILED ("Expected only 5 elements (5)"); + + g_strfreev (v); + + v = g_strsplit_set ("abcXYXdefXY", "XY", -1); + if (strcmp (v [0], "abc") != 0) + return FAILED ("Invalid value 14"); + + if (strcmp (v [1], "") != 0) + return FAILED ("Invalid value 15"); + + if (strcmp (v [2], "") != 0) + return FAILED ("Invalid value 16"); + + if (strcmp (v [3], "def") != 0) + return FAILED ("Invalid value 17"); + + if (strcmp (v [4], "") != 0) + return FAILED ("Invalid value 18"); + + if (strcmp (v [5], "") != 0) + return FAILED ("Invalid value 19"); + + if (v [6] != NULL) + return FAILED ("Expected only 6 elements (4)"); + + g_strfreev (v); + + v = g_strsplit_set ("XYXabcXYdef", "XY", -1); + if (strcmp (v [0], "") != 0) + return FAILED ("Invalid value 20"); + + if (strcmp (v [1], "") != 0) + return FAILED ("Invalid value 21"); + + if (strcmp (v [2], "") != 0) + return FAILED ("Invalid value 22"); + + if (strcmp (v [3], "abc") != 0) + return FAILED ("Invalid value 23"); + + if (strcmp (v [4], "") != 0) + return FAILED ("Invalid value 24"); + + if (strcmp (v [5], "def") != 0) + return FAILED ("Invalid value 25"); + + if (v [6] != NULL) + return FAILED ("Expected only 6 elements (5)"); + + g_strfreev (v); + + return OK; +} + +static RESULT +test_strreverse (void) +{ + RESULT res = OK; + gchar *a = g_strdup ("onetwothree"); + gchar *a_target = (char*)"eerhtowteno"; + gchar *b = g_strdup ("onetwothre"); + gchar *b_target = (char*)"erhtowteno"; + gchar *c = g_strdup (""); + gchar *c_target = (char*)""; + + g_strreverse (a); + if (strcmp (a, a_target)) { + res = FAILED("strreverse failed. Expecting: '%s' and got '%s'\n", a, a_target); + goto cleanup; + } + + g_strreverse (b); + if (strcmp (b, b_target)) { + res = FAILED("strreverse failed. Expecting: '%s' and got '%s'\n", b, b_target); + goto cleanup; + } + + g_strreverse (c); + if (strcmp (c, c_target)) { + res = FAILED("strreverse failed. Expecting: '%s' and got '%s'\n", b, b_target); + goto cleanup; + } + +cleanup: + g_free (c); + g_free (b); + g_free (a); + return res; +} + +static RESULT +test_strjoin (void) +{ + char *s; + + s = g_strjoin (NULL, "a", "b", NULL); + if (strcmp (s, "ab") != 0) + return FAILED ("Join of two strings with no separator fails"); + g_free (s); + + s = g_strjoin ("", "a", "b", NULL); + if (strcmp (s, "ab") != 0) + return FAILED ("Join of two strings with empty separator fails"); + g_free (s); + + s = g_strjoin ("-", "a", "b", NULL); + if (strcmp (s, "a-b") != 0) + return FAILED ("Join of two strings with separator fails"); + g_free (s); + + s = g_strjoin ("-", "aaaa", "bbbb", "cccc", "dddd", NULL); + if (strcmp (s, "aaaa-bbbb-cccc-dddd") != 0) + return FAILED ("Join of multiple strings fails"); + g_free (s); + + s = g_strjoin ("-", NULL); + if (s == NULL || (strcmp (s, "") != 0)) + return FAILED ("Failed to join empty arguments"); + g_free (s); + + return OK; +} + +static RESULT +test_strchug (void) +{ + char *str = g_strdup (" \t\n hola"); + + g_strchug (str); + if (strcmp ("hola", str)) { + fprintf (stderr, "%s\n", str); + g_free (str); + return FAILED ("Failed."); + } + g_free (str); + return OK; +} + +static RESULT +test_strchomp (void) +{ + char *str = g_strdup ("hola \t"); + + g_strchomp (str); + if (strcmp ("hola", str)) { + fprintf (stderr, "%s\n", str); + g_free (str); + return FAILED ("Failed."); + } + g_free (str); + return OK; +} + +static RESULT +test_strstrip (void) +{ + char *str = g_strdup (" \t hola "); + + g_strstrip (str); + if (strcmp ("hola", str)) { + fprintf (stderr, "%s\n", str); + g_free (str); + return FAILED ("Failed."); + } + g_free (str); + return OK; +} + +#define urit(so,j) do { s = g_filename_to_uri (so, NULL, NULL); if (strcmp (s, j) != 0) return FAILED("Got %s expected %s", s, j); g_free (s); } while (0); + +#define errit(so) do { s = g_filename_to_uri (so, NULL, NULL); if (s != NULL) return FAILED ("got %s, expected NULL", s); } while (0); + +static RESULT +test_filename_to_uri (void) +{ +#ifdef G_OS_WIN32 +#else + char *s; + + urit ("/a", "file:///a"); + urit ("/home/miguel", "file:///home/miguel"); + urit ("/home/mig uel", "file:///home/mig%20uel"); + urit ("/\303\241", "file:///%C3%A1"); + urit ("/\303\241/octal", "file:///%C3%A1/octal"); + urit ("/%", "file:///%25"); + urit ("/\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037\040", "file:///%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20"); + urit ("/!$&'()*+,-./", "file:///!$&'()*+,-./"); + urit ("/\042\043\045", "file:///%22%23%25"); + urit ("/0123456789:=", "file:///0123456789:="); + urit ("/\073\074\076\077", "file:///%3B%3C%3E%3F"); + urit ("/\133\134\135\136_\140\173\174\175", "file:///%5B%5C%5D%5E_%60%7B%7C%7D"); + urit ("/\173\174\175\176\177\200", "file:///%7B%7C%7D~%7F%80"); + urit ("/@ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", "file:///@ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); + errit ("a"); + errit ("./hola"); +#endif + + return OK; +} + +#define fileit(so,j) do { s = g_filename_from_uri (so, NULL, NULL); if (strcmp (s, j) != 0) return FAILED("Got %s expected %s", s, j); g_free (s); } while (0); + +#define ferrit(so) do { s = g_filename_from_uri (so, NULL, NULL); if (s != NULL) return FAILED ("got %s, expected NULL", s); } while (0); + +static RESULT +test_filename_from_uri (void) +{ +#ifndef G_OS_WIN32 + char *s; + + fileit ("file:///a", "/a"); + fileit ("file:///%41", "/A"); + fileit ("file:///home/miguel", "/home/miguel"); + fileit ("file:///home/mig%20uel", "/home/mig uel"); + fileit ("file:///home/c%2B%2B", "/home/c++"); + fileit ("file:///home/c%2b%2b", "/home/c++"); + ferrit ("/a"); + ferrit ("a"); + ferrit ("file://a"); + ferrit ("file:a"); + ferrit ("file:///%"); + ferrit ("file:///%0"); + ferrit ("file:///%jj"); +#endif + + return OK; +} + +static RESULT +test_ascii_xdigit_value (void) +{ + int i; + gchar j; + + i = g_ascii_xdigit_value ('9' + 1); + if (i != -1) + return FAILED ("'9' + 1"); + i = g_ascii_xdigit_value ('0' - 1); + if (i != -1) + return FAILED ("'0' - 1"); + i = g_ascii_xdigit_value ('a' - 1); + if (i != -1) + return FAILED ("'a' - 1"); + i = g_ascii_xdigit_value ('f' + 1); + if (i != -1) + return FAILED ("'f' + 1"); + i = g_ascii_xdigit_value ('A' - 1); + if (i != -1) + return FAILED ("'A' - 1"); + i = g_ascii_xdigit_value ('F' + 1); + if (i != -1) + return FAILED ("'F' + 1"); + + for (j = '0'; j < '9'; j++) { + int c = g_ascii_xdigit_value (j); + if (c != (j - '0')) + return FAILED ("Digits %c -> %d", j, c); + } + for (j = 'a'; j < 'f'; j++) { + int c = g_ascii_xdigit_value (j); + if (c != (j - 'a' + 10)) + return FAILED ("Lower %c -> %d", j, c); + } + for (j = 'A'; j < 'F'; j++) { + int c = g_ascii_xdigit_value (j); + if (c != (j - 'A' + 10)) + return FAILED ("Upper %c -> %d", j, c); + } + return OK; +} + +#define G_STR_DELIMITERS "_-|> <." + +static void +g_strdelimits (char *a, const char *old, char new) +{ + old = old ? old : G_STR_DELIMITERS; + while (*old) + g_strdelimit (a, *old++, new); +} + +static RESULT +test_strdelimit (void) +{ + gchar *str; + + str = g_strdup (G_STR_DELIMITERS); + g_strdelimits (str, NULL, 'a'); + if (0 != strcmp ("aaaaaaa", str)) + return FAILED ("All delimiters: '%s'", str); + g_free (str); + str = g_strdup ("hola"); + g_strdelimits (str, "ha", '+'); + if (0 != strcmp ("+ol+", str)) + return FAILED ("2 delimiters: '%s'", str); + g_free (str); + return OK; +} + +#define NUMBERS "0123456789" + +static RESULT +test_strlcpy (void) +{ + const gchar *src = "onetwothree"; + gchar *dest; + gsize i; + + dest = g_malloc (strlen (src) + 1); + memset (dest, 0, strlen (src) + 1); + i = g_strlcpy (dest, src, (gsize)-1); + if (i != strlen (src)) + return FAILED ("Test1 got %d", i); + + if (0 != strcmp (dest, src)) + return FAILED ("Src and dest not equal"); + + i = g_strlcpy (dest, src, 3); + if (i != strlen (src)) + return FAILED ("Test1 got %d", i); + if (0 != strcmp (dest, "on")) + return FAILED ("Test2"); + + i = g_strlcpy (dest, src, 1); + if (i != strlen (src)) + return FAILED ("Test3 got %d", i); + if (*dest != '\0') + return FAILED ("Test4"); + + i = g_strlcpy (dest, src, 12345); + if (i != strlen (src)) + return FAILED ("Test4 got %d", i); + if (0 != strcmp (dest, src)) + return FAILED ("Src and dest not equal 2"); + g_free (dest); + + /* This is a test for g_filename_from_utf8, even if it does not look like it */ + dest = g_filename_from_utf8 (NUMBERS, strlen (NUMBERS), NULL, NULL, NULL); + if (0 != strcmp (dest, NUMBERS)) + return FAILED ("problem [%s] and [%s]", dest, NUMBERS); + g_free (dest); + + return OK; +} + +static RESULT +test_strescape (void) +{ + gchar *str; + + str = g_strescape ("abc", NULL); + if (strcmp ("abc", str)) + return FAILED ("#1"); + str = g_strescape ("\t\b\f\n\r\\\"abc", NULL); + if (strcmp ("\\t\\b\\f\\n\\r\\\\\\\"abc", str)) + return FAILED ("#2 %s", str); + str = g_strescape ("\001abc", NULL); + if (strcmp ("\\001abc", str)) + return FAILED ("#3 %s", str); + str = g_strescape ("\001abc", "\001"); + if (strcmp ("\001abc", str)) + return FAILED ("#3 %s", str); + return OK; +} + +static RESULT +test_ascii_strncasecmp (void) +{ + int n; + + n = g_ascii_strncasecmp ("123", "123", 1); + if (n != 0) + return FAILED ("Should have been 0"); + + n = g_ascii_strncasecmp ("423", "123", 1); + if (n != 3) + return FAILED ("Should have been 3, got %d", n); + + n = g_ascii_strncasecmp ("123", "423", 1); + if (n != -3) + return FAILED ("Should have been -3, got %d", n); + + n = g_ascii_strncasecmp ("1", "1", 10); + if (n != 0) + return FAILED ("Should have been 0, got %d", n); + return OK; +} + +static RESULT +test_ascii_strdown (void) +{ + const gchar *a = "~09+AaBcDeFzZ$0909EmPAbCdEEEEEZZZZAAA"; + const gchar *b = "~09+aabcdefzz$0909empabcdeeeeezzzzaaa"; + gchar *c; + gint n, l; + + l = (gint)strlen (b); + c = g_ascii_strdown (a, l); + n = g_ascii_strncasecmp (b, c, l); + + if (n != 0) { + g_free (c); + return FAILED ("Should have been 0, got %d", n); + } + + g_free (c); + return OK; +} + +static RESULT +test_strdupv (void) +{ + gchar **one; + gchar **two; + gint len; + + one = g_strdupv (NULL); + if (one) + return FAILED ("Should have been NULL"); + + one = g_malloc (sizeof (gchar *)); + *one = NULL; + two = g_strdupv (one); + if (!two) + FAILED ("Should have been not NULL"); + len = g_strv_length (two); + if (len) + FAILED ("Should have been 0"); + g_strfreev (two); + g_strfreev (one); + return NULL; +} + +static Test strutil_tests [] = { + {"g_strfreev", test_strfreev}, + {"g_strconcat", test_concat}, + {"g_strsplit", test_split}, + {"g_strsplit_set", test_split_set}, + {"g_strreverse", test_strreverse}, + {"g_strjoin", test_strjoin}, + {"g_strchug", test_strchug}, + {"g_strchomp", test_strchomp}, + {"g_strstrip", test_strstrip}, + {"g_filename_to_uri", test_filename_to_uri}, + {"g_filename_from_uri", test_filename_from_uri}, + {"g_ascii_xdigit_value", test_ascii_xdigit_value}, + {"g_strdelimit", test_strdelimit}, + {"g_strlcpy", test_strlcpy}, + {"g_strescape", test_strescape}, + {"g_ascii_strncasecmp", test_ascii_strncasecmp }, + {"g_ascii_strdown", test_ascii_strdown }, + {"g_strdupv", test_strdupv }, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(strutil_tests_init, strutil_tests) diff --git a/mono/eglib/test/string.c b/mono/eglib/test/string.c new file mode 100644 index 0000000000..ab73d25ed2 --- /dev/null +++ b/mono/eglib/test/string.c @@ -0,0 +1,204 @@ +#include +#include +#include +#include "test.h" + +#define sfail(k,p) if (s->str [p] != k) { g_string_free (s,TRUE); return FAILED("Got %s, Failed at %d, expected '%c'", s->str, p, k);} + +static RESULT +test_append_speed (void) +{ + GString *s = g_string_new(""); + gint i; + + for(i = 0; i < 1024; i++) { + g_string_append(s, "x"); + } + + if(strlen (s->str) != 1024) { + return FAILED("Incorrect string size, got: %s %d", + s->str, strlen(s->str)); + } + + g_string_free (s, TRUE); + + return OK; +} + +static RESULT +test_append_c_speed (void) +{ + GString *s = g_string_new(""); + gint i; + + for(i = 0; i < 1024; i++) { + g_string_append_c(s, 'x'); + } + + if(strlen(s->str) != 1024) { + return FAILED("Incorrect string size, got: %s %d", s->str, + strlen(s->str)); + } + + g_string_free(s, TRUE); + + return OK; +} + +static RESULT +test_gstring (void) +{ + GString *s = g_string_new_len ("My stuff", 2); + char *ret; + int i; + + if (strcmp (s->str, "My") != 0) + return (char*)"Expected only 'My' on the string"; + g_string_free (s, TRUE); + + s = g_string_new_len ("My\0\0Rest", 6); + if (s->str [2] != 0) + return (char*)"Null was not copied"; + if (strcmp (s->str+4, "Re") != 0){ + return (char*)"Did not find the 'Re' part"; + } + + g_string_append (s, "lalalalalalalalalalalalalalalalalalalalalalal"); + if (s->str [2] != 0) + return (char*)"Null as not copied"; + if (strncmp (s->str+4, "Relala", 6) != 0){ + return FAILED("Did not copy correctly, got: %s", s->str+4); + } + + g_string_free (s, TRUE); + + s = g_string_new (""); + for (i = 0; i < 1024; i++){ + g_string_append_c (s, 'x'); + } + if (strlen (s->str) != 1024){ + return FAILED("Incorrect string size, got: %s %d\n", s->str, strlen (s->str)); + } + g_string_free (s, TRUE); + + s = g_string_new ("hola"); + g_string_sprintfa (s, "%s%d", ", bola", 5); + if (strcmp (s->str, "hola, bola5") != 0){ + return FAILED("Incorrect data, got: %s\n", s->str); + } + g_string_free (s, TRUE); + + s = g_string_new ("Hola"); + g_string_printf (s, "Dingus"); + + /* Test that it does not release it */ + ret = g_string_free (s, FALSE); + g_free (ret); + + s = g_string_new_len ("H" "\000" "H", 3); + g_string_append_len (s, "1" "\000" "2", 3); + sfail ('H', 0); + sfail ( 0, 1); + sfail ('H', 2); + sfail ('1', 3); + sfail ( 0, 4); + sfail ('2', 5); + g_string_free (s, TRUE); + + return OK; +} + +static RESULT +test_sized (void) +{ + GString *s = g_string_sized_new (20); + + if (s->str [0] != 0) + return FAILED ("Expected an empty string"); + if (s->len != 0) + return FAILED ("Expected an empty len"); + + g_string_free (s, TRUE); + + return NULL; +} + +static RESULT +test_truncate (void) +{ + GString *s = g_string_new ("0123456789"); + g_string_truncate (s, 3); + + if (strlen (s->str) != 3) + return FAILED ("size of string should have been 3, instead it is [%s]\n", s->str); + g_string_free (s, TRUE); + + s = g_string_new ("a"); + s = g_string_truncate (s, 10); + if (strlen (s->str) != 1) + return FAILED ("The size is not 1"); + g_string_truncate (s, (gsize)-1); + if (strlen (s->str) != 1) + return FAILED ("The size is not 1"); + g_string_truncate (s, 0); + if (strlen (s->str) != 0) + return FAILED ("The size is not 0"); + + g_string_free (s, TRUE); + + return NULL; +} + +static RESULT +test_appendlen (void) +{ + GString *s = g_string_new (""); + + g_string_append_len (s, "boo\000x", 0); + if (s->len != 0) + return FAILED ("The length is not zero %d", s->len); + g_string_append_len (s, "boo\000x", 5); + if (s->len != 5) + return FAILED ("The length is not five %d", s->len); + g_string_append_len (s, "ha", -1); + if (s->len != 7) + return FAILED ("The length is not seven %d", s->len); + + g_string_free (s, TRUE); + + return NULL; +} + +static RESULT +test_macros (void) +{ + char *s = g_strdup (G_STRLOC); + char *p = strchr (s + 2, ':'); + int n; + + if (p == NULL) + return FAILED ("Did not find a separator"); + n = atoi (p+1); + if (n <= 0) + return FAILED ("did not find a valid line number"); + + *p = 0; + if (strcmp (s + strlen(s) - 8 , "string.c") != 0) + return FAILED ("This did not store the filename on G_STRLOC"); + + g_free (s); + return NULL; +} + +static Test string_tests [] = { + {"append-speed", test_append_speed}, + {"append_c-speed", test_append_c_speed}, + {"ctor+append", test_gstring }, + {"ctor+sized", test_sized }, + {"truncate", test_truncate }, + {"append_len", test_appendlen }, + {"macros", test_macros }, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(string_tests_init, string_tests) diff --git a/mono/eglib/test/test.c b/mono/eglib/test/test.c new file mode 100644 index 0000000000..426812df62 --- /dev/null +++ b/mono/eglib/test/test.c @@ -0,0 +1,272 @@ +/* + * EGLib Unit Group/Test Runners + * + * Author: + * Aaron Bockover (abockover@novell.com) + * + * (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. + */ + +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif + +#include +#include +#include +#include +#include +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef G_OS_WIN32 +#include +#endif + +#include "test.h" + +extern gint global_passed, global_tests; +static gchar *last_result = NULL; + +static gboolean +run_test(const Test *test, char **result_out) +{ + gchar *result; + + if((result = test->handler()) == NULL) { + *result_out = NULL; + return TRUE; + } else { + *result_out = result; + return FALSE; + } +} + +gboolean +run_group(const Group *group, gint iterations, gboolean quiet, + gboolean time, const char *tests_to_run_s) +{ + Test *tests = group->handler(); + gint i, j, passed = 0, total = 0; + gdouble start_time_group, start_time_test; + gchar **tests_to_run = NULL; + + if(!quiet) { + if(iterations > 1) { + printf("[%s] (%dx)\n", group->name, iterations); + } else { + printf("[%s]\n", group->name); + } + } + + if(tests_to_run_s != NULL) { + tests_to_run = eg_strsplit(tests_to_run_s, ",", -1); + } + + start_time_group = get_timestamp(); + + for(i = 0; tests[i].name != NULL; i++) { + gchar *result = (char*)""; + gboolean iter_pass, run; + + iter_pass = FALSE; + if(tests_to_run != NULL) { + gint j; + run = FALSE; + for(j = 0; tests_to_run[j] != NULL; j++) { + if(strcmp(tests_to_run[j], tests[i].name) == 0) { + run = TRUE; + break; + } + } + } else { + run = TRUE; + } + + if(!run) { + continue; + } + + total++; + + if(!quiet) { + printf(" %s: ", tests[i].name); + } + + start_time_test = get_timestamp(); + + for(j = 0; j < iterations; j++) { + iter_pass = run_test(&(tests[i]), &result); + if(!iter_pass) { + break; + } + } + + if(iter_pass) { + passed++; + if(!quiet) { + if(time) { + printf("OK (%g)\n", get_timestamp() - start_time_test); + } else { + printf("OK\n"); + } + } + } else { + if(!quiet) { + printf("FAILED (%s)\n", result); + } + + if(last_result == result) { + last_result = NULL; + g_free(result); + } + } + } + + global_passed += passed; + global_tests += total; + + if(!quiet) { + gdouble pass_percentage = ((gdouble)passed / (gdouble)total) * 100.0; + if(time) { + printf(" %d / %d (%g%%, %g)\n", passed, total, + pass_percentage, get_timestamp() - start_time_group); + } else { + printf(" %d / %d (%g%%)\n", passed, total, pass_percentage); + } + } + + if(tests_to_run != NULL) { + eg_strfreev(tests_to_run); + } + + return passed == total; +} + +RESULT +FAILED(const gchar *format, ...) +{ + gchar *ret; + va_list args; + gint n; + +#if !defined(HAVE_VASPRINTF) && !defined(_EGLIB_MAJOR) + /* We are linked against the real glib, no vasprintf */ + g_assert_not_reached (); + return NULL; +#else + va_start(args, format); + n = g_vasprintf(&ret, format, args); + va_end(args); + + if(n == -1) { + last_result = NULL; + return NULL; + } + + last_result = ret; + return ret; +#endif +} + +gdouble +get_timestamp (void) +{ + /* FIXME: We should use g_get_current_time here */ + GTimeVal res; + g_get_current_time (&res); + return res.tv_sec + (1.e-6) * res.tv_usec; +} + +/* + * Duplicating code here from EGlib to avoid g_strsplit skew between + * EGLib and GLib + */ + +gchar ** +eg_strsplit (const gchar *string, const gchar *delimiter, gint max_tokens) +{ + gchar *string_c; + gchar *strtok_save, **vector; + gchar *token, *token_c; + gint size = 1; + size_t token_length; + + g_return_val_if_fail(string != NULL, NULL); + g_return_val_if_fail(delimiter != NULL, NULL); + g_return_val_if_fail(delimiter[0] != 0, NULL); + + token_length = strlen(string); + string_c = (gchar *)g_malloc(token_length + 1); + memcpy(string_c, string, token_length); + string_c[token_length] = 0; + + vector = NULL; + token = (gchar *)strtok_r(string_c, delimiter, &strtok_save); + + while(token != NULL) { + token_length = strlen(token); + token_c = (gchar *)g_malloc(token_length + 1); + memcpy(token_c, token, token_length); + token_c[token_length] = 0; + + vector = vector == NULL ? + (gchar **)g_malloc(2 * sizeof(vector)) : + (gchar **)g_realloc(vector, (size + 1) * sizeof(vector)); + + vector[size - 1] = token_c; + size++; + + if(max_tokens > 0 && size >= max_tokens) { + if(size > max_tokens) { + break; + } + + token = strtok_save; + } else { + token = (gchar *)strtok_r(NULL, delimiter, &strtok_save); + } + } + + if(vector != NULL && size > 0) { + vector[size - 1] = NULL; + } + + g_free(string_c); + string_c = NULL; + + return vector; +} + +void +eg_strfreev (gchar **str_array) +{ + gchar **orig = str_array; + if (str_array == NULL) + return; + while (*str_array != NULL){ + g_free (*str_array); + str_array++; + } + g_free (orig); +} diff --git a/mono/eglib/test/test.h b/mono/eglib/test/test.h new file mode 100644 index 0000000000..a2003211ee --- /dev/null +++ b/mono/eglib/test/test.h @@ -0,0 +1,81 @@ +/* + * EGLib Unit Group/Test Runners + * + * Author: + * Aaron Bockover (abockover@novell.com) + * + * (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. + */ + +#ifndef _TEST_H +#define _TEST_H + +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +/* disable the following warnings + * C4100: The formal parameter is not referenced in the body of the function. The unreferenced parameter is ignored. + * C4127: conditional expression is constant (test macros produce a lot of these) +*/ +#pragma warning(disable:4100 4127) +#endif + +typedef gchar * RESULT; + +typedef struct _Test Test; +typedef struct _Group Group; + +typedef gchar * (* RunTestHandler)(void); +typedef Test * (* LoadGroupHandler)(void); + +struct _Test { + const gchar *name; + RunTestHandler handler; +}; + +struct _Group { + const gchar *name; + LoadGroupHandler handler; +}; + +gboolean run_group(const Group *group, gint iterations, gboolean quiet, + gboolean time, const char *tests); +#undef FAILED +RESULT FAILED(const gchar *format, ...); +gdouble get_timestamp (void); +gchar ** eg_strsplit (const gchar *string, const gchar *delimiter, gint max_tokens); +void eg_strfreev (gchar **str_array); + +#define OK NULL + +#define DEFINE_TEST_GROUP_INIT(name, table) \ + const Test * (name) (void); \ + const Test * (name) (void) { return table; } + +#define DEFINE_TEST_GROUP_INIT_H(name) \ + Test * (name) (void); + +#endif /* _TEST_H */ diff --git a/mono/eglib/test/tests.h b/mono/eglib/test/tests.h new file mode 100644 index 0000000000..885d87a7ca --- /dev/null +++ b/mono/eglib/test/tests.h @@ -0,0 +1,59 @@ +#include "test.h" + +DEFINE_TEST_GROUP_INIT_H(string_tests_init); +DEFINE_TEST_GROUP_INIT_H(strutil_tests_init); +DEFINE_TEST_GROUP_INIT_H(slist_tests_init); +DEFINE_TEST_GROUP_INIT_H(list_tests_init); +DEFINE_TEST_GROUP_INIT_H(hashtable_tests_init); +DEFINE_TEST_GROUP_INIT_H(ptrarray_tests_init); +DEFINE_TEST_GROUP_INIT_H(size_tests_init); +DEFINE_TEST_GROUP_INIT_H(fake_tests_init); +DEFINE_TEST_GROUP_INIT_H(array_tests_init); +DEFINE_TEST_GROUP_INIT_H(queue_tests_init); +DEFINE_TEST_GROUP_INIT_H(path_tests_init); +DEFINE_TEST_GROUP_INIT_H(shell_tests_init); +DEFINE_TEST_GROUP_INIT_H(spawn_tests_init); +DEFINE_TEST_GROUP_INIT_H(timer_tests_init); +DEFINE_TEST_GROUP_INIT_H(file_tests_init); +DEFINE_TEST_GROUP_INIT_H(pattern_tests_init); +DEFINE_TEST_GROUP_INIT_H(dir_tests_init); +DEFINE_TEST_GROUP_INIT_H(markup_tests_init); +DEFINE_TEST_GROUP_INIT_H(unicode_tests_init); +DEFINE_TEST_GROUP_INIT_H(utf8_tests_init); +DEFINE_TEST_GROUP_INIT_H(endian_tests_init); +DEFINE_TEST_GROUP_INIT_H(module_tests_init); +DEFINE_TEST_GROUP_INIT_H(memory_tests_init); +DEFINE_TEST_GROUP_INIT_H(enum_tests_init); + +const +static Group test_groups [] = { + {"string", string_tests_init}, + {"strutil", strutil_tests_init}, + {"ptrarray", ptrarray_tests_init}, + {"slist", slist_tests_init}, + {"list", list_tests_init}, + {"hashtable", hashtable_tests_init}, + {"sizes", size_tests_init}, + {"fake", fake_tests_init}, + {"array", array_tests_init}, + {"queue", queue_tests_init}, + {"path", path_tests_init}, + {"shell", shell_tests_init}, + {"markup", markup_tests_init}, +#if !DISABLE_PROCESS_TESTS + {"spawn", spawn_tests_init}, + {"module", module_tests_init}, +#endif +#if !DISABLE_FILESYSTEM_TESTS + {"file", file_tests_init}, +#endif + {"timer", timer_tests_init}, + {"pattern", pattern_tests_init}, + {"dir", dir_tests_init}, + {"unicode", unicode_tests_init}, + {"utf8", utf8_tests_init}, + {"endian", endian_tests_init}, + {"memory", memory_tests_init}, + {"enum", enum_tests_init}, + {NULL, NULL} +}; diff --git a/mono/eglib/test/timer.c b/mono/eglib/test/timer.c new file mode 100644 index 0000000000..eb8efb99dd --- /dev/null +++ b/mono/eglib/test/timer.c @@ -0,0 +1,53 @@ +#include +#include +#include +#include +#ifdef HAVE_UNISTD_H +#include +#endif +#include +#include + +#ifdef G_OS_WIN32 +#include +#define sleep(t) Sleep((t) * 1000) +#endif + +#include "test.h" + +static RESULT +test_timer (void) +{ + GTimer *timer; + gdouble elapsed1, elapsed2; + gulong usec = 0; + + timer = g_timer_new (); + sleep (1); + elapsed1 = g_timer_elapsed (timer, NULL); + if ((elapsed1 + 0.1) < 1.0) + return FAILED ("Elapsed time should be around 1s and was %f", elapsed1); + + g_timer_stop (timer); + elapsed1 = g_timer_elapsed (timer, NULL); + elapsed2 = g_timer_elapsed (timer, &usec); + if (fabs (elapsed1 - elapsed2) > 0.000001) + return FAILED ("The elapsed times are not equal %f - %f.", elapsed1, elapsed2); + + elapsed2 *= 1000000; + while (elapsed2 > 1000000) + elapsed2 -= 1000000; + + if (fabs (usec - elapsed2) > 100.0) + return FAILED ("usecs are wrong."); + + g_timer_destroy (timer); + return OK; +} + +static Test timer_tests [] = { + {"g_timer", test_timer}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(timer_tests_init, timer_tests) diff --git a/mono/eglib/test/unicode.c b/mono/eglib/test/unicode.c new file mode 100644 index 0000000000..1865950369 --- /dev/null +++ b/mono/eglib/test/unicode.c @@ -0,0 +1,99 @@ +#include "test.h" + +/* + * g_unichar_type + */ +static RESULT +test_g_unichar_type (void) +{ + if (g_unichar_type ('A') != G_UNICODE_UPPERCASE_LETTER) + return FAILED ("#1"); + if (g_unichar_type ('a') != G_UNICODE_LOWERCASE_LETTER) + return FAILED ("#2"); + if (g_unichar_type ('1') != G_UNICODE_DECIMAL_NUMBER) + return FAILED ("#3"); + if (g_unichar_type (0xA3) != G_UNICODE_CURRENCY_SYMBOL) + return FAILED ("#4"); + return NULL; +} + +/* + * g_unichar_toupper + */ +static RESULT +test_g_unichar_toupper (void) +{ + if (g_unichar_toupper (0) != 0) + return FAILED ("#0"); + if (g_unichar_toupper ('a') != 'A') + return FAILED ("#1"); + if (g_unichar_toupper ('1') != '1') + return FAILED ("#2"); + if (g_unichar_toupper (0x1C4) != 0x1C4) + return FAILED ("#3"); + if (g_unichar_toupper (0x1F2) != 0x1F1) + return FAILED ("#4"); + if (g_unichar_toupper (0x1F3) != 0x1F1) + return FAILED ("#5"); + if (g_unichar_toupper (0xFFFF) != 0xFFFF) + return FAILED ("#6"); + if (g_unichar_toupper (0x10428) != 0x10400) + return FAILED ("#7"); + return NULL; +} + +/* + * g_unichar_tolower + */ +static RESULT +test_g_unichar_tolower (void) +{ + if (g_unichar_tolower (0) != 0) + return FAILED ("#0"); + if (g_unichar_tolower ('A') != 'a') + return FAILED ("#1"); + if (g_unichar_tolower ('1') != '1') + return FAILED ("#2"); + if (g_unichar_tolower (0x1C5) != 0x1C6) + return FAILED ("#3"); + if (g_unichar_tolower (0x1F1) != 0x1F3) + return FAILED ("#4"); + if (g_unichar_tolower (0x1F2) != 0x1F3) + return FAILED ("#5"); + if (g_unichar_tolower (0xFFFF) != 0xFFFF) + return FAILED ("#6"); + return NULL; +} + +/* + * g_unichar_totitle + */ +static RESULT +test_g_unichar_totitle (void) +{ + if (g_unichar_toupper (0) != 0) + return FAILED ("#0"); + if (g_unichar_totitle ('a') != 'A') + return FAILED ("#1"); + if (g_unichar_totitle ('1') != '1') + return FAILED ("#2"); + if (g_unichar_totitle (0x1C4) != 0x1C5) + return FAILED ("#3"); + if (g_unichar_totitle (0x1F2) != 0x1F2) + return FAILED ("#4"); + if (g_unichar_totitle (0x1F3) != 0x1F2) + return FAILED ("#5"); + if (g_unichar_toupper (0xFFFF) != 0xFFFF) + return FAILED ("#6"); + return NULL; +} + +static Test unicode_tests [] = { + {"g_unichar_type", test_g_unichar_type}, + {"g_unichar_toupper", test_g_unichar_toupper}, + {"g_unichar_tolower", test_g_unichar_tolower}, + {"g_unichar_totitle", test_g_unichar_totitle}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(unicode_tests_init, unicode_tests) diff --git a/mono/eglib/test/utf8.c b/mono/eglib/test/utf8.c new file mode 100644 index 0000000000..cc298b0d2c --- /dev/null +++ b/mono/eglib/test/utf8.c @@ -0,0 +1,932 @@ +#include + +#include "test.h" + +/* + * g_utf16_to_utf8 + */ + +static glong +compare_strings_utf8_pos (const gchar *expected, const gchar *actual, glong size) +{ + int i; + for (i = 0; i < size; i++) + if (expected [i] != actual [i]) + return i; + return -1; +} + +static RESULT +compare_strings_utf8_RESULT (const gchar *expected, const gchar *actual, glong size) +{ + glong ret; + + ret = compare_strings_utf8_pos (expected, actual, size); + if (ret < 0) + return OK; + return FAILED ("Incorrect output: expected '%s' but was '%s', differ at %d\n", expected, actual, ret); +} + +static void +gchar_to_gunichar2 (gunichar2 ret[], const gchar *src) +{ + int i; + + for (i = 0; src [i]; i++) + ret [i] = src [i]; + ret [i] = 0; +} + +static RESULT +compare_utf16_to_utf8_explicit (const gchar *expected, const gunichar2 *utf16, glong len_in, glong len_out, glong size_spec) +{ + GError *gerror; + gchar* ret; + RESULT result; + glong in_read, out_read; + + result = NULL; + + gerror = NULL; + ret = g_utf16_to_utf8 (utf16, size_spec, &in_read, &out_read, &gerror); + if (gerror) { + result = FAILED ("The error is %d %s\n", gerror->code, gerror->message); + g_error_free (gerror); + if (ret) + g_free (ret); + return result; + } + if (in_read != len_in) + result = FAILED ("Read size is incorrect: expected %d but was %d\n", len_in, in_read); + else if (out_read != len_out) + result = FAILED ("Converted size is incorrect: expected %d but was %d\n", len_out, out_read); + else + result = compare_strings_utf8_RESULT (expected, ret, len_out); + + g_free (ret); + if (result) + return result; + + return OK; +} + +static RESULT +compare_utf16_to_utf8 (const gchar *expected, const gunichar2 *utf16, glong len_in, glong len_out) +{ + RESULT result; + + result = compare_utf16_to_utf8_explicit (expected, utf16, len_in, len_out, -1); + if (result != OK) + return result; + return compare_utf16_to_utf8_explicit (expected, utf16, len_in, len_out, len_in); +} + +static RESULT +test_utf16_to_utf8 (void) +{ + const gchar *src0 = "", *src1 = "ABCDE", *src2 = "\xE5\xB9\xB4\x27", *src3 = "\xEF\xBC\xA1", *src4 = "\xEF\xBD\x81", *src5 = "\xF0\x90\x90\x80"; + gunichar2 str0 [] = {0}, str1 [6], str2 [] = {0x5E74, 39, 0}, str3 [] = {0xFF21, 0}, str4 [] = {0xFF41, 0}, str5 [] = {0xD801, 0xDC00, 0}; + RESULT result; + + gchar_to_gunichar2 (str1, src1); + + /* empty string */ + result = compare_utf16_to_utf8 (src0, str0, 0, 0); + if (result != OK) + return result; + + result = compare_utf16_to_utf8 (src1, str1, 5, 5); + if (result != OK) + return result; + result = compare_utf16_to_utf8 (src2, str2, 2, 4); + if (result != OK) + return result; + result = compare_utf16_to_utf8 (src3, str3, 1, 3); + if (result != OK) + return result; + result = compare_utf16_to_utf8 (src4, str4, 1, 3); + if (result != OK) + return result; + result = compare_utf16_to_utf8 (src5, str5, 2, 4); + if (result != OK) + return result; + + return OK; +} + +/* + * g_utf8_to_utf16 + */ + +static glong +compare_strings_utf16_pos (const gunichar2 *expected, const gunichar2 *actual, glong size) +{ + int i; + for (i = 0; i < size; i++) + if (expected [i] != actual [i]) + return i; + return -1; +} + +static RESULT +compare_strings_utf16_RESULT (const gunichar2 *expected, const gunichar2 *actual, glong size) +{ + glong ret; + + ret = compare_strings_utf16_pos (expected, actual, size); + if (ret < 0) + return OK; + return FAILED ("Incorrect output: expected '%s' but was '%s', differ at %d ('%c' x '%c')\n", expected, actual, ret, expected [ret], actual [ret]); +} + +#if !defined(EGLIB_TESTS) +#define eg_utf8_to_utf16_with_nuls g_utf8_to_utf16 +#endif + +static RESULT +compare_utf8_to_utf16_explicit (const gunichar2 *expected, const gchar *utf8, glong len_in, glong len_out, glong size_spec, gboolean include_nuls) +{ + GError *gerror; + gunichar2* ret; + RESULT result; + glong in_read, out_read; + + result = NULL; + + gerror = NULL; + if (include_nuls) + ret = eg_utf8_to_utf16_with_nuls (utf8, size_spec, &in_read, &out_read, &gerror); + else + ret = g_utf8_to_utf16 (utf8, size_spec, &in_read, &out_read, &gerror); + + if (gerror) { + result = FAILED ("The error is %d %s\n", gerror->code, gerror->message); + g_error_free (gerror); + if (ret) + g_free (ret); + return result; + } + if (in_read != len_in) + result = FAILED ("Read size is incorrect: expected %d but was %d\n", len_in, in_read); + else if (out_read != len_out) + result = FAILED ("Converted size is incorrect: expected %d but was %d\n", len_out, out_read); + else + result = compare_strings_utf16_RESULT (expected, ret, len_out); + + g_free (ret); + if (result) + return result; + + return OK; +} + +static RESULT +compare_utf8_to_utf16_general (const gunichar2 *expected, const gchar *utf8, glong len_in, glong len_out, gboolean include_nuls) +{ + RESULT result; + + result = compare_utf8_to_utf16_explicit (expected, utf8, len_in, len_out, -1, include_nuls); + if (result != OK) + return result; + return compare_utf8_to_utf16_explicit (expected, utf8, len_in, len_out, len_in, include_nuls); +} + +static RESULT +compare_utf8_to_utf16 (const gunichar2 *expected, const gchar *utf8, glong len_in, glong len_out) +{ + return compare_utf8_to_utf16_general (expected, utf8, len_in, len_out, FALSE); +} + +static RESULT +compare_utf8_to_utf16_with_nuls (const gunichar2 *expected, const gchar *utf8, glong len_in, glong len_out) +{ + return compare_utf8_to_utf16_explicit (expected, utf8, len_in, len_out, len_in, TRUE); +} + +static RESULT +test_utf8_seq (void) +{ + const gchar *src = "\xE5\xB9\xB4\x27"; + glong in_read, out_read; + //gunichar2 expected [6]; + GError *gerror = NULL; + gunichar2 *dst; + + //printf ("got: %s\n", src); + dst = g_utf8_to_utf16 (src, (glong)strlen (src), &in_read, &out_read, &gerror); + if (gerror != NULL){ + return gerror->message; + } + + if (in_read != 4) { + return FAILED ("in_read is expected to be 4 but was %d\n", in_read); + } + if (out_read != 2) { + return FAILED ("out_read is expected to be 2 but was %d\n", out_read); + } + g_free (dst); + + return OK; +} + +static RESULT +test_utf8_to_utf16 (void) +{ + const gchar *src0 = "", *src1 = "ABCDE", *src2 = "\xE5\xB9\xB4\x27", *src3 = "\xEF\xBC\xA1", *src4 = "\xEF\xBD\x81"; + gunichar2 str0 [] = {0}, str1 [6], str2 [] = {0x5E74, 39, 0}, str3 [] = {0xFF21, 0}, str4 [] = {0xFF41, 0}; + RESULT result; + + gchar_to_gunichar2 (str1, src1); + + /* empty string */ + result = compare_utf8_to_utf16 (str0, src0, 0, 0); + if (result != OK) + return result; + + result = compare_utf8_to_utf16 (str1, src1, 5, 5); + if (result != OK) + return result; + result = compare_utf8_to_utf16 (str2, src2, 4, 2); + if (result != OK) + return result; + result = compare_utf8_to_utf16 (str3, src3, 3, 1); + if (result != OK) + return result; + result = compare_utf8_to_utf16 (str4, src4, 3, 1); + if (result != OK) + return result; + + return OK; +} + +static RESULT +test_utf8_to_utf16_with_nuls (void) +{ + const gchar *src0 = "", *src1 = "AB\0DE", *src2 = "\xE5\xB9\xB4\x27", *src3 = "\xEF\xBC\xA1", *src4 = "\xEF\xBD\x81"; + gunichar2 str0 [] = {0}, str1 [] = {'A', 'B', 0, 'D', 'E', 0}, str2 [] = {0x5E74, 39, 0}, str3 [] = {0xFF21, 0}, str4 [] = {0xFF41, 0}; + RESULT result; + +#if !defined(EGLIB_TESTS) + return OK; +#endif + + /* implicit length is forbidden */ + if (eg_utf8_to_utf16_with_nuls (src1, -1, NULL, NULL, NULL) != NULL) + return FAILED ("explicit nulls must fail with -1 length\n"); + + /* empty string */ + result = compare_utf8_to_utf16_with_nuls (str0, src0, 0, 0); + if (result != OK) + return result; + + result = compare_utf8_to_utf16_with_nuls (str1, src1, 5, 5); + if (result != OK) + return result; + result = compare_utf8_to_utf16_with_nuls (str2, src2, 4, 2); + if (result != OK) + return result; + result = compare_utf8_to_utf16_with_nuls (str3, src3, 3, 1); + if (result != OK) + return result; + result = compare_utf8_to_utf16_with_nuls (str4, src4, 3, 1); + if (result != OK) + return result; + + return OK; +} + +typedef struct { + char *content; + size_t length; +} convert_result_t; + +static RESULT +test_convert (void) +{ + static const char *charsets[] = { "UTF-8", "UTF-16LE", "UTF-16BE", "UTF-32LE", "UTF-32BE" }; + gsize length, converted_length, n; + char *content, *converted, *path; + convert_result_t **expected; + GError *err = NULL; + const char *srcdir; + gboolean loaded; + guint i, j, k; + char c; + + if (!(srcdir = getenv ("srcdir")) && !(srcdir = getenv ("PWD"))) + return FAILED ("srcdir not defined!"); + + expected = g_malloc (sizeof (convert_result_t *) * G_N_ELEMENTS (charsets)); + + /* first load all our test samples... */ + for (i = 0; i < G_N_ELEMENTS (charsets); i++) { + path = g_strdup_printf ("%s%c%s.txt", srcdir, G_DIR_SEPARATOR, charsets[i]); + loaded = g_file_get_contents (path, &content, &length, &err); + g_free (path); + + if (!loaded) { + for (j = 0; j < i; j++) { + g_free (expected[j]->content); + g_free (expected[j]); + } + + g_free (expected); + + return FAILED ("Failed to load content for %s: %s", charsets[i], err->message); + } + + expected[i] = g_malloc (sizeof (convert_result_t)); + expected[i]->content = content; + expected[i]->length = length; + } + + /* test conversion from every charset to every other charset */ + for (i = 0; i < G_N_ELEMENTS (charsets); i++) { + for (j = 0; j < G_N_ELEMENTS (charsets); j++) { + converted = g_convert (expected[i]->content, expected[i]->length, charsets[j], + charsets[i], NULL, &converted_length, NULL); + + if (converted == NULL) { + for (k = 0; k < G_N_ELEMENTS (charsets); k++) { + g_free (expected[k]->content); + g_free (expected[k]); + } + + g_free (expected); + + return FAILED ("Failed to convert from %s to %s: NULL", charsets[i], charsets[j]); + } + + if (converted_length != expected[j]->length) { + length = expected[j]->length; + + for (k = 0; k < G_N_ELEMENTS (charsets); k++) { + g_free (expected[k]->content); + g_free (expected[k]); + } + + g_free (converted); + g_free (expected); + + return FAILED ("Failed to convert from %s to %s: expected %u bytes, got %u", + charsets[i], charsets[j], length, converted_length); + } + + for (n = 0; n < converted_length; n++) { + if (converted[n] != expected[j]->content[n]) { + c = expected[j]->content[n]; + + for (k = 0; k < G_N_ELEMENTS (charsets); k++) { + g_free (expected[k]->content); + g_free (expected[k]); + } + + g_free (converted); + g_free (expected); + + return FAILED ("Failed to convert from %s to %s: expected 0x%x at offset %u, got 0x%x", + charsets[i], charsets[j], c, n, converted[n]); + } + } + + g_free (converted); + } + } + + for (k = 0; k < G_N_ELEMENTS (charsets); k++) { + g_free (expected[k]->content); + g_free (expected[k]); + } + + g_free (expected); + + return OK; +} + +static RESULT +test_xdigit (void) +{ + static char test_chars[] = { + '0', '1', '2', '3', '4', + '5', '6', '7', '8', '9', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', + 'A', 'B', 'C', 'D', 'E', 'F', 'G'}; + static gint32 test_values[] = { + 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, -1, + 10, 11, 12, 13, 14, 15, -1}; + + int i =0; + + for (i = 0; i < sizeof(test_chars); i++) + if (g_unichar_xdigit_value ((gunichar)test_chars[i]) != test_values[i]) + return FAILED("Incorrect value %d at index %d", test_values[i], i); + + return OK; +} + +static RESULT +ucs4_to_utf16_check_result (const gunichar2 *result_str, const gunichar2 *expected_str, + glong result_items_read, glong expected_items_read, + glong result_items_written, glong expected_items_written, + GError* result_error, gboolean expect_error) +{ + glong i; + if (result_items_read != expected_items_read) + return FAILED("Incorrect number of items read; expected %d, got %d", expected_items_read, result_items_read); + if (result_items_written != expected_items_written) + return FAILED("Incorrect number of items written; expected %d, got %d", expected_items_written, result_items_written); + if (result_error && !expect_error) + return FAILED("There should not be an error code."); + if (!result_error && expect_error) + return FAILED("Unexpected error object."); + if (expect_error && result_str) + return FAILED("NULL should be returned when an error occurs."); + if (!expect_error && !result_str) + return FAILED("When no error occurs NULL should not be returned."); + for (i=0; i 4) + return FAILED ("Word1 has gone past its expected length"); + if (*ptr != word1ExpectedValues[count]) + return FAILED ("Word1 has an incorrect next_char at index %i", count); + ptr = g_utf8_next_char (ptr); + count++; + } + + //Test word2 + count = 0; + ptr = word2; + while (*ptr != 0) { + if (count > 4) + return FAILED ("Word2 has gone past its expected length"); + if (*ptr != word2ExpectedValues[count]) + return FAILED ("Word2 has an incorrect next_char at index %i", count); + ptr = g_utf8_next_char (ptr); + count++; + } + + return OK; +} + +static RESULT +test_utf8_validate (void) +{ + gchar invalidWord1 [] = {0xC3, 0x82, 0xC1,0x90,'\0'}; //Invalid, 1nd oct Can't be 0xC0 or 0xC1 + gchar invalidWord2 [] = {0xC1, 0x89, 0x60, '\0'}; //Invalid, 1st oct can not be 0xC1 + gchar invalidWord3 [] = {0xC2, 0x45,0xE1, 0x81, 0x83,0x58,'\0'}; //Invalid, oct after 0xC2 must be > 0x80 + + gchar validWord1 [] = {0xC2, 0x82, 0xC3,0xA0,'\0'}; //Valid + gchar validWord2 [] = {0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,0xF1, 0x82, 0x82, 0x82,'\0'}; //Valid + + const gchar* end; + gboolean retVal = g_utf8_validate (invalidWord1, -1, &end); + if (retVal != FALSE) + return FAILED ("Expected invalidWord1 to be invalid"); + if (end != &invalidWord1 [2]) + return FAILED ("Expected end parameter to be pointing to invalidWord1[2]"); + + end = NULL; + retVal = g_utf8_validate (invalidWord2, -1, &end); + if (retVal != FALSE) + return FAILED ("Expected invalidWord2 to be invalid"); + if (end != &invalidWord2 [0]) + return FAILED ("Expected end parameter to be pointing to invalidWord2[0]"); + + end = NULL; + retVal = g_utf8_validate (invalidWord3, -1, &end); + if (retVal != FALSE) + return FAILED ("Expected invalidWord3 to be invalid"); + if (end != &invalidWord3 [0]) + return FAILED ("Expected end parameter to be pointing to invalidWord3[1]"); + + end = NULL; + retVal = g_utf8_validate (validWord1, -1, &end); + if (retVal != TRUE) + return FAILED ("Expected validWord1 to be valid"); + if (end != &validWord1 [4]) + return FAILED ("Expected end parameter to be pointing to validWord1[4]"); + + end = NULL; + retVal = g_utf8_validate (validWord2, -1, &end); + if (retVal != TRUE) + return FAILED ("Expected validWord2 to be valid"); + if (end != &validWord2 [11]) + return FAILED ("Expected end parameter to be pointing to validWord2[11]"); + return OK; +} + +static glong +utf8_byteslen (const gchar *src) +{ + int i = 0; + do { + if (src [i] == '\0') + return i; + i++; + } while (TRUE); +} + +static RESULT +test_utf8_strcase_each (const gchar *src, const gchar *expected, gboolean strup) +{ + gchar *tmp; + glong len, len2; + RESULT r; + + len = utf8_byteslen (src); + tmp = strup ? g_utf8_strup (src, len) : g_utf8_strdown (src, len); + len2 = utf8_byteslen (tmp); + r = compare_strings_utf8_RESULT (expected, tmp, len < len2 ? len2 : len); + g_free (tmp); + return r; +} + +static RESULT +test_utf8_strup_each (const gchar *src, const gchar *expected) +{ + return test_utf8_strcase_each (src, expected, TRUE); +} + +static RESULT +test_utf8_strdown_each (const gchar *src, const gchar *expected) +{ + return test_utf8_strcase_each (src, expected, FALSE); +} + +/* + * g_utf8_strup + */ +static RESULT +test_utf8_strup (void) +{ + RESULT r; + + if ((r = test_utf8_strup_each ("aBc", "ABC")) != OK) + return r; + if ((r = test_utf8_strup_each ("x86-64", "X86-64")) != OK) + return r; + // U+3B1 U+392 -> U+391 U+392 + if ((r = test_utf8_strup_each ("\xCE\xB1\xCE\x92", "\xCE\x91\xCE\x92")) != OK) + return r; + // U+FF21 -> U+FF21 + if ((r = test_utf8_strup_each ("\xEF\xBC\xA1", "\xEF\xBC\xA1")) != OK) + return r; + // U+FF41 -> U+FF21 + if ((r = test_utf8_strup_each ("\xEF\xBD\x81", "\xEF\xBC\xA1")) != OK) + return r; + // U+10428 -> U+10400 + if ((r = test_utf8_strup_each ("\xF0\x90\x90\xA8", "\xF0\x90\x90\x80")) != OK) + return r; + + return OK; +} + +/* + * g_utf8_strdown + */ +static RESULT +test_utf8_strdown (void) +{ + RESULT r; + + if ((r = test_utf8_strdown_each ("aBc", "abc")) != OK) + return r; + if ((r = test_utf8_strdown_each ("X86-64", "x86-64")) != OK) + return r; + // U+391 U+3B2 -> U+3B1 U+3B2 + if ((r = test_utf8_strdown_each ("\xCE\x91\xCE\xB2", "\xCE\xB1\xCE\xB2")) != OK) + return r; +/* + // U+FF41 -> U+FF41 + if ((r = test_utf8_strdown_each ("\xEF\xBC\x81", "\xEF\xBC\x81")) != OK) + return r; + // U+FF21 -> U+FF41 + if ((r = test_utf8_strdown_each ("\xEF\xBC\xA1", "\xEF\xBD\x81")) != OK) + return r; + // U+10400 -> U+10428 + if ((r = test_utf8_strdown_each ("\xF0\x90\x90\x80", "\xF0\x90\x90\xA8")) != OK) + return r; +*/ + return OK; +} + +/* + * test initialization + */ + +static Test utf8_tests [] = { + {"g_utf16_to_utf8", test_utf16_to_utf8}, + {"g_utf8_to_utf16", test_utf8_to_utf16}, + {"g_utf8_to_utf16_with_nuls", test_utf8_to_utf16_with_nuls}, + {"g_utf8_seq", test_utf8_seq}, + {"g_convert", test_convert }, + {"g_unichar_xdigit_value", test_xdigit }, + {"g_ucs4_to_utf16", test_ucs4_to_utf16 }, + {"g_utf16_to_ucs4", test_utf16_to_ucs4 }, + {"g_utf8_strlen", test_utf8_strlen }, + {"g_utf8_get_char", test_utf8_get_char }, + {"g_utf8_next_char", test_utf8_next_char }, + {"g_utf8_validate", test_utf8_validate }, + {"g_utf8_strup", test_utf8_strup}, + {"g_utf8_strdown", test_utf8_strdown}, + {NULL, NULL} +}; + +DEFINE_TEST_GROUP_INIT(utf8_tests_init, utf8_tests) diff --git a/mono/metadata/Makefile.am b/mono/metadata/Makefile.am index 2e3dcc632f..9b9cba7d66 100644 --- a/mono/metadata/Makefile.am +++ b/mono/metadata/Makefile.am @@ -64,10 +64,6 @@ endif glib_libs = $(top_builddir)/mono/eglib/libeglib.la -if HOST_ANDROID -platform_sources += ../../support/libm/complex.c -endif - if HOST_WASM platform_sources += threadpool-worker-wasm.c else @@ -94,7 +90,45 @@ if !ENABLE_ILGEN ilgen_libraries = libmono-ilgen.la endif -noinst_LTLIBRARIES = libmonoruntime-config.la $(boehm_libraries) $(sgen_libraries) +support_sources=empty.c + +if ENABLE_MONOTOUCH +support_sources += ../../support/zlib-helper.c +else +if ENABLE_MONODROID +support_sources += \ + ../../support/nl.c \ + ../../support/zlib-helper.c +if HAVE_ZLIB +# See libmonoruntime_support_la_LDFLAGS +else +support_sources += \ + ../../support/adler32.c \ + ../../support/compress.c \ + ../../support/crc32.c \ + ../../support/crc32.h \ + ../../support/deflate.c \ + ../../support/deflate.h \ + ../../support/infback.c \ + ../../support/inffast.c \ + ../../support/inffast.h \ + ../../support/inffixed.h \ + ../../support/inflate.c \ + ../../support/inflate.h \ + ../../support/inftrees.c \ + ../../support/inftrees.h \ + ../../support/trees.c \ + ../../support/trees.h \ + ../../support/uncompr.c \ + ../../support/zconf.h \ + ../../support/zlib.h \ + ../../support/zutil.c \ + ../../support/zutil.h +endif +endif +endif + +noinst_LTLIBRARIES = libmonoruntime-config.la libmonoruntime-support.la $(boehm_libraries) $(sgen_libraries) lib_LTLIBRARIES = $(icall_table_libraries) $(ilgen_libraries) @@ -116,7 +150,17 @@ mono-config-dirs.lo: Makefile libmonoruntime_config_la_SOURCES = \ mono-config-dirs.h \ mono-config-dirs.c -libmonoruntime_config_la_CPPFLAGS = $(AM_CPPFLAGS) -DMONO_BINDIR=\"$(bindir)/\" -DMONO_ASSEMBLIES=\"$(assembliesdir)\" -DMONO_CFG_DIR=\"$(confdir)\" -DMONO_RELOC_LIBDIR=\"../$(reloc_libdir)\" +libmonoruntime_config_la_CPPFLAGS = $(AM_CPPFLAGS) -DMONO_BINDIR=\"$(bindir)/\" -DMONO_ASSEMBLIES=\"$(assembliesdir)\" -DMONO_CFG_DIR=\"$(confdir)\" -DMONO_RELOC_LIBDIR=\"../$(reloc_libdir)\" @CXX_ADD_CFLAGS@ + +# +# This library is only used to compile the required support/ sources. We can't use them directly in platform_sources +# because they aren't C++ compatible. +# +libmonoruntime_support_la_SOURCES = $(support_sources) +libmonoruntime_support_la_CFLAGS = $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) +if HAVE_ZLIB +libmonoruntime_support_la_LDFLAGS = -lz +endif # # This library contains the icall tables if the runtime was configured with --disable-icall-tables @@ -152,43 +196,6 @@ libmono_ilgen_la_LIBADD = $(glib_libs) ../utils/libmonoutils.la ../sgen/libmonos endif endif -if !HOST_WIN32 -if !HOST_WASM -if !ENABLE_MONODROID -if !ENABLE_MONOTOUCH -lib_LTLIBRARIES += libmono-system-native.la -endif -endif -endif -endif - -libmono_system_native_la_SOURCES = \ - pal_config.h \ - ../../external/corefx/src/Native/Unix/Common/pal_compiler.h \ - ../../external/corefx/src/Native/Unix/Common/pal_safecrt.h \ - ../../external/corefx/src/Native/Unix/Common/pal_types.h \ - ../../external/corefx/src/Native/Unix/Common/pal_utilities.h \ - ../../external/corefx/src/Native/Unix/System.Native/pal_errno.c \ - ../../external/corefx/src/Native/Unix/System.Native/pal_errno.h \ - ../../external/corefx/src/Native/Unix/System.Native/pal_io.c \ - ../../external/corefx/src/Native/Unix/System.Native/pal_io.h \ - ../../external/corefx/src/Native/Unix/System.Native/pal_maphardwaretype.c \ - ../../external/corefx/src/Native/Unix/System.Native/pal_maphardwaretype.h \ - ../../external/corefx/src/Native/Unix/System.Native/pal_memory.c \ - ../../external/corefx/src/Native/Unix/System.Native/pal_memory.h \ - ../../external/corefx/src/Native/Unix/System.Native/pal_networking.c \ - ../../external/corefx/src/Native/Unix/System.Native/pal_networking.h \ - ../../external/corefx/src/Native/Unix/System.Native/pal_networkstatistics.c \ - ../../external/corefx/src/Native/Unix/System.Native/pal_networkstatistics.h \ - ../../external/corefx/src/Native/Unix/System.Native/pal_tcpstate.c \ - ../../external/corefx/src/Native/Unix/System.Native/pal_tcpstate.h \ - ../../external/corefx/src/Native/Unix/System.Native/pal_random.c \ - ../../external/corefx/src/Native/Unix/System.Native/pal_random.h \ - pal-icalls.h \ - pal-icalls.c - -# Add back CXX_REMOVE_CFLAGS to keep this as C until/unless https://github.com/dotnet/corefx/pull/31342. -libmono_system_native_la_CFLAGS = -I$(abs_top_srcdir)/external/corefx/src/Native/Unix/Common -I$(abs_top_srcdir)/external/corefx/src/Native/Unix/System.Native -Wno-typedef-redefinition @CXX_REMOVE_CFLAGS@ CLEANFILES = mono-bundle.stamp @@ -269,6 +276,7 @@ common_sources = \ image-internals.h \ jit-info.c \ loader.c \ + loader-internals.h \ locales.c \ locales.h \ lock-tracer.c \ @@ -336,7 +344,6 @@ common_sources = \ security-manager.h \ string-icalls.c \ string-icalls.h \ - sysmath.h \ sysmath.c \ tabledefs.h \ threads.c \ @@ -366,6 +373,7 @@ common_sources = \ seq-points-data.h \ seq-points-data.c \ handle.c \ + handle-decl.h \ handle.h \ w32mutex.h \ w32semaphore.h \ @@ -384,7 +392,8 @@ common_sources = \ fdhandle.h \ fdhandle.c \ callspec.h \ - callspec.c + callspec.c \ + abi.c # These source files have compile time dependencies on GC code gc_dependent_sources = \ @@ -416,12 +425,12 @@ CFLAGS := $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) libmonoruntime_la_SOURCES = $(common_sources) $(icall_tables_sources) $(ilgen_sources) $(gc_dependent_sources) $(null_gc_sources) $(boehm_sources) # Add CXX_ADD_CFLAGS per-library until/unless https://github.com/dotnet/corefx/pull/31342. libmonoruntime_la_CFLAGS = $(BOEHM_DEFINES) @CXX_ADD_CFLAGS@ -libmonoruntime_la_LIBADD = libmonoruntime-config.la +libmonoruntime_la_LIBADD = libmonoruntime-config.la libmonoruntime-support.la libmonoruntimesgen_la_SOURCES = $(common_sources) $(icall_tables_sources) $(ilgen_sources) $(gc_dependent_sources) $(sgen_sources) # Add CXX_ADD_CFLAGS per-library until/unless https://github.com/dotnet/corefx/pull/31342. libmonoruntimesgen_la_CFLAGS = $(SGEN_DEFINES) @CXX_ADD_CFLAGS@ -libmonoruntimesgen_la_LIBADD = libmonoruntime-config.la +libmonoruntimesgen_la_LIBADD = libmonoruntime-config.la libmonoruntime-support.la libmonoruntimeincludedir = $(includedir)/mono-$(API_VER)/mono/metadata diff --git a/mono/metadata/Makefile.in.REMOVED.git-id b/mono/metadata/Makefile.in.REMOVED.git-id index 401f54dd41..d8b7f11f05 100644 --- a/mono/metadata/Makefile.in.REMOVED.git-id +++ b/mono/metadata/Makefile.in.REMOVED.git-id @@ -1 +1 @@ -0520a7641867371318fe0b6288ff1dc9631904da \ No newline at end of file +c9bbecd23a10be4082498e293ae36a5302bc8beb \ No newline at end of file diff --git a/mono/metadata/abi-details.h b/mono/metadata/abi-details.h index 6d6bafde3c..37566f4330 100644 --- a/mono/metadata/abi-details.h +++ b/mono/metadata/abi-details.h @@ -23,29 +23,30 @@ * is given by the --with-cross-offsets= configure argument. */ -#define MONO_ABI_ALIGNOF(type) MONO_ALIGN_ ## type -#define MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(type) typedef struct { char c; type x; } Mono_Align_Struct_ ##type; -#define MONO_CURRENT_ABI_ALIGNOF(type) ((int)G_STRUCT_OFFSET(Mono_Align_Struct_ ##type, x)) -#define MONO_ABI_SIZEOF(type) MONO_SIZEOF_ ## type +typedef enum { + MONO_ALIGN_gint8, + MONO_ALIGN_gint16, + MONO_ALIGN_gint32, + MONO_ALIGN_gint64, + MONO_ALIGN_float, + MONO_ALIGN_double, + MONO_ALIGN_gpointer, + MONO_ALIGN_COUNT +} CoreTypeAlign; + +int mono_abi_alignment (CoreTypeAlign type); + +#define MONO_ABI_ALIGNOF(type) mono_abi_alignment (MONO_ALIGN_ ## type) +#define MONO_ABI_SIZEOF(type) (MONO_STRUCT_SIZE (type)) #define MONO_CURRENT_ABI_SIZEOF(type) ((int)sizeof(type)) -#undef DECL_OFFSET #undef DECL_OFFSET2 #define DECL_OFFSET(struct,field) MONO_OFFSET_ ## struct ## _ ## field = -1, #define DECL_OFFSET2(struct,field,offset) MONO_OFFSET_ ## struct ## _ ## field = offset, -#define DECL_ALIGN(type) MONO_ALIGN_ ##type = MONO_CURRENT_ABI_ALIGNOF (type), -#define DECL_ALIGN2(type,size) MONO_ALIGN_ ##type = size, -#define DECL_SIZE(type) MONO_SIZEOF_ ##type = MONO_CURRENT_ABI_SIZEOF (type), +#define DECL_ALIGN2(type,size) +#define DECL_SIZE(type) MONO_SIZEOF_ ##type = -1, #define DECL_SIZE2(type,size) MONO_SIZEOF_ ##type = size, -/* Needed by MONO_CURRENT_ABI_ALIGNOF */ -MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(gint8) -MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(gint16) -MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(gint32) -MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(gint64) -MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(float) -MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(double) -MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(gpointer) enum { #include "object-offsets.h" @@ -53,14 +54,17 @@ enum { #ifdef USED_CROSS_COMPILER_OFFSETS #define MONO_STRUCT_OFFSET(struct,field) MONO_OFFSET_ ## struct ## _ ## field +#define MONO_STRUCT_SIZE(struct) MONO_SIZEOF_ ## struct #else #if defined(HAS_CROSS_COMPILER_OFFSETS) || defined(MONO_CROSS_COMPILE) #define MONO_STRUCT_OFFSET(struct,field) (MONO_OFFSET_ ## struct ## _ ## field == -1, G_STRUCT_OFFSET (struct,field)) +#define MONO_STRUCT_SIZE(struct) (MONO_SIZEOF_ ## struct == -1, (int)sizeof(struct)) #else #define MONO_STRUCT_OFFSET(struct,field) G_STRUCT_OFFSET (struct,field) +#define MONO_STRUCT_SIZE(struct) ((int)sizeof(struct)) #endif #endif +// #define MONO_SIZEOF_MonoObject (2 * MONO_ABI_SIZEOF(gpointer)) #define MONO_SIZEOF_MonoObject (2 * MONO_SIZEOF_gpointer) - #endif diff --git a/mono/metadata/abi.c b/mono/metadata/abi.c new file mode 100644 index 0000000000..291f9a3201 --- /dev/null +++ b/mono/metadata/abi.c @@ -0,0 +1,75 @@ +#include + +#include +#include + + +typedef struct { + const char alignment [MONO_ALIGN_COUNT]; +} AbiDetails; + + +#define DECLARE_ABI_DETAILS(I8, I16, I32, I64, F32, F64, PTR) \ +const static AbiDetails mono_abi_details = { \ + { I8, I16, I32, I64, F32, F64, PTR } \ +}; \ + +#ifdef MONO_CROSS_COMPILE + +#if TARGET_WASM + +DECLARE_ABI_DETAILS (1, 2, 4, 8, 4, 8, 4) + +#else + +#define DECL_OFFSET(struct,field) +#define DECL_OFFSET2(struct,field,offset) +#define DECL_ALIGN2(type,size) MONO_ALIGN_value_ ##type = size, +#define DECL_SIZE(type) +#define DECL_SIZE2(type,size) + +enum { +#include "object-offsets.h" +}; + +DECLARE_ABI_DETAILS ( + MONO_ALIGN_value_gint8, + MONO_ALIGN_value_gint16, + MONO_ALIGN_value_gint32, + MONO_ALIGN_value_gint64, + MONO_ALIGN_value_float, + MONO_ALIGN_value_double, + MONO_ALIGN_value_gpointer) + +#endif + +#else + +#define MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(type) typedef struct { char c; type x; } Mono_Align_Struct_ ##type; +#define MONO_CURRENT_ABI_ALIGNOF(type) ((int)G_STRUCT_OFFSET(Mono_Align_Struct_ ##type, x)) + +/* Needed by MONO_CURRENT_ABI_ALIGNOF */ +MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(gint8) +MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(gint16) +MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(gint32) +MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(gint64) +MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(float) +MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(double) +MONO_CURRENT_ABI_ALIGNOF_TYPEDEF(gpointer) + +DECLARE_ABI_DETAILS ( + MONO_CURRENT_ABI_ALIGNOF (gint8), + MONO_CURRENT_ABI_ALIGNOF (gint16), + MONO_CURRENT_ABI_ALIGNOF (gint32), + MONO_CURRENT_ABI_ALIGNOF (gint64), + MONO_CURRENT_ABI_ALIGNOF (float), + MONO_CURRENT_ABI_ALIGNOF (double), + MONO_CURRENT_ABI_ALIGNOF (gpointer)) + +#endif + +int +mono_abi_alignment (CoreTypeAlign type) +{ + return mono_abi_details.alignment [type]; +} diff --git a/mono/metadata/appdomain-icalls.h b/mono/metadata/appdomain-icalls.h index d67c51a6e1..d3c5185ad0 100644 --- a/mono/metadata/appdomain-icalls.h +++ b/mono/metadata/appdomain-icalls.h @@ -12,6 +12,7 @@ #include #include #include +#include "reflection-internals.h" ICALL_EXPORT MonoAppDomainHandle diff --git a/mono/metadata/appdomain.c b/mono/metadata/appdomain.c index d1bed3444a..d081a161ff 100644 --- a/mono/metadata/appdomain.c +++ b/mono/metadata/appdomain.c @@ -274,7 +274,6 @@ mono_runtime_init_checked (MonoDomain *domain, MonoThreadStartCB start_cb, MonoT MonoAppDomainSetupHandle setup; MonoAppDomainHandle ad; - MonoClass *klass; error_init (error); @@ -295,18 +294,20 @@ mono_runtime_init_checked (MonoDomain *domain, MonoThreadStartCB start_cb, MonoT mono_thread_init (start_cb, attach_cb); - klass = mono_class_load_from_name (mono_defaults.corlib, "System", "AppDomainSetup"); - setup = MONO_HANDLE_CAST (MonoAppDomainSetup, mono_object_new_pinned_handle (domain, klass, error)); - goto_if_nok (error, exit); + if (!mono_runtime_get_no_exec ()) { + MonoClass *klass = mono_class_load_from_name (mono_defaults.corlib, "System", "AppDomainSetup"); + setup = MONO_HANDLE_CAST (MonoAppDomainSetup, mono_object_new_pinned_handle (domain, klass, error)); + goto_if_nok (error, exit); - klass = mono_class_load_from_name (mono_defaults.corlib, "System", "AppDomain"); + klass = mono_class_load_from_name (mono_defaults.corlib, "System", "AppDomain"); - ad = MONO_HANDLE_CAST (MonoAppDomain, mono_object_new_pinned_handle (domain, klass, error)); - goto_if_nok (error, exit); + ad = MONO_HANDLE_CAST (MonoAppDomain, mono_object_new_pinned_handle (domain, klass, error)); + goto_if_nok (error, exit); - MONO_HANDLE_SETVAL (ad, data, MonoDomain*, domain); - domain->domain = MONO_HANDLE_RAW (ad); - domain->setup = MONO_HANDLE_RAW (setup); + MONO_HANDLE_SETVAL (ad, data, MonoDomain*, domain); + domain->domain = MONO_HANDLE_RAW (ad); + domain->setup = MONO_HANDLE_RAW (setup); + } mono_thread_attach (domain); @@ -342,6 +343,9 @@ exit: static void mono_context_set_default_context (MonoDomain *domain) { + if (mono_runtime_get_no_exec ()) + return; + HANDLE_FUNCTION_ENTER (); mono_context_set_handle (MONO_HANDLE_NEW (MonoAppContext, domain->default_context)); HANDLE_FUNCTION_RETURN (); @@ -350,36 +354,30 @@ mono_context_set_default_context (MonoDomain *domain) static char* mono_get_corlib_version (void) { - // Return NULL for errors, including the old integer form, else - // a string to be passed to g_free (or typically just exit). - - HANDLE_FUNCTION_ENTER (); ERROR_DECL (error); MonoClass *klass; MonoClassField *field; - MonoObjectHandle value; - char *result = NULL; klass = mono_class_load_from_name (mono_defaults.corlib, "System", "Environment"); mono_class_init (klass); field = mono_class_get_field_from_name_full (klass, "mono_corlib_version", NULL); if (!field) - goto exit; + return NULL; - if (! (field->type->attrs & FIELD_ATTRIBUTE_STATIC)) - goto exit; + if (! (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_LITERAL))) + return NULL; - value = mono_static_field_get_value_handle (mono_domain_get (), field, error); + char *value; + MonoTypeEnum field_type; + const char *data = mono_class_get_field_default_value (field, &field_type); + mono_metadata_read_constant_value (data, field_type, &value, error); mono_error_assert_ok (error); - klass = mono_handle_class (value); - if (klass != mono_defaults.string_class) - goto exit; - result = mono_string_handle_to_utf8 (MONO_HANDLE_CAST (MonoString, value), error); + char *res = mono_string_from_blob (value, error); mono_error_assert_ok (error); -exit: - HANDLE_FUNCTION_RETURN_VAL (result); + + return res; } /** @@ -401,7 +399,7 @@ mono_check_corlib_version (void) static const char * mono_check_corlib_version_internal (void) { -#if defined(MONO_CROSS_COMPILE) && SIZEOF_VOID_P != TARGET_SIZEOF_VOID_P +#if defined(MONO_CROSS_COMPILE) /* Can't read the corlib version because we only have the target class layouts */ return NULL; #endif @@ -448,20 +446,26 @@ mono_context_init (MonoDomain *domain) void mono_context_init_checked (MonoDomain *domain, MonoError *error) { + HANDLE_FUNCTION_ENTER (); + MonoClass *klass; - MonoAppContext *context; + MonoAppContextHandle context; error_init (error); + if (mono_runtime_get_no_exec ()) + goto exit; klass = mono_class_load_from_name (mono_defaults.corlib, "System.Runtime.Remoting.Contexts", "Context"); - context = (MonoAppContext *) mono_object_new_pinned (domain, klass, error); - return_if_nok (error); + context = MONO_HANDLE_CAST (MonoAppContext, mono_object_new_pinned_handle (domain, klass, error)); + goto_if_nok (error, exit); - context->domain_id = domain->domain_id; - context->context_id = 0; + MONO_HANDLE_SETVAL (context, domain_id, intptr_t, domain->domain_id); + MONO_HANDLE_SETVAL (context, context_id, gint32, 0); mono_threads_register_app_context (context, error); mono_error_assert_ok (error); - domain->default_context = context; + domain->default_context = MONO_HANDLE_RAW (context); +exit: + HANDLE_FUNCTION_RETURN (); } /** @@ -560,7 +564,8 @@ mono_domain_create_appdomain_checked (char *friendly_name, char *configuration_f } MONO_HANDLE_SET (setup, configuration_file, config_file); - MonoAppDomainHandle ad = mono_domain_create_appdomain_internal (friendly_name, setup, error); + MonoAppDomainHandle ad; + ad = mono_domain_create_appdomain_internal (friendly_name, setup, error); goto_if_nok (error, leave); result = mono_domain_from_appdomain_handle (ad); @@ -600,7 +605,8 @@ mono_domain_set_config_checked (MonoDomain *domain, const char *base_dir, const MonoStringHandle base_dir_str = mono_string_new_handle (domain, base_dir, error); goto_if_nok (error, leave); MONO_HANDLE_SET (setup, application_base, base_dir_str); - MonoStringHandle config_file_name_str = mono_string_new_handle (domain, config_file_name, error); + MonoStringHandle config_file_name_str; + config_file_name_str = mono_string_new_handle (domain, config_file_name, error); goto_if_nok (error, leave); MONO_HANDLE_SET (setup, configuration_file, config_file_name_str); leave: @@ -692,7 +698,8 @@ mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetupHa MONO_PROFILER_RAISE (domain_name, (data, data->friendly_name)); - MonoStringHandle app_base = MONO_HANDLE_NEW_GET (MonoString, setup, application_base); + MonoStringHandle app_base; + app_base = MONO_HANDLE_NEW_GET (MonoString, setup, application_base); if (MONO_HANDLE_IS_NULL (app_base)) { /* Inherit from the root domain since MS.NET does this */ MonoDomain *root = mono_get_root_domain (); @@ -725,7 +732,8 @@ mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetupHa #ifndef DISABLE_SHADOW_COPY /*FIXME, guard this for when the debugger is not running */ - char *shadow_location = get_shadow_assembly_location_base (data, error); + char *shadow_location; + shadow_location = get_shadow_assembly_location_base (data, error); if (!mono_error_ok (error)) { g_free (data->friendly_name); goto leave; @@ -778,20 +786,29 @@ mono_domain_has_type_resolve (MonoDomain *domain) * \returns A \c MonoReflectionAssembly or NULL if not found */ MonoReflectionAssembly * -mono_domain_try_type_resolve (MonoDomain *domain, char *name, MonoObject *typebuilder) +mono_domain_try_type_resolve (MonoDomain *domain, char *name, MonoObject *typebuilder_raw) { + HANDLE_FUNCTION_ENTER (); + g_assert (domain); - g_assert (name || typebuilder); + g_assert (name || typebuilder_raw); ERROR_DECL (error); - error_init (error); - MonoReflectionAssembly * const ret = name - ? mono_domain_try_type_resolve_name (domain, name, error) - : mono_domain_try_type_resolve_typebuilder (domain, (MonoReflectionTypeBuilder *)typebuilder, error); + MonoReflectionAssemblyHandle ret = NULL_HANDLE_INIT; + if (name) { + MonoStringHandle name_handle = mono_string_new_handle (mono_domain_get (), name, error); + goto_if_nok (error, exit); + ret = mono_domain_try_type_resolve_name (domain, name_handle, error); + } else { + MONO_HANDLE_DCL (MonoObject, typebuilder); + ret = mono_domain_try_type_resolve_typebuilder (domain, MONO_HANDLE_CAST (MonoReflectionTypeBuilder, typebuilder), error); + } + +exit: mono_error_cleanup (error); - return ret; + HANDLE_FUNCTION_RETURN_OBJ (ret); } /** @@ -827,25 +844,35 @@ mono_class_get_appdomain_do_type_resolve_method (MonoError *error) * * \returns A \c MonoReflectionAssembly or NULL if not found */ -MonoReflectionAssembly * -mono_domain_try_type_resolve_name (MonoDomain *domain, const char *name, MonoError *error) +MonoReflectionAssemblyHandle +mono_domain_try_type_resolve_name (MonoDomain *domain, MonoStringHandle name, MonoError *error) { + HANDLE_FUNCTION_ENTER (); + + void *params [1] = { 0 }; + g_assert (domain); - g_assert (name); + g_assert (MONO_HANDLE_BOOL (name)); g_assert (error); error_init (error); - void *params [] = { mono_string_new_checked (mono_domain_get (), name, error) }; - return_val_if_nok (error, NULL); + MonoMethod *method; + method = mono_class_get_appdomain_do_type_resolve_method (error); + goto_if_nok (error, return_null); - MonoMethod * const method = mono_class_get_appdomain_do_type_resolve_method (error); - return_val_if_nok (error, NULL); + MonoAppDomainHandle appdomain; + appdomain = MONO_HANDLE_NEW (MonoAppDomain, domain->domain); - MonoObject * const ret = mono_runtime_invoke_checked (method, domain->domain, params, error); - return_val_if_nok (error, NULL); - - return (MonoReflectionAssembly *)ret; + MonoObjectHandle ret; + params [0] = MONO_HANDLE_RAW (name); + ret = mono_runtime_invoke_handle (method, MONO_HANDLE_CAST (MonoObject, appdomain), params, error); + goto_if_nok (error, return_null); + goto exit; +return_null: + ret = NULL_HANDLE; +exit: + HANDLE_FUNCTION_RETURN_REF (MonoReflectionAssembly, MONO_HANDLE_CAST (MonoReflectionAssembly, ret)); } /** @@ -856,24 +883,35 @@ mono_domain_try_type_resolve_name (MonoDomain *domain, const char *name, MonoErr * This routine invokes the internal \c System.AppDomain.DoTypeResolve and returns * the assembly that matches typebuilder.FullName. * - * \returns A \c MonoReflectionAssembly or NULL if not found + * \returns A \c MonoReflectionAssembly or NULL_HANDLE if not found */ -MonoReflectionAssembly * -mono_domain_try_type_resolve_typebuilder (MonoDomain *domain, MonoReflectionTypeBuilder *typebuilder, MonoError *error) +MonoReflectionAssemblyHandle +mono_domain_try_type_resolve_typebuilder (MonoDomain *domain, MonoReflectionTypeBuilderHandle typebuilder, MonoError *error) { + HANDLE_FUNCTION_ENTER (); + g_assert (domain); - g_assert (typebuilder); + g_assert (MONO_HANDLE_BOOL (typebuilder)); g_assert (error); error_init (error); MonoMethod * const method = mono_class_get_appdomain_do_type_resolve_method (error); - return_val_if_nok (error, NULL); + goto_if_nok (error, return_null); - MonoObject * const ret = mono_runtime_invoke_checked (method, domain->domain, (void**)&typebuilder, error); - return_val_if_nok (error, NULL); + MonoAppDomainHandle appdomain; + appdomain = MONO_HANDLE_NEW (MonoAppDomain, domain->domain); + void *args [1]; + args [0] = MONO_HANDLE_RAW (typebuilder); - return (MonoReflectionAssembly *)ret; + MonoObjectHandle ret; + ret = mono_runtime_invoke_handle (method, MONO_HANDLE_CAST (MonoObject, appdomain), args, error); + goto_if_nok (error, return_null); + goto exit; +return_null: + ret = NULL_HANDLE; +exit: + HANDLE_FUNCTION_RETURN_REF (MonoReflectionAssembly, MONO_HANDLE_CAST (MonoReflectionAssembly, ret)); } /** @@ -953,7 +991,7 @@ ves_icall_System_AppDomain_GetData (MonoAppDomainHandle ad, MonoStringHandle nam else if (!strcmp (str, "FORCE_CACHE_INSTALL")) o = MONO_HANDLE_NEW_GET (MonoString, ad_setup, shadow_copy_files); else - o = MONO_HANDLE_NEW (MonoString, mono_g_hash_table_lookup (add->env, MONO_HANDLE_RAW (name))); + o = MONO_HANDLE_NEW (MonoString, (MonoString*)mono_g_hash_table_lookup (add->env, MONO_HANDLE_RAW (name))); mono_domain_unlock (add); g_free (str); @@ -1280,10 +1318,12 @@ mono_try_assembly_resolve_handle (MonoDomain *domain, MonoStringHandle fname, Mo goto_if_nok (error, leave); } params [0] = MONO_HANDLE_RAW (fname); - params[1] = requesting ? MONO_HANDLE_RAW (requesting_handle) : NULL; + params [1] = requesting ? MONO_HANDLE_RAW (requesting_handle) : NULL; params [2] = &isrefonly; - MonoObject *exc = NULL; - MonoReflectionAssemblyHandle result = MONO_HANDLE_CAST (MonoReflectionAssembly, MONO_HANDLE_NEW (MonoObject, mono_runtime_try_invoke (method, domain->domain, params, &exc, error))); + MonoObject *exc; + exc = NULL; + MonoReflectionAssemblyHandle result; + result = MONO_HANDLE_CAST (MonoReflectionAssembly, MONO_HANDLE_NEW (MonoObject, mono_runtime_try_invoke (method, domain->domain, params, &exc, error))); if (!is_ok (error) || exc != NULL) { if (is_ok (error)) mono_error_set_exception_instance (error, (MonoException*)exc); @@ -1375,20 +1415,19 @@ mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data) ERROR_DECL (error); MonoDomain *domain = mono_domain_get (); MonoClass *klass; - gpointer load_value; - void *params [1]; + MonoObjectHandle appdomain; + + if (!MONO_BOOL (domain->domain)) + goto leave; // This can happen during startup - if (!domain->domain) - /* This can happen during startup */ - goto leave; if (mono_runtime_get_no_exec ()) goto leave; + #ifdef ASSEMBLY_LOAD_DEBUG fprintf (stderr, "Loading %s into domain %s\n", assembly->aname.name, domain->friendly_name); #endif - klass = domain->domain->mbr.obj.vtable->klass; - - error_init (error); + appdomain = MONO_HANDLE_NEW (MonoObject, &domain->domain->mbr.obj); + klass = mono_handle_class (appdomain); mono_domain_assemblies_lock (domain); add_assemblies_to_domain (domain, assembly, NULL); @@ -1399,13 +1438,11 @@ mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data) g_assert (assembly_load_field); } - mono_field_get_value ((MonoObject*) domain->domain, assembly_load_field, &load_value); - if (load_value == NULL) { - /* No events waiting to be triggered */ - goto leave; - } + if (!MONO_HANDLE_GET_FIELD_BOOL (appdomain, MonoObject*, assembly_load_field)) + goto leave; // No events waiting to be triggered - MonoReflectionAssemblyHandle ref_assembly = mono_assembly_get_object_handle (domain, assembly, error); + MonoReflectionAssemblyHandle reflection_assembly; + reflection_assembly = mono_assembly_get_object_handle (domain, assembly, error); mono_error_assert_ok (error); if (assembly_load_method == NULL) { @@ -1413,11 +1450,11 @@ mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data) g_assert (assembly_load_method); } - *params = MONO_HANDLE_RAW(ref_assembly); - - mono_runtime_invoke_checked (assembly_load_method, domain->domain, params, error); - mono_error_cleanup (error); + void *params [1]; + params [0] = MONO_HANDLE_RAW (reflection_assembly); + mono_runtime_invoke_handle (assembly_load_method, appdomain, params, error); leave: + mono_error_cleanup (error); HANDLE_FUNCTION_RETURN (); } @@ -1442,12 +1479,12 @@ mono_domain_asmctx_from_path (const char *fname, MonoAssembly *requesting_assemb static void set_domain_search_path (MonoDomain *domain) { + HANDLE_FUNCTION_ENTER (); ERROR_DECL (error); - MonoAppDomainSetup *setup; + MonoAppDomainSetupHandle setup; gchar **tmp; gchar *search_path = NULL; - gint i; - gint npaths = 0; + gint npaths = 1; gchar **pvt_split = NULL; GError *gerror = NULL; gint appbaselen = -1; @@ -1458,30 +1495,22 @@ set_domain_search_path (MonoDomain *domain) */ mono_domain_assemblies_lock (domain); - if (!domain->setup) { - mono_domain_assemblies_unlock (domain); - return; - } + if (!MONO_BOOL (domain->setup)) + goto exit; - if ((domain->search_path != NULL) && !domain->setup->path_changed) { - mono_domain_assemblies_unlock (domain); - return; - } - setup = domain->setup; - if (!setup->application_base) { - mono_domain_assemblies_unlock (domain); - return; /* Must set application base to get private path working */ - } + setup = MONO_HANDLE_NEW (MonoAppDomainSetup, domain->setup); - npaths++; + if (domain->search_path && !MONO_HANDLE_GET_BOOL (setup, path_changed)) + goto exit; + + if (!MONO_HANDLE_GET_BOOL (setup, application_base)) + goto exit; // Must set application base to get private path working - if (setup->private_bin_path) { - search_path = mono_string_to_utf8_checked (setup->private_bin_path, error); + if (MONO_HANDLE_GET_BOOL (setup, private_bin_path)) { + search_path = mono_string_handle_to_utf8 (MONO_HANDLE_NEW_GET (MonoString, setup, private_bin_path), error); if (!mono_error_ok (error)) { /*FIXME maybe we should bubble up the error.*/ g_warning ("Could not decode AppDomain search path since it contains invalid characters"); - mono_error_cleanup (error); - mono_domain_assemblies_unlock (domain); - return; + goto exit; } } @@ -1506,49 +1535,24 @@ set_domain_search_path (MonoDomain *domain) * * The issue was reported in bug #81446 */ - #ifndef TARGET_WIN32 - gint slen; - - slen = strlen (search_path); - for (i = 0; i < slen; i++) - if (search_path [i] == ':') - search_path [i] = ';'; + g_strdelimit (search_path, ':', ';'); #endif - pvt_split = g_strsplit (search_path, ";", 1000); g_free (search_path); for (tmp = pvt_split; *tmp; tmp++, npaths++); } - if (!npaths) { - if (pvt_split) - g_strfreev (pvt_split); - /* - * Don't do this because the first time is called, the domain - * setup is not finished. - * - * domain->search_path = g_malloc (sizeof (char *)); - * domain->search_path [0] = NULL; - */ - mono_domain_assemblies_unlock (domain); - return; - } + g_strfreev (domain->search_path); + domain->search_path = NULL; - if (domain->search_path) - g_strfreev (domain->search_path); - - tmp = (gchar **)g_malloc ((npaths + 1) * sizeof (gchar *)); + tmp = g_new (gchar*, npaths + 1); tmp [npaths] = NULL; - *tmp = mono_string_to_utf8_checked (setup->application_base, error); + *tmp = mono_string_handle_to_utf8 (MONO_HANDLE_NEW_GET (MonoString, setup, application_base), error); if (!mono_error_ok (error)) { - mono_error_cleanup (error); - g_strfreev (pvt_split); g_free (tmp); - - mono_domain_assemblies_unlock (domain); - return; + goto exit; } domain->search_path = tmp; @@ -1579,7 +1583,7 @@ set_domain_search_path (MonoDomain *domain) } } - for (i = 1; pvt_split && i < npaths; i++) { + for (gsize i = 1; pvt_split && i < npaths; i++) { if (g_path_is_absolute (pvt_split [i - 1])) { tmp [i] = g_strdup (pvt_split [i - 1]); } else { @@ -1607,16 +1611,17 @@ set_domain_search_path (MonoDomain *domain) } } - if (setup->private_bin_path_probe != NULL) { + if (MONO_HANDLE_GET_BOOL (setup, private_bin_path_probe)) { g_free (tmp [0]); tmp [0] = g_strdup (""); } - - domain->setup->path_changed = FALSE; + MONO_HANDLE_SETVAL (setup, path_changed, MonoBoolean, FALSE); +exit: + mono_error_cleanup (error); g_strfreev (pvt_split); - mono_domain_assemblies_unlock (domain); + HANDLE_FUNCTION_RETURN (); } #ifdef DISABLE_SHADOW_COPY @@ -1667,27 +1672,20 @@ make_sibling_path (const gchar *path, gint pathlen, const char *extension, Shado static gboolean shadow_copy_sibling (const gchar *src_pristine, gint srclen, const char *extension, ShadowCopySiblingExt extopt, const gchar *target_pristine, gint targetlen) { - guint16 *orig, *dest; - gboolean copy_result; - gint32 copy_error; - gchar *src = NULL; + gchar *file = NULL; + gunichar2 *orig = NULL; + gunichar2 *dest = NULL; + gboolean copy_result = TRUE; gchar *target = NULL; - src = make_sibling_path (src_pristine, srclen, extension, extopt); + char *src = make_sibling_path (src_pristine, srclen, extension, extopt); if (IS_PORTABILITY_CASE) { - gchar *file = mono_portability_find_file (src, TRUE); - - if (file == NULL) { - g_free (src); - return TRUE; - } - - g_free (file); - } else if (!g_file_test (src, G_FILE_TEST_IS_REGULAR)) { - g_free (src); - return TRUE; - } + file = mono_portability_find_file (src, TRUE); + if (file == NULL) + goto exit; + } else if (!g_file_test (src, G_FILE_TEST_IS_REGULAR)) + goto exit; orig = g_utf8_to_utf16 (src, strlen (src), NULL, NULL, NULL); @@ -1697,6 +1695,7 @@ shadow_copy_sibling (const gchar *src_pristine, gint srclen, const char *extensi mono_w32file_delete (dest); + gint32 copy_error; copy_result = mono_w32file_copy (orig, dest, TRUE, ©_error); /* Fix for bug #556884 - make sure the files have the correct mode so that they can be @@ -1704,9 +1703,10 @@ shadow_copy_sibling (const gchar *src_pristine, gint srclen, const char *extensi if (copy_result) copy_result = mono_w32file_set_attributes (dest, FILE_ATTRIBUTE_NORMAL); +exit: + g_free (file); g_free (orig); g_free (dest); - g_free (src); g_free (target); return copy_result; @@ -1715,16 +1715,15 @@ shadow_copy_sibling (const gchar *src_pristine, gint srclen, const char *extensi static gint32 get_cstring_hash (const char *str) { - int len, i; const char *p; gint32 h = 0; if (!str || !str [0]) return 0; - len = strlen (str); + gsize const len = strlen (str); p = str; - for (i = 0; i < len; i++) { + for (gsize i = 0; i < len; i++) { h = (h << 5) - h + *p; p++; } @@ -1739,8 +1738,9 @@ static char * get_shadow_assembly_location_base (MonoDomain *domain, MonoError *error) { MonoAppDomainSetup *setup; - char *cache_path, *appname; - char *userdir; + char *cache_path = NULL; + char *appname = NULL; + char *userdir = NULL; char *location; error_init (error); @@ -1766,13 +1766,13 @@ get_shadow_assembly_location_base (MonoDomain *domain, MonoError *error) } location = g_build_filename (cache_path, appname, "assembly", "shadow", NULL); - g_free (appname); - g_free (cache_path); } else { userdir = g_strdup_printf ("%s-mono-cachepath", g_get_user_name ()); location = g_build_filename (g_get_tmp_dir (), userdir, "assembly", "shadow", NULL); - g_free (userdir); } + g_free (appname); + g_free (cache_path); + g_free (userdir); return location; } @@ -1847,38 +1847,37 @@ private_file_needs_copying (const char *src, struct stat *sbuf_src, char *dest) static gboolean shadow_copy_create_ini (const char *shadow, const char *filename) { - char *dir_name; - char *ini_file; - guint16 *u16_ini; - gboolean result; + gunichar2 *u16_ini = NULL; + gboolean result = FALSE; guint32 n; - HANDLE handle; - gchar *full_path; + HANDLE handle = INVALID_HANDLE_VALUE; + gchar *full_path = NULL; - dir_name = g_path_get_dirname (shadow); - ini_file = g_build_filename (dir_name, "__AssemblyInfo__.ini", NULL); + char *dir_name = g_path_get_dirname (shadow); + char *ini_file = g_build_filename (dir_name, "__AssemblyInfo__.ini", NULL); g_free (dir_name); - if (g_file_test (ini_file, G_FILE_TEST_IS_REGULAR)) { - g_free (ini_file); - return TRUE; - } + result = g_file_test (ini_file, G_FILE_TEST_IS_REGULAR); + if (result) + goto exit; u16_ini = g_utf8_to_utf16 (ini_file, strlen (ini_file), NULL, NULL, NULL); - g_free (ini_file); - if (!u16_ini) { - return FALSE; - } + if (!u16_ini) + goto exit; + handle = mono_w32file_create (u16_ini, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, CREATE_NEW, FileAttributes_Normal); - g_free (u16_ini); - if (handle == INVALID_HANDLE_VALUE) { - return FALSE; - } + if (handle == INVALID_HANDLE_VALUE) + goto exit; full_path = mono_path_resolve_symlinks (filename); - gint32 win32error = 0; + gint32 win32error; + win32error = 0; result = mono_w32file_write (handle, full_path, strlen (full_path), &n, &win32error); +exit: + if (handle != INVALID_HANDLE_VALUE) + mono_w32file_close (handle); + g_free (u16_ini); g_free (full_path); - mono_w32file_close (handle); + g_free (ini_file); return result; } @@ -1887,63 +1886,57 @@ mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name) { ERROR_DECL (error); MonoAppDomainSetup *setup; - gchar *all_dirs; + gchar *all_dirs = NULL; gchar **dir_ptr; - gchar **directories; + gchar **directories = NULL; gchar *shadow_status_string; - gchar *base_dir; + gchar *base_dir = NULL; gboolean shadow_enabled; gboolean found = FALSE; if (domain == NULL) - return FALSE; + goto exit; setup = domain->setup; if (setup == NULL || setup->shadow_copy_files == NULL) - return FALSE; + goto exit; shadow_status_string = mono_string_to_utf8_checked (setup->shadow_copy_files, error); - if (!mono_error_ok (error)) { - mono_error_cleanup (error); - return FALSE; - } + if (!mono_error_ok (error)) + goto exit; + shadow_enabled = !g_ascii_strncasecmp (shadow_status_string, "true", 4); g_free (shadow_status_string); if (!shadow_enabled) - return FALSE; + goto exit; - if (setup->shadow_copy_directories == NULL) - return TRUE; + found = (setup->shadow_copy_directories == NULL); + if (found) + goto exit; /* Is dir_name a shadow_copy destination already? */ base_dir = get_shadow_assembly_location_base (domain, error); - if (!mono_error_ok (error)) { - mono_error_cleanup (error); - return FALSE; - } + if (!mono_error_ok (error)) + goto exit; - if (strstr (dir_name, base_dir)) { - g_free (base_dir); - return TRUE; - } - g_free (base_dir); + found = !!strstr (dir_name, base_dir); + if (found) + goto exit; all_dirs = mono_string_to_utf8_checked (setup->shadow_copy_directories, error); - if (!mono_error_ok (error)) { - mono_error_cleanup (error); - return FALSE; - } + if (!mono_error_ok (error)) + goto exit; directories = g_strsplit (all_dirs, G_SEARCHPATH_SEPARATOR_S, 1000); dir_ptr = directories; - while (*dir_ptr) { - if (**dir_ptr != '\0' && !strcmp (*dir_ptr, dir_name)) { - found = TRUE; - break; - } + while (!found && *dir_ptr) { + found = (**dir_ptr != '\0' && !strcmp (*dir_ptr, dir_name)); dir_ptr++; } +exit: + mono_error_cleanup (error); + g_free (base_dir); g_strfreev (directories); g_free (all_dirs); return found; @@ -1961,7 +1954,7 @@ mono_make_shadow_copy (const char *filename, MonoError *oerror) { ERROR_DECL (error); gint filename_len, shadow_len; - guint16 *orig, *dest; + gunichar2 *orig, *dest; guint32 attrs; char *shadow; gboolean copy_result; @@ -2287,8 +2280,8 @@ mono_domain_assembly_search (MonoAssemblyName *aname, /* If it's not a strong name, any version that has the right simple * name is good enough to satisfy the request. .NET Framework also * ignores case differences in this case. */ - const MonoAssemblyNameEqFlags eq_flags = strong_name ? MONO_ANAME_EQ_IGNORE_CASE : - (MONO_ANAME_EQ_IGNORE_PUBKEY | MONO_ANAME_EQ_IGNORE_VERSION | MONO_ANAME_EQ_IGNORE_CASE); + const MonoAssemblyNameEqFlags eq_flags = (MonoAssemblyNameEqFlags)(strong_name ? MONO_ANAME_EQ_IGNORE_CASE : + (MONO_ANAME_EQ_IGNORE_PUBKEY | MONO_ANAME_EQ_IGNORE_VERSION | MONO_ANAME_EQ_IGNORE_CASE)); mono_domain_assemblies_lock (domain); for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) { @@ -2326,14 +2319,16 @@ ves_icall_System_Reflection_Assembly_LoadFrom (MonoStringHandle fname, MonoBoole name = filename = mono_string_handle_to_utf8 (fname, error); goto_if_nok (error, leave); - MonoAssembly *requesting_assembly = NULL; + MonoAssembly *requesting_assembly; + requesting_assembly = NULL; if (!refOnly) { MonoMethod *executing_method = mono_runtime_get_caller_no_system_or_reflection (); MonoAssembly *executing_assembly = executing_method ? m_class_get_image (executing_method->klass)->assembly : NULL; requesting_assembly = executing_assembly; } - MonoAssembly *ass = mono_assembly_open_predicate (filename, refOnly ? MONO_ASMCTX_REFONLY : MONO_ASMCTX_LOADFROM, NULL, NULL, requesting_assembly, &status); + MonoAssembly *ass; + ass = mono_assembly_open_predicate (filename, refOnly ? MONO_ASMCTX_REFONLY : MONO_ASMCTX_LOADFROM, NULL, NULL, requesting_assembly, &status); if (!ass) { if (status == MONO_IMAGE_IMAGE_INVALID) @@ -2370,10 +2365,12 @@ ves_icall_System_Reflection_Assembly_LoadFile_internal (MonoStringHandle fname, } MonoImageOpenStatus status; - - MonoMethod *executing_method = mono_runtime_get_caller_no_system_or_reflection (); - MonoAssembly *executing_assembly = executing_method ? m_class_get_image (executing_method->klass)->assembly : NULL; - MonoAssembly *ass = mono_assembly_open_predicate (filename, MONO_ASMCTX_INDIVIDUAL, NULL, NULL, executing_assembly, &status); + MonoMethod *executing_method; + executing_method = mono_runtime_get_caller_no_system_or_reflection (); + MonoAssembly *executing_assembly; + executing_assembly = executing_method ? m_class_get_image (executing_method->klass)->assembly : NULL; + MonoAssembly *ass; + ass = mono_assembly_open_predicate (filename, MONO_ASMCTX_INDIVIDUAL, NULL, NULL, executing_assembly, &status); if (!ass) { if (status == MONO_IMAGE_IMAGE_INVALID) mono_error_set_bad_image_by_name (error, filename, "Invalid Image"); @@ -2386,7 +2383,6 @@ ves_icall_System_Reflection_Assembly_LoadFile_internal (MonoStringHandle fname, leave: g_free (filename); return result; - } MonoReflectionAssemblyHandle @@ -2490,8 +2486,10 @@ ves_icall_System_AppDomain_LoadAssembly (MonoAppDomainHandle ad, MonoStringHandl return refass; } - MonoAssemblyContextKind asmctx = refOnly ? MONO_ASMCTX_REFONLY : MONO_ASMCTX_DEFAULT; - const char *basedir = NULL; + MonoAssemblyContextKind asmctx; + asmctx = refOnly ? MONO_ASMCTX_REFONLY : MONO_ASMCTX_DEFAULT; + const char *basedir; + basedir = NULL; if (!refOnly) { /* Determine if the current assembly is in LoadFrom context. * If it is, we must include the executing assembly's basedir @@ -2521,7 +2519,8 @@ ves_icall_System_AppDomain_LoadAssembly (MonoAppDomainHandle ad, MonoStringHandl } g_assert (ass); - MonoReflectionAssemblyHandle refass = mono_assembly_get_object_handle (domain, ass, error); + MonoReflectionAssemblyHandle refass; + refass = mono_assembly_get_object_handle (domain, ass, error); goto_if_nok (error, fail); MONO_HANDLE_SET (refass, evidence, evidence); @@ -2755,6 +2754,8 @@ typedef struct unload_data { static void unload_data_unref (unload_data *data) { + if (!data) + return; gint32 count; do { mono_atomic_load_acquire (count, gint32, &data->refcount); @@ -2819,6 +2820,7 @@ unload_thread_main (void *arg) MonoDomain *domain = data->domain; MonoInternalThread *internal; int i; + gsize result = 1; // failure internal = mono_thread_internal_current (); @@ -2827,7 +2829,6 @@ unload_thread_main (void *arg) mono_thread_set_name_internal (internal, thread_name_str, TRUE, FALSE, error); if (!is_ok (error)) { data->failure_reason = g_strdup (mono_error_get_message (error)); - mono_error_cleanup (error); goto failure; } @@ -2890,14 +2891,16 @@ unload_thread_main (void *arg) mono_gc_collect (mono_gc_max_generation ()); + result = 0; // success +exit: + mono_error_cleanup (error); mono_atomic_store_release (&data->done, TRUE); unload_data_unref (data); - return 0; + return result; failure: - mono_atomic_store_release (&data->done, TRUE); - unload_data_unref (data); - return 1; + result = 1; + goto exit; } /** @@ -2950,16 +2953,15 @@ guarded_wait (MonoThreadHandle *thread_handle, guint32 timeout, gboolean alertab void mono_domain_try_unload (MonoDomain *domain, MonoObject **exc) { + HANDLE_FUNCTION_ENTER (); ERROR_DECL (error); - MonoThreadHandle *thread_handle; + MonoThreadHandle *thread_handle = NULL; MonoAppDomainState prev_state; MonoMethod *method; - unload_data *thread_data; - MonoInternalThread *internal; + unload_data *thread_data = NULL; + MonoInternalThreadHandle internal; MonoDomain *caller_domain = mono_domain_get (); - error_init(error); - /* printf ("UNLOAD STARTING FOR %s (%p) IN THREAD 0x%x.\n", domain->friendly_name, domain, mono_native_thread_id_get ()); */ /* Atomically change our state to UNLOADING */ @@ -2971,10 +2973,10 @@ mono_domain_try_unload (MonoDomain *domain, MonoObject **exc) case MONO_APPDOMAIN_UNLOADING_START: case MONO_APPDOMAIN_UNLOADING: *exc = (MonoObject *) mono_get_exception_cannot_unload_appdomain ("Appdomain is already being unloaded."); - return; + goto exit; case MONO_APPDOMAIN_UNLOADED: *exc = (MonoObject *) mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded."); - return; + goto exit; default: g_warning ("Invalid appdomain state %d", prev_state); g_assert_not_reached (); @@ -2999,7 +3001,7 @@ mono_domain_try_unload (MonoDomain *domain, MonoObject **exc) /* Roll back the state change */ domain->state = MONO_APPDOMAIN_CREATED; mono_domain_set (caller_domain, FALSE); - return; + goto exit; } mono_domain_set (caller_domain, FALSE); @@ -3019,24 +3021,20 @@ mono_domain_try_unload (MonoDomain *domain, MonoObject **exc) * * Force it to be attached to avoid racing during shutdown. */ - internal = mono_thread_create_internal (mono_get_root_domain (), unload_thread_main, thread_data, MONO_THREAD_CREATE_FLAGS_FORCE_CREATE, error); + internal = mono_thread_create_internal_handle (mono_get_root_domain (), unload_thread_main, thread_data, MONO_THREAD_CREATE_FLAGS_FORCE_CREATE, error); mono_error_assert_ok (error); - thread_handle = mono_threads_open_thread_handle (internal->handle); + thread_handle = mono_threads_open_thread_handle (MONO_HANDLE_GETVAL (internal, handle)); /* Wait for the thread */ while (!thread_data->done && guarded_wait (thread_handle, MONO_INFINITE_WAIT, TRUE) == MONO_THREAD_INFO_WAIT_RET_ALERTED) { if (mono_thread_internal_has_appdomain_ref (mono_thread_internal_current (), domain) && (mono_thread_interruption_requested ())) { /* The unload thread tries to abort us */ /* The icall wrapper will execute the abort */ - mono_threads_close_thread_handle (thread_handle); - unload_data_unref (thread_data); - return; + goto exit; } } - mono_threads_close_thread_handle (thread_handle); - if (thread_data->failure_reason) { /* Roll back the state change */ domain->state = MONO_APPDOMAIN_CREATED; @@ -3049,5 +3047,8 @@ mono_domain_try_unload (MonoDomain *domain, MonoObject **exc) thread_data->failure_reason = NULL; } +exit: + mono_threads_close_thread_handle (thread_handle); unload_data_unref (thread_data); + HANDLE_FUNCTION_RETURN (); } diff --git a/mono/metadata/appdomain.h b/mono/metadata/appdomain.h index 618f186025..92c8d18005 100644 --- a/mono/metadata/appdomain.h +++ b/mono/metadata/appdomain.h @@ -13,6 +13,7 @@ #include +#include #include #include @@ -23,7 +24,6 @@ typedef void (*MonoThreadStartCB) (intptr_t tid, void* stack_start, typedef void (*MonoThreadAttachCB) (intptr_t tid, void* stack_start); typedef struct _MonoAppDomain MonoAppDomain; -typedef struct _MonoJitInfo MonoJitInfo; typedef void (*MonoDomainFunc) (MonoDomain *domain, void* user_data); diff --git a/mono/metadata/assembly.c.REMOVED.git-id b/mono/metadata/assembly.c.REMOVED.git-id index 57efb36e79..6fd581c2d6 100644 --- a/mono/metadata/assembly.c.REMOVED.git-id +++ b/mono/metadata/assembly.c.REMOVED.git-id @@ -1 +1 @@ -1a14fe3ffc1c2781bbc8d385160e0c05b9414aa8 \ No newline at end of file +f296f4ca05c6c01ebf7938b41d323ce9b3b82158 \ No newline at end of file diff --git a/mono/metadata/attach.c b/mono/metadata/attach.c index 1f94d89a18..4eec3a3dba 100644 --- a/mono/metadata/attach.c +++ b/mono/metadata/attach.c @@ -11,6 +11,7 @@ #include #include +#include "attach.h" #ifdef HOST_WIN32 #define DISABLE_ATTACH @@ -39,7 +40,6 @@ #include #include #include -#include "attach.h" #include @@ -491,7 +491,7 @@ transport_start_receive (void) if (!listen_fd) return; - internal = mono_thread_create_internal (mono_get_root_domain (), receiver_thread, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error); + internal = mono_thread_create_internal (mono_get_root_domain (), (gpointer)receiver_thread, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error); mono_error_assert_ok (error); receiver_thread_handle = mono_threads_open_thread_handle (internal->handle); diff --git a/mono/metadata/attach.h b/mono/metadata/attach.h index ff33b83fa5..27ab78663b 100644 --- a/mono/metadata/attach.h +++ b/mono/metadata/attach.h @@ -8,8 +8,6 @@ #include #include -G_BEGIN_DECLS - void mono_attach_parse_options (char *options); @@ -25,6 +23,4 @@ mono_attach_maybe_start (void); void mono_attach_cleanup (void); -G_END_DECLS - #endif diff --git a/mono/metadata/boehm-gc.c b/mono/metadata/boehm-gc.c index 4f965c6e2b..93cb489581 100644 --- a/mono/metadata/boehm-gc.c +++ b/mono/metadata/boehm-gc.c @@ -59,6 +59,7 @@ void *pthread_get_stackaddr_np(pthread_t); #define MIN_BOEHM_MAX_HEAP_SIZE (MIN_BOEHM_MAX_HEAP_SIZE_IN_MB << 20) static gboolean gc_initialized = FALSE; +static gboolean gc_dont_gc_env = FALSE; static mono_mutex_t mono_gc_lock; typedef void (*GC_push_other_roots_proc)(void); @@ -203,6 +204,9 @@ mono_gc_base_init (void) } } + /* cache value rather than calling during collection since g_hasenv may take locks and can deadlock */ + gc_dont_gc_env = g_hasenv ("GC_DONT_GC"); + GC_init (); GC_set_warn_proc (mono_gc_warning); @@ -546,7 +550,7 @@ typedef struct { static gpointer register_root (gpointer arg) { - RootData* root_data = arg; + RootData* root_data = (RootData*)arg; g_hash_table_insert (roots, root_data->start, root_data->end); return NULL; } @@ -613,7 +617,7 @@ mono_push_other_roots (void) { g_hash_table_foreach (roots, push_root, NULL); FOREACH_THREAD_EXCLUDE (info, MONO_THREAD_INFO_FLAGS_NO_GC) { - HandleStack* stack = (HandleStack*)info->handle_stack; + HandleStack* stack = info->handle_stack; if (stack) push_handle_stack (stack); } FOREACH_THREAD_END @@ -699,12 +703,18 @@ mono_gc_make_root_descr_all_refs (int numbits) return NULL; } -void* +MonoObject* mono_gc_alloc_fixed (size_t size, void *descr, MonoGCRootSource source, void *key, const char *msg) { void *start = GC_MALLOC_UNCOLLECTABLE (size); MONO_PROFILER_RAISE (gc_root_register, ((const mono_byte *) start, size, source, key, msg)); - return start; + return (MonoObject*)start; +} + +MonoObject* +mono_gc_alloc_fixed_no_descriptor (size_t size, MonoGCRootSource source, void *key, const char *msg) +{ + return mono_gc_alloc_fixed (size, 0, source, key, msg); } void @@ -714,7 +724,7 @@ mono_gc_free_fixed (void* addr) GC_FREE (addr); } -void * +MonoObject* mono_gc_alloc_obj (MonoVTable *vtable, size_t size) { MonoObject *obj; @@ -746,7 +756,7 @@ mono_gc_alloc_obj (MonoVTable *vtable, size_t size) return obj; } -void * +MonoArray* mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length) { MonoArray *obj; @@ -780,7 +790,7 @@ mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length) return obj; } -void * +MonoArray* mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size) { MonoArray *obj; @@ -817,7 +827,7 @@ mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uint return obj; } -void * +MonoString* mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len) { MonoString *obj = (MonoString *)GC_MALLOC_ATOMIC (size); @@ -835,13 +845,13 @@ mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len) return obj; } -void* +MonoObject* mono_gc_alloc_mature (MonoVTable *vtable, size_t size) { return mono_gc_alloc_obj (vtable, size); } -void* +MonoObject* mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size) { return mono_gc_alloc_obj (vtable, size); @@ -1389,19 +1399,19 @@ mono_gc_is_moving (void) gboolean mono_gc_is_disabled (void) { - if (GC_dont_gc || g_hasenv ("GC_DONT_GC")) + if (GC_dont_gc || gc_dont_gc_env) return TRUE; else return FALSE; } void -mono_gc_wbarrier_range_copy (gpointer _dest, gpointer _src, int size) +mono_gc_wbarrier_range_copy (gpointer _dest, gconstpointer _src, int size) { g_assert_not_reached (); } -void* +MonoRangeCopyFunction mono_gc_get_range_copy_func (void) { return &mono_gc_wbarrier_range_copy; @@ -1415,10 +1425,10 @@ mono_gc_get_card_table (int *shift_bits, gpointer *card_mask) } guint8* -mono_gc_get_target_card_table (int *shift_bits, gpointer *card_mask) +mono_gc_get_target_card_table (int *shift_bits, target_mgreg_t *card_mask) { *shift_bits = 0; - *card_mask = NULL; + *card_mask = 0; return NULL; } @@ -1516,7 +1526,7 @@ mono_gc_register_for_finalization (MonoObject *obj, MonoFinalizationProc user_da g_assert (GC_base (obj) == (char*)obj - offset); #endif - GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, (GC_finalization_proc)user_data, GUINT_TO_POINTER (offset), NULL, NULL); + GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, user_data, GUINT_TO_POINTER (offset), NULL, NULL); } #ifndef HOST_WIN32 @@ -1804,7 +1814,7 @@ alloc_handle (HandleData *handles, MonoObject *obj, gboolean track) #endif unlock_handles (handles); res = MONO_GC_HANDLE (slot, handles->type); - MONO_PROFILER_RAISE (gc_handle_created, (res, handles->type, obj)); + MONO_PROFILER_RAISE (gc_handle_created, (res, (MonoGCHandleType)handles->type, obj)); return res; } @@ -2005,7 +2015,7 @@ mono_gchandle_free (guint32 gchandle) #endif /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/ unlock_handles (handles); - MONO_PROFILER_RAISE (gc_handle_deleted, (gchandle, handles->type)); + MONO_PROFILER_RAISE (gc_handle_deleted, (gchandle, (MonoGCHandleType)handles->type)); } /** diff --git a/mono/metadata/callspec.c b/mono/metadata/callspec.c index 97069751fc..31deb1389c 100644 --- a/mono/metadata/callspec.c +++ b/mono/metadata/callspec.c @@ -36,12 +36,12 @@ mono_callspec_eval_exception (MonoClass *klass, MonoCallSpec *spec) switch (op->op) { case MONO_TRACEOP_EXCEPTION: - if (strcmp ("", op->data) == 0 && - strcmp ("all", op->data2) == 0) + if (strcmp ("", (const char*)op->data) == 0 && + strcmp ("all", (const char*)op->data2) == 0) inc = 1; - else if (strcmp ("", op->data) == 0 || - strcmp (m_class_get_name_space (klass), op->data) == 0) - if (strcmp (m_class_get_name (klass), op->data2) == 0) + else if (strcmp ("", (const char*)op->data) == 0 || + strcmp (m_class_get_name_space (klass), (const char*)op->data) == 0) + if (strcmp (m_class_get_name (klass), (const char*)op->data2) == 0) inc = 1; break; default: @@ -86,7 +86,7 @@ gboolean mono_callspec_eval (MonoMethod *method, const MonoCallSpec *spec) inc = 1; break; case MONO_TRACEOP_METHOD: - mdesc = op->data; + mdesc = (MonoMethodDesc*)op->data; is_full = mono_method_desc_is_full (mdesc); if (is_full && mono_method_desc_full_match (mdesc, method)) @@ -95,18 +95,18 @@ gboolean mono_callspec_eval (MonoMethod *method, const MonoCallSpec *spec) inc = 1; break; case MONO_TRACEOP_CLASS: - if (strcmp (m_class_get_name_space (method->klass), op->data) == 0) - if (strcmp (m_class_get_name (method->klass), op->data2) == + if (strcmp (m_class_get_name_space (method->klass), (const char*)op->data) == 0) + if (strcmp (m_class_get_name (method->klass), (const char*)op->data2) == 0) inc = 1; break; case MONO_TRACEOP_ASSEMBLY: if (strcmp (mono_image_get_name (m_class_get_image (method->klass)), - op->data) == 0) + (const char*)op->data) == 0) inc = 1; break; case MONO_TRACEOP_NAMESPACE: - if (strcmp (m_class_get_name_space (method->klass), op->data) == 0) + if (strcmp (m_class_get_name_space (method->klass), (const char*)op->data) == 0) inc = 1; break; case MONO_TRACEOP_EXCEPTION: diff --git a/mono/metadata/class-accessors.c b/mono/metadata/class-accessors.c index ad3ec667bc..f377383a25 100644 --- a/mono/metadata/class-accessors.c +++ b/mono/metadata/class-accessors.c @@ -244,7 +244,7 @@ mono_class_set_field_count (MonoClass *klass, guint32 count) MonoMarshalType* mono_class_get_marshal_info (MonoClass *klass) { - return mono_property_bag_get (m_class_get_infrequent_data (klass), PROP_MARSHAL_INFO); + return (MonoMarshalType*)mono_property_bag_get (m_class_get_infrequent_data (klass), PROP_MARSHAL_INFO); } void @@ -262,7 +262,7 @@ typedef struct { guint32 mono_class_get_ref_info_handle (MonoClass *klass) { - Uint32Property *prop = mono_property_bag_get (m_class_get_infrequent_data (klass), PROP_REF_INFO_HANDLE); + Uint32Property *prop = (Uint32Property*)mono_property_bag_get (m_class_get_infrequent_data (klass), PROP_REF_INFO_HANDLE); return prop ? prop->value : 0; } @@ -270,16 +270,16 @@ guint32 mono_class_set_ref_info_handle (MonoClass *klass, guint32 value) { if (!value) { - Uint32Property *prop = mono_property_bag_get (m_class_get_infrequent_data (klass), PROP_REF_INFO_HANDLE); + Uint32Property *prop = (Uint32Property*)mono_property_bag_get (m_class_get_infrequent_data (klass), PROP_REF_INFO_HANDLE); if (prop) prop->value = 0; return 0; } - Uint32Property *prop = mono_class_alloc (klass, sizeof (Uint32Property)); + Uint32Property *prop = (Uint32Property*)mono_class_alloc (klass, sizeof (Uint32Property)); prop->head.tag = PROP_REF_INFO_HANDLE; prop->value = value; - prop = mono_property_bag_add (m_class_get_infrequent_data (klass), prop); + prop = (Uint32Property*)mono_property_bag_add (m_class_get_infrequent_data (klass), prop); return prop->value; } @@ -291,7 +291,7 @@ typedef struct { static void set_pointer_property (MonoClass *klass, InfrequentDataKind property, gpointer value) { - PointerProperty *prop = mono_class_alloc (klass, sizeof (PointerProperty)); + PointerProperty *prop = (PointerProperty*)mono_class_alloc (klass, sizeof (PointerProperty)); prop->head.tag = property; prop->value = value; mono_property_bag_add (m_class_get_infrequent_data (klass), prop); @@ -331,7 +331,7 @@ mono_class_set_nested_classes_property (MonoClass *klass, GList *value) MonoClassPropertyInfo* mono_class_get_property_info (MonoClass *klass) { - return mono_property_bag_get (m_class_get_infrequent_data (klass), PROP_PROPERTY_INFO); + return (MonoClassPropertyInfo*)mono_property_bag_get (m_class_get_infrequent_data (klass), PROP_PROPERTY_INFO); } void @@ -344,7 +344,7 @@ mono_class_set_property_info (MonoClass *klass, MonoClassPropertyInfo *info) MonoClassEventInfo* mono_class_get_event_info (MonoClass *klass) { - return mono_property_bag_get (m_class_get_infrequent_data (klass), PROP_EVENT_INFO); + return (MonoClassEventInfo*)mono_property_bag_get (m_class_get_infrequent_data (klass), PROP_EVENT_INFO); } void @@ -369,14 +369,14 @@ mono_class_set_field_def_values (MonoClass *klass, MonoFieldDefaultValue *values guint32 mono_class_get_declsec_flags (MonoClass *klass) { - Uint32Property *prop = mono_property_bag_get (m_class_get_infrequent_data (klass), PROP_DECLSEC_FLAGS); + Uint32Property *prop = (Uint32Property*)mono_property_bag_get (m_class_get_infrequent_data (klass), PROP_DECLSEC_FLAGS); return prop ? prop->value : 0; } void mono_class_set_declsec_flags (MonoClass *klass, guint32 value) { - Uint32Property *prop = mono_class_alloc (klass, sizeof (Uint32Property)); + Uint32Property *prop = (Uint32Property*)mono_class_alloc (klass, sizeof (Uint32Property)); prop->head.tag = PROP_DECLSEC_FLAGS; prop->value = value; mono_property_bag_add (m_class_get_infrequent_data (klass), prop); @@ -409,7 +409,7 @@ typedef struct { void mono_class_set_weak_bitmap (MonoClass *klass, int nbits, gsize *bits) { - WeakBitmapData *info = mono_class_alloc (klass, sizeof (WeakBitmapData)); + WeakBitmapData *info = (WeakBitmapData *)mono_class_alloc (klass, sizeof (WeakBitmapData)); info->nbits = nbits; info->bits = bits; @@ -420,7 +420,7 @@ mono_class_set_weak_bitmap (MonoClass *klass, int nbits, gsize *bits) gsize* mono_class_get_weak_bitmap (MonoClass *klass, int *nbits) { - WeakBitmapData *prop = mono_property_bag_get (m_class_get_infrequent_data (klass), PROP_WEAK_BITMAP); + WeakBitmapData *prop = (WeakBitmapData*)mono_property_bag_get (m_class_get_infrequent_data (klass), PROP_WEAK_BITMAP); g_assert (prop); *nbits = prop->nbits; @@ -451,7 +451,7 @@ typedef struct { void mono_class_set_dim_conflicts (MonoClass *klass, GSList *conflicts) { - DimConflictData *info = mono_class_alloc (klass, sizeof (DimConflictData)); + DimConflictData *info = (DimConflictData*)mono_class_alloc (klass, sizeof (DimConflictData)); info->data = conflicts; g_assert (!mono_class_is_ginst (klass)); @@ -466,7 +466,7 @@ mono_class_get_dim_conflicts (MonoClass *klass) if (mono_class_is_ginst (klass)) return mono_class_get_dim_conflicts (mono_class_get_generic_class (klass)->container_class); - DimConflictData *info = mono_property_bag_get (&klass->infrequent_data, PROP_DIM_CONFLICTS); + DimConflictData *info = (DimConflictData*)mono_property_bag_get (&klass->infrequent_data, PROP_DIM_CONFLICTS); g_assert (info); return info->data; diff --git a/mono/metadata/class-init.c.REMOVED.git-id b/mono/metadata/class-init.c.REMOVED.git-id index 533cbf851b..685ecb75cb 100644 --- a/mono/metadata/class-init.c.REMOVED.git-id +++ b/mono/metadata/class-init.c.REMOVED.git-id @@ -1 +1 @@ -46d49f6e526bdb14c329f92c43d12391d5efb963 \ No newline at end of file +670446618186fcbd5ef674faa0394ae01e0a61a1 \ No newline at end of file diff --git a/mono/metadata/class-internals.h b/mono/metadata/class-internals.h index 59606534c1..29df058ba1 100644 --- a/mono/metadata/class-internals.h +++ b/mono/metadata/class-internals.h @@ -1067,6 +1067,22 @@ mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignatu MonoJitICallInfo * mono_register_jit_icall_full (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean no_wrapper, const char *c_symbol); +#ifdef __cplusplus +template +inline MonoJitICallInfo * +mono_register_jit_icall (T func, const char *name, MonoMethodSignature *sig, gboolean is_save) +{ + return mono_register_jit_icall ((gconstpointer)func, name, sig, is_save); +} + +template +inline MonoJitICallInfo * +mono_register_jit_icall_full (T func, const char *name, MonoMethodSignature *sig, gboolean no_wrapper, const char *c_symbol) +{ + return mono_register_jit_icall_full ((gconstpointer)func, name, sig, no_wrapper, c_symbol); +} +#endif // __cplusplus + void mono_register_jit_icall_wrapper (MonoJitICallInfo *info, gconstpointer wrapper); @@ -1181,6 +1197,8 @@ mono_class_alloc (MonoClass *klass, int size); gpointer mono_class_alloc0 (MonoClass *klass, int size); +#define mono_class_alloc0(klass, size) (g_cast (mono_class_alloc0 ((klass), (size)))) + void mono_class_setup_interfaces (MonoClass *klass, MonoError *error); @@ -1226,7 +1244,7 @@ void mono_unload_interface_id (MonoClass *klass); GPtrArray* -mono_class_get_methods_by_name (MonoClass *klass, const char *name, guint32 bflags, gboolean ignore_case, gboolean allow_ctors, MonoError *error); +mono_class_get_methods_by_name (MonoClass *klass, const char *name, guint32 bflags, guint32 mlisttype, gboolean allow_ctors, MonoError *error); char* mono_class_full_name (MonoClass *klass); diff --git a/mono/metadata/class.c.REMOVED.git-id b/mono/metadata/class.c.REMOVED.git-id index aa68c63e97..e032b3dbd0 100644 --- a/mono/metadata/class.c.REMOVED.git-id +++ b/mono/metadata/class.c.REMOVED.git-id @@ -1 +1 @@ -06b1a4e63783d78c067bb06485cfb9c96a6301fc \ No newline at end of file +7a39e6197aff51202639413d30bb6f11b2e4f4ca \ No newline at end of file diff --git a/mono/metadata/cominterop.c.REMOVED.git-id b/mono/metadata/cominterop.c.REMOVED.git-id index 529aad4e51..70e0f89268 100644 --- a/mono/metadata/cominterop.c.REMOVED.git-id +++ b/mono/metadata/cominterop.c.REMOVED.git-id @@ -1 +1 @@ -f3ea672e15453de2868058f01c611ae9cae38bed \ No newline at end of file +0f861082aa118ae629a5ccc44af6798ba69d9829 \ No newline at end of file diff --git a/mono/metadata/console-unix.c b/mono/metadata/console-unix.c index be18bae3f8..9e5120a36e 100644 --- a/mono/metadata/console-unix.c +++ b/mono/metadata/console-unix.c @@ -218,13 +218,13 @@ tty_teardown (void) static void do_console_cancel_event (void) { - static MonoMethod *System_Console_DoConsoleCancelEventBackground_method = ((gpointer)-1); + static MonoMethod *System_Console_DoConsoleCancelEventBackground_method = (MonoMethod*)(intptr_t)-1; ERROR_DECL (error); if (mono_defaults.console_class == NULL) return; - if (System_Console_DoConsoleCancelEventBackground_method == ((gpointer)-1)) { + if (System_Console_DoConsoleCancelEventBackground_method == (gpointer)(intptr_t)-1) { System_Console_DoConsoleCancelEventBackground_method = mono_class_get_method_from_name_checked (mono_defaults.console_class, "DoConsoleCancelEventInBackground", 0, 0, error); mono_error_assert_ok (error); } diff --git a/mono/metadata/coree.c b/mono/metadata/coree.c index a8a006a826..e10d66d24d 100644 --- a/mono/metadata/coree.c +++ b/mono/metadata/coree.c @@ -20,6 +20,7 @@ #include "cil-coff.h" #include "metadata-internals.h" #include "image.h" +#include "image-internals.h" #include "assembly-internals.h" #include "domain-internals.h" #include "appdomain.h" @@ -119,7 +120,7 @@ BOOL STDMETHODCALLTYPE _CorDllMain(HINSTANCE hInst, DWORD dwReason, LPVOID lpRes * loader trampolines should be used and assembly loading should * probably be delayed until the first call to an exported function. */ - if (image->tables [MONO_TABLE_ASSEMBLY].rows && ((MonoCLIImageInfo*) image->image_info)->cli_cli_header.ch_vtable_fixups.rva) + if (image->tables [MONO_TABLE_ASSEMBLY].rows && image->image_info->cli_cli_header.ch_vtable_fixups.rva) assembly = mono_assembly_open_predicate (file_name, MONO_ASMCTX_DEFAULT, NULL, NULL, NULL, NULL); g_free (file_name); @@ -129,7 +130,7 @@ BOOL STDMETHODCALLTYPE _CorDllMain(HINSTANCE hInst, DWORD dwReason, LPVOID lpRes /* The process is terminating. */ return TRUE; file_name = mono_get_module_file_name (hInst); - image = mono_image_loaded (file_name); + image = mono_image_loaded_internal (file_name, FALSE); if (image) mono_image_close (image); @@ -511,13 +512,13 @@ typedef struct _EXPORT_FIXUP /* Has to be binary ordered. */ static const EXPORT_FIXUP ExportFixups[] = { - {"CorBindToRuntime", {&CorBindToRuntime}}, - {"CorBindToRuntimeEx", {&CorBindToRuntimeEx}}, - {"CorExitProcess", {&CorExitProcess}}, - {"_CorDllMain", {&_CorDllMain}}, - {"_CorExeMain", {&_CorExeMain}}, - {"_CorImageUnloading", {&_CorImageUnloading}}, - {"_CorValidateImage", {&_CorValidateImage}}, + {"CorBindToRuntime", {(PVOID)&CorBindToRuntime}}, + {"CorBindToRuntimeEx", {(PVOID)&CorBindToRuntimeEx}}, + {"CorExitProcess", {(PVOID)&CorExitProcess}}, + {"_CorDllMain", {(PVOID)&_CorDllMain}}, + {"_CorExeMain", {(PVOID)&_CorExeMain}}, + {"_CorImageUnloading", {(PVOID)&_CorImageUnloading}}, + {"_CorValidateImage", {(PVOID)&_CorValidateImage}}, {NULL, {NULL}} }; @@ -827,7 +828,7 @@ STDAPI MonoFixupExe(HMODULE ModuleHandle) else { IMAGE_IMPORT_BY_NAME* ImportByName = (IMAGE_IMPORT_BY_NAME*)((DWORD_PTR)DosHeader + ImportThunkData->u1.AddressOfData); - ProcAddress = (DWORD_PTR)GetProcAddress(ImportModuleHandle, ImportByName->Name); + ProcAddress = (DWORD_PTR)GetProcAddress(ImportModuleHandle, (PCSTR)ImportByName->Name); } if (ProcAddress == 0) return E_FAIL; @@ -893,7 +894,7 @@ mono_coree_set_act_ctx (const char* file_name) act_ctx.dwFlags = ACTCTX_FLAG_SET_PROCESS_DEFAULT | ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID | ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_APPLICATION_NAME_VALID; act_ctx.lpSource = full_path_utf16; act_ctx.lpAssemblyDirectory = dir_name_utf16; - act_ctx.lpResourceName = MAKEINTRESOURCE (CREATEPROCESS_MANIFEST_RESOURCE_ID); + act_ctx.lpResourceName = CREATEPROCESS_MANIFEST_RESOURCE_ID; act_ctx.lpApplicationName = base_name_utf16; handle = CreateActCtx_proc (&act_ctx); diff --git a/mono/metadata/coree.h b/mono/metadata/coree.h index 5057ab1cf2..c4cd166edf 100644 --- a/mono/metadata/coree.h +++ b/mono/metadata/coree.h @@ -24,7 +24,7 @@ #define STATUS_SUCCESS 0x00000000L #define STATUS_INVALID_IMAGE_FORMAT 0xC000007BL -MONO_API STDAPI MonoFixupCorEE(HMODULE ModuleHandle); +MONO_API HRESULT STDAPICALLTYPE MonoFixupCorEE(HMODULE ModuleHandle); /* Defined by the linker. */ #ifndef _MSC_VER @@ -34,8 +34,7 @@ MONO_API STDAPI MonoFixupCorEE(HMODULE ModuleHandle); #define __ImageBase _image_base__ #endif #endif -extern IMAGE_DOS_HEADER __ImageBase; - +G_BEGIN_DECLS extern IMAGE_DOS_HEADER __ImageBase; G_END_DECLS extern HMODULE coree_module_handle; HMODULE WINAPI MonoLoadImage(LPCWSTR FileName); diff --git a/mono/metadata/custom-attrs.c b/mono/metadata/custom-attrs.c index 8c6fa272cd..ff5e5c4f11 100644 --- a/mono/metadata/custom-attrs.c +++ b/mono/metadata/custom-attrs.c @@ -133,15 +133,14 @@ free_param_data (MonoMethodSignature *sig, void **params) { */ static guint32 find_field_index (MonoClass *klass, MonoClassField *field) { - 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 (field == &klass_fields [i]) - return mono_class_get_first_field_idx (klass) + 1 + i; - } - return 0; + int index = field - klass_fields; + if (index > fcount) + return 0; + + g_assert (field == &klass_fields [index]); + return mono_class_get_first_field_idx (klass) + 1 + index; } /* @@ -377,13 +376,14 @@ handle_enum: if (slen > 0 && !bcheck_blob (p, slen - 1, boundp, error)) return NULL; *end = p + slen; + if (!out_obj) + return (void*)p; // https://bugzilla.xamarin.com/show_bug.cgi?id=60848 // Custom attribute strings are encoded as wtf-8 instead of utf-8. // If we decode using utf-8 like the spec says, we will silently fail // to decode some attributes in assemblies that Windows .NET Framework // and CoreCLR both manage to decode. // See https://simonsapin.github.io/wtf-8/ for a description of wtf-8. - g_assert (out_obj); *out_obj = (MonoObject*)mono_string_new_wtf8_len_checked (mono_domain_get (), p, slen, error); return NULL; case MONO_TYPE_CLASS: { @@ -1333,8 +1333,13 @@ reflection_resolve_custom_attribute_data (MonoReflectionMethod *ref_method, Mono for (i = 0; i < mono_method_signature (method)->param_count; ++i) { MonoObject *obj = mono_array_get (typedargs, MonoObject*, i); MonoObject *typedarg; + MonoType *t; + + t = mono_method_signature (method)->params [i]; + if (t->type == MONO_TYPE_OBJECT && obj) + t = m_class_get_byval_arg (obj->vtable->klass); + typedarg = create_cattr_typed_arg (t, obj, error); - typedarg = create_cattr_typed_arg (mono_method_signature (method)->params [i], obj, error); goto_if_nok (error, leave); mono_array_setref (typedargs, i, typedarg); } @@ -1400,9 +1405,11 @@ create_custom_attr_data (MonoImage *image, MonoCustomAttrEntry *cattr, MonoError MonoObjectHandle attr = mono_object_new_handle (domain, mono_defaults.customattribute_data_class, error); goto_if_nok (error, fail); - MonoReflectionMethodHandle ctor_obj = mono_method_get_object_handle (domain, cattr->ctor, NULL, error); + MonoReflectionMethodHandle ctor_obj; + ctor_obj = mono_method_get_object_handle (domain, cattr->ctor, NULL, error); goto_if_nok (error, fail); - MonoReflectionAssemblyHandle assm = mono_assembly_get_object_handle (domain, image->assembly, error); + MonoReflectionAssemblyHandle assm; + assm = mono_assembly_get_object_handle (domain, image->assembly, error); goto_if_nok (error, fail); params [0] = MONO_HANDLE_RAW (ctor_obj); params [1] = MONO_HANDLE_RAW (assm); diff --git a/mono/metadata/debug-helpers.c b/mono/metadata/debug-helpers.c index 993629b514..27a3877123 100644 --- a/mono/metadata/debug-helpers.c +++ b/mono/metadata/debug-helpers.c @@ -555,6 +555,8 @@ mono_method_desc_is_full (MonoMethodDesc *desc) 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)) diff --git a/mono/metadata/debug-mono-ppdb.c b/mono/metadata/debug-mono-ppdb.c index 9a5f7ed0fa..5531f5dc33 100644 --- a/mono/metadata/debug-mono-ppdb.c +++ b/mono/metadata/debug-mono-ppdb.c @@ -68,7 +68,7 @@ get_pe_debug_guid (MonoImage *image, guint8 *out_guid, gint32 *out_age, gint32 * MonoPEDirEntry *debug_dir_entry; ImageDebugDirectory *debug_dir; - debug_dir_entry = &((MonoCLIImageInfo*)image->image_info)->cli_header.datadir.pe_debug; + debug_dir_entry = &image->image_info->cli_header.datadir.pe_debug; if (!debug_dir_entry->size) return FALSE; diff --git a/mono/metadata/domain-internals.h b/mono/metadata/domain-internals.h index cc9045778a..375e955aa2 100644 --- a/mono/metadata/domain-internals.h +++ b/mono/metadata/domain-internals.h @@ -7,6 +7,7 @@ #ifndef __MONO_METADATA_DOMAIN_INTERNALS_H__ #define __MONO_METADATA_DOMAIN_INTERNALS_H__ +#include #include #include #include @@ -17,6 +18,7 @@ #include #include #include +#include /* * If this is set, the memory belonging to appdomains is not freed when a domain is @@ -205,6 +207,8 @@ typedef enum { JIT_INFO_HAS_UNWIND_INFO = (1 << 4) } MonoJitInfoFlags; +G_ENUM_FUNCTIONS (MonoJitInfoFlags) + struct _MonoJitInfo { /* NOTE: These first two elements (method and next_jit_code_hash) must be in the same order and at the @@ -213,12 +217,12 @@ struct _MonoJitInfo { union { MonoMethod *method; MonoImage *image; - gpointer aot_info; - gpointer tramp_info; + MonoAotModule *aot_info; + MonoTrampInfo *tramp_info; } d; union { - struct _MonoJitInfo *next_jit_code_hash; - struct _MonoJitInfo *next_tombstone; + MonoJitInfo *next_jit_code_hash; + MonoJitInfo *next_tombstone; } n; gpointer code_start; guint32 unwind_info; @@ -514,18 +518,28 @@ mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name); gpointer mono_domain_alloc (MonoDomain *domain, guint size); +#define mono_domain_alloc(domain, size) (g_cast (mono_domain_alloc ((domain), (size)))) + gpointer mono_domain_alloc0 (MonoDomain *domain, guint size); +#define mono_domain_alloc0(domain, size) (g_cast (mono_domain_alloc0 ((domain), (size)))) + gpointer mono_domain_alloc0_lock_free (MonoDomain *domain, guint size); +#define mono_domain_alloc0_lock_free(domain, size) (g_cast (mono_domain_alloc0_lock_free ((domain), (size)))) + void* mono_domain_code_reserve (MonoDomain *domain, int size) MONO_LLVM_INTERNAL; +#define mono_domain_code_reserve(domain, size) (g_cast (mono_domain_code_reserve ((domain), (size)))) + void* mono_domain_code_reserve_align (MonoDomain *domain, int size, int alignment); +#define mono_domain_code_reserve_align(domain, size, align) (g_cast (mono_domain_code_reserve_align ((domain), (size), (align)))) + void mono_domain_code_commit (MonoDomain *domain, void *data, int size, int newsize); @@ -603,12 +617,6 @@ MonoJitInfo* mono_jit_info_table_find_internal (MonoDomain *domain, gpointer add void mono_enable_debug_domain_unload (gboolean enable); -MonoReflectionAssembly * -mono_domain_try_type_resolve_name (MonoDomain *domain, const char *name, MonoError *error); - -MonoReflectionAssembly * -mono_domain_try_type_resolve_typebuilder (MonoDomain *domain, MonoReflectionTypeBuilder *typebuilder, MonoError *error); - void mono_runtime_init_checked (MonoDomain *domain, MonoThreadStartCB start_cb, MonoThreadAttachCB attach_cb, MonoError *error); diff --git a/mono/metadata/domain.c b/mono/metadata/domain.c index f598aa7c15..0144c35781 100644 --- a/mono/metadata/domain.c +++ b/mono/metadata/domain.c @@ -52,7 +52,7 @@ //#define DEBUG_DOMAIN_UNLOAD 1 -#define GET_APPDOMAIN() ((MonoDomain*)mono_tls_get_domain ()) +#define GET_APPDOMAIN mono_tls_get_domain #define SET_APPDOMAIN(x) do { \ MonoThreadInfo *info; \ mono_tls_set_domain (x); \ @@ -258,7 +258,7 @@ mono_string_equal (MonoString *s1, MonoString *s2) guint mono_string_hash (MonoString *s) { - const guint16 *p = mono_string_chars (s); + const gunichar2 *p = mono_string_chars (s); int i, len = mono_string_length (s); guint h = 0; @@ -859,6 +859,8 @@ mono_cleanup (void) { mono_close_exe_image (); + mono_thread_info_cleanup (); + mono_defaults.corlib = NULL; mono_config_cleanup (); @@ -1317,7 +1319,7 @@ mono_domain_get_friendly_name (MonoDomain *domain) * LOCKING: Acquires the domain lock. */ gpointer -mono_domain_alloc (MonoDomain *domain, guint size) +(mono_domain_alloc) (MonoDomain *domain, guint size) { gpointer res; @@ -1337,7 +1339,7 @@ mono_domain_alloc (MonoDomain *domain, guint size) * LOCKING: Acquires the domain lock. */ gpointer -mono_domain_alloc0 (MonoDomain *domain, guint size) +(mono_domain_alloc0) (MonoDomain *domain, guint size) { gpointer res; @@ -1352,7 +1354,7 @@ mono_domain_alloc0 (MonoDomain *domain, guint size) } gpointer -mono_domain_alloc0_lock_free (MonoDomain *domain, guint size) +(mono_domain_alloc0_lock_free) (MonoDomain *domain, guint size) { return lock_free_mempool_alloc0 (domain->lock_free_mp, size); } @@ -1363,7 +1365,7 @@ mono_domain_alloc0_lock_free (MonoDomain *domain, guint size) * LOCKING: Acquires the domain lock. */ void* -mono_domain_code_reserve (MonoDomain *domain, int size) +(mono_domain_code_reserve) (MonoDomain *domain, int size) { gpointer res; @@ -1380,7 +1382,7 @@ mono_domain_code_reserve (MonoDomain *domain, int size) * LOCKING: Acquires the domain lock. */ void* -mono_domain_code_reserve_align (MonoDomain *domain, int size, int alignment) +(mono_domain_code_reserve_align) (MonoDomain *domain, int size, int alignment) { gpointer res; diff --git a/mono/metadata/dynamic-image-internals.h b/mono/metadata/dynamic-image-internals.h index bb1084e981..39a7c0867e 100644 --- a/mono/metadata/dynamic-image-internals.h +++ b/mono/metadata/dynamic-image-internals.h @@ -46,10 +46,9 @@ MonoDynamicImage* mono_dynamic_image_create (MonoDynamicAssembly *assembly, char *assembly_name, char *module_name); guint32 -mono_dynamic_image_add_to_blob_cached (MonoDynamicImage *assembly, char *b1, int s1, char *b2, int s2); +mono_dynamic_image_add_to_blob_cached (MonoDynamicImage *assembly, gconstpointer b1, int s1, gconstpointer b2, int s2); void mono_dynimage_alloc_table (MonoDynamicTable *table, guint nrows); #endif /* __MONO_METADATA_DYNAMIC_IMAGE_INTERNALS_H__ */ - diff --git a/mono/metadata/dynamic-image.c b/mono/metadata/dynamic-image.c index 8270470135..dc35b2397d 100644 --- a/mono/metadata/dynamic-image.c +++ b/mono/metadata/dynamic-image.c @@ -177,8 +177,8 @@ mono_dynamic_image_register_token (MonoDynamicImage *assembly, guint32 token, Mo } #endif -static MonoObject* -lookup_dyn_token (MonoDynamicImage *assembly, guint32 token) +static gboolean +lookup_dyn_token (MonoDynamicImage *assembly, guint32 token, MonoObjectHandle *object_handle) { MONO_REQ_GC_UNSAFE_MODE; @@ -188,15 +188,19 @@ lookup_dyn_token (MonoDynamicImage *assembly, guint32 token) obj = (MonoObject *)mono_g_hash_table_lookup (assembly->tokens, GUINT_TO_POINTER (token)); dynamic_image_unlock (assembly); - return obj; + if (object_handle) + *object_handle = MONO_HANDLE_NEW (MonoObject, obj); + + return obj != NULL; } #ifndef DISABLE_REFLECTION_EMIT MonoObjectHandle mono_dynamic_image_get_registered_token (MonoDynamicImage *dynimage, guint32 token, MonoError *error) { - error_init (error); - return MONO_HANDLE_NEW (MonoObject, lookup_dyn_token (dynimage, token)); + MonoObjectHandle obj; + lookup_dyn_token (dynimage, token, &obj); + return obj; } #else /* DISABLE_REFLECTION_EMIT */ MonoObjectHandle @@ -217,7 +221,7 @@ mono_dynamic_image_get_registered_token (MonoDynamicImage *dynimage, guint32 tok gboolean mono_dynamic_image_is_valid_token (MonoDynamicImage *image, guint32 token) { - return lookup_dyn_token (image, token) != NULL; + return lookup_dyn_token (image, token, NULL); } #ifndef DISABLE_REFLECTION_EMIT @@ -238,14 +242,16 @@ mono_dynamic_image_is_valid_token (MonoDynamicImage *image, guint32 token) gpointer mono_reflection_lookup_dynamic_token (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context, MonoError *error) { + HANDLE_FUNCTION_ENTER (); + MonoDynamicImage *assembly = (MonoDynamicImage*)image; - MonoObject *obj; + MonoObjectHandle obj; MonoClass *klass; error_init (error); - obj = lookup_dyn_token (assembly, token); - if (!obj) { + lookup_dyn_token (assembly, token, &obj); + if (MONO_HANDLE_IS_NULL (obj)) { if (valid_token) g_error ("Could not find required dynamic token 0x%08x", token); else { @@ -256,8 +262,8 @@ mono_reflection_lookup_dynamic_token (MonoImage *image, guint32 token, gboolean if (!handle_class) handle_class = &klass; - gpointer result = mono_reflection_resolve_object (image, obj, handle_class, context, error); - return result; + gpointer result = mono_reflection_resolve_object_handle (image, obj, handle_class, context, error); + HANDLE_FUNCTION_RETURN_VAL (result); } #else /* DISABLE_REFLECTION_EMIT */ gpointer @@ -369,9 +375,9 @@ mono_dynamic_image_create (MonoDynamicAssembly *assembly, char *assembly_name, c /*g_print ("string heap create for image %p (%s)\n", image, module_name);*/ string_heap_init (&image->sheap); mono_dynstream_add_data (&image->us, "", 1); - mono_dynamic_image_add_to_blob_cached (image, (char*) "", 1, NULL, 0); + mono_dynamic_image_add_to_blob_cached (image, "", 1, NULL, 0); /* import tables... */ - mono_dynstream_add_data (&image->code, (char*)entrycode, sizeof (entrycode)); + mono_dynstream_add_data (&image->code, entrycode, sizeof (entrycode)); image->iat_offset = mono_dynstream_add_zero (&image->code, 8); /* two IAT entries */ image->idt_offset = mono_dynstream_add_zero (&image->code, 2 * sizeof (MonoIDT)); /* two IDT entries */ image->imp_names_offset = mono_dynstream_add_zero (&image->code, 2); /* flags for name entry */ @@ -416,7 +422,7 @@ mono_dynamic_image_create (MonoDynamicAssembly *assembly, char *assembly_name, c #endif /* DISABLE_REFLECTION_EMIT */ guint32 -mono_dynamic_image_add_to_blob_cached (MonoDynamicImage *assembly, char *b1, int s1, char *b2, int s2) +mono_dynamic_image_add_to_blob_cached (MonoDynamicImage *assembly, gconstpointer b1, int s1, gconstpointer b2, int s2) { MONO_REQ_GC_NEUTRAL_MODE; diff --git a/mono/metadata/dynamic-stream-internals.h b/mono/metadata/dynamic-stream-internals.h index 19570fb391..295019f4e2 100644 --- a/mono/metadata/dynamic-stream-internals.h +++ b/mono/metadata/dynamic-stream-internals.h @@ -19,7 +19,7 @@ guint32 mono_dynstream_insert_mstring (MonoDynamicStream *sh, MonoString *str, MonoError *error); guint32 -mono_dynstream_add_data (MonoDynamicStream *stream, const char *data, guint32 len); +mono_dynstream_add_data (MonoDynamicStream *stream, gconstpointer data, guint32 len); guint32 mono_dynstream_add_zero (MonoDynamicStream *stream, guint32 len); @@ -28,4 +28,3 @@ void mono_dynstream_data_align (MonoDynamicStream *stream); #endif /* __MONO_METADATA_DYNAMIC_STREAM_INTERNALS_H__ */ - diff --git a/mono/metadata/dynamic-stream.c b/mono/metadata/dynamic-stream.c index 0081f0e3fe..72ce25dabb 100644 --- a/mono/metadata/dynamic-stream.c +++ b/mono/metadata/dynamic-stream.c @@ -87,7 +87,7 @@ mono_dynstream_insert_mstring (MonoDynamicStream *sh, MonoString *str, MonoError } guint32 -mono_dynstream_add_data (MonoDynamicStream *stream, const char *data, guint32 len) +mono_dynstream_add_data (MonoDynamicStream *stream, gconstpointer data, guint32 len) { MONO_REQ_GC_NEUTRAL_MODE; diff --git a/mono/metadata/empty.c b/mono/metadata/empty.c new file mode 100644 index 0000000000..14b972d6cb --- /dev/null +++ b/mono/metadata/empty.c @@ -0,0 +1,4 @@ + +#include "utils/mono-compiler.h" + +MONO_EMPTY_SOURCE_FILE(empty); \ No newline at end of file diff --git a/mono/metadata/exception.c b/mono/metadata/exception.c index 0dc02bfee4..d4de1f13ab 100644 --- a/mono/metadata/exception.c +++ b/mono/metadata/exception.c @@ -660,7 +660,11 @@ mono_get_exception_argument_internal (const char *type, const char *arg, const c MonoException* mono_get_exception_argument_null (const char *arg) { - return mono_get_exception_argument_internal ("ArgumentNullException", arg, NULL); + MonoException *ex; + MONO_ENTER_GC_UNSAFE; + ex = mono_get_exception_argument_internal ("ArgumentNullException", arg, NULL); + MONO_EXIT_GC_UNSAFE; + return ex; } /** @@ -1146,7 +1150,7 @@ mono_exception_handle_get_native_backtrace (MonoExceptionHandle exc) len = mono_array_handle_length (arr); text = g_string_new_len (NULL, len * 20); uint32_t gchandle; - void *addr = MONO_ARRAY_HANDLE_PIN (arr, gpointer, 0, &gchandle); + gpointer *addr = MONO_ARRAY_HANDLE_PIN (arr, gpointer, 0, &gchandle); MONO_ENTER_GC_SAFE; messages = backtrace_symbols (addr, len); MONO_EXIT_GC_SAFE; diff --git a/mono/metadata/exception.h b/mono/metadata/exception.h index d05a0b239d..721dd493ae 100644 --- a/mono/metadata/exception.h +++ b/mono/metadata/exception.h @@ -100,7 +100,7 @@ mono_get_exception_not_implemented (const char *msg); MONO_API MonoException * mono_get_exception_not_supported (const char *msg); -MONO_API MonoException* +MONO_API MONO_RT_EXTERNAL_ONLY MonoException* mono_get_exception_argument_null (const char *arg); MONO_API MonoException * diff --git a/mono/metadata/file-mmap-posix.c b/mono/metadata/file-mmap-posix.c index 32618afd8f..1773bf4352 100644 --- a/mono/metadata/file-mmap-posix.c +++ b/mono/metadata/file-mmap-posix.c @@ -347,7 +347,7 @@ open_memory_map (const char *c_mapName, int mode, gint64 *capacity, int access, *ioerror = COULD_NOT_MAP_MEMORY; goto done; } - file_name = (char *)alloca (alloc_size); + file_name = g_newa (char, alloc_size); strcpy (file_name, tmp_dir); strcat (file_name, MONO_ANON_FILE_TEMPLATE); @@ -387,7 +387,7 @@ mono_mmap_open_file (const gunichar2 *path, gint path_length, int mode, const gu if (!mapName) { char * c_path = mono_utf16_to_utf8 (path, path_length, error); return_val_if_nok (error, NULL); - handle = open_file_map (c_path, -1, mode, capacity, access, options, ioerror); + handle = (MmapHandle*)open_file_map (c_path, -1, mode, capacity, access, options, ioerror); g_free (c_path); return handle; } @@ -416,7 +416,7 @@ mono_mmap_open_file (const gunichar2 *path, gint path_length, int mode, const gu } named_regions_unlock (); } else - handle = open_memory_map (c_mapName, mode, capacity, access, options, ioerror); + handle = (MmapHandle*)open_memory_map (c_mapName, mode, capacity, access, options, ioerror); g_free (c_mapName); return handle; diff --git a/mono/metadata/filewatcher.c b/mono/metadata/filewatcher.c index d3e0237e6c..c472b1a45c 100644 --- a/mono/metadata/filewatcher.c +++ b/mono/metadata/filewatcher.c @@ -64,24 +64,15 @@ ves_icall_System_IO_FSW_SupportsFSW (void) return 3; /* kqueue */ else return 6; /* CoreFX */ -#elif defined(HAVE_SYS_INOTIFY_H) && !defined(TARGET_ANDROID) +#elif defined(HAVE_SYS_INOTIFY_H) return 6; /* CoreFX */ #elif HAVE_KQUEUE return 3; /* kqueue */ #else MonoDl *fam_module; int lib_used = 4; /* gamin */ - int inotify_instance; char *err; -#if defined (TARGET_ANDROID) - inotify_instance = ves_icall_System_IO_InotifyWatcher_GetInotifyInstance (); - if (inotify_instance != -1) { - close (inotify_instance); - return 5; /* inotify */ - } -#endif - fam_module = mono_dl_open ("libgamin-1.so", MONO_DL_LAZY, NULL); if (fam_module == NULL) { lib_used = 2; /* FAM */ @@ -136,96 +127,12 @@ ves_icall_System_IO_FAMW_InternalFAMNextEvent (gpointer conn, } #endif -#if defined(TARGET_ANDROID) -#ifndef HAVE_SYS_INOTIFY_H -int ves_icall_System_IO_InotifyWatcher_GetInotifyInstance () -{ - return -1; -} - -int ves_icall_System_IO_InotifyWatcher_AddWatch (int fd, MonoString *directory, gint32 mask) -{ - return -1; -} - -int ves_icall_System_IO_InotifyWatcher_RemoveWatch (int fd, gint32 watch_descriptor) -{ - return -1; -} -#else -#include -#include - -int -ves_icall_System_IO_InotifyWatcher_GetInotifyInstance () -{ - return inotify_init (); -} - -int -ves_icall_System_IO_InotifyWatcher_AddWatch (int fd, MonoString *name, gint32 mask) -{ - ERROR_DECL (error); - char *str, *path; - int retval; - - if (name == NULL) - return -1; - - str = mono_string_to_utf8_checked (name, error); - if (mono_error_set_pending_exception (error)) - return -1; - path = mono_portability_find_file (str, TRUE); - if (!path) - path = str; - - retval = inotify_add_watch (fd, path, mask); - if (retval < 0) { - switch (errno) { - case EACCES: - errno = ERROR_ACCESS_DENIED; - break; - case EBADF: - errno = ERROR_INVALID_HANDLE; - break; - case EFAULT: - errno = ERROR_INVALID_ACCESS; - break; - case EINVAL: - errno = ERROR_INVALID_DATA; - break; - case ENOMEM: - errno = ERROR_NOT_ENOUGH_MEMORY; - break; - case ENOSPC: - errno = ERROR_TOO_MANY_OPEN_FILES; - break; - default: - errno = ERROR_GEN_FAILURE; - break; - } - mono_marshal_set_last_error (); - } - if (path != str) - g_free (path); - g_free (str); - return retval; -} - -int -ves_icall_System_IO_InotifyWatcher_RemoveWatch (int fd, gint32 watch_descriptor) -{ - return inotify_rm_watch (fd, watch_descriptor); -} -#endif -#endif - #if HAVE_KQUEUE static void interrupt_kevent (gpointer data) { - int *kq_ptr = data; + int *kq_ptr = (int*)data; /* Interrupt the kevent () call by closing the fd */ close (*kq_ptr); @@ -252,7 +159,7 @@ ves_icall_System_IO_KqueueMonitor_kevent_notimeout (int *kq_ptr, gpointer change } MONO_ENTER_GC_SAFE; - res = kevent (*kq_ptr, changelist, nchanges, eventlist, nevents, NULL); + res = kevent (*kq_ptr, (const struct kevent*)changelist, nchanges, (struct kevent*)eventlist, nevents, NULL); MONO_EXIT_GC_SAFE; mono_thread_info_uninstall_interrupt (&interrupted); @@ -270,18 +177,3 @@ ves_icall_System_IO_KqueueMonitor_kevent_notimeout (int *kq_ptr, gpointer change } #endif /* #if HAVE_KQUEUE */ - -#ifdef HOST_IOS - -MONO_API char* SystemNative_RealPath(const char* path) -{ - g_assert(path != NULL); - return realpath(path, NULL); -} - -MONO_API void SystemNative_Sync(void) -{ - sync(); -} - -#endif // HOST_IOS diff --git a/mono/metadata/filewatcher.h b/mono/metadata/filewatcher.h index 6404507e14..8d75e5ef2e 100644 --- a/mono/metadata/filewatcher.h +++ b/mono/metadata/filewatcher.h @@ -30,15 +30,6 @@ gboolean ves_icall_System_IO_FAMW_InternalFAMNextEvent (gpointer conn, MonoString **filename, gint *code, gint *reqnum); -ICALL_EXPORT -int ves_icall_System_IO_InotifyWatcher_GetInotifyInstance (void); - -ICALL_EXPORT -int ves_icall_System_IO_InotifyWatcher_AddWatch (int fd, MonoString *directory, gint32 mask); - -ICALL_EXPORT -int ves_icall_System_IO_InotifyWatcher_RemoveWatch (int fd, gint32 watch_descriptor); - ICALL_EXPORT int ves_icall_System_IO_KqueueMonitor_kevent_notimeout (int *kq, gpointer changelist, int nchanges, gpointer eventlist, int nevents); diff --git a/mono/metadata/gc-internals.h b/mono/metadata/gc-internals.h index ed57e02823..4930de6e9f 100644 --- a/mono/metadata/gc-internals.h +++ b/mono/metadata/gc-internals.h @@ -160,7 +160,13 @@ gboolean mono_gc_user_markers_supported (void); * size bytes will be available from the returned address (ie, descr * must not be stored in the returned memory) */ -void* mono_gc_alloc_fixed (size_t size, MonoGCDescriptor descr, MonoGCRootSource source, void *key, const char *msg); +MonoObject* mono_gc_alloc_fixed (size_t size, MonoGCDescriptor descr, MonoGCRootSource source, void *key, const char *msg); + +// C++ callers outside of metadata (mini/tasklets.c) must use mono_gc_alloc_fixed_no_descriptor +// instead of mono_gc_alloc_fixed, or else compile twice -- boehm and sgen. +MonoObject* +mono_gc_alloc_fixed_no_descriptor (size_t size, MonoGCRootSource source, void *key, const char *msg); + void mono_gc_free_fixed (void* addr); /* make sure the gchandle was allocated for an object in domain */ @@ -169,32 +175,39 @@ void mono_gchandle_free_domain (MonoDomain *domain); typedef void (*FinalizerThreadCallback) (gpointer user_data); -void* mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size); +MonoObject* +mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size); MonoObjectHandle mono_gc_alloc_handle_pinned_obj (MonoVTable *vtable, gsize size); -void* mono_gc_alloc_obj (MonoVTable *vtable, size_t size); +MonoObject* +mono_gc_alloc_obj (MonoVTable *vtable, size_t size); MonoObjectHandle mono_gc_alloc_handle_obj (MonoVTable *vtable, gsize size); -void* mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length); +MonoArray* +mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length); MonoArrayHandle mono_gc_alloc_handle_vector (MonoVTable *vtable, gsize size, gsize max_length); -void* mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size); +MonoArray* +mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size); MonoArrayHandle mono_gc_alloc_handle_array (MonoVTable *vtable, gsize size, gsize max_length, gsize bounds_size); -void* mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len); +MonoString* +mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len); MonoStringHandle mono_gc_alloc_handle_string (MonoVTable *vtable, gsize size, gint32 len); -void* mono_gc_alloc_mature (MonoVTable *vtable, size_t size); +MonoObject* +mono_gc_alloc_mature (MonoVTable *vtable, size_t size); + MonoGCDescriptor mono_gc_make_descr_for_string (gsize *bitmap, int numbits); MonoObjectHandle @@ -263,8 +276,12 @@ MonoMethod* mono_gc_get_write_barrier (void); /* Fast valuetype copy */ /* WARNING: [dest, dest + size] must be within the bounds of a single type, otherwise the GC will lose remset entries */ -void mono_gc_wbarrier_range_copy (gpointer dest, gpointer src, int size); -void* mono_gc_get_range_copy_func (void); +G_EXTERN_C void mono_gc_wbarrier_range_copy (gpointer dest, gconstpointer src, int size); + +typedef void (*MonoRangeCopyFunction)(gpointer, gconstpointer, int size); + +MonoRangeCopyFunction +mono_gc_get_range_copy_func (void); /* helper for the managed alloc support */ @@ -352,7 +369,7 @@ void* mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data); int mono_gc_get_los_limit (void); guint8* mono_gc_get_card_table (int *shift_bits, gpointer *card_mask); -guint8* mono_gc_get_target_card_table (int *shift_bits, gpointer *card_mask); +guint8* mono_gc_get_target_card_table (int *shift_bits, target_mgreg_t *card_mask); gboolean mono_gc_card_table_nursery_check (void); void* mono_gc_get_nursery (int *shift_bits, size_t *size); @@ -426,10 +443,13 @@ void mono_gc_register_altstack (gpointer stack, gint32 stack_size, gpointer alts gboolean mono_gc_is_critical_method (MonoMethod *method); +G_EXTERN_C // due to THREAD_INFO_TYPE varying gpointer mono_gc_thread_attach (THREAD_INFO_TYPE *info); +G_EXTERN_C // due to THREAD_INFO_TYPE varying void mono_gc_thread_detach_with_lock (THREAD_INFO_TYPE *info); +G_EXTERN_C // due to THREAD_INFO_TYPE varying gboolean mono_gc_thread_in_critical_region (THREAD_INFO_TYPE *info); /* If set, print debugging messages around finalizers. */ @@ -441,4 +461,3 @@ extern gboolean mono_do_not_finalize; extern gchar **mono_do_not_finalize_class_names; #endif /* __MONO_METADATA_GC_INTERNAL_H__ */ - diff --git a/mono/metadata/gc.c b/mono/metadata/gc.c index ca74b6708b..5349195b3d 100644 --- a/mono/metadata/gc.c +++ b/mono/metadata/gc.c @@ -46,6 +46,7 @@ #include #include #include +#include #ifndef HOST_WIN32 #include @@ -70,6 +71,7 @@ gchar **mono_do_not_finalize_class_names ; #define mono_finalizer_unlock() mono_coop_mutex_unlock (&finalizer_mutex) static MonoCoopMutex finalizer_mutex; static MonoCoopMutex reference_queue_mutex; +static mono_lazy_init_t reference_queue_mutex_inited = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED; static GSList *domains_to_finalize; @@ -320,8 +322,11 @@ mono_gc_run_finalize (void *obj, void *data) MONO_PROFILER_RAISE (gc_finalizing_object, (o)); #ifdef HOST_WASM - gpointer params[] = { NULL }; - mono_runtime_try_invoke (finalizer, o, params, &exc, error); + if (finalizer) { // null finalizers work fine when using the vcall invoke as Object has an empty one + gpointer params [1]; + params [0] = NULL; + mono_runtime_try_invoke (finalizer, o, params, &exc, error); + } #else runtime_invoke (o, NULL, &exc, NULL); #endif @@ -804,7 +809,7 @@ finalize_domain_objects (void) DomainFinalizationReq *req = NULL; MonoDomain *domain; - if (UnlockedReadPointer ((gpointer)&domains_to_finalize)) { + if (UnlockedReadPointer ((gpointer volatile*)&domains_to_finalize)) { mono_finalizer_lock (); if (domains_to_finalize) { req = (DomainFinalizationReq *)domains_to_finalize->data; @@ -954,15 +959,21 @@ void mono_gc_init_finalizer_thread (void) { ERROR_DECL (error); - gc_thread = mono_thread_create_internal (mono_domain_get (), finalizer_thread, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error); + gc_thread = mono_thread_create_internal (mono_domain_get (), (gpointer)finalizer_thread, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error); mono_error_assert_ok (error); } +static void +reference_queue_mutex_init (void) +{ + mono_coop_mutex_init_recursive (&reference_queue_mutex); +} + void mono_gc_init (void) { + mono_lazy_initialize (&reference_queue_mutex_inited, reference_queue_mutex_init); mono_coop_mutex_init_recursive (&finalizer_mutex); - mono_coop_mutex_init_recursive (&reference_queue_mutex); mono_counters_register ("Minor GC collections", MONO_COUNTER_GC | MONO_COUNTER_INT, &mono_gc_stats.minor_gc_count); mono_counters_register ("Major GC collections", MONO_COUNTER_GC | MONO_COUNTER_INT, &mono_gc_stats.major_gc_count); @@ -989,7 +1000,8 @@ mono_gc_init (void) mono_coop_sem_init (&finalizer_sem, 0); #ifndef LAZY_GC_THREAD_CREATION - mono_gc_init_finalizer_thread (); + if (!mono_runtime_get_no_exec ()) + mono_gc_init_finalizer_thread (); #endif } @@ -1237,6 +1249,7 @@ mono_gc_reference_queue_new_internal (mono_reference_queue_callback callback) MonoReferenceQueue *res = g_new0 (MonoReferenceQueue, 1); res->callback = callback; + mono_lazy_initialize (&reference_queue_mutex_inited, reference_queue_mutex_init); mono_coop_mutex_lock (&reference_queue_mutex); res->next = ref_queues; ref_queues = res; @@ -1281,7 +1294,9 @@ mono_gc_reference_queue_add_internal (MonoReferenceQueue *queue, MonoObject *obj entry->domain = mono_object_domain (obj); entry->gchandle = mono_gchandle_new_weakref (obj, TRUE); +#ifndef HAVE_SGEN_GC mono_object_register_finalizer (obj); +#endif ref_list_push (&queue->queue, entry); return TRUE; diff --git a/mono/metadata/handle-decl.h b/mono/metadata/handle-decl.h new file mode 100644 index 0000000000..7ca337dd9e --- /dev/null +++ b/mono/metadata/handle-decl.h @@ -0,0 +1,135 @@ +/** + * \file + * Handle to object in native code + * + * Authors: + * - Ludovic Henry + * - Aleksey Klieger + * - Rodrigo Kumpera + * + * Copyright 2016 Dot net foundation. + * Licensed under the MIT license. See LICENSE file in the project root for full license information. + */ + +#ifndef __MONO_HANDLE_DECL_H__ +#define __MONO_HANDLE_DECL_H__ + +#include +#include +#include +#include + +// Type-safe handles are a struct with a pointer to pointer. +// The only operations allowed on them are the functions/macros in this file, and assignment +// from same handle type to same handle type. +// +// Type-unsafe handles are a pointer to a struct with a pointer. +// Besides the type-safe operations, these can also be: +// 1. compared to NULL, instead of only MONO_HANDLE_IS_NULL +// 2. assigned from NULL, instead of only a handle +// 3. MONO_HANDLE_NEW (T) from anything, instead of only a T* +// 4. MONO_HANDLE_CAST from anything, instead of only another handle type +// 5. assigned from any void*, at least in C +// 6. Cast from any handle type to any handle type, without using MONO_HANDLE_CAST. +// 7. Cast from any handle type to any pointer type and vice versa, such as incorrect unboxing. +// 8. mono_object_class (handle), instead of mono_handle_class +// +// None of those operations were likely intended. +// +// FIXME Do this only on checked builds? Or certain architectures? +// There is not runtime cost. +// NOTE: Running this code depends on the ABI to pass a struct +// with a pointer the same as a pointer. This is tied in with +// marshaling. If this is not the case, turn off type-safety, perhaps per-OS per-CPU. +#if defined (HOST_DARWIN) || defined (HOST_WIN32) || defined (HOST_ARM64) || defined (HOST_ARM) || defined (HOST_AMD64) +#define MONO_TYPE_SAFE_HANDLES 1 +#else +#define MONO_TYPE_SAFE_HANDLES 0 // PowerPC, S390X, SPARC, MIPS, Linux/x86, BSD/x86, etc. +#endif + +/* +Handle macros/functions +*/ + +#define TYPED_HANDLE_PAYLOAD_NAME(TYPE) TYPE ## HandlePayload +#define TYPED_HANDLE_NAME(TYPE) TYPE ## Handle +#define TYPED_OUT_HANDLE_NAME(TYPE) TYPE ## HandleOut + +// internal helpers: +#define MONO_HANDLE_CAST_FOR(type) mono_handle_cast_##type +#define MONO_HANDLE_TYPECHECK_FOR(type) mono_handle_typecheck_##type + +/* + * TYPED_HANDLE_DECL(SomeType): + * Expands to a decl for handles to SomeType and to an internal payload struct. + * + * For example, TYPED_HANDLE_DECL(MonoObject) (see below) expands to: + * + * #if MONO_TYPE_SAFE_HANDLES + * + * typedef struct { + * MonoObject **__raw; + * } MonoObjectHandlePayload, + * MonoObjectHandle, + * MonoObjectHandleOut; + * + * Internal helper functions are also generated. + * + * #else + * + * typedef struct { + * MonoObject *__raw; + * } MonoObjectHandlePayload; + * + * typedef MonoObjectHandlePayload* MonoObjectHandle; + * typedef MonoObjectHandlePayload* MonoObjectHandleOut; + * + * #endif + */ + +#ifdef __cplusplus +#define MONO_IF_CPLUSPLUS(x) x +#else +#define MONO_IF_CPLUSPLUS(x) /* nothing */ +#endif + +#if MONO_TYPE_SAFE_HANDLES +#define TYPED_HANDLE_DECL(TYPE) \ + typedef struct { \ + MONO_IF_CPLUSPLUS ( \ + MONO_ALWAYS_INLINE \ + TYPE * GetRaw () { return __raw ? *__raw : NULL; } \ + ) \ + TYPE **__raw; \ + } TYPED_HANDLE_PAYLOAD_NAME (TYPE), \ + TYPED_HANDLE_NAME (TYPE), \ + TYPED_OUT_HANDLE_NAME (TYPE); \ +/* Do not call these functions directly. Use MONO_HANDLE_NEW and MONO_HANDLE_CAST. */ \ +/* Another way to do this involved casting mono_handle_new function to a different type. */ \ +static inline MONO_ALWAYS_INLINE TYPED_HANDLE_NAME (TYPE) \ +MONO_HANDLE_CAST_FOR (TYPE) (gpointer a) \ +{ \ + TYPED_HANDLE_NAME (TYPE) b = { (TYPE**)a }; \ + return b; \ +} \ +static inline MONO_ALWAYS_INLINE MonoObject* \ +MONO_HANDLE_TYPECHECK_FOR (TYPE) (TYPE *a) \ +{ \ + return (MonoObject*)a; \ +} + +#else +#define TYPED_HANDLE_DECL(TYPE) \ + typedef struct { TYPE *__raw; } TYPED_HANDLE_PAYLOAD_NAME (TYPE) ; \ + typedef TYPED_HANDLE_PAYLOAD_NAME (TYPE) * TYPED_HANDLE_NAME (TYPE); \ + typedef TYPED_HANDLE_PAYLOAD_NAME (TYPE) * TYPED_OUT_HANDLE_NAME (TYPE); +#endif + +/* + * TYPED_VALUE_HANDLE_DECL(SomeType): + * Expands to a decl for handles to SomeType (which is a managed valuetype (likely a struct) of some sort) and to an internal payload struct. + * It is currently identical to TYPED_HANDLE_DECL (valuetypes vs. referencetypes). + */ +#define TYPED_VALUE_HANDLE_DECL(TYPE) TYPED_HANDLE_DECL(TYPE) + +#endif /* __MONO_HANDLE_DECL_H__ */ diff --git a/mono/metadata/handle.c b/mono/metadata/handle.c index e0ff8f58f7..3988fdeae7 100644 --- a/mono/metadata/handle.c +++ b/mono/metadata/handle.c @@ -94,7 +94,7 @@ free_handle_chunk (HandleChunk *chunk) g_free (chunk); } -const MonoObjectHandle mono_null_value_handle; +const MonoObjectHandle mono_null_value_handle = { 0 }; #define THIS_IS_AN_OK_NUMBER_OF_HANDLES 100 @@ -198,7 +198,7 @@ mono_handle_new (MonoObject *obj, const char *owner) #endif { MonoThreadInfo *info = mono_thread_info_current (); - HandleStack *handles = (HandleStack *)info->handle_stack; + HandleStack *handles = info->handle_stack; HandleChunk *top = handles->top; #ifdef MONO_HANDLE_TRACK_SP mono_handle_chunk_leak_check (handles); @@ -252,7 +252,7 @@ mono_handle_new_interior (gpointer rawptr, const char *owner) #endif { MonoThreadInfo *info = mono_thread_info_current (); - HandleStack *handles = (HandleStack *)info->handle_stack; + HandleStack *handles = info->handle_stack; HandleChunk *top = handles->interior; #ifdef MONO_HANDLE_TRACK_SP mono_handle_chunk_leak_check (handles); @@ -428,7 +428,7 @@ mono_handle_stack_scan (HandleStack *stack, GcScanFunc func, gpointer gc_data, g void mono_stack_mark_record_size (MonoThreadInfo *info, HandleStackMark *stackmark, const char *func_name) { - HandleStack *handles = (HandleStack *)info->handle_stack; + HandleStack *handles = info->handle_stack; HandleChunk *cur = stackmark->chunk; int size = -stackmark->size; //discard the starting point of the stack while (cur) { @@ -493,7 +493,7 @@ mono_gchandle_from_handle (MonoObjectHandle handle, mono_bool pinned) /* FIXME: chunk_element_to_chunk_idx does a linear search through the * chunks and we only need it for the assert */ MonoThreadInfo *info = mono_thread_info_current (); - HandleStack *stack = (HandleStack*) info->handle_stack; + HandleStack *stack = info->handle_stack; HandleChunkElem* elem = handle_to_chunk_element (handle); int elem_idx = 0; HandleChunk *chunk = chunk_element_to_chunk_idx (stack, elem, &elem_idx); diff --git a/mono/metadata/handle.h b/mono/metadata/handle.h index 4a4a2aedb0..c5bf17bbef 100644 --- a/mono/metadata/handle.h +++ b/mono/metadata/handle.h @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -24,34 +25,6 @@ #include #include -// Type-safe handles are a struct with a pointer to pointer. -// The only operations allowed on them are the functions/macros in this file, and assignment -// from same handle type to same handle type. -// -// Type-unsafe handles are a pointer to a struct with a pointer. -// Besides the type-safe operations, these can also be: -// 1. compared to NULL, instead of only MONO_HANDLE_IS_NULL -// 2. assigned from NULL, instead of only a handle -// 3. MONO_HANDLE_NEW (T) from anything, instead of only a T* -// 4. MONO_HANDLE_CAST from anything, instead of only another handle type -// 5. assigned from any void*, at least in C -// 6. Cast from any handle type to any handle type, without using MONO_HANDLE_CAST. -// 7. Cast from any handle type to any pointer type and vice versa, such as incorrect unboxing. -// 8. mono_object_class (handle), instead of mono_handle_class -// -// None of those operations were likely intended. -// -// FIXME Do this only on checked builds? Or certain architectures? -// There is not runtime cost. -// NOTE: Running this code depends on the ABI to pass a struct -// with a pointer the same as a pointer. This is tied in with -// marshaling. If this is not the case, turn off type-safety, perhaps per-OS per-CPU. -#if defined (HOST_DARWIN) || defined (HOST_WIN32) || defined (HOST_ARM64) || defined (HOST_ARM) || defined (HOST_AMD64) -#define MONO_TYPE_SAFE_HANDLES 1 -#else -#define MONO_TYPE_SAFE_HANDLES 0 // PowerPC, S390X, SPARC, MIPS, Linux/x86, BSD/x86, etc. -#endif - G_BEGIN_DECLS /* @@ -112,7 +85,7 @@ struct _HandleChunk { HandleChunkElem elems [OBJECTS_PER_HANDLES_CHUNK]; }; -typedef struct { +typedef struct MonoHandleStack { HandleChunk *top; //alloc from here HandleChunk *bottom; //scan from here #ifdef MONO_HANDLE_TRACK_SP @@ -177,7 +150,7 @@ mono_stack_mark_init (MonoThreadInfo *info, HandleStackMark *stackmark) #ifdef MONO_HANDLE_TRACK_SP gpointer sptop = &stackmark; #endif - HandleStack *handles = (HandleStack *)info->handle_stack; + HandleStack *handles = info->handle_stack; stackmark->size = handles->top->size; stackmark->chunk = handles->top; stackmark->interior_size = handles->interior->size; @@ -190,7 +163,7 @@ mono_stack_mark_init (MonoThreadInfo *info, HandleStackMark *stackmark) static inline void mono_stack_mark_pop (MonoThreadInfo *info, HandleStackMark *stackmark) { - HandleStack *handles = (HandleStack *)info->handle_stack; + HandleStack *handles = info->handle_stack; HandleChunk *old_top = stackmark->chunk; old_top->size = stackmark->size; mono_memory_write_barrier (); @@ -224,7 +197,7 @@ Icall macros #define CLEAR_ICALL_FRAME_VALUE(RESULT, HANDLE) \ mono_stack_mark_record_size (__info, &__mark, __FUNCTION__); \ - (RESULT) = mono_stack_mark_pop_value (__info, &__mark, (HANDLE)); + (RESULT) = g_cast (mono_stack_mark_pop_value (__info, &__mark, (HANDLE))); #define HANDLE_FUNCTION_ENTER() do { \ MonoThreadInfo *__info = mono_thread_info_current (); \ @@ -245,7 +218,7 @@ Icall macros do { \ void* __result = MONO_HANDLE_RAW (HANDLE); \ CLEAR_ICALL_FRAME; \ - return __result; \ + return g_cast (__result); \ } while (0); } while (0); #if MONO_TYPE_SAFE_HANDLES @@ -326,89 +299,18 @@ mono_thread_info_push_stack_mark (MonoThreadInfo *info, void *mark) CLEAR_ICALL_COMMON \ void* __ret = MONO_HANDLE_RAW (HANDLE); \ CLEAR_ICALL_FRAME \ - return __ret; \ + return g_cast (__ret); \ } while (0); } while (0) /* Handle macros/functions */ - -#define TYPED_HANDLE_PAYLOAD_NAME(TYPE) TYPE ## HandlePayload -#define TYPED_HANDLE_NAME(TYPE) TYPE ## Handle -#define TYPED_OUT_HANDLE_NAME(TYPE) TYPE ## HandleOut - -// internal helpers: -#define MONO_HANDLE_CAST_FOR(type) mono_handle_cast_##type -#define MONO_HANDLE_TYPECHECK_FOR(type) mono_handle_typecheck_##type - #ifdef MONO_HANDLE_TRACK_OWNER #define STRINGIFY_(x) #x #define STRINGIFY(x) STRINGIFY_(x) #define HANDLE_OWNER (__FILE__ ":" STRINGIFY (__LINE__)) #endif - -/* - * TYPED_HANDLE_DECL(SomeType): - * Expands to a decl for handles to SomeType and to an internal payload struct. - * - * For example, TYPED_HANDLE_DECL(MonoObject) (see below) expands to: - * - * #if MONO_TYPE_SAFE_HANDLES - * - * typedef struct { - * MonoObject **__raw; - * } MonoObjectHandlePayload, - * MonoObjectHandle, - * MonoObjectHandleOut; - * - * Internal helper functions are also generated. - * - * #else - * - * typedef struct { - * MonoObject *__raw; - * } MonoObjectHandlePayload; - * - * typedef MonoObjectHandlePayload* MonoObjectHandle; - * typedef MonoObjectHandlePayload* MonoObjectHandleOut; - * - * #endif - */ - -#if MONO_TYPE_SAFE_HANDLES -#define TYPED_HANDLE_DECL(TYPE) \ - typedef struct { TYPE **__raw; } TYPED_HANDLE_PAYLOAD_NAME (TYPE), \ - TYPED_HANDLE_NAME (TYPE), \ - TYPED_OUT_HANDLE_NAME (TYPE); \ -/* Do not call these functions directly. Use MONO_HANDLE_NEW and MONO_HANDLE_CAST. */ \ -/* Another way to do this involved casting mono_handle_new function to a different type. */ \ -static inline MONO_ALWAYS_INLINE TYPED_HANDLE_NAME (TYPE) \ -MONO_HANDLE_CAST_FOR (TYPE) (gpointer a) \ -{ \ - TYPED_HANDLE_NAME (TYPE) b = { (TYPE**)a }; \ - return b; \ -} \ -static inline MONO_ALWAYS_INLINE gpointer \ -MONO_HANDLE_TYPECHECK_FOR (TYPE) (TYPE *a) \ -{ \ - return a; \ -} - -#else -#define TYPED_HANDLE_DECL(TYPE) \ - typedef struct { TYPE *__raw; } TYPED_HANDLE_PAYLOAD_NAME (TYPE) ; \ - typedef TYPED_HANDLE_PAYLOAD_NAME (TYPE) * TYPED_HANDLE_NAME (TYPE); \ - typedef TYPED_HANDLE_PAYLOAD_NAME (TYPE) * TYPED_OUT_HANDLE_NAME (TYPE) -#endif - -/* - * TYPED_VALUE_HANDLE_DECL(SomeType): - * Expands to a decl for handles to SomeType (which is a managed valuetype (likely a struct) of some sort) and to an internal payload struct. - * It is currently identical to TYPED_HANDLE_DECL (valuetypes vs. referencetypes). - */ -#define TYPED_VALUE_HANDLE_DECL(TYPE) TYPED_HANDLE_DECL(TYPE) - /* Have to double expand because MONO_STRUCT_OFFSET is doing token pasting on cross-compilers. */ #define MONO_HANDLE_PAYLOAD_OFFSET_(PayloadType) MONO_STRUCT_OFFSET(PayloadType, __raw) #define MONO_HANDLE_PAYLOAD_OFFSET(TYPE) MONO_HANDLE_PAYLOAD_OFFSET_(TYPED_HANDLE_PAYLOAD_NAME (TYPE)) @@ -424,7 +326,7 @@ MONO_HANDLE_TYPECHECK_FOR (TYPE) (TYPE *a) \ typedef struct _MonoTypeofCastHelper *MonoTypeofCastHelper; // a pointer type unrelated to anything else #define MONO_TYPEOF_CAST(typeexpr, expr) __pragma(warning(suppress:4133))(0 ? (typeexpr) : (MonoTypeofCastHelper)(expr)) #else -#define MONO_TYPEOF_CAST(typeexpr, expr) ((typeof (typeexpr))(expr)) +#define MONO_TYPEOF_CAST(typeexpr, expr) ((__typeof__ (typeexpr))(expr)) #endif #if MONO_TYPE_SAFE_HANDLES @@ -442,7 +344,11 @@ typedef struct _MonoTypeofCastHelper *MonoTypeofCastHelper; // a pointer type un #endif #define MONO_HANDLE_CAST(type, value) (MONO_HANDLE_CAST_FOR (type) ((value).__raw)) +#ifdef __cplusplus +#define MONO_HANDLE_RAW(handle) ((handle).GetRaw()) +#else #define MONO_HANDLE_RAW(handle) (MONO_TYPEOF_CAST (*(handle).__raw, mono_handle_raw ((handle).__raw))) +#endif #define MONO_HANDLE_IS_NULL(handle) (mono_handle_is_null ((handle).__raw)) #else // MONO_TYPE_SAFE_HANDLES @@ -459,6 +365,9 @@ typedef struct _MonoTypeofCastHelper *MonoTypeofCastHelper; // a pointer type un #endif // MONO_TYPE_SAFE_HANDLES +#define MONO_BOOL(x) (!!MONO_HANDLE_SUPPRESS (x)) +#define MONO_HANDLE_BOOL(handle) (MONO_BOOL (!MONO_HANDLE_IS_NULL (handle))) + /* WARNING WARNING WARNING @@ -500,12 +409,17 @@ This is why we evaluate index and value before any call to MONO_HANDLE_RAW or ot #endif -// Get ((type)handle)->field as a handle. +// Get handle->field as a type-handle. #define MONO_HANDLE_NEW_GET(TYPE,HANDLE,FIELD) (MONO_HANDLE_NEW(TYPE,MONO_HANDLE_SUPPRESS (MONO_HANDLE_RAW (MONO_HANDLE_UNSUPPRESS (HANDLE))->FIELD))) // Get handle->field, where field is not a pointer (an integer or non-managed pointer). #define MONO_HANDLE_GETVAL(HANDLE, FIELD) MONO_HANDLE_SUPPRESS (MONO_HANDLE_RAW (MONO_HANDLE_UNSUPPRESS (HANDLE))->FIELD) +// Get handle->field as a boolean, i.e. typically compare managed pointer to NULL, +// though any type is ok. +#define MONO_HANDLE_GET_BOOL(handle, field) (MONO_BOOL (MONO_HANDLE_GETVAL (handle, field))) + +// handle->field = (type)value, for non-managed pointers // This would be easier to write with the gcc extension typeof, // but it is not widely enough implemented (i.e. Microsoft C). #define MONO_HANDLE_SETVAL(HANDLE, FIELD, TYPE, VALUE) do { \ @@ -561,6 +475,7 @@ This is why we evaluate index and value before any call to MONO_HANDLE_RAW or ot * of the field. It's the caller's responsibility to check that the object is * of the correct class. */ #define MONO_HANDLE_GET_FIELD_VAL(HANDLE,TYPE,FIELD) (*(TYPE *)(mono_handle_unsafe_field_addr (MONO_HANDLE_CAST (MonoObject, (HANDLE)), (FIELD)))) +#define MONO_HANDLE_GET_FIELD_BOOL(handle, type, field) (MONO_BOOL (MONO_HANDLE_GET_FIELD_VAL ((handle), type, (field)))) #define MONO_HANDLE_NEW_GET_FIELD(HANDLE,TYPE,FIELD) MONO_HANDLE_NEW (TYPE, MONO_HANDLE_SUPPRESS (*(TYPE**)(mono_handle_unsafe_field_addr (MONO_HANDLE_CAST (MonoObject, MONO_HANDLE_UNSUPPRESS (HANDLE)), (FIELD))))) @@ -638,6 +553,7 @@ be reviewed and probably changed FIXME. */ extern const MonoObjectHandle mono_null_value_handle; #define NULL_HANDLE mono_null_value_handle +#define NULL_HANDLE_INIT { 0 } #define NULL_HANDLE_STRING (MONO_HANDLE_CAST (MonoString, NULL_HANDLE)) #define NULL_HANDLE_ARRAY (MONO_HANDLE_CAST (MonoArray, NULL_HANDLE)) @@ -730,7 +646,7 @@ mono_array_handle_memcpy_refs (MonoArrayHandle dest, uintptr_t dest_idx, MonoArr gpointer mono_array_handle_pin_with_size (MonoArrayHandle handle, int size, uintptr_t index, uint32_t *gchandle); -#define MONO_ARRAY_HANDLE_PIN(handle,type,index,gchandle_out) mono_array_handle_pin_with_size (MONO_HANDLE_CAST(MonoArray,(handle)), sizeof (type), (index), (gchandle_out)) +#define MONO_ARRAY_HANDLE_PIN(handle,type,index,gchandle_out) ((type*)mono_array_handle_pin_with_size (MONO_HANDLE_CAST(MonoArray,(handle)), sizeof (type), (index), (gchandle_out))) gunichar2 * mono_string_handle_pin_chars (MonoStringHandle s, uint32_t *gchandle_out); diff --git a/mono/metadata/icall-def.h b/mono/metadata/icall-def.h index 900da62748..b0d29b5187 100644 --- a/mono/metadata/icall-def.h +++ b/mono/metadata/icall-def.h @@ -201,7 +201,7 @@ HANDLES(ICALL(CONSOLE_4, "SetEcho", ves_icall_System_ConsoleDriver_SetEcho)) HANDLES(ICALL(CONSOLE_5, "TtySetup", ves_icall_System_ConsoleDriver_TtySetup)) ICALL_TYPE(DTIME, "System.DateTime", DTIME_1) -ICALL(DTIME_1, "GetSystemTimeAsFileTime", mono_100ns_datetime) +ICALL(DTIME_1, "GetSystemTimeAsFileTime", ves_icall_System_DateTime_GetSystemTimeAsFileTime) ICALL_TYPE(DELEGATE, "System.Delegate", DELEGATE_1) HANDLES(ICALL(DELEGATE_1, "AllocDelegateLike_internal", ves_icall_System_Delegate_AllocDelegateLike_internal)) @@ -245,7 +245,7 @@ ICALL(PROCESS_10, "ProcessName_internal(intptr)", ves_icall_System_Diagnostics_P HANDLES(ICALL(PROCESS_13, "ShellExecuteEx_internal(System.Diagnostics.ProcessStartInfo,System.Diagnostics.Process/ProcInfo&)", ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal)) ICALL_TYPE(STOPWATCH, "System.Diagnostics.Stopwatch", STOPWATCH_1) -ICALL(STOPWATCH_1, "GetTimestamp", mono_100ns_ticks) +ICALL(STOPWATCH_1, "GetTimestamp", ves_icall_System_Diagnostics_Stopwatch_GetTimestamp) ICALL_TYPE(ENUM, "System.Enum", ENUM_1) HANDLES(ICALL(ENUM_1, "GetEnumValuesAndNames", ves_icall_System_Enum_GetEnumValuesAndNames)) @@ -320,6 +320,15 @@ ICALL_TYPE(REGINF, "System.Globalization.RegionInfo", REGINF_1) ICALL(REGINF_1, "construct_internal_region_from_lcid", ves_icall_System_Globalization_RegionInfo_construct_internal_region_from_lcid) ICALL(REGINF_2, "construct_internal_region_from_name", ves_icall_System_Globalization_RegionInfo_construct_internal_region_from_name) +#if defined(ENABLE_MONODROID) || defined(ENABLE_MONOTOUCH) +ICALL_TYPE(DEFLATESTREAM, "System.IO.Compression.DeflateStreamNative", DEFLATESTREAM_1) +NOHANDLES(ICALL(DEFLATESTREAM_1, "CloseZStream", ves_icall_System_IO_Compression_DeflateStreamNative_CloseZStream)) +NOHANDLES(ICALL(DEFLATESTREAM_2, "CreateZStream", ves_icall_System_IO_Compression_DeflateStreamNative_CreateZStream)) +NOHANDLES(ICALL(DEFLATESTREAM_3, "Flush", ves_icall_System_IO_Compression_DeflateStreamNative_Flush)) +NOHANDLES(ICALL(DEFLATESTREAM_4, "ReadZStream", ves_icall_System_IO_Compression_DeflateStreamNative_ReadZStream)) +NOHANDLES(ICALL(DEFLATESTREAM_5, "WriteZStream", ves_icall_System_IO_Compression_DeflateStreamNative_WriteZStream)) +#endif + #ifndef PLATFORM_NO_DRIVEINFO ICALL_TYPE(IODRIVEINFO, "System.IO.DriveInfo", IODRIVEINFO_1) ICALL(IODRIVEINFO_1, "GetDiskFreeSpaceInternal", ves_icall_System_IO_DriveInfo_GetDiskFreeSpace) @@ -333,13 +342,6 @@ ICALL(FAMW_1, "InternalFAMNextEvent", ves_icall_System_IO_FAMW_InternalFAMNextEv ICALL_TYPE(FILEW, "System.IO.FileSystemWatcher", FILEW_4) ICALL(FILEW_4, "InternalSupportsFSW", ves_icall_System_IO_FSW_SupportsFSW) -#if defined (TARGET_ANDROID) -ICALL_TYPE(INOW, "System.IO.InotifyWatcher", INOW_1) -ICALL(INOW_1, "AddWatch", ves_icall_System_IO_InotifyWatcher_AddWatch) -ICALL(INOW_2, "GetInotifyInstance", ves_icall_System_IO_InotifyWatcher_GetInotifyInstance) -ICALL(INOW_3, "RemoveWatch", ves_icall_System_IO_InotifyWatcher_RemoveWatch) -#endif - ICALL_TYPE(KQUEM, "System.IO.KqueueMonitor", KQUEM_1) ICALL(KQUEM_1, "kevent_notimeout", ves_icall_System_IO_KqueueMonitor_kevent_notimeout) @@ -414,21 +416,26 @@ ICALL_TYPE(MATH, "System.Math", MATH_19) NOHANDLES(ICALL(MATH_19, "Abs(double)", ves_icall_System_Math_Abs_double)) NOHANDLES(ICALL(MATH_20, "Abs(single)", ves_icall_System_Math_Abs_single)) NOHANDLES(ICALL(MATH_1, "Acos", ves_icall_System_Math_Acos)) +NOHANDLES(ICALL(MATH_1a, "Acosh", ves_icall_System_Math_Acosh)) NOHANDLES(ICALL(MATH_2, "Asin", ves_icall_System_Math_Asin)) +NOHANDLES(ICALL(MATH_2a, "Asinh", ves_icall_System_Math_Asinh)) NOHANDLES(ICALL(MATH_3, "Atan", ves_icall_System_Math_Atan)) NOHANDLES(ICALL(MATH_4, "Atan2", ves_icall_System_Math_Atan2)) +NOHANDLES(ICALL(MATH_4a, "Atanh", ves_icall_System_Math_Atanh)) +NOHANDLES(ICALL(MATH_4b, "Cbrt", ves_icall_System_Math_Cbrt)) NOHANDLES(ICALL(MATH_21, "Ceiling", ves_icall_System_Math_Ceiling)) NOHANDLES(ICALL(MATH_5, "Cos", ves_icall_System_Math_Cos)) NOHANDLES(ICALL(MATH_6, "Cosh", ves_icall_System_Math_Cosh)) NOHANDLES(ICALL(MATH_7, "Exp", ves_icall_System_Math_Exp)) +NOHANDLES(ICALL(MATH_7a, "FMod", ves_icall_System_Math_FMod)) NOHANDLES(ICALL(MATH_8, "Floor", ves_icall_System_Math_Floor)) NOHANDLES(ICALL(MATH_9, "Log", ves_icall_System_Math_Log)) NOHANDLES(ICALL(MATH_10, "Log10", ves_icall_System_Math_Log10)) +NOHANDLES(ICALL(MATH_10a, "ModF", ves_icall_System_Math_ModF)) NOHANDLES(ICALL(MATH_11, "Pow", ves_icall_System_Math_Pow)) NOHANDLES(ICALL(MATH_12, "Round", ves_icall_System_Math_Round)) NOHANDLES(ICALL(MATH_14, "Sin", ves_icall_System_Math_Sin)) NOHANDLES(ICALL(MATH_15, "Sinh", ves_icall_System_Math_Sinh)) -NOHANDLES(ICALL(MATH_22, "SplitFractionDouble", ves_icall_System_Math_SplitFractionDouble)) NOHANDLES(ICALL(MATH_16, "Sqrt", ves_icall_System_Math_Sqrt)) NOHANDLES(ICALL(MATH_17, "Tan", ves_icall_System_Math_Tan)) NOHANDLES(ICALL(MATH_18, "Tanh", ves_icall_System_Math_Tanh)) @@ -468,12 +475,21 @@ ICALL_TYPE(NDNS, "System.Net.Dns", NDNS_1) HANDLES(ICALL(NDNS_1, "GetHostByAddr_internal(string,string&,string[]&,string[]&,int)", ves_icall_System_Net_Dns_GetHostByAddr_internal)) HANDLES(ICALL(NDNS_2, "GetHostByName_internal(string,string&,string[]&,string[]&,int)", ves_icall_System_Net_Dns_GetHostByName_internal)) HANDLES(ICALL(NDNS_3, "GetHostName_internal(string&)", ves_icall_System_Net_Dns_GetHostName_internal)) +#endif -#if defined(HOST_DARWIN) || defined(HOST_BSD) +#if defined(ENABLE_MONODROID) +ICALL_TYPE(LINUXNETWORKCHANGE, "System.Net.NetworkInformation.LinuxNetworkChange", LINUXNETWORKCHANGE_1) +NOHANDLES(ICALL(LINUXNETWORKCHANGE_1, "CloseNLSocket", ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_CloseNLSocket)) +NOHANDLES(ICALL(LINUXNETWORKCHANGE_2, "CreateNLSocket", ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_CreateNLSocket)) +NOHANDLES(ICALL(LINUXNETWORKCHANGE_3, "ReadEvents", ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_ReadEvents)) +#endif + +#if !defined(DISABLE_SOCKETS) && (defined(HOST_DARWIN) || defined(HOST_BSD)) ICALL_TYPE(MAC_IFACE_PROPS, "System.Net.NetworkInformation.MacOsIPInterfaceProperties", MAC_IFACE_PROPS_1) ICALL(MAC_IFACE_PROPS_1, "ParseRouteInfo_internal", ves_icall_System_Net_NetworkInformation_MacOsIPInterfaceProperties_ParseRouteInfo_internal) #endif +#ifndef DISABLE_SOCKETS ICALL_TYPE(SOCK, "System.Net.Sockets.Socket", SOCK_1) HANDLES(ICALL(SOCK_1, "Accept_internal(intptr,int&,bool)", ves_icall_System_Net_Sockets_Socket_Accept_internal)) HANDLES(ICALL(SOCK_2, "Available_internal(intptr,int&)", ves_icall_System_Net_Sockets_Socket_Available_internal)) @@ -503,7 +519,9 @@ HANDLES(ICALL(SOCK_19, "Shutdown_internal(intptr,System.Net.Sockets.SocketShutdo HANDLES(ICALL(SOCK_20, "Socket_internal(System.Net.Sockets.AddressFamily,System.Net.Sockets.SocketType,System.Net.Sockets.ProtocolType,int&)", ves_icall_System_Net_Sockets_Socket_Socket_internal)) HANDLES(ICALL(SOCK_20a, "SupportsPortReuse", ves_icall_System_Net_Sockets_Socket_SupportPortReuse)) HANDLES(ICALL(SOCK_21a, "cancel_blocking_socket_operation", ves_icall_cancel_blocking_socket_operation)) +#endif +#ifndef DISABLE_SOCKETS ICALL_TYPE(SOCKEX, "System.Net.Sockets.SocketException", SOCKEX_1) ICALL(SOCKEX_1, "WSAGetLastError_internal", ves_icall_System_Net_Sockets_SocketException_WSAGetLastError_internal) #endif /* !DISABLE_SOCKETS */ @@ -591,12 +609,8 @@ ICALL_TYPE(EVENTI, "System.Reflection.EventInfo", EVENTI_1) HANDLES(ICALL(EVENTI_1, "internal_from_handle_type", ves_icall_System_Reflection_EventInfo_internal_from_handle_type)) ICALL_TYPE(FIELDI, "System.Reflection.FieldInfo", FILEDI_1) -HANDLES(ICALL(FILEDI_1, "GetTypeModifiers", ves_icall_System_Reflection_FieldInfo_GetTypeModifiers)) -HANDLES(ICALL(FILEDI_2, "get_marshal_info", ves_icall_System_Reflection_FieldInfo_get_marshal_info)) -HANDLES(ICALL(FILEDI_3, "internal_from_handle_type", ves_icall_System_Reflection_FieldInfo_internal_from_handle_type)) - -ICALL_TYPE(MEMBERI, "System.Reflection.MemberInfo", MEMBERI_1) -HANDLES(ICALL(MEMBERI_1, "get_MetadataToken", ves_icall_reflection_get_token)) +HANDLES(ICALL(FILEDI_1, "get_marshal_info", ves_icall_System_Reflection_FieldInfo_get_marshal_info)) +HANDLES(ICALL(FILEDI_2, "internal_from_handle_type", ves_icall_System_Reflection_FieldInfo_internal_from_handle_type)) ICALL_TYPE(MBASE, "System.Reflection.MethodBase", MBASE_1) HANDLES(ICALL(MBASE_1, "GetCurrentMethod", ves_icall_GetCurrentMethod)) @@ -623,6 +637,10 @@ ICALL_TYPE(MCMETH, "System.Reflection.MonoCMethod", MCMETH_1) HANDLES(ICALL(MCMETH_1, "GetGenericMethodDefinition_impl", ves_icall_MonoMethod_GetGenericMethodDefinition)) ICALL(MCMETH_2, "InternalInvoke", ves_icall_InternalInvoke) HANDLES(ICALL(MCMETH_3, "get_core_clr_security_level", ves_icall_MonoMethod_get_core_clr_security_level)) +HANDLES(ICALL(MCMETH_4, "get_metadata_token", ves_icall_reflection_get_token)) + +ICALL_TYPE(MEV, "System.Reflection.MonoEvent", MEV_1) +HANDLES(ICALL(MEV_1, "get_metadata_token", ves_icall_reflection_get_token)) ICALL_TYPE(MEVIN, "System.Reflection.MonoEventInfo", MEVIN_1) HANDLES(ICALL(MEVIN_1, "get_event_info", ves_icall_MonoEventInfo_get_event_info)) @@ -631,10 +649,12 @@ ICALL_TYPE(MFIELD, "System.Reflection.MonoField", MFIELD_1) HANDLES(ICALL(MFIELD_1, "GetFieldOffset", ves_icall_MonoField_GetFieldOffset)) HANDLES(ICALL(MFIELD_2, "GetParentType", ves_icall_MonoField_GetParentType)) ICALL(MFIELD_5, "GetRawConstantValue", ves_icall_MonoField_GetRawConstantValue) +HANDLES(ICALL(MFIELD_9, "GetTypeModifiers", ves_icall_System_Reflection_FieldInfo_GetTypeModifiers)) ICALL(MFIELD_3, "GetValueInternal", ves_icall_MonoField_GetValueInternal) HANDLES(ICALL(MFIELD_6, "ResolveType", ves_icall_MonoField_ResolveType)) HANDLES(ICALL(MFIELD_4, "SetValueInternal", ves_icall_MonoField_SetValueInternal)) ICALL(MFIELD_7, "get_core_clr_security_level", ves_icall_MonoField_get_core_clr_security_level) +HANDLES(ICALL(MFIELD_8, "get_metadata_token", ves_icall_reflection_get_token)) ICALL_TYPE(MMETH, "System.Reflection.MonoMethod", MMETH_2) HANDLES(ICALL(MMETH_2, "GetGenericArguments", ves_icall_MonoMethod_GetGenericArguments)) @@ -646,6 +666,7 @@ HANDLES(ICALL(MMETH_6, "get_IsGenericMethod", ves_icall_MonoMethod_get_IsGeneric HANDLES(ICALL(MMETH_7, "get_IsGenericMethodDefinition", ves_icall_MonoMethod_get_IsGenericMethodDefinition)) HANDLES(ICALL(MMETH_8, "get_base_method", ves_icall_MonoMethod_get_base_method)) HANDLES(ICALL(MMETH_10, "get_core_clr_security_level", ves_icall_MonoMethod_get_core_clr_security_level)) +HANDLES(ICALL(MMETH_12, "get_metadata_token", ves_icall_reflection_get_token)) HANDLES(ICALL(MMETH_9, "get_name", ves_icall_MonoMethod_get_name)) ICALL_TYPE(MMETHI, "System.Reflection.MonoMethodInfo", MMETHI_4) @@ -654,18 +675,19 @@ HANDLES(ICALL(MMETHI_1, "get_method_info", ves_icall_get_method_info)) HANDLES(ICALL(MMETHI_2, "get_parameter_info", ves_icall_System_Reflection_MonoMethodInfo_get_parameter_info)) HANDLES(ICALL(MMETHI_3, "get_retval_marshal", ves_icall_System_MonoMethodInfo_get_retval_marshal)) +ICALL_TYPE(PARAMI, "System.Reflection.MonoParameterInfo", MPARAMI_1) +HANDLES(ICALL(MPARAMI_1, "GetMetadataToken", ves_icall_reflection_get_token)) +HANDLES(ICALL(MPARAMI_2, "GetTypeModifiers", ves_icall_ParameterInfo_GetTypeModifiers)) + +ICALL_TYPE(MPROP, "System.Reflection.MonoProperty", MPROP_1) +HANDLES(ICALL(MPROP_1, "get_metadata_token", ves_icall_reflection_get_token)) +HANDLES(ICALL(MPROP_2, "internal_from_handle_type", ves_icall_System_Reflection_PropertyInfo_internal_from_handle_type)) + ICALL_TYPE(MPROPI, "System.Reflection.MonoPropertyInfo", MPROPI_1) HANDLES(ICALL(MPROPI_1, "GetTypeModifiers", ves_icall_MonoPropertyInfo_GetTypeModifiers)) ICALL(MPROPI_3, "get_default_value", ves_icall_property_info_get_default_value) HANDLES(ICALL(MPROPI_2, "get_property_info", ves_icall_MonoPropertyInfo_get_property_info)) -ICALL_TYPE(PARAMI, "System.Reflection.ParameterInfo", PARAMI_1) -HANDLES(ICALL(PARAMI_1, "GetMetadataToken", ves_icall_reflection_get_token)) -HANDLES(ICALL(PARAMI_2, "GetTypeModifiers", ves_icall_ParameterInfo_GetTypeModifiers)) - -ICALL_TYPE(PROPI, "System.Reflection.PropertyInfo", PROPI_1) -HANDLES(ICALL(PROPI_1, "internal_from_handle_type", ves_icall_System_Reflection_PropertyInfo_internal_from_handle_type)) - ICALL_TYPE(RTFIELD, "System.Reflection.RtFieldInfo", RTFIELD_1) ICALL(RTFIELD_1, "UnsafeGetValue", ves_icall_MonoField_GetValueInternal) @@ -744,6 +766,10 @@ HANDLES(ICALL(MARSHAL_34, "StructureToPtr", ves_icall_System_Runtime_InteropServ ICALL(MARSHAL_35, "UnsafeAddrOfPinnedArrayElement", ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement) HANDLES(ICALL(MARSHAL_41, "copy_from_unmanaged_fixed", ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged)) HANDLES(ICALL(MARSHAL_42, "copy_to_unmanaged_fixed", ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged)) + +ICALL_TYPE(RUNTIMEINFO, "System.Runtime.InteropServices.RuntimeInformation", RUNTIMEINFO_1) +HANDLES(ICALL(RUNTIMEINFO_1, "get_RuntimeArchitecture", ves_icall_System_Runtime_InteropServices_RuntimeInformation_get_RuntimeArchitecture)) + #ifndef DISABLE_COM ICALL_TYPE(WINDOWSRUNTIME_UNM, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods", WINDOWSRUNTIME_UNM_0) HANDLES(ICALL(WINDOWSRUNTIME_UNM_0, "GetRestrictedErrorInfo", ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_GetRestrictedErrorInfo)) @@ -944,8 +970,8 @@ ICALL_TYPE(NATIVEC, "System.Threading.NativeEventCalls", NATIVEC_1) ICALL(NATIVEC_1, "CloseEvent_internal", ves_icall_System_Threading_Events_CloseEvent_internal) HANDLES(ICALL(NATIVEC_2, "CreateEvent_internal(bool,bool,string,int&)", ves_icall_System_Threading_Events_CreateEvent_internal)) HANDLES(ICALL(NATIVEC_3, "OpenEvent_internal(string,System.Security.AccessControl.EventWaitHandleRights,int&)", ves_icall_System_Threading_Events_OpenEvent_internal)) -ICALL(NATIVEC_4, "ResetEvent_internal", ves_icall_System_Threading_Events_ResetEvent_internal) -ICALL(NATIVEC_5, "SetEvent_internal", ves_icall_System_Threading_Events_SetEvent_internal) +NOHANDLES(ICALL(NATIVEC_4, "ResetEvent_internal", ves_icall_System_Threading_Events_ResetEvent_internal)) +NOHANDLES(ICALL(NATIVEC_5, "SetEvent_internal", ves_icall_System_Threading_Events_SetEvent_internal)) ICALL_TYPE(SEMA, "System.Threading.Semaphore", SEMA_1) ICALL(SEMA_1, "CreateSemaphore_internal(int,int,string,int&)", ves_icall_System_Threading_Semaphore_CreateSemaphore_internal) @@ -1025,7 +1051,7 @@ HANDLES(ICALL(THREADP_13, "SetMaxThreadsNative", ves_icall_System_Threading_Thre HANDLES(ICALL(THREADP_14, "SetMinThreadsNative", ves_icall_System_Threading_ThreadPool_SetMinThreadsNative)) ICALL_TYPE(TTIMER, "System.Threading.Timer", TTIMER_1) -NOHANDLES(ICALL(TTIMER_1, "GetTimeMonotonic", mono_100ns_ticks)) +NOHANDLES(ICALL(TTIMER_1, "GetTimeMonotonic", ves_icall_System_Threading_Timer_GetTimeMonotonic)) ICALL_TYPE(VOLATILE, "System.Threading.Volatile", VOLATILE_28) ICALL(VOLATILE_28, "Read(T&)", ves_icall_System_Threading_Volatile_Read_T) @@ -1066,7 +1092,7 @@ HANDLES(ICALL(TYPE_1, "internal_from_handle", ves_icall_System_Type_internal_fro HANDLES(ICALL(TYPE_2, "internal_from_name", ves_icall_System_Type_internal_from_name)) ICALL_TYPE(TYPEDR, "System.TypedReference", TYPEDR_1) -ICALL(TYPEDR_1, "InternalToObject", mono_TypedReference_ToObject) +HANDLES(ICALL(TYPEDR_1, "InternalToObject", mono_TypedReference_ToObject)) ICALL(TYPEDR_2, "MakeTypedReferenceInternal", mono_TypedReference_MakeTypedReferenceInternal) ICALL_TYPE(VALUET, "System.ValueType", VALUET_1) diff --git a/mono/metadata/icall-internals.h b/mono/metadata/icall-internals.h index 12cfa45f0a..8915ab66b1 100644 --- a/mono/metadata/icall-internals.h +++ b/mono/metadata/icall-internals.h @@ -66,7 +66,8 @@ mono_icall_drive_info_get_drive_type (MonoString *root_path_name); #endif /* !G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */ void* -mono_lookup_internal_call_full (MonoMethod *method, mono_bool *uses_handles, mono_bool *foreign); +mono_lookup_internal_call_full (MonoMethod *method, gboolean warn_on_missing, mono_bool *uses_handles, mono_bool *foreign); + MONO_PAL_API void mono_add_internal_call_with_flags (const char *name, const void* method, gboolean cooperative); @@ -74,4 +75,26 @@ mono_add_internal_call_with_flags (const char *name, const void* method, gboolea MONO_PROFILER_API void mono_add_internal_call_internal (const char *name, gconstpointer method); +#ifdef __cplusplus + +#include + +template +inline typename std::enable_if::value || + std::is_function::type>::value >::type +mono_add_internal_call_with_flags (const char *name, T method, gboolean cooperative) +{ + return mono_add_internal_call_with_flags (name, (const void*)method, cooperative); +} + +template +inline typename std::enable_if::value || + std::is_function::type>::value >::type +mono_add_internal_call_internal (const char *name, T method) +{ + return mono_add_internal_call_internal (name, (const void*)method); +} + +#endif // __cplusplus + #endif /* __MONO_METADATA_ICALL_INTERNALS_H__ */ diff --git a/mono/metadata/icall-table.c b/mono/metadata/icall-table.c index 36868ad689..030d74aff8 100644 --- a/mono/metadata/icall-table.c +++ b/mono/metadata/icall-table.c @@ -41,7 +41,7 @@ * icall.c defines a lot of icalls as static, to avoid having to add prototypes for * them, just don't include any mono headers and emit dummy prototypes. */ -// Generate prototypes +// Generate incorrect prototypes. #define ICALL_TYPE(id,name,first) #define ICALL(id,name,func) ICALL_EXPORT void func (void); #define HANDLES(inner) inner @@ -211,7 +211,7 @@ static const char* const icall_names [] = { static const gconstpointer icall_functions [] = { #define ICALL_TYPE(id,name,first) -#define ICALL(id,name,func) func, +#define ICALL(id,name,func) ((gpointer)(func)), #define HANDLES(inner) inner #define NOHANDLES(inner) inner #include "metadata/icall-def.h" @@ -256,7 +256,7 @@ static int compare_method_imap (const void *key, const void *elem) { const char* method_name = (const char*)&icall_names_str + (*(guint16*)elem); - return strcmp (key, method_name); + return strcmp ((const char*)key, method_name); } static gsize @@ -290,7 +290,7 @@ static int compare_class_imap (const void *key, const void *elem) { const char* class_name = (const char*)&icall_type_names_str + (*(guint16*)elem); - return strcmp (key, class_name); + return strcmp ((const char*)key, class_name); } static const IcallTypeDesc* @@ -308,13 +308,13 @@ static int compare_method_imap (const void *key, const void *elem) { const char** method_name = (const char**)elem; - return strcmp (key, *method_name); + return strcmp ((const char*)key, *method_name); } static gsize find_slot_icall (const IcallTypeDesc *imap, const char *name) { - const char **nameslot = mono_binary_search (name, icall_names + imap->first_icall, icall_desc_num_icalls (imap), sizeof (icall_names [0]), compare_method_imap); + const char **nameslot = (const char**)mono_binary_search (name, icall_names + imap->first_icall, icall_desc_num_icalls (imap), sizeof (icall_names [0]), compare_method_imap); if (!nameslot) return -1; return nameslot - icall_names; @@ -342,13 +342,13 @@ static int compare_class_imap (const void *key, const void *elem) { const char** class_name = (const char**)elem; - return strcmp (key, *class_name); + return strcmp ((const char*)key, *class_name); } static const IcallTypeDesc* find_class_icalls (const char *name) { - const char **nameslot = mono_binary_search (name, icall_type_names, Icall_type_num, sizeof (icall_type_names [0]), compare_class_imap); + const char **nameslot = (const char**)mono_binary_search (name, icall_type_names, Icall_type_num, sizeof (icall_type_names [0]), compare_class_imap); if (!nameslot) return NULL; return &icall_type_descs [nameslot - icall_type_names]; @@ -425,7 +425,7 @@ lookup_icall_symbol (gpointer func) functions_sorted [i + 1] = tmp; tmp = symbols_sorted [i]; symbols_sorted [i] = symbols_sorted [i + 1]; - symbols_sorted [i + 1] = tmp; + symbols_sorted [i + 1] = (const char*)tmp; changed = TRUE; } } diff --git a/mono/metadata/icall.c.REMOVED.git-id b/mono/metadata/icall.c.REMOVED.git-id index 2831ee5163..00b71d0ff0 100644 --- a/mono/metadata/icall.c.REMOVED.git-id +++ b/mono/metadata/icall.c.REMOVED.git-id @@ -1 +1 @@ -78b1e10d5bb202f8aea2f2e2a63e51dbc997a68f \ No newline at end of file +72f3266ed6af0d120d78b70b19fc239dec5fe6d1 \ No newline at end of file diff --git a/mono/metadata/image-internals.h b/mono/metadata/image-internals.h index 5867157902..51fce9bdaf 100644 --- a/mono/metadata/image-internals.h +++ b/mono/metadata/image-internals.h @@ -8,6 +8,9 @@ #include +MonoImage* +mono_image_loaded_internal (const char *name, mono_bool refonly); + MonoImage * mono_find_image_owner (void *ptr); diff --git a/mono/metadata/image.c b/mono/metadata/image.c index 7246b854a6..b49bd5aea8 100644 --- a/mono/metadata/image.c +++ b/mono/metadata/image.c @@ -180,7 +180,7 @@ mono_install_image_loader (const MonoImageLoader *loader) guint32 mono_cli_rva_image_map (MonoImage *image, guint32 addr) { - MonoCLIImageInfo *iinfo = (MonoCLIImageInfo *)image->image_info; + MonoCLIImageInfo *iinfo = image->image_info; const int top = iinfo->cli_section_count; MonoSectionTable *tables = iinfo->cli_section_tables; int i; @@ -216,7 +216,7 @@ mono_cli_rva_image_map (MonoImage *image, guint32 addr) char * mono_image_rva_map (MonoImage *image, guint32 addr) { - MonoCLIImageInfo *iinfo = (MonoCLIImageInfo *)image->image_info; + MonoCLIImageInfo *iinfo = image->image_info; const int top = iinfo->cli_section_count; MonoSectionTable *tables = iinfo->cli_section_tables; int i; @@ -305,7 +305,7 @@ mono_images_cleanup (void) int mono_image_ensure_section_idx (MonoImage *image, int section) { - MonoCLIImageInfo *iinfo = (MonoCLIImageInfo *)image->image_info; + MonoCLIImageInfo *iinfo = image->image_info; MonoSectionTable *sect; g_return_val_if_fail (section < iinfo->cli_section_count, FALSE); @@ -340,7 +340,7 @@ mono_image_ensure_section_idx (MonoImage *image, int section) int mono_image_ensure_section (MonoImage *image, const char *section) { - MonoCLIImageInfo *ii = (MonoCLIImageInfo *)image->image_info; + MonoCLIImageInfo *ii = image->image_info; int i; for (i = 0; i < ii->cli_section_count; i++){ @@ -725,7 +725,7 @@ mono_image_load_module_checked (MonoImage *image, int idx, MonoError *error) name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]); for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) { /* be safe with string dups, but we could just compare string indexes */ - if (strcmp (list_iter->data, name) == 0) { + if (strcmp ((const char*)list_iter->data, name) == 0) { valid = TRUE; break; } @@ -977,7 +977,7 @@ pe_image_load_pe_data (MonoImage *image) MonoMSDOSHeader msdos; gint32 offset = 0; - iinfo = (MonoCLIImageInfo *)image->image_info; + iinfo = image->image_info; header = &iinfo->cli_header; #ifdef HOST_WIN32 @@ -1046,7 +1046,7 @@ pe_image_load_cli_data (MonoImage *image) MonoCLIImageInfo *iinfo; MonoDotNetHeader *header; - iinfo = (MonoCLIImageInfo *)image->image_info; + iinfo = image->image_info; header = &iinfo->cli_header; /* Load the CLI header */ @@ -1166,7 +1166,7 @@ static const char *ignored_assemblies_file_names[] = { "System.Threading.Overlapped.dll" }; -#define IGNORED_ASSEMBLY(HASH, NAME, GUID, VER_STR) { HASH, NAME, GUID } +#define IGNORED_ASSEMBLY(HASH, NAME, GUID, VER_STR) { (int)HASH, NAME, GUID } static const IgnoredAssembly ignored_assemblies [] = { IGNORED_ASSEMBLY (0x10CADA75, SYS_NET_HTTP, "EA2EC6DC-51DD-479C-BFC2-E713FB9E7E47", "4.1.1 net46"), @@ -1334,7 +1334,7 @@ do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status, mono_image_init (image); - iinfo = (MonoCLIImageInfo *)image->image_info; + iinfo = image->image_info; header = &iinfo->cli_header; if (!image->metadata_only) { @@ -1479,6 +1479,26 @@ do_mono_image_open (const char *fname, MonoImageOpenStatus *status, */ MonoImage * mono_image_loaded_full (const char *name, gboolean refonly) +{ + MonoImage *result; + MONO_ENTER_GC_UNSAFE; + result = mono_image_loaded_internal (name, refonly); + MONO_EXIT_GC_UNSAFE; + return result; +} + +/** + * mono_image_loaded_internal: + * \param name path or assembly name of the image to load + * \param refonly Check with respect to reflection-only loads? + * + * This routine verifies that the given image is loaded. + * It checks either reflection-only loads only, or normal loads only, as specified by parameter. + * + * \returns the loaded \c MonoImage, or NULL on failure. + */ +MonoImage * +mono_image_loaded_internal (const char *name, gboolean refonly) { MonoImage *res; @@ -1500,7 +1520,11 @@ mono_image_loaded_full (const char *name, gboolean refonly) MonoImage * mono_image_loaded (const char *name) { - return mono_image_loaded_full (name, FALSE); + MonoImage *result; + MONO_ENTER_GC_UNSAFE; + result = mono_image_loaded_internal (name, FALSE); + MONO_EXIT_GC_UNSAFE; + return result; } typedef struct { @@ -1704,7 +1728,7 @@ mono_image_open_a_lot (const char *fname, MonoImageOpenStatus *status, gboolean // then assemblies need to be loaded with LoadLibrary: if (!refonly && coree_module_handle) { HMODULE module_handle; - guint16 *fname_utf16; + gunichar2 *fname_utf16; DWORD last_error; absfname = mono_path_resolve_symlinks (fname); @@ -1712,7 +1736,7 @@ mono_image_open_a_lot (const char *fname, MonoImageOpenStatus *status, gboolean /* There is little overhead because the OS loader lock is held by LoadLibrary. */ mono_images_lock (); - image = g_hash_table_lookup (loaded_images, absfname); + image = (MonoImage*)g_hash_table_lookup (loaded_images, absfname); if (image) { // Image already loaded if (!load_from_context && mono_is_problematic_image (image)) { // If we previously loaded a problematic image, don't @@ -1749,7 +1773,7 @@ mono_image_open_a_lot (const char *fname, MonoImageOpenStatus *status, gboolean last_error = mono_w32error_get_last (); /* mono_image_open_from_module_handle is called by _CorDllMain. */ - image = g_hash_table_lookup (loaded_images, absfname); + image = (MonoImage*)g_hash_table_lookup (loaded_images, absfname); if (image) mono_image_addref (image); mono_images_unlock (); @@ -1918,7 +1942,7 @@ mono_image_fixup_vtable (MonoImage *image) slot_count = vtfixup->count; if (slot_type & VTFIXUP_TYPE_32BIT) while (slot_count--) { - *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type); + *((guint32*) slot) = (guint32)(gsize)mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type); slot = ((guint32*) slot) + 1; } else if (slot_type & VTFIXUP_TYPE_64BIT) @@ -2124,7 +2148,7 @@ mono_image_close_except_pools (MonoImage *image) if (image->raw_data_allocated) { /* FIXME: do we need this? (image is disposed anyway) */ /* image->raw_metadata and cli_sections might lie inside image->raw_data */ - MonoCLIImageInfo *ii = (MonoCLIImageInfo *)image->image_info; + MonoCLIImageInfo *ii = image->image_info; if ((image->raw_metadata > image->raw_data) && (image->raw_metadata <= (image->raw_data + image->raw_data_len))) @@ -2213,7 +2237,7 @@ mono_image_close_except_pools (MonoImage *image) mono_bitset_free (image->interface_bitset); } if (image->image_info){ - MonoCLIImageInfo *ii = (MonoCLIImageInfo *)image->image_info; + MonoCLIImageInfo *ii = image->image_info; g_free (ii->cli_section_tables); g_free (ii->cli_sections); @@ -2484,7 +2508,7 @@ mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, g guint32 mono_image_get_entry_point (MonoImage *image) { - return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point; + return image->image_info->cli_cli_header.ch_entry_point; } /** @@ -2502,7 +2526,7 @@ mono_image_get_entry_point (MonoImage *image) const char* mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size) { - MonoCLIImageInfo *iinfo = (MonoCLIImageInfo *)image->image_info; + MonoCLIImageInfo *iinfo = image->image_info; MonoCLIHeader *ch = &iinfo->cli_cli_header; const char* data; @@ -2614,7 +2638,7 @@ mono_image_load_file_for_image (MonoImage *image, int fileidx) const char* mono_image_get_strong_name (MonoImage *image, guint32 *size) { - MonoCLIImageInfo *iinfo = (MonoCLIImageInfo *)image->image_info; + MonoCLIImageInfo *iinfo = image->image_info; MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name; const char* data; @@ -2642,7 +2666,7 @@ mono_image_get_strong_name (MonoImage *image, guint32 *size) guint32 mono_image_strong_name_position (MonoImage *image, guint32 *size) { - MonoCLIImageInfo *iinfo = (MonoCLIImageInfo *)image->image_info; + MonoCLIImageInfo *iinfo = image->image_info; MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name; guint32 pos; @@ -2790,7 +2814,7 @@ mono_image_is_dynamic (MonoImage *image) gboolean mono_image_has_authenticode_entry (MonoImage *image) { - MonoCLIImageInfo *iinfo = (MonoCLIImageInfo *)image->image_info; + MonoCLIImageInfo *iinfo = image->image_info; MonoDotNetHeader *header = &iinfo->cli_header; if (!header) return FALSE; diff --git a/mono/metadata/image.h b/mono/metadata/image.h index 903f1acf7e..d078e35db1 100644 --- a/mono/metadata/image.h +++ b/mono/metadata/image.h @@ -42,8 +42,10 @@ MONO_API MONO_RT_EXTERNAL_ONLY MonoImage *mono_image_open_from_data_with_name (char *data, uint32_t data_len, mono_bool need_copy, MonoImageOpenStatus *status, mono_bool refonly, const char *name); MONO_API void mono_image_fixup_vtable (MonoImage *image); -MONO_API MonoImage *mono_image_loaded (const char *name); -MONO_API MonoImage *mono_image_loaded_full (const char *name, mono_bool refonly); +MONO_API MONO_RT_EXTERNAL_ONLY +MonoImage *mono_image_loaded (const char *name); +MONO_API MONO_RT_EXTERNAL_ONLY +MonoImage *mono_image_loaded_full (const char *name, mono_bool refonly); MONO_API MonoImage *mono_image_loaded_by_guid (const char *guid); MONO_API MonoImage *mono_image_loaded_by_guid_full (const char *guid, mono_bool refonly); MONO_API void mono_image_init (MonoImage *image); diff --git a/mono/metadata/loader-internals.h b/mono/metadata/loader-internals.h new file mode 100644 index 0000000000..b1725644cc --- /dev/null +++ b/mono/metadata/loader-internals.h @@ -0,0 +1,8 @@ +/** +* \file +*/ + +#ifndef _MONO_METADATA_LOADER_INTERNALS_H_ +#define _MONO_METADATA_LOADER_INTERNALS_H_ + +#endif diff --git a/mono/metadata/loader.c b/mono/metadata/loader.c index 1546ee1adf..b9d61b83c6 100644 --- a/mono/metadata/loader.c +++ b/mono/metadata/loader.c @@ -2325,7 +2325,8 @@ async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer if (!frame->ji) return FALSE; - MonoMethod *method = frame->ji->async ? NULL : frame->actual_method; + MonoMethod *method; + method = frame->ji->async ? NULL : frame->actual_method; return d->func (method, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data); default: diff --git a/mono/metadata/loader.h b/mono/metadata/loader.h index bd7803f5df..fe3f13ac49 100644 --- a/mono/metadata/loader.h +++ b/mono/metadata/loader.h @@ -5,6 +5,7 @@ #ifndef _MONO_METADATA_LOADER_H_ #define _MONO_METADATA_LOADER_H_ 1 +#include #include #include #include diff --git a/mono/metadata/locales.c b/mono/metadata/locales.c index e6d7074d62..de3a10f838 100644 --- a/mono/metadata/locales.c +++ b/mono/metadata/locales.c @@ -467,15 +467,15 @@ get_darwin_locale (void) locale = CFLocaleCopyCurrent (); if (locale) { - locale_language = CFLocaleGetValue (locale, kCFLocaleLanguageCode); + locale_language = (CFStringRef)CFLocaleGetValue (locale, kCFLocaleLanguageCode); if (locale_language != NULL && CFStringGetBytes(locale_language, CFRangeMake (0, CFStringGetLength (locale_language)), kCFStringEncodingMacRoman, 0, FALSE, NULL, 0, &bytes_converted) > 0) { len = bytes_converted + 1; - locale_country = CFLocaleGetValue (locale, kCFLocaleCountryCode); + locale_country = (CFStringRef)CFLocaleGetValue (locale, kCFLocaleCountryCode); if (locale_country != NULL && CFStringGetBytes (locale_country, CFRangeMake (0, CFStringGetLength (locale_country)), kCFStringEncodingMacRoman, 0, FALSE, NULL, 0, &bytes_converted) > 0) { len += bytes_converted + 1; - locale_script = CFLocaleGetValue (locale, kCFLocaleScriptCode); + locale_script = (CFStringRef)CFLocaleGetValue (locale, kCFLocaleScriptCode); if (locale_script != NULL && CFStringGetBytes (locale_script, CFRangeMake (0, CFStringGetLength (locale_script)), kCFStringEncodingMacRoman, 0, FALSE, NULL, 0, &bytes_converted) > 0) { len += bytes_converted + 1; } diff --git a/mono/metadata/marshal-ilgen.c.REMOVED.git-id b/mono/metadata/marshal-ilgen.c.REMOVED.git-id index b63b5d5e2b..33f2a1d553 100644 --- a/mono/metadata/marshal-ilgen.c.REMOVED.git-id +++ b/mono/metadata/marshal-ilgen.c.REMOVED.git-id @@ -1 +1 @@ -50283eaba9baec930da951d144ff8d60f41cb9c3 \ No newline at end of file +5247b896359ea0dbda5e1129a69ebad9bad8e2d1 \ No newline at end of file diff --git a/mono/metadata/marshal-windows.c b/mono/metadata/marshal-windows.c index 3973585b60..4a197590b4 100644 --- a/mono/metadata/marshal-windows.c +++ b/mono/metadata/marshal-windows.c @@ -68,7 +68,7 @@ ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (const guni * large. */ size_t len = MAX (strlen (tres) + 1, length); - char* ret = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (len, error); + char* ret = (char*)ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (len, error); if (ret) memcpy (ret, tres, len); g_free (tres); @@ -82,7 +82,7 @@ ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (const gunic return NULL; gsize const len = ((gsize)length + 1) * 2; - gunichar2 *res = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (len, error); + gunichar2 *res = (gunichar2*)ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (len, error); if (res) { memcpy (res, s, length * 2); res [length] = 0; @@ -101,7 +101,7 @@ mono_string_to_utf8str_handle (MonoStringHandle s, MonoError *error) return NULL; if (!mono_string_handle_length (s)) { - as = CoTaskMemAlloc (1); + as = (char*)CoTaskMemAlloc (1); g_assert (as); as [0] = '\0'; return as; @@ -117,7 +117,7 @@ mono_string_to_utf8str_handle (MonoStringHandle s, MonoError *error) g_error_free (gerror); return NULL; } else { - as = CoTaskMemAlloc (len + 1); + as = (char*)CoTaskMemAlloc (len + 1); g_assert (as); memcpy (as, tmp, len + 1); g_free (tmp); diff --git a/mono/metadata/marshal.c.REMOVED.git-id b/mono/metadata/marshal.c.REMOVED.git-id index 6eed39eb50..148f819079 100644 --- a/mono/metadata/marshal.c.REMOVED.git-id +++ b/mono/metadata/marshal.c.REMOVED.git-id @@ -1 +1 @@ -8ef5d5e78f32040d8fed0ca34877bb61d2a83acc \ No newline at end of file +54b8434fbd51e08cfe64ee7dc8bda94fe7b12376 \ No newline at end of file diff --git a/mono/metadata/marshal.h b/mono/metadata/marshal.h index bfd0c0da89..ce3b64e507 100644 --- a/mono/metadata/marshal.h +++ b/mono/metadata/marshal.h @@ -648,6 +648,8 @@ mono_icall_handle_new (gpointer rawobj); gpointer mono_icall_handle_new_interior (gpointer rawobj); +MonoObject* mono_marshal_get_type_object (MonoClass *klass); + ICALL_EXPORT void* ves_icall_marshal_alloc (gsize size); @@ -672,11 +674,11 @@ ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (const char ICALL_EXPORT MonoStringHandle -ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (const guint16 *ptr, MonoError *error); +ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (const gunichar2 *ptr, MonoError *error); ICALL_EXPORT MonoStringHandle -ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (const guint16 *ptr, gint32 len, MonoError *error); +ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (const gunichar2 *ptr, gint32 len, MonoError *error); ICALL_EXPORT MonoStringHandle diff --git a/mono/metadata/mempool.c b/mono/metadata/mempool.c index be5af1083f..85879ec1e6 100644 --- a/mono/metadata/mempool.c +++ b/mono/metadata/mempool.c @@ -260,7 +260,7 @@ get_next_size (MonoMemPool *pool, int size) * \returns the address of a newly allocated memory block. */ gpointer -mono_mempool_alloc (MonoMemPool *pool, guint size) +(mono_mempool_alloc) (MonoMemPool *pool, guint size) { gpointer rval = pool->pos; // Return value @@ -318,7 +318,7 @@ mono_mempool_alloc (MonoMemPool *pool, guint size) * same as \c mono_mempool_alloc, but fills memory with zero. */ gpointer -mono_mempool_alloc0 (MonoMemPool *pool, guint size) +(mono_mempool_alloc0) (MonoMemPool *pool, guint size) { gpointer rval; diff --git a/mono/metadata/mempool.h b/mono/metadata/mempool.h index 1abc25cc40..7cbbb944a1 100644 --- a/mono/metadata/mempool.h +++ b/mono/metadata/mempool.h @@ -7,8 +7,6 @@ #include -MONO_BEGIN_DECLS - typedef struct _MonoMemPool MonoMemPool; MONO_API MonoMemPool * @@ -29,9 +27,13 @@ mono_mempool_stats (MonoMemPool *pool); MONO_API void* mono_mempool_alloc (MonoMemPool *pool, unsigned int size); +#define mono_mempool_alloc(pool, size) (g_cast (mono_mempool_alloc ((pool), (size)))) + MONO_API void* mono_mempool_alloc0 (MonoMemPool *pool, unsigned int size); +#define mono_mempool_alloc0(pool, size) (g_cast (mono_mempool_alloc0 ((pool), (size)))) + MONO_API mono_bool mono_mempool_contains_addr (MonoMemPool *pool, void* addr); @@ -41,6 +43,4 @@ mono_mempool_strdup (MonoMemPool *pool, const char *s); MONO_API uint32_t mono_mempool_get_allocated (MonoMemPool *pool); -MONO_END_DECLS - #endif diff --git a/mono/metadata/metadata-internals.h b/mono/metadata/metadata-internals.h index 58d9f5669d..05ceefcc4b 100644 --- a/mono/metadata/metadata-internals.h +++ b/mono/metadata/metadata-internals.h @@ -5,6 +5,7 @@ #ifndef __MONO_METADATA_INTERNALS_H__ #define __MONO_METADATA_INTERNALS_H__ +#include "mono/utils/mono-forward-internal.h" #include "mono/metadata/image.h" #include "mono/metadata/blob.h" #include "mono/metadata/cil-coff.h" @@ -280,7 +281,7 @@ struct _MonoImage { char *version; gint16 md_version_major, md_version_minor; char *guid; - void *image_info; + MonoCLIImageInfo *image_info; MonoMemPool *mempool; /*protected by the image lock*/ char *raw_metadata; @@ -321,7 +322,7 @@ struct _MonoImage { MonoImage **files; guint32 file_count; - gpointer aot_module; + MonoAotModule *aot_module; guint8 aotid[16]; diff --git a/mono/metadata/metadata-verify.c.REMOVED.git-id b/mono/metadata/metadata-verify.c.REMOVED.git-id index ac49d23e7e..17d7dcb7f2 100644 --- a/mono/metadata/metadata-verify.c.REMOVED.git-id +++ b/mono/metadata/metadata-verify.c.REMOVED.git-id @@ -1 +1 @@ -4e5a6dc72cf930aebcd9a832ec790d15d611ebec \ No newline at end of file +60fab34f29a1869563044b25c0a8dab8b3a1ea93 \ No newline at end of file diff --git a/mono/metadata/metadata.c.REMOVED.git-id b/mono/metadata/metadata.c.REMOVED.git-id index 6aead65193..a9de7eda7c 100644 --- a/mono/metadata/metadata.c.REMOVED.git-id +++ b/mono/metadata/metadata.c.REMOVED.git-id @@ -1 +1 @@ -04468d1600fb87495862f1ac3fc3f0aa0e673090 \ No newline at end of file +4a9586b79217a2e6d64c857e5f56884238cec117 \ No newline at end of file diff --git a/mono/metadata/metadata.h b/mono/metadata/metadata.h index ed75175f39..c280f10e83 100644 --- a/mono/metadata/metadata.h +++ b/mono/metadata/metadata.h @@ -7,6 +7,7 @@ #include +#include #include #include #include @@ -23,8 +24,6 @@ MONO_BEGIN_DECLS #define MONO_CLASS_IS_IMPORT(c) ((mono_class_get_flags (c) & TYPE_ATTRIBUTE_IMPORT)) -typedef struct _MonoDomain MonoDomain; - typedef enum { MONO_EXCEPTION_CLAUSE_NONE, MONO_EXCEPTION_CLAUSE_FILTER, diff --git a/mono/metadata/method-builder-ilgen.h b/mono/metadata/method-builder-ilgen.h index a75300bf14..45626f5476 100644 --- a/mono/metadata/method-builder-ilgen.h +++ b/mono/metadata/method-builder-ilgen.h @@ -44,12 +44,30 @@ mono_mb_emit_calli (MonoMethodBuilder *mb, MonoMethodSignature *sig); void mono_mb_emit_native_call (MonoMethodBuilder *mb, MonoMethodSignature *sig, gpointer func); +#ifdef __cplusplus +template +inline void +mono_mb_emit_native_call (MonoMethodBuilder *mb, MonoMethodSignature *sig, T func) +{ + mono_mb_emit_native_call (mb, sig, (gpointer)func); +} +#endif // __cplusplus + void mono_mb_emit_managed_call (MonoMethodBuilder *mb, MonoMethod *method, MonoMethodSignature *opt_sig); void mono_mb_emit_icall (MonoMethodBuilder *mb, gpointer func); +#ifdef __cplusplus +template +inline void +mono_mb_emit_icall (MonoMethodBuilder *mb, T func) +{ + mono_mb_emit_icall (mb, (gpointer)func); +} +#endif // __cplusplus + int mono_mb_add_local (MonoMethodBuilder *mb, MonoType *type); diff --git a/mono/metadata/mono-basic-block.h b/mono/metadata/mono-basic-block.h index 7ffcc55063..65fddf61ea 100644 --- a/mono/metadata/mono-basic-block.h +++ b/mono/metadata/mono-basic-block.h @@ -9,6 +9,7 @@ #include #include #include +#include G_BEGIN_DECLS @@ -28,13 +29,7 @@ mono_basic_block_split (MonoMethod *method, MonoError *error, MonoMethodHeader * void mono_basic_block_free (MonoSimpleBasicBlock *bb); - /*This function is here because opcodes.h is a public header*/ - -#ifndef __MONO_METADATA_OPCODES_H__ -typedef enum _MonoOpcodeEnum MonoOpcodeEnum; -#endif - int mono_opcode_value_and_size (const unsigned char **ip, const unsigned char *end, MonoOpcodeEnum *value); diff --git a/mono/metadata/mono-conc-hash.c b/mono/metadata/mono-conc-hash.c index b2c9107077..5dd6f2eb0e 100644 --- a/mono/metadata/mono-conc-hash.c +++ b/mono/metadata/mono-conc-hash.c @@ -111,7 +111,7 @@ set_key (conc_table *table, int slot, gpointer key) { gpointer *key_addr = &table->keys [slot]; if (table->gc_type & MONO_HASH_KEY_GC) - mono_gc_wbarrier_generic_store (key_addr, key); + mono_gc_wbarrier_generic_store (key_addr, (MonoObject*)key); else *key_addr = key; } @@ -131,7 +131,7 @@ set_value (conc_table *table, int slot, gpointer value) { gpointer *value_addr = &table->values [slot]; if (table->gc_type & MONO_HASH_VALUE_GC) - mono_gc_wbarrier_generic_store (value_addr, value); + mono_gc_wbarrier_generic_store (value_addr, (MonoObject*)value); else *value_addr = value; } diff --git a/mono/metadata/mono-config.c b/mono/metadata/mono-config.c index eeee76e9b2..5c1058d5a8 100644 --- a/mono/metadata/mono-config.c +++ b/mono/metadata/mono-config.c @@ -194,7 +194,7 @@ typedef struct { void *user_data; MonoImage *assembly; int inited; -} ParseState; +} MonoConfigParseState; static void start_element (GMarkupParseContext *context, const gchar *element_name, @@ -203,7 +203,7 @@ static void start_element (GMarkupParseContext *context, gpointer user_data, GError **gerror) { - ParseState *state = (ParseState *)user_data; + MonoConfigParseState *state = (MonoConfigParseState *)user_data; if (!state->current) { state->current = (MonoParseHandler *)g_hash_table_lookup (config_handlers, element_name); if (state->current && state->current->init) @@ -218,7 +218,7 @@ static void end_element (GMarkupParseContext *context, gpointer user_data, GError **gerror) { - ParseState *state = (ParseState *)user_data; + MonoConfigParseState *state = (MonoConfigParseState *)user_data; if (state->current) { if (state->current->end) state->current->end (state->user_data, element_name); @@ -237,7 +237,7 @@ static void parse_text (GMarkupParseContext *context, gpointer user_data, GError **gerror) { - ParseState *state = (ParseState *)user_data; + MonoConfigParseState *state = (MonoConfigParseState *)user_data; if (state->current && state->current->text) state->current->text (state->user_data, text, text_len); } @@ -255,7 +255,7 @@ static void parse_error (GMarkupParseContext *context, GError *gerror, gpointer user_data) { - ParseState *state = (ParseState *)user_data; + MonoConfigParseState *state = (MonoConfigParseState *)user_data; const gchar *msg; const gchar *filename; @@ -315,7 +315,7 @@ dllmap_start (gpointer user_data, if (strcmp (attribute_names [i], "dll") == 0) info->dll = g_strdup (attribute_values [i]); else if (strcmp (attribute_names [i], "target") == 0){ - char *p = strstr (attribute_values [i], "$mono_libdir"); + const char* p = strstr (attribute_values [i], "$mono_libdir"); if (p != NULL){ char *libdir = mono_native_getrootdir (); size_t libdir_len = strlen (libdir); @@ -482,7 +482,7 @@ mono_config_cleanup (void) /* FIXME: error handling */ static void -mono_config_parse_xml_with_context (ParseState *state, const char *text, gsize len) +mono_config_parse_xml_with_context (MonoConfigParseState *state, const char *text, gsize len) { GMarkupParseContext *context; @@ -498,7 +498,7 @@ mono_config_parse_xml_with_context (ParseState *state, const char *text, gsize l /* If assembly is NULL, parse in the global context */ static int -mono_config_parse_file_with_context (ParseState *state, const char *filename) +mono_config_parse_file_with_context (MonoConfigParseState *state, const char *filename) { gchar *text; gsize len; @@ -528,7 +528,7 @@ mono_config_parse_file_with_context (ParseState *state, const char *filename) void mono_config_parse_memory (const char *buffer) { - ParseState state = {NULL}; + MonoConfigParseState state = {NULL}; state.user_data = (gpointer) ""; mono_config_parse_xml_with_context (&state, buffer, strlen (buffer)); @@ -537,7 +537,7 @@ mono_config_parse_memory (const char *buffer) static void mono_config_parse_file (const char *filename) { - ParseState state = {NULL}; + MonoConfigParseState state = {NULL}; state.user_data = (gpointer) filename; mono_config_parse_file_with_context (&state, filename); } @@ -618,7 +618,7 @@ mono_config_for_assembly_internal (MonoImage *assembly) { MONO_REQ_GC_UNSAFE_MODE; - ParseState state = {NULL}; + MonoConfigParseState state = {NULL}; int got_it = 0, i; char *aname, *cfg, *cfg_name; const char *bundled_config; @@ -883,7 +883,7 @@ mono_config_parse_publisher_policy (const gchar *filename, MonoAssemblyBindingIn NULL, NULL }; - ParseState state = { + MonoConfigParseState state = { &publisher_policy_parser, /* MonoParseHandler */ &user_data, /* user_data */ NULL, /* MonoImage (we don't need it right now)*/ @@ -908,7 +908,7 @@ mono_config_parse_assembly_bindings (const char *filename, int amajor, int amino { MonoAssemblyBindingInfo info; ParserUserData pud; - ParseState state; + MonoConfigParseState state; info.major = amajor; info.minor = aminor; diff --git a/mono/metadata/mono-hash.c b/mono/metadata/mono-hash.c index 1353d27cc4..648fec9aae 100644 --- a/mono/metadata/mono-hash.c +++ b/mono/metadata/mono-hash.c @@ -293,7 +293,7 @@ mono_g_hash_table_lookup_extended (MonoGHashTable *hash, gconstpointer key, gpoi g_return_val_if_fail (hash != NULL, FALSE); - slot = mono_g_hash_table_find_slot (hash, key); + slot = mono_g_hash_table_find_slot (hash, (MonoObject*)key); if (hash->keys [slot]) { if (orig_key) @@ -347,7 +347,7 @@ mono_g_hash_table_remove (MonoGHashTable *hash, gconstpointer key) int slot, last_clear_slot; g_return_val_if_fail (hash != NULL, FALSE); - slot = mono_g_hash_table_find_slot (hash, key); + slot = mono_g_hash_table_find_slot (hash, (MonoObject*)key); if (!hash->keys [slot]) return FALSE; @@ -456,7 +456,7 @@ mono_g_hash_table_insert_replace (MonoGHashTable *hash, gpointer key, gpointer v if (hash->in_use > (hash->table_size * HASH_TABLE_MAX_LOAD_FACTOR)) rehash (hash); - slot = mono_g_hash_table_find_slot (hash, key); + slot = mono_g_hash_table_find_slot (hash, (MonoObject*)key); if (hash->keys [slot]) { if (replace) { diff --git a/mono/metadata/mono-perfcounters.c b/mono/metadata/mono-perfcounters.c index f283a70c6a..2cac263ab8 100644 --- a/mono/metadata/mono-perfcounters.c +++ b/mono/metadata/mono-perfcounters.c @@ -633,7 +633,7 @@ static int mono_string_compare_ascii (MonoString *str, const char *ascii_str) { /* FIXME: make this case insensitive */ - guint16 *strc = mono_string_chars (str); + const gunichar2 *strc = mono_string_chars (str); while (*strc == *ascii_str++) { if (*strc == 0) return 0; diff --git a/mono/metadata/mono-security-windows.c b/mono/metadata/mono-security-windows.c index 4a2339b207..e3d14c35d3 100644 --- a/mono/metadata/mono-security-windows.c +++ b/mono/metadata/mono-security-windows.c @@ -211,7 +211,7 @@ gpointer ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token, MonoError *error) { gpointer dupe = NULL; - return DuplicateToken (token, SecurityImpersonation, &dupe) ? dup : NULL; + return DuplicateToken (token, SecurityImpersonation, &dupe) ? dupe : NULL; } #endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */ diff --git a/mono/metadata/mono-security.c b/mono/metadata/mono-security.c index c023079ee8..dc2fc5d596 100644 --- a/mono/metadata/mono-security.c +++ b/mono/metadata/mono-security.c @@ -9,21 +9,20 @@ * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ -#ifdef HAVE_CONFIG_H #include -#endif #include #include #include #include +#include #include #include #include #include +#include "reflection-internals.h" #ifndef HOST_WIN32 -#include #ifdef HAVE_GRP_H #include #endif @@ -622,7 +621,7 @@ void mono_invoke_protected_memory_method (MonoArray *data, MonoObject *scope, gb error_init (error); if (system_security_assembly == NULL) { - system_security_assembly = mono_image_loaded ("System.Security"); + system_security_assembly = mono_image_loaded_internal ("System.Security", FALSE); if (!system_security_assembly) { MonoAssembly *sa = mono_assembly_open_predicate ("System.Security.dll", MONO_ASMCTX_DEFAULT, NULL, NULL, NULL, NULL); if (!sa) diff --git a/mono/metadata/null-gc.c b/mono/metadata/null-gc.c index fdcdccc07a..d7fea35b63 100644 --- a/mono/metadata/null-gc.c +++ b/mono/metadata/null-gc.c @@ -164,10 +164,16 @@ mono_gc_make_root_descr_all_refs (int numbits) return NULL; } -void* +MonoObject* mono_gc_alloc_fixed (size_t size, void *descr, MonoGCRootSource source, void *key, const char *msg) { - return g_malloc0 (size); + return (MonoObject*)g_malloc0 (size); +} + +MonoObject* +mono_gc_alloc_fixed_no_descriptor (size_t size, MonoGCRootSource source, void *key, const char *msg) +{ + return mono_gc_alloc_fixed (size, NULL, source, key, msg); } void @@ -176,7 +182,7 @@ mono_gc_free_fixed (void* addr) g_free (addr); } -void * +MonoObject* mono_gc_alloc_obj (MonoVTable *vtable, size_t size) { MonoObject *obj = g_calloc (1, size); @@ -186,7 +192,7 @@ mono_gc_alloc_obj (MonoVTable *vtable, size_t size) return obj; } -void * +MonoArray* mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length) { MonoArray *obj = g_calloc (1, size); @@ -197,7 +203,7 @@ mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length) return obj; } -void * +MonoArray* mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size) { MonoArray *obj = g_calloc (1, size); @@ -211,7 +217,7 @@ mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uint return obj; } -void * +MonoString* mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len) { MonoString *obj = g_calloc (1, size); @@ -223,13 +229,13 @@ mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len) return obj; } -void* +MonoObject* mono_gc_alloc_mature (MonoVTable *vtable, size_t size) { return mono_gc_alloc_obj (vtable, size); } -void* +MonoObject* mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size) { return mono_gc_alloc_obj (vtable, size); @@ -411,12 +417,12 @@ mono_gc_is_disabled (void) } void -mono_gc_wbarrier_range_copy (gpointer _dest, gpointer _src, int size) +mono_gc_wbarrier_range_copy (gpointer _dest, gconstpointer _src, int size) { g_assert_not_reached (); } -void* +MonoRangeCopyFunction mono_gc_get_range_copy_func (void) { return &mono_gc_wbarrier_range_copy; @@ -430,10 +436,10 @@ mono_gc_get_card_table (int *shift_bits, gpointer *card_mask) } guint8* -mono_gc_get_target_card_table (int *shift_bits, gpointer *card_mask) +mono_gc_get_target_card_table (int *shift_bits, target_mgreg_t *card_mask) { *shift_bits = 0; - *card_mask = NULL; + *card_mask = 0; return NULL; } diff --git a/mono/metadata/object-forward.h b/mono/metadata/object-forward.h index 2688c87767..010dc8b0f7 100644 --- a/mono/metadata/object-forward.h +++ b/mono/metadata/object-forward.h @@ -10,11 +10,13 @@ #include -typedef struct _MonoReflectionTypeBuilder MonoReflectionTypeBuilder; -typedef struct _MonoException MONO_RT_MANAGED_ATTR MonoException; typedef struct _MonoClass MonoClass; typedef struct _MonoImage MonoImage; typedef struct _MonoMethod MonoMethod; +typedef struct _MonoObject MONO_RT_MANAGED_ATTR MonoObject; +typedef struct _MonoException MONO_RT_MANAGED_ATTR MonoException; +typedef struct _MonoReflectionAssembly MONO_RT_MANAGED_ATTR MonoReflectionAssembly; +typedef struct _MonoReflectionTypeBuilder MONO_RT_MANAGED_ATTR MonoReflectionTypeBuilder; #endif /* __MONO_OBJECT_FORWARD_H__ */ diff --git a/mono/metadata/object-internals.h b/mono/metadata/object-internals.h index f63546c4d4..563b8a005a 100644 --- a/mono/metadata/object-internals.h +++ b/mono/metadata/object-internals.h @@ -5,7 +5,10 @@ #ifndef __MONO_OBJECT_INTERNALS_H__ #define __MONO_OBJECT_INTERNALS_H__ +#include #include +#include + #include #include #include @@ -358,7 +361,7 @@ struct _MonoIUnknownVTable struct _MonoIUnknown { - MonoIUnknownVTable const * const vtable; + const MonoIUnknownVTable *vtable; }; typedef struct { @@ -441,7 +444,7 @@ struct _MonoInternalThread { gpointer unused3; gunichar2 *name; guint32 name_len; - guint32 state; + guint32 state; /* must be accessed while longlived->synch_cs is locked */ MonoException *abort_exc; int abort_state_handle; guint64 tid; /* This is accessed as a gsize in the code (so it can hold a 64bit pointer on systems that need it), but needs to reserve 64 bits of space on all machines as it corresponds to a field in managed code */ @@ -455,7 +458,10 @@ struct _MonoInternalThread { gpointer appdomain_refs; /* This is modified using atomic ops, so keep it a gint32 */ gint32 __interruption_requested; - MonoCoopMutex *synch_cs; + /* data that must live as long as this managed object is not finalized + * or as long as the underlying thread is attached, whichever is + * longer */ + MonoLongLivedThreadData *longlived; MonoBoolean threadpool_thread; MonoBoolean thread_interrupt_requested; int stack_size; @@ -491,7 +497,7 @@ struct _MonoInternalThread { struct _MonoThread { MonoObject obj; - struct _MonoInternalThread *internal_thread; + MonoInternalThread *internal_thread; MonoObject *start_obj; MonoException *pending_exception; }; @@ -918,12 +924,12 @@ TYPED_HANDLE_DECL (MonoReflectionMonoEvent); typedef struct { MonoObject object; + guint32 AttrsImpl; MonoReflectionType *ClassImpl; MonoObject *DefaultValueImpl; MonoObject *MemberImpl; MonoString *NameImpl; gint32 PositionImpl; - guint32 AttrsImpl; MonoObject *MarshalAsImpl; } MonoReflectionParameter; @@ -959,9 +965,6 @@ struct _MonoReflectionAssembly { MonoString *name; }; -/* Safely access System.Reflection.Assembly from native code */ -TYPED_HANDLE_DECL (MonoReflectionAssembly); - typedef struct { MonoReflectionType *utype; MonoArray *values; @@ -1329,9 +1332,6 @@ struct _MonoReflectionTypeBuilder { gint32 state; }; -/* Safely access System.Reflection.Emit.TypeBuilder from native code */ -TYPED_HANDLE_DECL (MonoReflectionTypeBuilder); - typedef struct { MonoReflectionType type; MonoReflectionType *element_type; @@ -1610,6 +1610,12 @@ mono_image_build_metadata (MonoReflectionModuleBuilder *module, MonoError *error int mono_get_constant_value_from_blob (MonoDomain* domain, MonoTypeEnum type, const char *blob, void *value, MonoError *error); +gboolean +mono_metadata_read_constant_value (const char *blob, MonoTypeEnum type, void *value, MonoError *error); + +char* +mono_string_from_blob (const char *str, MonoError *error); + void mono_release_type_locks (MonoInternalThread *thread); @@ -1771,6 +1777,8 @@ mono_method_add_generic_virtual_invocation (MonoDomain *domain, MonoVTable *vtab gpointer mono_method_alloc_generic_virtual_trampoline (MonoDomain *domain, int size); +#define mono_method_alloc_generic_virtual_trampoline(domain, size) (g_cast (mono_method_alloc_generic_virtual_trampoline ((domain), (size)))) + typedef enum { MONO_UNHANDLED_POLICY_LEGACY, MONO_UNHANDLED_POLICY_CURRENT @@ -1805,13 +1813,10 @@ mono_class_is_reflection_method_or_constructor (MonoClass *klass); MonoObject * mono_get_object_from_blob (MonoDomain *domain, MonoType *type, const char *blob, MonoError *error); -MonoObjectHandle -mono_class_get_ref_info (MonoClass *klass); - gboolean mono_class_has_ref_info (MonoClass *klass); -MonoObject* +MonoReflectionTypeBuilder* mono_class_get_ref_info_raw (MonoClass *klass); void @@ -1953,10 +1958,10 @@ MonoString* mono_string_new_wtf8_len_checked (MonoDomain *domain, const char *text, guint length, MonoError *error); MonoString * -mono_string_new_utf16_checked (MonoDomain *domain, const guint16 *text, gint32 len, MonoError *error); +mono_string_new_utf16_checked (MonoDomain *domain, const gunichar2 *text, gint32 len, MonoError *error); MonoStringHandle -mono_string_new_utf16_handle (MonoDomain *domain, const guint16 *text, gint32 len, MonoError *error); +mono_string_new_utf16_handle (MonoDomain *domain, const gunichar2 *text, gint32 len, MonoError *error); MonoStringHandle mono_string_new_utf8_len_handle (MonoDomain *domain, const char *text, guint length, MonoError *error); @@ -2074,10 +2079,6 @@ ICALL_EXPORT void ves_icall_DynamicMethod_create_dynamic_method (MonoReflectionDynamicMethodHandle mb, MonoError *error); -ICALL_EXPORT -MonoReflectionTypeHandle -ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilderHandle tb, MonoError *error); - ICALL_EXPORT void ves_icall_EnumBuilder_setup_enum_type (MonoReflectionTypeHandle enumtype, @@ -2115,6 +2116,6 @@ gpointer mono_object_get_data (MonoObject *o); gpointer -mono_vtype_get_field_addr (guint8 *vtype, MonoClassField *field); +mono_vtype_get_field_addr (gpointer vtype, MonoClassField *field); #endif /* __MONO_OBJECT_INTERNALS_H__ */ diff --git a/mono/metadata/object-offsets.h b/mono/metadata/object-offsets.h index 9343b9a612..3a8700e70c 100644 --- a/mono/metadata/object-offsets.h +++ b/mono/metadata/object-offsets.h @@ -8,7 +8,6 @@ Input defines: (those to be defined by the includer file) Required: DECL_OFFSET(struct,field) DECL_OFFSET2(struct,field,offset) -DECL_ALIGN(name,type) DECL_ALIGN2(name,alignment) Optional: @@ -43,14 +42,6 @@ MONO_OFFSETS_FILE - Name of the header file containing the offsets to be used. #ifndef USED_CROSS_COMPILER_OFFSETS -DECL_ALIGN(gint8) -DECL_ALIGN(gint16) -DECL_ALIGN(gint32) -DECL_ALIGN(gint64) -DECL_ALIGN(float) -DECL_ALIGN(double) -DECL_ALIGN(gpointer) - DECL_SIZE(gint8) DECL_SIZE(gint16) DECL_SIZE(gint32) @@ -154,6 +145,12 @@ DECL_OFFSET(SgenThreadInfo, tlab_temp_end) // Offsets for structures defined in mini/ #ifndef DISABLE_JIT_OFFSETS +DECL_SIZE(MonoMethodRuntimeGenericContext) +DECL_SIZE(MonoLMF) +DECL_SIZE(MonoTypedRef) +DECL_SIZE(CallContext) +DECL_SIZE(MonoContext) + DECL_OFFSET(MonoLMF, previous_lmf) DECL_OFFSET(MonoMethodRuntimeGenericContext, class_vtable) @@ -303,7 +300,6 @@ DECL_OFFSET(MonoFtnDesc, addr) #undef DECL_OFFSET #undef DECL_OFFSET2 -#undef DECL_ALIGN #undef DECL_ALIGN2 #undef DECL_SIZE #undef DECL_SIZE2 diff --git a/mono/metadata/object.c.REMOVED.git-id b/mono/metadata/object.c.REMOVED.git-id index 0ffff9641e..1a80c494ba 100644 --- a/mono/metadata/object.c.REMOVED.git-id +++ b/mono/metadata/object.c.REMOVED.git-id @@ -1 +1 @@ -6a17fd80a783c36f4230b1587ab35c19ce2c68c9 \ No newline at end of file +2b5e48f6b5e4004a85e795fdd0ab63d28067d42b \ No newline at end of file diff --git a/mono/metadata/object.h b/mono/metadata/object.h index c338ce0c72..8155aef797 100644 --- a/mono/metadata/object.h +++ b/mono/metadata/object.h @@ -5,6 +5,7 @@ #ifndef _MONO_CLI_OBJECT_H_ #define _MONO_CLI_OBJECT_H_ +#include #include #include #include @@ -16,7 +17,6 @@ typedef mono_byte MonoBoolean; typedef struct _MonoString MONO_RT_MANAGED_ATTR MonoString; typedef struct _MonoArray MONO_RT_MANAGED_ATTR MonoArray; typedef struct _MonoReflectionMethod MONO_RT_MANAGED_ATTR MonoReflectionMethod; -typedef struct _MonoReflectionAssembly MONO_RT_MANAGED_ATTR MonoReflectionAssembly; typedef struct _MonoReflectionModule MONO_RT_MANAGED_ATTR MonoReflectionModule; typedef struct _MonoReflectionField MONO_RT_MANAGED_ATTR MonoReflectionField; typedef struct _MonoReflectionProperty MONO_RT_MANAGED_ATTR MonoReflectionProperty; @@ -30,10 +30,10 @@ typedef struct _MonoDynamicImage MonoDynamicImage; typedef struct _MonoReflectionMethodBody MONO_RT_MANAGED_ATTR MonoReflectionMethodBody; typedef struct _MonoAppContext MONO_RT_MANAGED_ATTR MonoAppContext; -typedef struct MONO_RT_MANAGED_ATTR _MonoObject { +struct _MonoObject { MonoVTable *vtable; MonoThreadsSync *synchronisation; -} MonoObject; +}; typedef MonoObject* (*MonoInvokeFunc) (MonoMethod *method, void *obj, void **params, MonoObject **exc, MonoError *error); typedef void* (*MonoCompileFunc) (MonoMethod *method); @@ -386,6 +386,8 @@ MONO_API MonoReferenceQueue* mono_gc_reference_queue_new (mono_reference_queue_c MONO_API void mono_gc_reference_queue_free (MonoReferenceQueue *queue); MONO_API mono_bool mono_gc_reference_queue_add (MonoReferenceQueue *queue, MonoObject *obj, void *user_data); +#define mono_gc_reference_queue_add_handle(queue, obj, user_data) \ + (mono_gc_reference_queue_add ((queue), MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, obj)), (user_data))) /* GC write barriers support */ diff --git a/mono/metadata/opcodes.h b/mono/metadata/opcodes.h index 30edc54c29..107755cd89 100644 --- a/mono/metadata/opcodes.h +++ b/mono/metadata/opcodes.h @@ -23,15 +23,11 @@ MONO_BEGIN_DECLS #define OPDEF(a,b,c,d,e,f,g,h,i,j) \ MONO_ ## a, -#ifndef __MONO_METADATA_BASIC_BLOCK_H__ -typedef enum _MonoOpcodeEnum MonoOpcodeEnum; -#endif - -enum _MonoOpcodeEnum { +typedef enum MonoOpcodeEnum { MonoOpcodeEnum_Invalid = -1, #include "mono/cil/opcode.def" MONO_CEE_LAST -}; +} MonoOpcodeEnum; #undef OPDEF diff --git a/mono/metadata/pal_config.h b/mono/metadata/pal_config.h deleted file mode 100644 index d166722bfe..0000000000 --- a/mono/metadata/pal_config.h +++ /dev/null @@ -1,3 +0,0 @@ -#include - -#define MONO 1 diff --git a/mono/metadata/profiler.c b/mono/metadata/profiler.c index ed680d6427..bf62c04d7a 100644 --- a/mono/metadata/profiler.c +++ b/mono/metadata/profiler.c @@ -30,7 +30,7 @@ load_profiler (MonoDl *module, const char *name, const char *desc) char *err, *old_name = g_strdup_printf (OLD_INITIALIZER_NAME); MonoProfilerInitializer func; - if (!(err = mono_dl_symbol (module, old_name, (gpointer) &func))) { + if (!(err = mono_dl_symbol (module, old_name, (gpointer*) &func))) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_PROFILER, "Found old-style startup symbol '%s' for the '%s' profiler; it has not been migrated to the new API.", old_name, name); g_free (old_name); return FALSE; @@ -142,7 +142,8 @@ load_profiler_from_installation (const char *libname, const char *name, const ch void mono_profiler_load (const char *desc) { - char *col, *mname, *libname; + const char *col; + char *mname, *libname; mname = libname = NULL; @@ -319,7 +320,7 @@ mono_profiler_get_coverage_data (MonoProfilerHandle handle, MonoMethod *method, coverage_lock (); - MonoProfilerCoverageInfo *info = g_hash_table_lookup (mono_profiler_state.coverage_hash, method); + MonoProfilerCoverageInfo *info = (MonoProfilerCoverageInfo*)g_hash_table_lookup (mono_profiler_state.coverage_hash, method); coverage_unlock (); @@ -414,7 +415,7 @@ mono_profiler_coverage_instrumentation_enabled (MonoMethod *method) gboolean cover = FALSE; for (MonoProfilerHandle handle = mono_profiler_state.profilers; handle; handle = handle->next) { - MonoProfilerCoverageFilterCallback cb = handle->coverage_filter; + MonoProfilerCoverageFilterCallback cb = (MonoProfilerCoverageFilterCallback)handle->coverage_filter; if (cb) cover |= cb (handle->prof, method); @@ -770,13 +771,15 @@ mono_profiler_call_context_free_buffer (void *buffer) mono_profiler_state.context_free_buffer (buffer); } +G_ENUM_FUNCTIONS (MonoProfilerCallInstrumentationFlags) + MonoProfilerCallInstrumentationFlags mono_profiler_get_call_instrumentation_flags (MonoMethod *method) { MonoProfilerCallInstrumentationFlags flags = MONO_PROFILER_CALL_INSTRUMENTATION_NONE; for (MonoProfilerHandle handle = mono_profiler_state.profilers; handle; handle = handle->next) { - MonoProfilerCallInstrumentationFilterCallback cb = handle->call_instrumentation_filter; + MonoProfilerCallInstrumentationFilterCallback cb = (MonoProfilerCallInstrumentationFilterCallback)handle->call_instrumentation_filter; if (cb) flags |= cb (handle->prof, method); @@ -846,7 +849,7 @@ mono_profiler_cleanup (void) MonoProfilerHandle head = mono_profiler_state.profilers; while (head) { - MonoProfilerCleanupCallback cb = head->cleanup_callback; + MonoProfilerCleanupCallback cb = (MonoProfilerCleanupCallback)head->cleanup_callback; if (cb) cb (head->prof); @@ -934,7 +937,7 @@ update_callback (volatile gpointer *location, gpointer new_, volatile gint32 *co { \ if (!mono_profiler_state.startup_done) return; \ for (MonoProfilerHandle h = mono_profiler_state.profilers; h; h = h->next) { \ - MonoProfiler ## type ## Callback cb = h->name ## _cb; \ + MonoProfiler ## type ## Callback cb = (MonoProfiler ## type ## Callback)h->name ## _cb; \ if (cb) \ cb args; \ } \ diff --git a/mono/metadata/property-bag.c b/mono/metadata/property-bag.c index 41c2d6a121..9dc0634ec0 100644 --- a/mono/metadata/property-bag.c +++ b/mono/metadata/property-bag.c @@ -41,7 +41,7 @@ mono_property_bag_get (MonoPropertyBag *bag, int tag) void* mono_property_bag_add (MonoPropertyBag *bag, void *value) { - MonoPropertyBagItem *cur, **prev, *item = value; + MonoPropertyBagItem *cur, **prev, *item = (MonoPropertyBagItem*)value; int tag = item->tag; mono_memory_barrier (); //publish the values in value @@ -51,7 +51,7 @@ retry: cur = *prev; if (!cur || cur->tag > tag) { item->next = cur; - if (mono_atomic_cas_ptr ((void*)prev, item, cur) == cur) + if (mono_atomic_cas_ptr ((void**)prev, item, cur) == cur) return item; goto retry; } else if (cur->tag == tag) { diff --git a/mono/metadata/reflection-cache.h b/mono/metadata/reflection-cache.h index 0762e8da84..78b4f48af8 100644 --- a/mono/metadata/reflection-cache.h +++ b/mono/metadata/reflection-cache.h @@ -82,7 +82,7 @@ cache_object_handle (MonoDomain *domain, MonoClass *klass, gpointer item, MonoOb if (!domain->refobject_hash) domain->refobject_hash = mono_conc_g_hash_table_new_type (mono_reflected_hash, mono_reflected_equal, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DOMAIN, domain, "Domain Reflection Object Table"); - MonoObjectHandle obj = MONO_HANDLE_NEW (MonoObject, mono_conc_g_hash_table_lookup (domain->refobject_hash, &pe)); + MonoObjectHandle obj = MONO_HANDLE_NEW (MonoObject, (MonoObject*)mono_conc_g_hash_table_lookup (domain->refobject_hash, &pe)); if (MONO_HANDLE_IS_NULL (obj)) { ReflectedEntry *e = alloc_reflected_entry (domain); e->item = item; @@ -107,7 +107,7 @@ check_object_handle (MonoDomain* domain, MonoClass *klass, gpointer item) if (!hash) return MONO_HANDLE_NEW (MonoObject, NULL); - return MONO_HANDLE_NEW (MonoObject, mono_conc_g_hash_table_lookup (hash, &e)); + return MONO_HANDLE_NEW (MonoObject, (MonoObject*)mono_conc_g_hash_table_lookup (hash, &e)); } diff --git a/mono/metadata/reflection-internals.h b/mono/metadata/reflection-internals.h index 9309235d11..8bb500c580 100644 --- a/mono/metadata/reflection-internals.h +++ b/mono/metadata/reflection-internals.h @@ -13,6 +13,25 @@ #include #include +/* Safely access System.Reflection.Assembly from native code */ +TYPED_HANDLE_DECL (MonoReflectionAssembly) + +/* Safely access System.Reflection.Emit.TypeBuilder from native code */ +TYPED_HANDLE_DECL (MonoReflectionTypeBuilder) + +MonoReflectionAssemblyHandle +mono_domain_try_type_resolve_name (MonoDomain *domain, MonoStringHandle name, MonoError *error); + +MonoReflectionAssemblyHandle +mono_domain_try_type_resolve_typebuilder (MonoDomain *domain, MonoReflectionTypeBuilderHandle typebuilder, MonoError *error); + +ICALL_EXPORT +MonoReflectionTypeHandle +ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilderHandle tb, MonoError *error); + +MonoReflectionTypeBuilderHandle +mono_class_get_ref_info (MonoClass *klass); + gboolean mono_reflection_parse_type_checked (char *name, MonoTypeNameParse *info, MonoError *error); diff --git a/mono/metadata/reflection.c b/mono/metadata/reflection.c index 2e36b0b666..e429740e2d 100644 --- a/mono/metadata/reflection.c +++ b/mono/metadata/reflection.c @@ -85,18 +85,17 @@ mono_reflection_init (void) /* * mono_class_get_ref_info: * - * Return the type builder/generic param builder corresponding to KLASS, if it exists. + * Return the type builder corresponding to KLASS, if it exists. */ -MonoObjectHandle +MonoReflectionTypeBuilderHandle mono_class_get_ref_info (MonoClass *klass) { MONO_REQ_GC_UNSAFE_MODE; guint32 ref_info_handle = mono_class_get_ref_info_handle (klass); if (ref_info_handle == 0) - return MONO_HANDLE_NEW (MonoObject, NULL); - else - return mono_gchandle_get_target_handle (ref_info_handle); + return MONO_HANDLE_NEW (MonoReflectionTypeBuilder, NULL); + return MONO_HANDLE_CAST (MonoReflectionTypeBuilder, mono_gchandle_get_target_handle (ref_info_handle)); } gboolean @@ -106,7 +105,7 @@ mono_class_has_ref_info (MonoClass *klass) return 0 != mono_class_get_ref_info_handle (klass); } -MonoObject* +MonoReflectionTypeBuilder* mono_class_get_ref_info_raw (MonoClass *klass) { /* FIXME callers of mono_class_get_ref_info_raw should use handles */ @@ -115,8 +114,7 @@ mono_class_get_ref_info_raw (MonoClass *klass) if (ref_info_handle == 0) return NULL; - else - return mono_gchandle_get_target (ref_info_handle); + return (MonoReflectionTypeBuilder*)mono_gchandle_get_target (ref_info_handle); } void @@ -187,7 +185,7 @@ clear_cached_object (MonoDomain *domain, gpointer o, MonoClass *klass) if (mono_conc_g_hash_table_lookup_extended (domain->refobject_hash, &pe, &orig_pe, &orig_value)) { mono_conc_g_hash_table_remove (domain->refobject_hash, &pe); - free_reflected_entry (orig_pe); + free_reflected_entry ((ReflectedEntry*)orig_pe); } } mono_domain_unlock (domain); @@ -196,7 +194,7 @@ clear_cached_object (MonoDomain *domain, gpointer o, MonoClass *klass) static void cleanup_refobject_hash (gpointer key, gpointer value, gpointer user_data) { - free_reflected_entry (key); + free_reflected_entry ((ReflectedEntry*)key); } void @@ -275,7 +273,8 @@ module_object_construct (MonoDomain *domain, MonoClass *unused_klass, MonoImage goto_if_nok (error, fail); MONO_HANDLE_SETVAL (res, image, MonoImage *, image); - MonoReflectionAssemblyHandle assm_obj = mono_assembly_get_object_handle (domain, image->assembly, error); + MonoReflectionAssemblyHandle assm_obj; + assm_obj = mono_assembly_get_object_handle (domain, image->assembly, error); goto_if_nok (error, fail); MONO_HANDLE_SET (res, assembly, assm_obj); @@ -289,7 +288,8 @@ module_object_construct (MonoDomain *domain, MonoClass *unused_klass, MonoImage g_free (basename); - guint32 token = 0; + guint32 token; + token = 0; if (image->assembly->image == image) { token = mono_metadata_make_token (MONO_TABLE_MODULE, 1); } else { @@ -348,7 +348,8 @@ mono_module_file_get_object_handle (MonoDomain *domain, MonoImage *image, int ta mono_metadata_decode_row (table, table_index, cols, MONO_FILE_SIZE); MONO_HANDLE_SETVAL (res, image, MonoImage*, NULL); - MonoReflectionAssemblyHandle assm_obj = mono_assembly_get_object_handle (domain, image->assembly, error); + MonoReflectionAssemblyHandle assm_obj; + assm_obj = mono_assembly_get_object_handle (domain, image->assembly, error); goto_if_nok (error, fail); MONO_HANDLE_SET (res, assembly, assm_obj); name = mono_metadata_string_heap (image, cols [MONO_FILE_NAME]); @@ -532,7 +533,7 @@ mono_type_get_object_checked (MonoDomain *domain, MonoType *type, MonoError *err if (mono_class_has_ref_info (klass) && !m_class_was_typebuilder (klass) && !type->byref) { mono_domain_unlock (domain); mono_loader_unlock (); - return (MonoReflectionType *)mono_class_get_ref_info_raw (klass); /* FIXME use handles */ + return &mono_class_get_ref_info_raw (klass)->type; /* FIXME use handles */ } /* This is stored in vtables/JITted code so it has to be pinned */ res = (MonoReflectionType *)mono_object_new_pinned (domain, mono_defaults.runtimetype_class, error); @@ -607,7 +608,8 @@ method_object_construct (MonoDomain *domain, MonoClass *refclass, MonoMethod *me goto_if_nok (error, fail); MONO_HANDLE_SETVAL (ret, method, MonoMethod*, method); - MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (refclass), error); + MonoReflectionTypeHandle rt; + rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (refclass), error); goto_if_nok (error, fail); MONO_HANDLE_SET (ret, reftype, rt); @@ -707,7 +709,8 @@ field_object_construct (MonoDomain *domain, MonoClass *klass, MonoClassField *fi goto_if_nok (error, fail); MONO_HANDLE_SETVAL (res, klass, MonoClass *, klass); MONO_HANDLE_SETVAL (res, field, MonoClassField *, field); - MonoStringHandle name = mono_string_new_handle (domain, mono_field_get_name (field), error); + MonoStringHandle name; + name = mono_string_new_handle (domain, mono_field_get_name (field), error); goto_if_nok (error, fail); MONO_HANDLE_SET (res, name, name); @@ -945,14 +948,16 @@ add_parameter_object_to_array (MonoDomain *domain, MonoMethod *method, MonoObjec MonoReflectionParameterHandle param = MONO_HANDLE_CAST (MonoReflectionParameter, mono_object_new_handle (domain, mono_class_get_mono_parameter_info_class (), error)); goto_if_nok (error, leave); - MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, sig_param, error); + MonoReflectionTypeHandle rt; + rt = mono_type_get_object_handle (domain, sig_param, error); goto_if_nok (error, leave); MONO_HANDLE_SET (param, ClassImpl, rt); MONO_HANDLE_SET (param, MemberImpl, member); - MonoStringHandle name_str = mono_string_new_handle (domain, name, error); + MonoStringHandle name_str; + name_str = mono_string_new_handle (domain, name, error); goto_if_nok (error, leave); MONO_HANDLE_SET (param, NameImpl, name_str); @@ -1035,7 +1040,8 @@ param_objects_construct (MonoDomain *domain, MonoClass *refclass, MonoMethodSign if (MONO_HANDLE_IS_NULL (res)) goto leave; - gboolean any_default_value = FALSE; + gboolean any_default_value; + any_default_value = FALSE; for (i = 0; i < sig->param_count; ++i) { if ((sig->params [i]->attrs & PARAM_ATTRIBUTE_HAS_DEFAULT) != 0) { any_default_value = TRUE; @@ -1049,8 +1055,10 @@ param_objects_construct (MonoDomain *domain, MonoClass *refclass, MonoMethodSign } /* Handles missing and dbnull are assigned in add_parameter_object_to_array when needed */ - MonoObjectHandle missing = MONO_HANDLE_NEW (MonoObject, NULL); - MonoObjectHandle dbnull = MONO_HANDLE_NEW (MonoObject, NULL); + MonoObjectHandle missing; + missing = MONO_HANDLE_NEW (MonoObject, NULL); + MonoObjectHandle dbnull; + dbnull = MONO_HANDLE_NEW (MonoObject, NULL); for (i = 0; i < sig->param_count; ++i) { if (!add_parameter_object_to_array (domain, method, MONO_HANDLE_CAST(MonoObject, member), i, names[i], sig->params[i], types ? types[i] : 0, blobs ? blobs[i] : NULL, mspecs [i + 1], missing, dbnull, res, error)) goto leave; @@ -1128,7 +1136,8 @@ add_local_var_info_to_array (MonoDomain *domain, MonoMethodHeader *header, int i MonoReflectionLocalVariableInfoHandle info = MONO_HANDLE_CAST (MonoReflectionLocalVariableInfo, mono_object_new_handle (domain, mono_class_get_local_variable_info_class (), error)); goto_if_nok (error, leave); - MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, header->locals [idx], error); + MonoReflectionTypeHandle rt; + rt = mono_type_get_object_handle (domain, header->locals [idx], error); goto_if_nok (error, leave); MONO_HANDLE_SET (info, local_type, rt); @@ -1149,7 +1158,8 @@ add_exception_handling_clause_to_array (MonoDomain *domain, MonoMethodHeader *he error_init (error); MonoReflectionExceptionHandlingClauseHandle info = MONO_HANDLE_CAST (MonoReflectionExceptionHandlingClause, mono_object_new_handle (domain, mono_class_get_exception_handling_clause_class (), error)); goto_if_nok (error, leave); - MonoExceptionClause *clause = &header->clauses [idx]; + MonoExceptionClause *clause; + clause = &header->clauses [idx]; MONO_HANDLE_SETVAL (info, flags, gint32, clause->flags); MONO_HANDLE_SETVAL (info, try_offset, gint32, clause->try_offset); @@ -1238,22 +1248,26 @@ method_body_object_construct (MonoDomain *domain, MonoClass *unused_class, MonoM } else local_var_sig_token = 0; //FIXME - MonoReflectionMethodBodyHandle ret = MONO_HANDLE_CAST (MonoReflectionMethodBody, mono_object_new_handle (domain, mono_class_get_method_body_class (), error)); + MonoReflectionMethodBodyHandle ret; + ret = MONO_HANDLE_CAST (MonoReflectionMethodBody, mono_object_new_handle (domain, mono_class_get_method_body_class (), error)); goto_if_nok (error, fail); MONO_HANDLE_SETVAL (ret, init_locals, MonoBoolean, header->init_locals); MONO_HANDLE_SETVAL (ret, max_stack, guint32, header->max_stack); MONO_HANDLE_SETVAL (ret, local_var_sig_token, guint32, local_var_sig_token); - MonoArrayHandle il_arr = mono_array_new_handle (domain, mono_defaults.byte_class, header->code_size, error); + MonoArrayHandle il_arr; + il_arr = mono_array_new_handle (domain, mono_defaults.byte_class, header->code_size, error); goto_if_nok (error, fail); MONO_HANDLE_SET (ret, il, il_arr); uint32_t il_gchandle; - guint8* il_data = MONO_ARRAY_HANDLE_PIN (il_arr, guint8, 0, &il_gchandle); + guint8* il_data; + il_data = MONO_ARRAY_HANDLE_PIN (il_arr, guint8, 0, &il_gchandle); memcpy (il_data, header->code, header->code_size); mono_gchandle_free (il_gchandle); /* Locals */ - MonoArrayHandle locals_arr = mono_array_new_handle (domain, mono_class_get_local_variable_info_class (), header->num_locals, error); + MonoArrayHandle locals_arr; + locals_arr = mono_array_new_handle (domain, mono_class_get_local_variable_info_class (), header->num_locals, error); goto_if_nok (error, fail); MONO_HANDLE_SET (ret, locals, locals_arr); for (i = 0; i < header->num_locals; ++i) { @@ -1262,7 +1276,8 @@ method_body_object_construct (MonoDomain *domain, MonoClass *unused_class, MonoM } /* Exceptions */ - MonoArrayHandle exn_clauses = mono_array_new_handle (domain, mono_class_get_exception_handling_clause_class (), header->num_clauses, error); + MonoArrayHandle exn_clauses; + exn_clauses = mono_array_new_handle (domain, mono_class_get_exception_handling_clause_class (), header->num_clauses, error); goto_if_nok (error, fail); MONO_HANDLE_SET (ret, clauses, exn_clauses); for (i = 0; i < header->num_clauses; ++i) { @@ -1911,7 +1926,7 @@ mono_reflection_get_type_internal (MonoImage *rootimage, MonoImage* image, MonoT mono_class_init (parent); while ((klass = mono_class_get_nested_types (parent, &iter))) { - char *lastp; + const char *lastp; char *nested_name, *nested_nspace; gboolean match = TRUE; @@ -2090,7 +2105,8 @@ mono_reflection_get_type_internal_dynamic (MonoImage *rootimage, MonoAssembly *a /* Enumerate all modules */ - MonoArrayHandle modules = MONO_HANDLE_NEW (MonoArray, NULL); + MonoArrayHandle modules; + modules = MONO_HANDLE_NEW (MonoArray, NULL); MONO_HANDLE_GET (modules, abuilder, modules); if (!MONO_HANDLE_IS_NULL (modules)) { int n = mono_array_handle_length (modules); @@ -2102,7 +2118,8 @@ mono_reflection_get_type_internal_dynamic (MonoImage *rootimage, MonoAssembly *a } } - MonoArrayHandle loaded_modules = MONO_HANDLE_NEW (MonoArray, NULL); + MonoArrayHandle loaded_modules; + loaded_modules = MONO_HANDLE_NEW (MonoArray, NULL); MONO_HANDLE_GET (loaded_modules, abuilder, loaded_modules); if (!type && !MONO_HANDLE_IS_NULL(loaded_modules)) { int n = mono_array_handle_length (loaded_modules); @@ -2121,30 +2138,30 @@ leave: MonoType* mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve, MonoError *error) { + HANDLE_FUNCTION_ENTER (); + MonoType *type; - MonoReflectionAssembly *assembly; - GString *fullName; + MonoReflectionAssemblyHandle reflection_assembly; + GString *fullName = NULL; GList *mod; error_init (error); if (image && image_is_dynamic (image)) type = mono_reflection_get_type_internal_dynamic (rootimage, image->assembly, info, ignorecase, error); - else { + else type = mono_reflection_get_type_internal (rootimage, image, info, ignorecase, error); - } - return_val_if_nok (error, NULL); + goto_if_nok (error, return_null); if (type) - return type; + goto exit; if (!mono_domain_has_type_resolve (mono_domain_get ())) - return NULL; + goto return_null; if (type_resolve) { if (*type_resolve) - return NULL; - else - *type_resolve = TRUE; + goto return_null; + *type_resolve = TRUE; } /* Reconstruct the type name */ @@ -2156,23 +2173,32 @@ mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, for (mod = info->nested; mod; mod = mod->next) g_string_append_printf (fullName, "+%s", (char*)mod->data); - assembly = mono_domain_try_type_resolve_name ( mono_domain_get (), fullName->str, error); - if (!is_ok (error)) { - g_string_free (fullName, TRUE); - return NULL; - } + MonoStringHandle name_handle; + name_handle = mono_string_new_handle (mono_domain_get (), fullName->str, error); + goto_if_nok (error, return_null); + reflection_assembly = mono_domain_try_type_resolve_name ( mono_domain_get (), name_handle, error); + goto_if_nok (error, return_null); - if (assembly) { - if (assembly_is_dynamic (assembly->assembly)) - type = mono_reflection_get_type_internal_dynamic (rootimage, assembly->assembly, + if (MONO_HANDLE_BOOL (reflection_assembly)) { + MonoAssembly *assembly = MONO_HANDLE_GETVAL (reflection_assembly, assembly); + if (assembly_is_dynamic (assembly)) + type = mono_reflection_get_type_internal_dynamic (rootimage, assembly, info, ignorecase, error); else - type = mono_reflection_get_type_internal (rootimage, assembly->assembly->image, + type = mono_reflection_get_type_internal (rootimage, assembly->image, info, ignorecase, error); } - g_string_free (fullName, TRUE); - return_val_if_nok (error, NULL); - return type; + goto_if_nok (error, return_null); + goto exit; + +return_null: + type = NULL; + goto exit; + +exit: + if (fullName) + g_string_free (fullName, TRUE); + HANDLE_FUNCTION_RETURN_VAL (type); } /** @@ -2974,13 +3000,13 @@ mono_reflection_call_is_assignable_to (MonoClass *klass, MonoClass *oklass, Mono * need a TypeBuilder so use mono_class_get_ref_info (klass). */ g_assert (mono_class_has_ref_info (klass)); - g_assert (!strcmp (m_class_get_name (mono_object_class (mono_class_get_ref_info_raw (klass))), "TypeBuilder")); /* FIXME use handles */ + g_assert (!strcmp (m_class_get_name (mono_object_class (&mono_class_get_ref_info_raw (klass)->type.object)), "TypeBuilder")); /* FIXME use handles */ params [0] = mono_type_get_object_checked (mono_domain_get (), m_class_get_byval_arg (oklass), error); return_val_if_nok (error, FALSE); ERROR_DECL_VALUE (inner_error); - res = mono_runtime_try_invoke (method, mono_class_get_ref_info_raw (klass), params, &exc, &inner_error); /* FIXME use handles */ + res = mono_runtime_try_invoke (method, &mono_class_get_ref_info_raw (klass)->type.object, params, &exc, &inner_error); /* FIXME use handles */ if (exc || !is_ok (&inner_error)) { mono_error_cleanup (&inner_error); diff --git a/mono/metadata/remoting.c b/mono/metadata/remoting.c index 61b539f098..4d49afd70b 100644 --- a/mono/metadata/remoting.c +++ b/mono/metadata/remoting.c @@ -100,8 +100,14 @@ static MonoMethod *method_set_call_context, *method_needs_context_sink, *method_ static gpointer mono_compile_method_icall (MonoMethod *method); +#ifdef __cplusplus +template +static void +register_icall (T func, const char *name, const char *sigstr, gboolean save) +#else static void register_icall (gpointer func, const char *name, const char *sigstr, gboolean save) +#endif { MonoMethodSignature *sig = mono_create_icall_signature (sigstr); @@ -229,7 +235,6 @@ mono_remoting_marshal_init (void) register_icall (mono_context_get_icall, "mono_context_get_icall", "object", FALSE); register_icall (mono_context_set_icall, "mono_context_set_icall", "void object", FALSE); - } icalls_registered = TRUE; @@ -402,7 +407,7 @@ mono_remoting_wrapper (MonoMethod *method, gpointer *params) int i; MonoMethodSignature *sig = mono_method_signature (method); int count = sig->param_count; - gpointer* mparams = (gpointer*) alloca(count*sizeof(gpointer)); + gpointer* mparams = g_newa (gpointer, count); for (i=0; iparams [i]); @@ -1008,7 +1013,7 @@ mono_marshal_get_xappdomain_invoke (MonoMethod *method, MonoError *error) /* Count the number of parameters that need to be serialized */ - marshal_types = (int *)alloca (sizeof (int) * sig->param_count); + marshal_types = g_newa (int, sig->param_count); complex_count = complex_out_count = 0; for (i = 0; i < sig->param_count; i++) { MonoType *ptype = sig->params[i]; @@ -2044,9 +2049,11 @@ mono_marshal_xdomain_copy_value_handle (MonoObjectHandle val, MonoError *error) if (MONO_HANDLE_IS_NULL (val)) goto leave; - MonoDomain *domain = mono_domain_get (); + MonoDomain *domain; + domain = mono_domain_get (); - MonoClass *klass = mono_handle_class (val); + MonoClass *klass; + klass = mono_handle_class (val); switch (m_class_get_byval_arg (klass)->type) { case MONO_TYPE_VOID: diff --git a/mono/metadata/security.h b/mono/metadata/security.h index 28f268eeef..e35fcdf190 100644 --- a/mono/metadata/security.h +++ b/mono/metadata/security.h @@ -19,6 +19,7 @@ #include #include #include +#include "reflection-internals.h" G_BEGIN_DECLS @@ -27,81 +28,100 @@ ICALL_EXPORT MonoStringHandle ves_icall_System_Environment_get_UserName (MonoError *error); - /* System.Security.Principal.WindowsIdentity */ gpointer mono_security_principal_windows_identity_get_current_token (MonoError *error); +ICALL_EXPORT MonoArray* ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token); +ICALL_EXPORT gpointer ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (MonoError *error); +ICALL_EXPORT MonoStringHandle ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token, MonoError *error); +ICALL_EXPORT gpointer ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoStringHandle username, MonoError *error); +ICALL_EXPORT MonoArray* ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token); +ICALL_EXPORT gpointer ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (MonoError *error); +ICALL_EXPORT MonoStringHandle ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token, MonoError *error); +ICALL_EXPORT gpointer ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoStringHandle username, MonoError *error); /* System.Security.Principal.WindowsImpersonationContext */ +ICALL_EXPORT gboolean ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken (gpointer token, MonoError *error); +ICALL_EXPORT gpointer ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token, MonoError *error); +ICALL_EXPORT gboolean ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken (gpointer token, MonoError *error); +ICALL_EXPORT gboolean ves_icall_System_Security_Principal_WindowsImpersonationContext_RevertToSelf (MonoError *error); - /* System.Security.Principal.WindowsPrincipal */ +ICALL_EXPORT gboolean ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId (gpointer user, gpointer group, MonoError *error); +ICALL_EXPORT gboolean ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpointer user, const gchar *group, MonoError *error); /* Mono.Security.Cryptography.KeyPairPersistance */ +ICALL_EXPORT MonoBoolean ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure (const gunichar2 *root, MonoError *error); +ICALL_EXPORT MonoBoolean ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected (const gunichar2 *path, MonoError *error); +ICALL_EXPORT MonoBoolean ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected (const gunichar2 *path, MonoError *error); +ICALL_EXPORT MonoBoolean ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine (const gunichar2 *path, MonoError *error); +ICALL_EXPORT MonoBoolean ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser (const gunichar2 *path, MonoError *error); - /* System.Security.Policy.Evidence */ +ICALL_EXPORT MonoBoolean ves_icall_System_Security_Policy_Evidence_IsAuthenticodePresent (MonoReflectionAssemblyHandle refass, MonoError *error); /* System.Security.SecureString */ +ICALL_EXPORT void ves_icall_System_Security_SecureString_DecryptInternal (MonoArray *data, MonoObject *scope); +ICALL_EXPORT void ves_icall_System_Security_SecureString_EncryptInternal (MonoArray *data, MonoObject *scope); diff --git a/mono/metadata/seq-points-data.h b/mono/metadata/seq-points-data.h index 7b24b99962..8d07f44220 100644 --- a/mono/metadata/seq-points-data.h +++ b/mono/metadata/seq-points-data.h @@ -11,6 +11,7 @@ #define MONO_SEQ_POINT_FLAG_NONEMPTY_STACK 1 #define MONO_SEQ_POINT_FLAG_EXIT_IL 2 +#define MONO_SEQ_POINT_FLAG_NESTED_CALL 4 /* IL offsets used to mark the sequence points belonging to method entry/exit events */ #define METHOD_ENTRY_IL_OFFSET -1 diff --git a/mono/metadata/sgen-bridge.c b/mono/metadata/sgen-bridge.c index 8ca4fd249b..d5caf01fb8 100644 --- a/mono/metadata/sgen-bridge.c +++ b/mono/metadata/sgen-bridge.c @@ -699,7 +699,7 @@ sgen_bridge_handle_gc_debug (const char *opt) } else if (!strcmp (opt, "enable-bridge-accounting")) { bridge_processor_config.accounting = TRUE; } else if (g_str_has_prefix (opt, "bridge-dump=")) { - char *prefix = strchr (opt, '=') + 1; + const char* prefix = strchr (opt, '=') + 1; set_dump_prefix(prefix); } else if (g_str_has_prefix (opt, "bridge-compare-to=")) { const char *name = strchr (opt, '=') + 1; diff --git a/mono/metadata/sgen-client-mono.h b/mono/metadata/sgen-client-mono.h index 3ed143fd1d..d7d20336af 100644 --- a/mono/metadata/sgen-client-mono.h +++ b/mono/metadata/sgen-client-mono.h @@ -379,8 +379,8 @@ static void mono_binary_protocol_alloc_generic (gpointer obj, gpointer vtable, size_t size, gboolean pinned) { #ifdef ENABLE_DTRACE - const char *name_space = sgen_client_vtable_get_namespace (vtable); - const char *name = sgen_client_vtable_get_name (vtable); + const char *name_space = sgen_client_vtable_get_namespace ((GCVTable)vtable); + const char *name = sgen_client_vtable_get_name ((GCVTable)vtable); if (sgen_ptr_in_nursery (obj)) { if (G_UNLIKELY (MONO_GC_NURSERY_OBJ_ALLOC_ENABLED ())) @@ -411,7 +411,7 @@ sgen_client_binary_protocol_alloc_pinned (gpointer obj, gpointer vtable, size_t static void G_GNUC_UNUSED sgen_client_binary_protocol_alloc_degraded (gpointer obj, gpointer vtable, size_t size, gpointer provenance) { - MONO_GC_MAJOR_OBJ_ALLOC_DEGRADED ((mword)obj, size, sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable)); + MONO_GC_MAJOR_OBJ_ALLOC_DEGRADED ((mword)obj, size, sgen_client_vtable_get_namespace ((GCVTable)vtable), sgen_client_vtable_get_name ((GCVTable)vtable)); } static void G_GNUC_UNUSED @@ -436,8 +436,8 @@ sgen_client_binary_protocol_pin (gpointer obj, gpointer vtable, size_t size) if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) { int gen = sgen_ptr_in_nursery (obj) ? GENERATION_NURSERY : GENERATION_OLD; MONO_GC_OBJ_PINNED ((mword)obj, - sgen_safe_object_get_size (obj), - sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable), gen); + sgen_safe_object_get_size ((GCObject*)obj), + sgen_client_vtable_get_namespace ((GCVTable)vtable), sgen_client_vtable_get_name ((GCVTable)vtable), gen); } #endif } @@ -478,7 +478,7 @@ sgen_client_binary_protocol_cement (gpointer ptr, gpointer vtable, size_t size) #ifdef ENABLE_DTRACE if (G_UNLIKELY (MONO_GC_OBJ_CEMENTED_ENABLED())) { MONO_GC_OBJ_CEMENTED ((mword)ptr, sgen_safe_object_get_size ((GCObject*)ptr), - sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable)); + sgen_client_vtable_get_namespace ((GCVTable)vtable), sgen_client_vtable_get_name ((GCVTable)vtable)); } #endif } @@ -490,7 +490,7 @@ sgen_client_binary_protocol_copy (gpointer from, gpointer to, gpointer vtable, s if (G_UNLIKELY (MONO_GC_OBJ_MOVED_ENABLED ())) { int dest_gen = sgen_ptr_in_nursery (to) ? GENERATION_NURSERY : GENERATION_OLD; int src_gen = sgen_ptr_in_nursery (from) ? GENERATION_NURSERY : GENERATION_OLD; - MONO_GC_OBJ_MOVED ((mword)to, (mword)from, dest_gen, src_gen, size, sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable)); + MONO_GC_OBJ_MOVED ((mword)to, (mword)from, dest_gen, src_gen, size, sgen_client_vtable_get_namespace ((GCVTable)vtable), sgen_client_vtable_get_name ((GCVTable)vtable)); } #endif } @@ -500,8 +500,8 @@ sgen_client_binary_protocol_global_remset (gpointer ptr, gpointer value, gpointe { #ifdef ENABLE_DTRACE if (G_UNLIKELY (MONO_GC_GLOBAL_REMSET_ADD_ENABLED ())) { - MONO_GC_GLOBAL_REMSET_ADD ((mword)ptr, (mword)value, sgen_safe_object_get_size (value), - sgen_client_vtable_get_namespace (value_vtable), sgen_client_vtable_get_name (value_vtable)); + MONO_GC_GLOBAL_REMSET_ADD ((mword)ptr, (mword)value, sgen_safe_object_get_size ((GCObject*)value), + sgen_client_vtable_get_namespace ((GCVTable)value_vtable), sgen_client_vtable_get_name ((GCVTable)value_vtable)); } #endif } @@ -534,7 +534,7 @@ sgen_client_binary_protocol_dislink_update (gpointer link, gpointer obj, gboolea GCVTable vt = obj ? SGEN_LOAD_VTABLE (obj) : NULL; MONO_GC_WEAK_UPDATE ((mword)link, (mword)obj, - obj ? (mword)sgen_safe_object_get_size (obj) : (mword)0, + obj ? sgen_safe_object_get_size ((GCObject*)obj) : 0u, obj ? sgen_client_vtable_get_namespace (vt) : NULL, obj ? sgen_client_vtable_get_name (vt) : NULL, track ? 1 : 0); @@ -662,7 +662,7 @@ sgen_client_binary_protocol_pin_stats (int objects_pinned_in_nursery, size_t byt } static void G_GNUC_UNUSED -sgen_client_root_registered (char *start, size_t size, int source, void *key, const char *msg) +sgen_client_root_registered (char *start, size_t size, MonoGCRootSource source, void *key, const char *msg) { MONO_PROFILER_RAISE (gc_root_register, ((const mono_byte *) start, size, source, key, msg)); } @@ -683,7 +683,7 @@ sgen_client_binary_protocol_collection_end_stats (long long major_scan, long lon { } -#define TLAB_ACCESS_INIT SgenThreadInfo *__thread_info__ = (SgenThreadInfo*)mono_tls_get_sgen_thread_info () +#define TLAB_ACCESS_INIT SgenThreadInfo *__thread_info__ = mono_tls_get_sgen_thread_info () #define IN_CRITICAL_REGION (__thread_info__->client_info.in_critical_region) /* Enter must be visible before anything is done in the critical region. */ diff --git a/mono/metadata/sgen-dynarray.h b/mono/metadata/sgen-dynarray.h index 2d1587d498..97c331cc9b 100644 --- a/mono/metadata/sgen-dynarray.h +++ b/mono/metadata/sgen-dynarray.h @@ -250,7 +250,7 @@ dyn_array_ptr_set (DynPtrArray *da, int x, void *ptr) #ifdef OPTIMIZATION_SINGLETON_DYN_ARRAY if (da->array.capacity == 1) { g_assert (x == 0); - da->array.data = ptr; + da->array.data = (char*)ptr; } else #endif { diff --git a/mono/metadata/sgen-mono-ilgen.c b/mono/metadata/sgen-mono-ilgen.c index 4ab3c651bb..55b0023a68 100644 --- a/mono/metadata/sgen-mono-ilgen.c +++ b/mono/metadata/sgen-mono-ilgen.c @@ -201,7 +201,8 @@ emit_managed_allocater_ilgen (MonoMethodBuilder *mb, gboolean slowpath, gboolean goto done; } - MonoType *int_type = mono_get_int_type (); + MonoType *int_type; + int_type = mono_get_int_type (); /* * Tls access might call foreign code or code without jinfo. This can * only happen if we are outside of the critical region. diff --git a/mono/metadata/sgen-mono.c b/mono/metadata/sgen-mono.c index c6f95cc355..7c9e575464 100644 --- a/mono/metadata/sgen-mono.c +++ b/mono/metadata/sgen-mono.c @@ -184,12 +184,12 @@ mono_gc_wbarrier_set_field (MonoObject *obj, gpointer field_ptr, MonoObject* val } void -mono_gc_wbarrier_range_copy (gpointer _dest, gpointer _src, int size) +mono_gc_wbarrier_range_copy (gpointer _dest, gconstpointer _src, int size) { sgen_wbarrier_range_copy (_dest, _src, size); } -void* +MonoRangeCopyFunction mono_gc_get_range_copy_func (void) { return sgen_get_remset ()->wbarrier_range_copy; @@ -225,7 +225,12 @@ sgen_has_critical_method (void) gboolean mono_gc_is_critical_method (MonoMethod *method) { +#ifdef HOST_WASM + //methods can't be critical under wasm due to the single thread'ness of it + return FALSE; +#else return sgen_is_critical_method (method); +#endif } static void @@ -836,7 +841,7 @@ mono_gc_clear_domain (MonoDomain * domain) sgen_clear_nursery_fragments (); FOREACH_THREAD_ALL (info) { - mono_handle_stack_free_domain ((HandleStack*)info->client_info.info.handle_stack, domain); + mono_handle_stack_free_domain (info->client_info.info.handle_stack, domain); } FOREACH_THREAD_END if (sgen_mono_xdomain_checks && domain != mono_get_root_domain ()) { @@ -903,7 +908,7 @@ mono_gc_clear_domain (MonoDomain * domain) * Allocation */ -void* +MonoObject* mono_gc_alloc_obj (MonoVTable *vtable, size_t size) { MonoObject *obj = sgen_alloc_obj (vtable, size); @@ -914,7 +919,7 @@ mono_gc_alloc_obj (MonoVTable *vtable, size_t size) return obj; } -void* +MonoObject* mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size) { MonoObject *obj = sgen_alloc_obj_pinned (vtable, size); @@ -925,7 +930,7 @@ mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size) return obj; } -void* +MonoObject* mono_gc_alloc_mature (MonoVTable *vtable, size_t size) { MonoObject *obj = sgen_alloc_obj_mature (vtable, size); @@ -939,7 +944,7 @@ mono_gc_alloc_mature (MonoVTable *vtable, size_t size) /** * mono_gc_alloc_fixed: */ -void* +MonoObject* mono_gc_alloc_fixed (size_t size, MonoGCDescriptor descr, MonoGCRootSource source, void *key, const char *msg) { /* FIXME: do a single allocation */ @@ -950,7 +955,13 @@ mono_gc_alloc_fixed (size_t size, MonoGCDescriptor descr, MonoGCRootSource sourc g_free (res); res = NULL; } - return res; + return (MonoObject*)res; +} + +MonoObject* +mono_gc_alloc_fixed_no_descriptor (size_t size, MonoGCRootSource source, void *key, const char *msg) +{ + return mono_gc_alloc_fixed (size, 0, source, key, msg); } /** @@ -1287,7 +1298,7 @@ LOOP_HEAD: * Array and string allocation */ -void* +MonoArray* mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length) { MonoArray *arr; @@ -1328,7 +1339,7 @@ mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length) return arr; } -void* +MonoArray* mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size) { MonoArray *arr; @@ -1376,7 +1387,7 @@ mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uint return arr; } -void* +MonoString* mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len) { MonoString *str; @@ -1444,9 +1455,9 @@ mono_gc_set_string_length (MonoString *str, gint32 new_length) */ #define GC_ROOT_NUM 32 -#define SPECIAL_ADDRESS_FIN_QUEUE ((void*)1) -#define SPECIAL_ADDRESS_CRIT_FIN_QUEUE ((void*)2) -#define SPECIAL_ADDRESS_EPHEMERON ((void*)3) +#define SPECIAL_ADDRESS_FIN_QUEUE ((mono_byte*)1) +#define SPECIAL_ADDRESS_CRIT_FIN_QUEUE ((mono_byte*)2) +#define SPECIAL_ADDRESS_EPHEMERON ((mono_byte*)3) typedef struct { int count; /* must be the first field */ @@ -1476,7 +1487,7 @@ report_gc_root (GCRootReport *report, void *address, void *object) static void single_arg_report_root (MonoObject **obj, void *gc_data) { - GCRootReport *report = gc_data; + GCRootReport *report = (GCRootReport*)gc_data; if (*obj) report_gc_root (report, obj, *obj); } @@ -1484,7 +1495,7 @@ single_arg_report_root (MonoObject **obj, void *gc_data) static void two_args_report_root (void *address, MonoObject *obj, void *gc_data) { - GCRootReport *report = gc_data; + GCRootReport *report = (GCRootReport*)gc_data; if (obj) report_gc_root (report, address, obj); } @@ -1568,12 +1579,12 @@ find_pinned_obj (char *addr) if (idx != pinned_objects.next_slot) { if (pinned_objects.data [idx] == addr) - return pinned_objects.data [idx]; + return (GCObject*)pinned_objects.data [idx]; if (idx == 0) return NULL; } - GCObject *obj = pinned_objects.data [idx - 1]; + GCObject *obj = (GCObject*)pinned_objects.data [idx - 1]; if (addr > (char*)obj && addr < ((char*)obj + sgen_safe_object_get_size (obj))) return obj; return NULL; @@ -1584,7 +1595,7 @@ find_pinned_obj (char *addr) * We pass @root_report_address so register are properly accounted towards their thread */ static void -report_conservative_roots (GCRootReport *report, char *root_report_address, void **start, void **end) +report_conservative_roots (GCRootReport *report, void *root_report_address, void **start, void **end) { while (start < end) { mword addr = (mword)*start; @@ -1611,7 +1622,7 @@ typedef struct { static void report_handle_stack_root (gpointer *ptr, gpointer user_data) { - ReportHandleStackRoot *ud = user_data; + ReportHandleStackRoot *ud = (ReportHandleStackRoot*)user_data; GCRootReport *report = ud->report; gpointer addr = ud->info->client_info.info.handle_stack; @@ -1631,7 +1642,7 @@ report_handle_stack_roots (GCRootReport *report, SgenThreadInfo *info, gboolean ud.report = report; ud.info = info; - mono_handle_stack_scan ((HandleStack *) info->client_info.info.handle_stack, report_handle_stack_root, &ud, ud.precise, FALSE); + mono_handle_stack_scan (info->client_info.info.handle_stack, report_handle_stack_root, &ud, ud.precise, FALSE); } static void @@ -1691,7 +1702,7 @@ report_pin_queue (void) sgen_pointer_queue_sort_uniq (&pinned_objects); for (int i = 0; i < pinned_objects.next_slot; ++i) { - GCObject *obj = pinned_objects.data [i]; + GCObject *obj = (GCObject*)pinned_objects.data [i]; ssize_t size = sgen_safe_object_get_size (obj); ssize_t addr = (ssize_t)obj; @@ -2058,7 +2069,7 @@ sgen_client_thread_detach_with_lock (SgenThreadInfo *p) sgen_binary_protocol_thread_unregister ((gpointer)tid); SGEN_LOG (3, "unregister thread %p (%p)", p, (gpointer)tid); - HandleStack *handles = (HandleStack*) p->client_info.info.handle_stack; + HandleStack *handles = p->client_info.info.handle_stack; p->client_info.info.handle_stack = NULL; mono_handle_stack_free (handles); } @@ -2247,13 +2258,13 @@ sgen_client_scan_thread_data (void *start_nursery, void *end_nursery, gboolean p beginning of the object. */ if (precise) - mono_handle_stack_scan ((HandleStack*)info->client_info.info.handle_stack, (GcScanFunc)ctx.ops->copy_or_mark_object, ctx.queue, precise, TRUE); + mono_handle_stack_scan (info->client_info.info.handle_stack, (GcScanFunc)ctx.ops->copy_or_mark_object, ctx.queue, precise, TRUE); else { PinHandleStackInteriorPtrData ud; memset (&ud, 0, sizeof (ud)); ud.start_nursery = (void**)start_nursery; ud.end_nursery = (void**)end_nursery; - mono_handle_stack_scan ((HandleStack*)info->client_info.info.handle_stack, pin_handle_stack_interior_ptrs, &ud, precise, FALSE); + mono_handle_stack_scan (info->client_info.info.handle_stack, pin_handle_stack_interior_ptrs, &ud, precise, FALSE); } } } FOREACH_THREAD_END @@ -2464,7 +2475,7 @@ mono_gc_make_descr_for_string (gsize *bitmap, int numbits) void mono_gc_register_obj_with_weak_fields (void *obj) { - return sgen_register_obj_with_weak_fields (obj); + return sgen_register_obj_with_weak_fields ((MonoObject*)obj); } void* @@ -2634,7 +2645,7 @@ sgen_client_gchandle_created (int handle_type, GCObject *obj, guint32 handle) mono_atomic_inc_i32 (&mono_perfcounters->gc_num_handles); #endif - MONO_PROFILER_RAISE (gc_handle_created, (handle, handle_type, obj)); + MONO_PROFILER_RAISE (gc_handle_created, (handle, (MonoGCHandleType)handle_type, obj)); } void @@ -2644,7 +2655,7 @@ sgen_client_gchandle_destroyed (int handle_type, guint32 handle) mono_atomic_dec_i32 (&mono_perfcounters->gc_num_handles); #endif - MONO_PROFILER_RAISE (gc_handle_deleted, (handle, handle_type)); + MONO_PROFILER_RAISE (gc_handle_deleted, (handle, (MonoGCHandleType)handle_type)); } void @@ -2688,7 +2699,7 @@ mono_gc_get_card_table (int *shift_bits, gpointer *mask) } guint8* -mono_gc_get_target_card_table (int *shift_bits, gpointer *mask) +mono_gc_get_target_card_table (int *shift_bits, target_mgreg_t *mask) { return sgen_get_target_card_table_configuration (shift_bits, mask); } diff --git a/mono/metadata/sgen-new-bridge.c b/mono/metadata/sgen-new-bridge.c index 321c4a6ed6..b9d4c3a0b1 100644 --- a/mono/metadata/sgen-new-bridge.c +++ b/mono/metadata/sgen-new-bridge.c @@ -620,7 +620,7 @@ dump_graph (void) MonoObject *obj; HashEntry *entry; size_t prefix_len = strlen (dump_prefix); - char *filename = (char *)alloca (prefix_len + 64); + char *filename = g_newa (char, prefix_len + 64); FILE *file; int edge_id = 0; diff --git a/mono/metadata/sgen-stw.c b/mono/metadata/sgen-stw.c index 2af66e00b0..1ede28e8d5 100644 --- a/mono/metadata/sgen-stw.c +++ b/mono/metadata/sgen-stw.c @@ -329,7 +329,7 @@ sgen_unified_suspend_stop_world (void) if (!(suspend_count == 1)) g_error ("[%p] suspend_count = %d, but should be 1", mono_thread_info_get_tid (info), suspend_count); - info->client_info.skip = !mono_thread_info_begin_resume (info); + info->client_info.skip = !mono_thread_info_begin_pulse_resume_and_request_suspension (info); if (!info->client_info.skip) restart_counter += 1; diff --git a/mono/metadata/sre-encode.c b/mono/metadata/sre-encode.c index 96bdcb2ee1..e1e5a43e34 100644 --- a/mono/metadata/sre-encode.c +++ b/mono/metadata/sre-encode.c @@ -519,7 +519,7 @@ mono_dynimage_encode_constant (MonoDynamicImage *assembly, MonoObject *val, Mono char blob_size [64]; char *b = blob_size; - char *box_val; + gpointer box_val; char* buf; guint32 idx = 0, len = 0, dummy = 0; @@ -527,7 +527,7 @@ mono_dynimage_encode_constant (MonoDynamicImage *assembly, MonoObject *val, Mono if (!val) { *ret_type = MONO_TYPE_CLASS; len = 4; - box_val = (char*)&dummy; + box_val = &dummy; } else { box_val = mono_object_get_data (val); *ret_type = m_class_get_byval_arg (val->vtable->klass)->type; @@ -585,7 +585,7 @@ handle_enum: g_free (swapped); } #else - idx = mono_dynamic_image_add_to_blob_cached (assembly, blob_size, b-blob_size, (char*)mono_string_chars (str), len); + idx = mono_dynamic_image_add_to_blob_cached (assembly, blob_size, b-blob_size, mono_string_chars (str), len); #endif g_free (buf); @@ -779,7 +779,8 @@ mono_dynimage_encode_typedef_or_ref_full (MonoDynamicImage *assembly, MonoType * goto leave; klass = mono_class_from_mono_type (type); - MonoReflectionTypeBuilderHandle tb = MONO_HANDLE_CAST (MonoReflectionTypeBuilder, mono_class_get_ref_info (klass)); + MonoReflectionTypeBuilderHandle tb; + tb = MONO_HANDLE_CAST (MonoReflectionTypeBuilder, mono_class_get_ref_info (klass)); /* * If it's in the same module and not a generic type parameter: */ @@ -872,7 +873,8 @@ encode_sighelper_arg (MonoDynamicImage *assembly, int i, MonoArrayHandle helper_ encode_custom_modifiers (assembly, modreqs, modopts, buf, error); goto_if_nok (error, leave); - MonoReflectionTypeHandle pt = MONO_HANDLE_NEW (MonoReflectionType, NULL); + MonoReflectionTypeHandle pt; + pt = MONO_HANDLE_NEW (MonoReflectionType, NULL); MONO_HANDLE_ARRAY_GETREF (pt, helper_arguments, i); encode_reflection_type (assembly, pt, buf, error); goto_if_nok (error, leave); @@ -924,8 +926,10 @@ mono_dynimage_encode_reflection_sighelper (MonoDynamicImage *assembly, MonoRefle sigbuffer_add_value (&buf, nargs); encode_reflection_type (assembly, MONO_HANDLE_NEW_GET (MonoReflectionType, helper, return_type), &buf, error); goto_if_nok (error, fail); - MonoArrayHandle modreqs = MONO_HANDLE_NEW_GET (MonoArray, helper, modreqs); - MonoArrayHandle modopts = MONO_HANDLE_NEW_GET (MonoArray, helper, modopts); + MonoArrayHandle modreqs; + modreqs = MONO_HANDLE_NEW_GET (MonoArray, helper, modreqs); + MonoArrayHandle modopts; + modopts = MONO_HANDLE_NEW_GET (MonoArray, helper, modopts); for (i = 0; i < nargs; ++i) { if (!encode_sighelper_arg (assembly, i, arguments, modreqs, modopts, &buf, error)) goto fail; @@ -982,10 +986,12 @@ reflection_sighelper_get_signature_local (MonoReflectionSigHelperHandle sig, Mon } buflen = buf.p - buf.buf; - MonoArrayHandle result = mono_array_new_handle (mono_domain_get (), mono_defaults.byte_class, buflen, error); + MonoArrayHandle result; + result = mono_array_new_handle (mono_domain_get (), mono_defaults.byte_class, buflen, error); goto_if_nok (error, fail); uint32_t gchandle; - void *base = MONO_ARRAY_HANDLE_PIN (result, char, 0, &gchandle); + void *base; + base = MONO_ARRAY_HANDLE_PIN (result, char, 0, &gchandle); memcpy (base, buf.buf, buflen); sigbuffer_free (&buf); mono_gchandle_free (gchandle); @@ -1016,10 +1022,12 @@ reflection_sighelper_get_signature_field (MonoReflectionSigHelperHandle sig, Mon } buflen = buf.p - buf.buf; - MonoArrayHandle result = mono_array_new_handle (mono_domain_get (), mono_defaults.byte_class, buflen, error); + MonoArrayHandle result; + result = mono_array_new_handle (mono_domain_get (), mono_defaults.byte_class, buflen, error); goto_if_nok (error, fail); uint32_t gchandle; - void *base = MONO_ARRAY_HANDLE_PIN (result, char, 0, &gchandle); + void *base; + base = MONO_ARRAY_HANDLE_PIN (result, char, 0, &gchandle); memcpy (base, buf.buf, buflen); sigbuffer_free (&buf); mono_gchandle_free (gchandle); diff --git a/mono/metadata/sre-internals.h b/mono/metadata/sre-internals.h index 058092b6f1..3a56a90061 100644 --- a/mono/metadata/sre-internals.h +++ b/mono/metadata/sre-internals.h @@ -63,6 +63,8 @@ mono_reflection_dynimage_basic_init (MonoReflectionAssemblyBuilder *assemblyb); gpointer mono_image_g_malloc0 (MonoImage *image, guint size); +#define mono_image_g_malloc0(image, size) (g_cast (mono_image_g_malloc0 ((image), (size)))) + gboolean mono_is_sre_type_builder (MonoClass *klass); @@ -90,6 +92,9 @@ mono_reflection_type_get_handle (MonoReflectionType *ref, MonoError *error); gpointer mono_reflection_resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, MonoGenericContext *context, MonoError *error); +gpointer +mono_reflection_resolve_object_handle (MonoImage *image, MonoObjectHandle obj, MonoClass **handle_class, MonoGenericContext *context, MonoError *error); + MonoType* mono_type_array_get_and_resolve (MonoArrayHandle array, int idx, MonoError* error); void diff --git a/mono/metadata/sre-save.c.REMOVED.git-id b/mono/metadata/sre-save.c.REMOVED.git-id index 801e242260..f34758816d 100644 --- a/mono/metadata/sre-save.c.REMOVED.git-id +++ b/mono/metadata/sre-save.c.REMOVED.git-id @@ -1 +1 @@ -d56a4c56da6d95959efdfd1c2892411b6924e2b5 \ No newline at end of file +3745b716d63db5a70b8de99b3cdc80dc0f2538f5 \ No newline at end of file diff --git a/mono/metadata/sre.c.REMOVED.git-id b/mono/metadata/sre.c.REMOVED.git-id index e6c946b512..416d5bdfd7 100644 --- a/mono/metadata/sre.c.REMOVED.git-id +++ b/mono/metadata/sre.c.REMOVED.git-id @@ -1 +1 @@ -a8c931570e89a5bfc2e85f349c2162d26eb3f2c0 \ No newline at end of file +e2c5f2ea48d61eb98fe2afbeb0440fc0ec963399 \ No newline at end of file diff --git a/mono/metadata/sysmath.c b/mono/metadata/sysmath.c index 157de9c197..b37c4b9e69 100644 --- a/mono/metadata/sysmath.c +++ b/mono/metadata/sysmath.c @@ -25,436 +25,363 @@ #define __USE_ISOC99 #include -#include #include "number-ms.h" #include "utils/mono-compiler.h" +#include "icalls.h" -static const MonoDouble_double NaN = { MONO_INIT_DOUBLE (0, 0x7FF, 0x80000, 0) }; - -/* +Infinity */ -static const MonoDouble_double PInfinity = { MONO_INIT_DOUBLE (0, 0x7FF, 0, 0) }; - -/* -Infinity */ -static const MonoDouble_double MInfinity = { MONO_INIT_DOUBLE (1, 0x7FF, 0, 0) }; - -/* +1 */ -static const MonoDouble_double POne = { MONO_INIT_DOUBLE (0, 0x3FF, 0, 0) }; - -/* -1 */ -static const MonoDouble_double MOne = { MONO_INIT_DOUBLE (1, 0x3FF, 0, 0) }; - -static MONO_ALWAYS_INLINE gboolean -isplusinfinity (gdouble d) -{ - return d == PInfinity.d; -} - -static MONO_ALWAYS_INLINE gboolean -isminusinfinity (gdouble d) -{ - return d == MInfinity.d; -} - -static MONO_ALWAYS_INLINE gboolean -isinfinity (gdouble d) -{ - return isplusinfinity (d) || isminusinfinity (d); -} - -static MONO_ALWAYS_INLINE gboolean -isplusone (gdouble d) -{ - return d == POne.d; -} - -static MONO_ALWAYS_INLINE gboolean -isminusone (gdouble d) -{ - return d == MOne.d; -} - +ICALL_EXPORT gdouble ves_icall_System_Math_Floor (gdouble x) { return floor(x); } +ICALL_EXPORT gdouble ves_icall_System_Math_Round (gdouble x) { - gdouble tmp, floor_tmp; + gdouble floor_tmp; /* If the number has no fractional part do nothing This shortcut is necessary * to workaround precision loss in borderline cases on some platforms */ if (x == (gdouble)(gint64) x) return x; - tmp = x + 0.5; - floor_tmp = floor (tmp); + floor_tmp = floor (x + 0.5); - if (floor_tmp == tmp) { - if (fmod (tmp, 2.0) != 0) - floor_tmp -= 1.0; + if ((x == (floor (x) + 0.5)) && (fmod (floor_tmp, 2.0) != 0)) { + floor_tmp -= 1.0; } return copysign (floor_tmp, x); } +ICALL_EXPORT +gdouble +ves_icall_System_Math_FMod (gdouble x, gdouble y) +{ + return fmod (x, y); +} + +ICALL_EXPORT +gdouble +ves_icall_System_Math_ModF (gdouble x, gdouble *d) +{ + return modf (x, d); +} + +ICALL_EXPORT gdouble ves_icall_System_Math_Sin (gdouble x) { return sin (x); } +ICALL_EXPORT gdouble ves_icall_System_Math_Cos (gdouble x) { return cos (x); } +ICALL_EXPORT +gdouble +ves_icall_System_Math_Cbrt (gdouble x) +{ + return cbrt (x); +} + +ICALL_EXPORT gdouble ves_icall_System_Math_Tan (gdouble x) { return tan (x); } +ICALL_EXPORT gdouble ves_icall_System_Math_Sinh (gdouble x) { return sinh (x); } +ICALL_EXPORT gdouble ves_icall_System_Math_Cosh (gdouble x) { return cosh (x); } +ICALL_EXPORT gdouble ves_icall_System_Math_Tanh (gdouble x) { return tanh (x); } +ICALL_EXPORT gdouble ves_icall_System_Math_Acos (gdouble x) { - if (x < -1 || x > 1) - return NaN.d; - return acos (x); } +ICALL_EXPORT +gdouble +ves_icall_System_Math_Acosh (gdouble x) +{ + return acosh (x); +} + +ICALL_EXPORT gdouble ves_icall_System_Math_Asin (gdouble x) { - if (x < -1 || x > 1) - return NaN.d; - return asin (x); } +ICALL_EXPORT +gdouble +ves_icall_System_Math_Asinh (gdouble x) +{ + return asinh (x); +} + +ICALL_EXPORT gdouble ves_icall_System_Math_Atan (gdouble x) { return atan (x); } +ICALL_EXPORT gdouble ves_icall_System_Math_Atan2 (gdouble y, gdouble x) { - gdouble result; - - if (isinfinity (x) && isinfinity (y)) - return NaN.d; - - result = atan2 (y, x); - return result == -0.0 ? 0.0: result; + return atan2 (y, x); } +ICALL_EXPORT +gdouble +ves_icall_System_Math_Atanh (gdouble x) +{ + return atanh (x); +} + +ICALL_EXPORT gdouble ves_icall_System_Math_Exp (gdouble x) { - if (isinfinity (x)) - return x < 0 ? 0.0 : x; - return exp (x); } +ICALL_EXPORT gdouble ves_icall_System_Math_Log (gdouble x) { - if (x == 0) - return MInfinity.d; - else if (x < 0) - return NaN.d; - return log (x); } +ICALL_EXPORT gdouble ves_icall_System_Math_Log10 (gdouble x) { - if (x == 0) - return MInfinity.d; - else if (x < 0) - return NaN.d; - return log10 (x); } +ICALL_EXPORT gdouble ves_icall_System_Math_Pow (gdouble x, gdouble y) { - gdouble result; - - if (isnan (y)) - return y; - if (isnan (x)) - return x; - - if (isinfinity (y)) { - if (isplusone (x)) - return x; - if (isminusone (x)) - return NaN.d; - } - - /* following are cases from PAL_pow which abstract the implementation of pow for posix and win32 platforms - * (https://github.com/dotnet/coreclr/blob/master/src/pal/src/cruntime/finite.cpp#L331) */ - - if (isplusinfinity (y) && !isnan (x)) { - if (isplusone (x) || isminusone (x)) - result = NaN.d; - else if (x > MOne.d && x < POne.d) - result = 0.0; - else - result = PInfinity.d; - } else if (isminusinfinity (y) && !isnan (x)) { - if (isplusone (x) || isminusone (x)) - result = NaN.d; - if (x > MOne.d && x < POne.d) - result = PInfinity.d; - else - result = 0.0; - } else if (x == 0.0 && y < 0.0) { - result = PInfinity.d; - } else if (y == 0.0 && isnan (x)) { - /* Windows returns NaN for pow(NaN, 0), but POSIX specifies - * a return value of 1 for that case. We need to return - * the same result as Windows. */ - result = NaN.d; - } else { - result = pow (x, y); - } - - if (result == PInfinity.d && x < 0.0 && isfinite (x) && ceil (y / 2) != floor (y / 2)) - result = MInfinity.d; - - /* - * The even/odd test in the if (this one and the one above) used to be ((long long) y % 2 == 0) - * on SPARC (long long) y for large y (>2**63) is always 0x7fffffff7fffffff, which - * is an odd number, so the test ((long long) y % 2 == 0) will always fail for - * large y. Since large double numbers are always even (e.g., the representation of - * 1E20+1 is the same as that of 1E20, the last .+1. is too insignificant to be part - * of the representation), this test will always return the wrong result for large y. - * - * The (ceil(y/2) == floor(y/2)) test is slower, but more robust. - */ - if (result == MInfinity.d && x < 0.0 && isfinite (x) && ceil (y / 2) == floor (y / 2)) - result = PInfinity.d; - -#if defined (__linux__) && SIZEOF_VOID_P == 4 - /* On Linux 32bits, some tests erroneously return NaN */ - if (isnan (result)) { - if (isminusone (x) && (y > 9007199254740991.0 || y < -9007199254740991.0)) { - /* Math.Pow (-1, Double.MaxValue) and Math.Pow (-1, Double.MinValue) should return 1 */ - result = POne.d; - } else if (x < -9007199254740991.0 && y < -9007199254740991.0) { - /* Math.Pow (Double.MinValue, Double.MinValue) should return 0 */ - result = 0.0; - } else if (x < -9007199254740991.0 && y > 9007199254740991.0) { - /* Math.Pow (Double.MinValue, Double.MaxValue) should return Double.PositiveInfinity */ - result = PInfinity.d; - } - } -#endif - - return result == -0.0 ? 0 : result; + return pow (x, y); } +ICALL_EXPORT gdouble ves_icall_System_Math_Sqrt (gdouble x) { - if (x < 0) - return NaN.d; - return sqrt (x); } +ICALL_EXPORT gdouble ves_icall_System_Math_Abs_double (gdouble v) { return fabs (v); } +ICALL_EXPORT float ves_icall_System_Math_Abs_single (float v) { return fabsf (v); } +ICALL_EXPORT gdouble ves_icall_System_Math_Ceiling (gdouble v) { return ceil (v); } -gdouble -ves_icall_System_Math_SplitFractionDouble (gdouble *v) -{ - return modf (*v, v); -} - +ICALL_EXPORT float ves_icall_System_MathF_Acos (float x) { return acosf (x); } +ICALL_EXPORT float ves_icall_System_MathF_Acosh (float x) { return acoshf (x); } +ICALL_EXPORT float ves_icall_System_MathF_Asin (float x) { return asinf (x); } +ICALL_EXPORT float ves_icall_System_MathF_Asinh (float x) { return asinhf (x); } +ICALL_EXPORT float ves_icall_System_MathF_Atan (float x) { return atan (x); } +ICALL_EXPORT float ves_icall_System_MathF_Atan2 (float x, float y) { return atan2f (x, y); } +ICALL_EXPORT float ves_icall_System_MathF_Atanh (float x) { return atanhf (x); } +ICALL_EXPORT float ves_icall_System_MathF_Cbrt (float x) { return cbrtf (x); } +ICALL_EXPORT float ves_icall_System_MathF_Ceiling (float x) { return ceilf(x); } +ICALL_EXPORT float ves_icall_System_MathF_Cos (float x) { return cosf (x); } +ICALL_EXPORT float ves_icall_System_MathF_Cosh (float x) { return coshf (x); } +ICALL_EXPORT float ves_icall_System_MathF_Exp (float x) { return expf (x); } +ICALL_EXPORT float ves_icall_System_MathF_Floor (float x) { return floorf (x); } +ICALL_EXPORT float ves_icall_System_MathF_Log (float x) { return logf (x); } +ICALL_EXPORT float ves_icall_System_MathF_Log10 (float x) { return log10f (x); } +ICALL_EXPORT float ves_icall_System_MathF_Pow (float x, float y) { return powf (x, y); } +ICALL_EXPORT float ves_icall_System_MathF_Sin (float x) { return sinf (x); } +ICALL_EXPORT float ves_icall_System_MathF_Sinh (float x) { return sinh (x); } +ICALL_EXPORT float ves_icall_System_MathF_Sqrt (float x) { return sqrtf (x); } +ICALL_EXPORT float ves_icall_System_MathF_Tan (float x) { return tanf (x); } +ICALL_EXPORT float ves_icall_System_MathF_Tanh (float x) { return tanh (x); } +ICALL_EXPORT float ves_icall_System_MathF_FMod (float x, float y) { return fmodf (x, y); } +ICALL_EXPORT float ves_icall_System_MathF_ModF (float x, float *d) { - float f; - if (d == NULL) - d = &f; return modff (x, d); } - diff --git a/mono/metadata/sysmath.h b/mono/metadata/sysmath.h deleted file mode 100644 index e8f19a2311..0000000000 --- a/mono/metadata/sysmath.h +++ /dev/null @@ -1,196 +0,0 @@ -/** - * \file - * - * Author: - * Dan Lewis (dihlewis@yahoo.co.uk) - * Ludovic Henry (ludovic@xamarin.com) - * - * (C) Ximian, Inc. 2002 - * Copyright 2015 Xamarin, Inc (https://www.xamarin.com) - * Licensed under the MIT license. See LICENSE file in the project root for full license information. - */ - -#ifndef __METADATA_SYSMATH_H__ -#define __METADATA_SYSMATH_H__ - -#include -#include -#include - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Floor (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Round (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Sin (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Cos (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Tan (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Sinh (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Cosh (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Tanh (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Acos (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Asin (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Atan (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Atan2 (gdouble y, gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Exp (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Log (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Log10 (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Pow (gdouble x, gdouble y); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Sqrt (gdouble x); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Abs_double (gdouble v); - -ICALL_EXPORT -gfloat -ves_icall_System_Math_Abs_single (gfloat v); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_SplitFractionDouble (gdouble *v); - -ICALL_EXPORT -gdouble -ves_icall_System_Math_Ceiling (gdouble v); - -ICALL_EXPORT -float -ves_icall_System_MathF_Acos (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Acosh (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Asin (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Asinh (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Atan (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Atan2 (float x, float y); - -ICALL_EXPORT -float -ves_icall_System_MathF_Atanh (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Cbrt (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Ceiling (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Cos (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Cosh (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Exp (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Floor (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Log (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Log10 (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Pow (float x, float y); - -ICALL_EXPORT -float -ves_icall_System_MathF_Sin (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Sinh (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Sqrt (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Tan (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_Tanh (float x); - -ICALL_EXPORT -float -ves_icall_System_MathF_FMod (float x, float y); - -ICALL_EXPORT -float -ves_icall_System_MathF_ModF (float x, float *d); - -#endif diff --git a/mono/metadata/threadpool-io.c b/mono/metadata/threadpool-io.c index eed6f2cba5..c89f3e1fda 100644 --- a/mono/metadata/threadpool-io.c +++ b/mono/metadata/threadpool-io.c @@ -582,7 +582,7 @@ initialize (void) io_selector_running = TRUE; ERROR_DECL (error); - if (!mono_thread_create_internal (mono_get_root_domain (), selector_thread, NULL, MONO_THREAD_CREATE_FLAGS_THREADPOOL | MONO_THREAD_CREATE_FLAGS_SMALL_STACK, error)) + if (!mono_thread_create_internal (mono_get_root_domain (), (gpointer)selector_thread, NULL, (MonoThreadCreateFlags)(MONO_THREAD_CREATE_FLAGS_THREADPOOL | MONO_THREAD_CREATE_FLAGS_SMALL_STACK), error)) g_error ("initialize: mono_thread_create_internal () failed due to %s", mono_error_get_message (error)); mono_coop_mutex_unlock (&threadpool_io->updates_lock); diff --git a/mono/metadata/threadpool-worker-default.c b/mono/metadata/threadpool-worker-default.c index 81e54bfc48..96372a15f3 100644 --- a/mono/metadata/threadpool-worker-default.c +++ b/mono/metadata/threadpool-worker-default.c @@ -25,7 +25,6 @@ #include #include #include -#include #include #include #include @@ -34,6 +33,7 @@ #include #include #include +#include // This header has defines to muck with names, so put it late. #define CPU_USAGE_LOW 80 #define CPU_USAGE_HIGH 95 @@ -558,7 +558,7 @@ worker_try_create (void) counter._.starting ++; }); - thread = mono_thread_create_internal (mono_get_root_domain (), worker_thread, NULL, MONO_THREAD_CREATE_FLAGS_THREADPOOL, error); + thread = mono_thread_create_internal (mono_get_root_domain (), (gpointer)worker_thread, NULL, MONO_THREAD_CREATE_FLAGS_THREADPOOL, error); if (!thread) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: could not create thread due to %s", GUINT_TO_POINTER (MONO_NATIVE_THREAD_ID_TO_UINT (mono_native_thread_id_get ())), mono_error_get_message (error)); @@ -787,7 +787,7 @@ monitor_ensure_running (void) return; if (mono_atomic_cas_i32 (&worker.monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_NOT_RUNNING) == MONITOR_STATUS_NOT_RUNNING) { // printf ("monitor_thread: creating\n"); - if (!mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, MONO_THREAD_CREATE_FLAGS_THREADPOOL | MONO_THREAD_CREATE_FLAGS_SMALL_STACK, error)) { + if (!mono_thread_create_internal (mono_get_root_domain (), (gpointer)monitor_thread, NULL, (MonoThreadCreateFlags)(MONO_THREAD_CREATE_FLAGS_THREADPOOL | MONO_THREAD_CREATE_FLAGS_SMALL_STACK), error)) { // printf ("monitor_thread: creating failed\n"); worker.monitor_status = MONITOR_STATUS_NOT_RUNNING; mono_error_cleanup (error); diff --git a/mono/metadata/threads-types.h b/mono/metadata/threads-types.h index ca3ddd52a6..f8a75aa011 100644 --- a/mono/metadata/threads-types.h +++ b/mono/metadata/threads-types.h @@ -15,6 +15,7 @@ #include +#include #include #include "mono/metadata/handle.h" #include "mono/utils/mono-compiler.h" @@ -34,7 +35,9 @@ typedef enum { ThreadState_Suspended = 0x00000040, ThreadState_AbortRequested = 0x00000080, ThreadState_Aborted = 0x00000100 -} MonoThreadState; +} MonoThreadState; + +G_ENUM_FUNCTIONS (MonoThreadState) /* This is a copy of System.Threading.ApartmentState */ typedef enum { @@ -44,6 +47,8 @@ typedef enum { } MonoThreadApartmentState; typedef enum { +// These values match System.Threading.ThreadPriority. +// These values match System.Diagnostics.ThreadPriorityLevel and Windows, but are offset by 2. MONO_THREAD_PRIORITY_LOWEST = 0, MONO_THREAD_PRIORITY_BELOW_NORMAL = 1, MONO_THREAD_PRIORITY_NORMAL = 2, @@ -55,8 +60,6 @@ typedef enum { #define SPECIAL_STATIC_THREAD 1 #define SPECIAL_STATIC_CONTEXT 2 -typedef struct _MonoInternalThread MonoInternalThread; - /* It's safe to access System.Threading.InternalThread from native code via a * raw pointer because all instances should be pinned. But for uniformity of * icall wrapping, let's declare a MonoInternalThreadHandle anyway. @@ -78,9 +81,45 @@ typedef enum { MONO_THREAD_CREATE_FLAGS_SMALL_STACK = 0x8, } MonoThreadCreateFlags; +// FIXME func should be MonoThreadStart and remove the template MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error); +#ifdef __cplusplus +template +inline MonoInternalThread* +mono_thread_create_internal (MonoDomain *domain, T func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error) +{ + return mono_thread_create_internal(domain, (gpointer)func, arg, flags, error); +} +#endif + +MonoInternalThreadHandle +mono_thread_create_internal_handle (MonoDomain *domain, gpointer func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error); + +#ifdef __cplusplus +template +inline MonoInternalThreadHandle +mono_thread_create_internal_handle (MonoDomain *domain, T func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error) +{ + return mono_thread_create_internal_handle(domain, (gpointer)func, arg, flags, error); +} +#endif + +/* Data owned by a MonoInternalThread that must live until both the finalizer + * for MonoInternalThread has run, and the underlying machine thread has + * detached. + * + * Normally a thread is first detached and then the InternalThread object is + * finalized and collected. However during shutdown, when the root domain is + * finalized, all the InternalThread objects are finalized first and the + * machine threads are detached later. + */ +typedef struct { + MonoRefCount ref; + MonoCoopMutex *synch_cs; +} MonoLongLivedThreadData; + void mono_threads_install_cleanup (MonoThreadCleanupFunc func); ICALL_EXPORT @@ -361,7 +400,7 @@ void ves_icall_System_Threading_Thread_SpinWait_nop (MonoError *error); void -mono_threads_register_app_context (MonoAppContext* ctx, MonoError *error); +mono_threads_register_app_context (MonoAppContextHandle ctx, MonoError *error); void mono_threads_release_app_context (MonoAppContext* ctx, MonoError *error); @@ -373,6 +412,9 @@ void ves_icall_System_Runtime_Remoting_Contexts_Context_ReleaseContext (MonoAppC MONO_PROFILER_API MonoInternalThread *mono_thread_internal_current (void); +MonoInternalThreadHandle +mono_thread_internal_current_handle (void); + void mono_thread_internal_abort (MonoInternalThread *thread, gboolean appdomain_unload); void mono_thread_internal_suspend_for_shutdown (MonoInternalThread *thread); @@ -437,9 +479,19 @@ void mono_thread_resume_interruption (gboolean exec); void mono_threads_perform_thread_dump (void); +// FIXME Correct the type of func and remove the template. gboolean mono_thread_create_checked (MonoDomain *domain, gpointer func, gpointer arg, MonoError *error); +#ifdef __cplusplus +template +inline gboolean +mono_thread_create_checked (MonoDomain *domain, T func, gpointer arg, MonoError *error) +{ + return mono_thread_create_checked (domain, (gpointer)func, arg, error); +} +#endif + void mono_threads_add_joinable_runtime_thread (MonoThreadInfo *thread_info); void mono_threads_add_joinable_thread (gpointer tid); void mono_threads_join_threads (void); @@ -472,9 +524,15 @@ mono_thread_internal_describe (MonoInternalThread *internal, GString *str); gboolean mono_thread_internal_is_current (MonoInternalThread *internal); +gboolean +mono_thread_internal_is_current_handle (MonoInternalThreadHandle internal); + gboolean mono_threads_is_current_thread_in_protected_block (void); +gboolean +mono_threads_is_critical_method (MonoMethod *method); + gpointer mono_threads_enter_gc_unsafe_region_unbalanced_internal (MonoStackData *stackdata); @@ -527,8 +585,8 @@ typedef struct { } MonoFrameSummary; typedef struct { - intptr_t offset_free_hash; - intptr_t offset_rich_hash; + guint64 offset_free_hash; + guint64 offset_rich_hash; } MonoStackHash; typedef struct { @@ -538,8 +596,8 @@ typedef struct { // For managed stack walking MonoDomain *domain; - gpointer *jit_tls; - gpointer *lmf; + MonoJitTlsData *jit_tls; + MonoLMF *lmf; // Emitted attributes diff --git a/mono/metadata/threads.c.REMOVED.git-id b/mono/metadata/threads.c.REMOVED.git-id index e2fb07d6d2..79ff840a9a 100644 --- a/mono/metadata/threads.c.REMOVED.git-id +++ b/mono/metadata/threads.c.REMOVED.git-id @@ -1 +1 @@ -b637f0edaf83af7aee5679d8090c911271410f53 \ No newline at end of file +e3a110d89210ded88847f16c8aabfa0ba821eb0a \ No newline at end of file diff --git a/mono/metadata/w32file-unix-glob.c b/mono/metadata/w32file-unix-glob.c index 62d44889be..99636a3789 100644 --- a/mono/metadata/w32file-unix-glob.c +++ b/mono/metadata/w32file-unix-glob.c @@ -276,13 +276,11 @@ globextend(const gchar *path, mono_w32file_unix_glob_t *pglob, size_t *limitp) newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs); /* FIXME: Can just use realloc(). */ - pathv = (char **)(pglob->gl_pathv ? g_realloc ((char *)pglob->gl_pathv, newsize) : - g_malloc (newsize)); + pathv = pglob->gl_pathv ? (char**)g_realloc (pglob->gl_pathv, newsize) : + (char**)g_malloc (newsize); if (pathv == NULL) { - if (pglob->gl_pathv) { - g_free (pglob->gl_pathv); - pglob->gl_pathv = NULL; - } + g_free (pglob->gl_pathv); + pglob->gl_pathv = NULL; return(W32FILE_UNIX_GLOB_NOSPACE); } diff --git a/mono/metadata/w32file-unix.c.REMOVED.git-id b/mono/metadata/w32file-unix.c.REMOVED.git-id index ff0549a89a..7bfed477f1 100644 --- a/mono/metadata/w32file-unix.c.REMOVED.git-id +++ b/mono/metadata/w32file-unix.c.REMOVED.git-id @@ -1 +1 @@ -d031bed216d0d175359b356afab000ee125c567d \ No newline at end of file +5ad703bc1009ff8be7bc6e664c78ce30307bf34e \ No newline at end of file diff --git a/mono/metadata/w32file.c b/mono/metadata/w32file.c index 557f810587..4fdabfa9c0 100644 --- a/mono/metadata/w32file.c +++ b/mono/metadata/w32file.c @@ -509,7 +509,7 @@ ves_icall_System_IO_MonoIO_Read (HANDLE handle, MonoArrayHandle dest, gint32 *io_error, MonoError *error) { - guchar *buffer; + void *buffer; gboolean result; guint32 n; @@ -539,7 +539,7 @@ ves_icall_System_IO_MonoIO_Write (HANDLE handle, MonoArrayHandle src, gint32 *io_error, MonoError *error) { - guchar *buffer; + void *buffer; gboolean result; guint32 n; @@ -738,7 +738,7 @@ ves_icall_System_IO_MonoIO_DuplicateHandle (HANDLE source_process_handle, HANDLE *target_handle = mono_w32handle_duplicate (source_handle_data); - mono_w32handle_unref (source_handle); + mono_w32handle_unref ((MonoW32Handle*)source_handle); #else gboolean ret; diff --git a/mono/metadata/w32file.h b/mono/metadata/w32file.h index e780367465..2518fbcb4a 100644 --- a/mono/metadata/w32file.h +++ b/mono/metadata/w32file.h @@ -21,8 +21,6 @@ #include #include -G_BEGIN_DECLS - /* This is a copy of System.IO.FileAccess */ typedef enum { FileAccess_Read=0x01, @@ -502,6 +500,4 @@ mono_w32file_get_drive_type (const gunichar2 *root_path_name); gboolean mono_w32file_get_volume_information (const gunichar2 *path, gunichar2 *volumename, gint volumesize, gint *outserial, gint *maxcomp, gint *fsflags, gunichar2 *fsbuffer, gint fsbuffersize); -G_END_DECLS - #endif /* _MONO_METADATA_W32FILE_H_ */ diff --git a/mono/metadata/w32handle.c b/mono/metadata/w32handle.c index a2ef2beebb..cb84302761 100644 --- a/mono/metadata/w32handle.c +++ b/mono/metadata/w32handle.c @@ -13,14 +13,13 @@ #include #include - #include "w32handle.h" - #include "utils/atomic.h" #include "utils/mono-logger-internals.h" #include "utils/mono-proclib.h" #include "utils/mono-threads.h" #include "utils/mono-time.h" +#include "utils/mono-error-internals.h" #undef DEBUG_REFS @@ -48,7 +47,7 @@ static MonoCoopCond global_signal_cond; static MonoCoopMutex scan_mutex; -static gboolean shutting_down = FALSE; +static gboolean shutting_down; static const gchar* mono_w32handle_ops_typename (MonoW32Type type); @@ -593,11 +592,16 @@ mono_w32handle_lock_handles (MonoW32Handle **handles_data, gsize nhandles) /* Lock all the handles, with backoff */ again: for (i = 0; i < nhandles; i++) { + if (!handles_data [i]) + continue; if (!mono_w32handle_trylock (handles_data [i])) { /* Bummer */ - for (j = i - 1; j >= 0; j--) + for (j = i - 1; j >= 0; j--) { + if (!handles_data [j]) + continue; mono_w32handle_unlock (handles_data [j]); + } iter += 10; if (iter == 1000) @@ -630,8 +634,11 @@ mono_w32handle_unlock_handles (MonoW32Handle **handles_data, gsize nhandles) { gint i; - for (i = nhandles - 1; i >= 0; i--) + for (i = nhandles - 1; i >= 0; i--) { + if (!handles_data [i]) + continue; mono_w32handle_unlock (handles_data [i]); + } } static int @@ -897,14 +904,75 @@ done: return ret; } +static MonoW32Handle* +mono_w32handle_has_duplicates (MonoW32Handle *handles [ ], gsize nhandles) +{ + if (nhandles < 2 || nhandles > MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) + return NULL; + + MonoW32Handle *sorted [MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS]; // 64 + memcpy (sorted, handles, nhandles * sizeof (handles[0])); + qsort (sorted, nhandles, sizeof (sorted [0]), g_direct_equal); + for (gsize i = 1; i < nhandles; ++i) { + MonoW32Handle * const h1 = sorted [i - 1]; + MonoW32Handle * const h2 = sorted [i]; + if (h1 == h2) + return h1; + } + + return NULL; +} + +static void +mono_w32handle_clear_duplicates (MonoW32Handle *handles [ ], gsize nhandles) +{ + for (gsize i = 0; i < nhandles; ++i) { + if (!handles [i]) + continue; + for (gsize j = i + 1; j < nhandles; ++j) { + if (handles [i] == handles [j]) { + mono_w32handle_unref (handles [j]); + handles [j] = NULL; + } + } + } +} + +static void +mono_w32handle_check_duplicates (MonoW32Handle *handles [ ], gsize nhandles, gboolean waitall, MonoError *error) +{ + // Duplication is ok for WaitAny, exception for WaitAll. + // System.DuplicateWaitObjectException: Duplicate objects in argument. + + MonoW32Handle *duplicate = mono_w32handle_has_duplicates (handles, nhandles); + if (!duplicate) + return; + + if (waitall) { + mono_error_set_duplicate_wait_object (error); + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_HANDLE, "mono_w32handle_wait_multiple: handle %p is duplicated", duplicate); + return; + } + + // There is at least one duplicate. This is not an error. + // Remove all duplicates -- in-place in order to return the + // lowest signaled, equal to the caller's indices, and ease + // the exit path's dereference. + // That is, we cannot use sorted data, nor can we + // compress the array to remove elements. We must operate + // on each element in its original index, but we can skip some. + + mono_w32handle_clear_duplicates (handles, nhandles); +} + MonoW32HandleWaitRet -mono_w32handle_wait_multiple (gpointer *handles, gsize nhandles, gboolean waitall, guint32 timeout, gboolean alertable) +mono_w32handle_wait_multiple (gpointer *handles, gsize nhandles, gboolean waitall, guint32 timeout, gboolean alertable, MonoError *error) { MonoW32HandleWaitRet ret; gboolean alerted, poll; gint i; gint64 start; - MonoW32Handle *handles_data [MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS], *handles_data_sorted [MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS]; + MonoW32Handle *handles_data [MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS]; gboolean abandoned [MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS] = {0}; if (nhandles == 0) @@ -936,29 +1004,21 @@ mono_w32handle_wait_multiple (gpointer *handles, gsize nhandles, gboolean waital { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_HANDLE, "%s: handle %p can't be waited for", __func__, handles_data [i]); - for (i = nhandles - 1; i >= 0; --i) - mono_w32handle_unref (handles_data [i]); - - return MONO_W32HANDLE_WAIT_RET_FAILED; + ret = MONO_W32HANDLE_WAIT_RET_FAILED; + goto done; } - - handles_data_sorted [i] = handles_data [i]; } - qsort (handles_data_sorted, nhandles, sizeof (gpointer), g_direct_equal); - for (i = 1; i < nhandles; ++i) { - if (handles_data_sorted [i - 1] == handles_data_sorted [i]) { - mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_HANDLE, "%s: handle %p is duplicated", __func__, handles_data_sorted [i]); - - for (i = nhandles - 1; i >= 0; --i) - mono_w32handle_unref (handles_data [i]); - - return MONO_W32HANDLE_WAIT_RET_FAILED; - } + mono_w32handle_check_duplicates (handles_data, nhandles, waitall, error); + if (!is_ok (error)) { + ret = MONO_W32HANDLE_WAIT_RET_FAILED; + goto done; } poll = FALSE; for (i = 0; i < nhandles; ++i) { + if (!handles_data [i]) + continue; if (handles_data [i]->type == MONO_W32TYPE_PROCESS) { /* Can't wait for a process handle + another handle without polling */ poll = TRUE; @@ -979,6 +1039,8 @@ mono_w32handle_wait_multiple (gpointer *handles, gsize nhandles, gboolean waital mono_w32handle_lock_handles (handles_data, nhandles); for (i = 0; i < nhandles; i++) { + if (!handles_data [i]) + continue; if ((mono_w32handle_test_capabilities (handles_data [i], MONO_W32HANDLE_CAP_OWN) && mono_w32handle_ops_isowned (handles_data [i])) || mono_w32handle_issignalled (handles_data [i])) { @@ -993,6 +1055,8 @@ mono_w32handle_wait_multiple (gpointer *handles, gsize nhandles, gboolean waital if (signalled) { for (i = 0; i < nhandles; i++) { + if (!handles_data [i]) + continue; if (own_if_signalled (handles_data [i], &abandoned [i]) && !waitall) { /* if we are calling WaitHandle.WaitAny, .NET only owns the first one; it matters for Mutex which * throw AbandonedMutexException in case we owned it but didn't release it */ @@ -1004,10 +1068,10 @@ mono_w32handle_wait_multiple (gpointer *handles, gsize nhandles, gboolean waital mono_w32handle_unlock_handles (handles_data, nhandles); if (signalled) { - ret = MONO_W32HANDLE_WAIT_RET_SUCCESS_0 + lowest; + ret = (MonoW32HandleWaitRet)(MONO_W32HANDLE_WAIT_RET_SUCCESS_0 + lowest); for (i = lowest; i < nhandles; i++) { if (abandoned [i]) { - ret = MONO_W32HANDLE_WAIT_RET_ABANDONED_0 + lowest; + ret = (MonoW32HandleWaitRet)(MONO_W32HANDLE_WAIT_RET_ABANDONED_0 + lowest); break; } } @@ -1015,6 +1079,8 @@ mono_w32handle_wait_multiple (gpointer *handles, gsize nhandles, gboolean waital } for (i = 0; i < nhandles; i++) { + if (!handles_data [i]) + continue; mono_w32handle_ops_prewait (handles_data [i]); if (mono_w32handle_test_capabilities (handles_data [i], MONO_W32HANDLE_CAP_SPECIAL_WAIT) @@ -1026,9 +1092,12 @@ mono_w32handle_wait_multiple (gpointer *handles, gsize nhandles, gboolean waital mono_w32handle_lock_signal_mutex (); + // FIXME These two loops can be just one. if (waitall) { signalled = TRUE; for (i = 0; i < nhandles; ++i) { + if (!handles_data [i]) + continue; if (!mono_w32handle_issignalled (handles_data [i])) { signalled = FALSE; break; @@ -1037,6 +1106,8 @@ mono_w32handle_wait_multiple (gpointer *handles, gsize nhandles, gboolean waital } else { signalled = FALSE; for (i = 0; i < nhandles; ++i) { + if (!handles_data [i]) + continue; if (mono_w32handle_issignalled (handles_data [i])) { signalled = TRUE; break; @@ -1081,6 +1152,8 @@ mono_w32handle_wait_multiple (gpointer *handles, gsize nhandles, gboolean waital done: for (i = nhandles - 1; i >= 0; i--) { /* Unref everything we reffed above */ + if (!handles_data [i]) + continue; mono_w32handle_unref (handles_data [i]); } diff --git a/mono/metadata/w32handle.h b/mono/metadata/w32handle.h index 8b5d7541df..929a3baa4b 100644 --- a/mono/metadata/w32handle.h +++ b/mono/metadata/w32handle.h @@ -13,9 +13,10 @@ #endif #include "mono/utils/mono-coop-mutex.h" +#include "mono/utils/mono-error.h" #ifndef INVALID_HANDLE_VALUE -#define INVALID_HANDLE_VALUE (gpointer)-1 +#define INVALID_HANDLE_VALUE ((gpointer)-1) #endif #define MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS 64 @@ -160,7 +161,7 @@ MonoW32HandleWaitRet mono_w32handle_wait_one (gpointer handle, guint32 timeout, gboolean alertable); MonoW32HandleWaitRet -mono_w32handle_wait_multiple (gpointer *handles, gsize nhandles, gboolean waitall, guint32 timeout, gboolean alertable); +mono_w32handle_wait_multiple (gpointer *handles, gsize nhandles, gboolean waitall, guint32 timeout, gboolean alertable, MonoError *error); MonoW32HandleWaitRet mono_w32handle_signal_and_wait (gpointer signal_handle, gpointer wait_handle, guint32 timeout, gboolean alertable); @@ -170,9 +171,9 @@ static inline MonoW32HandleWaitRet mono_w32handle_convert_wait_ret (guint32 res, guint32 numobjects) { if (res >= WAIT_OBJECT_0 && res <= WAIT_OBJECT_0 + numobjects - 1) - return MONO_W32HANDLE_WAIT_RET_SUCCESS_0 + (res - WAIT_OBJECT_0); + return (MonoW32HandleWaitRet)(MONO_W32HANDLE_WAIT_RET_SUCCESS_0 + (res - WAIT_OBJECT_0)); else if (res >= WAIT_ABANDONED_0 && res <= WAIT_ABANDONED_0 + numobjects - 1) - return MONO_W32HANDLE_WAIT_RET_ABANDONED_0 + (res - WAIT_ABANDONED_0); + return (MonoW32HandleWaitRet)(MONO_W32HANDLE_WAIT_RET_ABANDONED_0 + (res - WAIT_ABANDONED_0)); else if (res == WAIT_IO_COMPLETION) return MONO_W32HANDLE_WAIT_RET_ALERTED; else if (res == WAIT_TIMEOUT) diff --git a/mono/metadata/w32mutex-unix.c b/mono/metadata/w32mutex-unix.c index 1183817acc..e0ca21d11e 100644 --- a/mono/metadata/w32mutex-unix.c +++ b/mono/metadata/w32mutex-unix.c @@ -36,27 +36,27 @@ gpointer mono_w32mutex_open (const gchar* utf8_name, gint32 right G_GNUC_UNUSED, gint32 *error); static void -thread_own_mutex (MonoInternalThread *internal, gpointer handle, MonoW32Handle *handle_data) +thread_own_mutex (MonoInternalThreadHandle internal, gpointer handle, MonoW32Handle *handle_data) { /* if we are not on the current thread, there is a * race condition when allocating internal->owned_mutexes */ - g_assert (mono_thread_internal_is_current (internal)); + g_assert (mono_thread_internal_is_current_handle (internal)); - if (!internal->owned_mutexes) - internal->owned_mutexes = g_ptr_array_new (); + if (!MONO_HANDLE_GETVAL (internal, owned_mutexes)) + MONO_HANDLE_SETVAL(internal, owned_mutexes, GPtrArray*, g_ptr_array_new ()); - g_ptr_array_add (internal->owned_mutexes, mono_w32handle_duplicate (handle_data)); + g_ptr_array_add (MONO_HANDLE_GETVAL (internal, owned_mutexes), mono_w32handle_duplicate (handle_data)); } static void -thread_disown_mutex (MonoInternalThread *internal, gpointer handle) +thread_disown_mutex (MonoInternalThreadHandle internal, gpointer handle) { gboolean removed; - g_assert (mono_thread_internal_is_current (internal)); + g_assert (mono_thread_internal_is_current_handle (internal)); - g_assert (internal->owned_mutexes); - removed = g_ptr_array_remove (internal->owned_mutexes, handle); + g_assert (MONO_HANDLE_GETVAL (internal, owned_mutexes)); + removed = g_ptr_array_remove (MONO_HANDLE_GETVAL (internal, owned_mutexes), handle); g_assert (removed); mono_w32handle_close (handle); @@ -65,6 +65,8 @@ thread_disown_mutex (MonoInternalThread *internal, gpointer handle) static void mutex_handle_signal (MonoW32Handle *handle_data) { + HANDLE_FUNCTION_ENTER (); + MonoW32HandleMutex *mutex_handle; pthread_t tid; @@ -86,7 +88,7 @@ mutex_handle_signal (MonoW32Handle *handle_data) mutex_handle->recursion--; if (mutex_handle->recursion == 0) { - thread_disown_mutex (mono_thread_internal_current (), handle_data); + thread_disown_mutex (mono_thread_internal_current_handle (), handle_data); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_MUTEX, "%s: unlocking %s handle %p, tid: %p recusion : %d", __func__, mono_w32handle_get_typename (handle_data->type), handle_data, (gpointer) mutex_handle->tid, mutex_handle->recursion); @@ -95,11 +97,15 @@ mutex_handle_signal (MonoW32Handle *handle_data) mono_w32handle_set_signal_state (handle_data, TRUE, FALSE); } } + + HANDLE_FUNCTION_RETURN (); } static gboolean mutex_handle_own (MonoW32Handle *handle_data, gboolean *abandoned) { + HANDLE_FUNCTION_ENTER (); + MonoW32HandleMutex *mutex_handle; *abandoned = FALSE; @@ -116,7 +122,7 @@ mutex_handle_own (MonoW32Handle *handle_data, gboolean *abandoned) mutex_handle->tid = pthread_self (); mutex_handle->recursion = 1; - thread_own_mutex (mono_thread_internal_current (), handle_data, handle_data); + thread_own_mutex (mono_thread_internal_current_handle (), handle_data, handle_data); } if (mutex_handle->abandoned) { @@ -126,7 +132,7 @@ mutex_handle_own (MonoW32Handle *handle_data, gboolean *abandoned) mono_w32handle_set_signal_state (handle_data, FALSE, FALSE); - return TRUE; + HANDLE_FUNCTION_RETURN_VAL (TRUE); } static gboolean @@ -407,7 +413,7 @@ ves_icall_System_Threading_Mutex_ReleaseMutex_internal (gpointer handle) mutex_handle->recursion--; if (mutex_handle->recursion == 0) { - thread_disown_mutex (mono_thread_internal_current (), handle); + thread_disown_mutex (mono_thread_internal_current_handle (), handle); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_MUTEX, "%s: unlocking %s handle %p, tid: %p recusion : %d", __func__, mono_w32handle_get_typename (handle_data->type), handle, (gpointer) mutex_handle->tid, mutex_handle->recursion); @@ -467,20 +473,24 @@ cleanup: } void -mono_w32mutex_abandon (MonoInternalThread *internal) +mono_w32mutex_abandon (MonoInternalThread *internal_raw) { - g_assert (mono_thread_internal_is_current (internal)); + HANDLE_FUNCTION_ENTER () - if (!internal->owned_mutexes) - return; + MONO_HANDLE_DCL (MonoInternalThread, internal); - while (internal->owned_mutexes->len) { + g_assert (mono_thread_internal_is_current_handle (internal)); + + if (!MONO_HANDLE_GETVAL (internal, owned_mutexes)) + goto exit; + + while (MONO_HANDLE_GETVAL (internal, owned_mutexes)->len) { MonoW32Handle *handle_data; MonoW32HandleMutex *mutex_handle; MonoNativeThreadId tid; gpointer handle; - handle = g_ptr_array_index (internal->owned_mutexes, 0); + handle = g_ptr_array_index (MONO_HANDLE_GETVAL (internal, owned_mutexes), 0); if (!mono_w32handle_lookup_and_ref (handle, &handle_data)) g_error ("%s: unkown handle %p", __func__, handle); @@ -493,7 +503,7 @@ mono_w32mutex_abandon (MonoInternalThread *internal) mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_MUTEX, "%s: abandoning %s handle %p", __func__, mono_w32handle_get_typename (handle_data->type), handle); - tid = MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid); + tid = MONO_UINT_TO_NATIVE_THREAD_ID (MONO_HANDLE_GETVAL (internal, tid)); if (!pthread_equal (mutex_handle->tid, tid)) g_error ("%s: trying to release mutex %p acquired by thread %p from thread %p", @@ -516,8 +526,11 @@ mono_w32mutex_abandon (MonoInternalThread *internal) mono_w32handle_unref (handle_data); } - g_ptr_array_free (internal->owned_mutexes, TRUE); - internal->owned_mutexes = NULL; + g_ptr_array_free (MONO_HANDLE_GETVAL (internal, owned_mutexes), TRUE); + MONO_HANDLE_SETVAL(internal, owned_mutexes, GPtrArray*, NULL); + +exit: + HANDLE_FUNCTION_RETURN (); } MonoW32HandleNamespace* diff --git a/mono/metadata/w32process-unix-bsd.c b/mono/metadata/w32process-unix-bsd.c index 7cd859c7aa..41b96cef4b 100644 --- a/mono/metadata/w32process-unix-bsd.c +++ b/mono/metadata/w32process-unix-bsd.c @@ -93,7 +93,30 @@ retry: gchar* mono_w32process_get_path (pid_t pid) { +#if defined (__OpenBSD__) + // No KERN_PROC_PATHNAME on OpenBSD return mono_w32process_get_name (pid); +#else + gsize path_len = PATH_MAX + 1; + gchar path [PATH_MAX + 1]; + gint mib [4]; + mib [0] = CTL_KERN; +#if defined (__NetBSD__) + mib [1] = KERN_PROC_ARGS; + mib [2] = pid; + mib [3] = KERN_PROC_PATHNAME; +#else // FreeBSD + mib [1] = KERN_PROC; + mib [2] = KERN_PROC_PATHNAME; + mib [3] = pid; +#endif + if (sysctl (mib, 4, path, &path_len, NULL, 0) < 0) { + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: sysctl() failed: %d", __func__, errno); + return NULL; + } else { + return g_strdup (path); + } +#endif } static gint diff --git a/mono/metadata/w32process-unix.c.REMOVED.git-id b/mono/metadata/w32process-unix.c.REMOVED.git-id index df67f46353..009ee2f62b 100644 --- a/mono/metadata/w32process-unix.c.REMOVED.git-id +++ b/mono/metadata/w32process-unix.c.REMOVED.git-id @@ -1 +1 @@ -159aed90965efd9a29b4d99db85e70e69a4cc999 \ No newline at end of file +ab58465e9226c2f612bb026a0a2ba705bd066c47 \ No newline at end of file diff --git a/mono/metadata/w32process-win32.c b/mono/metadata/w32process-win32.c index 5c8ef27c35..5811117d46 100644 --- a/mono/metadata/w32process-win32.c +++ b/mono/metadata/w32process-win32.c @@ -95,7 +95,7 @@ ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoW32ProcessStar shellex.lpDirectory = coop.working_directory; if (MONO_HANDLE_GETVAL (proc_start_info, error_dialog)) - shellex.hwnd = MONO_HANDLE_GETVAL (proc_start_info, error_dialog_parent_handle); + shellex.hwnd = (HWND)MONO_HANDLE_GETVAL (proc_start_info, error_dialog_parent_handle); else shellex.fMask = (gulong)(shellex.fMask | SEE_MASK_FLAG_NO_UI); @@ -306,11 +306,13 @@ ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoW32ProcessStart MonoArrayHandle array = MONO_HANDLE_NEW (MonoArray, process_info->env_variables); MonoStringHandle var = MONO_HANDLE_NEW (MonoString, NULL); gsize const array_length = mono_array_handle_length (array); - gsize len = 1; // nul-terminated + + // nul-separated and nul-terminated + gsize len = array_length + 1 + !array_length; for (gsize i = 0; i < array_length; i++) { MONO_HANDLE_ARRAY_GETREF (var, array, i); - len += mono_string_handle_length (var) + 1; // nul-separated + len += mono_string_handle_length (var); } gunichar2 *ptr = g_new0 (gunichar2, len); diff --git a/mono/metadata/w32process.c b/mono/metadata/w32process.c index 9f720bb892..b7748b21af 100644 --- a/mono/metadata/w32process.c +++ b/mono/metadata/w32process.c @@ -36,23 +36,23 @@ mono_w32process_try_get_modules (gpointer process, HMODULE *modules, guint32 siz static guint32 mono_w32process_module_get_name (gpointer process, gpointer module, gunichar2 *basename, guint32 size) { - return GetModuleBaseName (process, module, basename, size); + return GetModuleBaseName (process, (HMODULE)module, basename, size); } static guint32 mono_w32process_module_get_filename (gpointer process, gpointer module, gunichar2 *basename, guint32 size) { - return GetModuleFileNameEx (process, module, basename, size); + return GetModuleFileNameEx (process, (HMODULE)module, basename, size); } static gboolean mono_w32process_module_get_information (gpointer process, gpointer module, MODULEINFO *modinfo, guint32 size) { - return GetModuleInformation (process, module, modinfo, size); + return GetModuleInformation (process, (HMODULE)module, modinfo, size); } static gboolean -mono_w32process_get_fileversion_info (gunichar2 *filename, gpointer *data) +mono_w32process_get_fileversion_info (const gunichar2 *filename, gpointer *data) { DWORD handle; gsize datasize; diff --git a/mono/metadata/w32process.h b/mono/metadata/w32process.h index 4d32fb2214..87e5903af6 100644 --- a/mono/metadata/w32process.h +++ b/mono/metadata/w32process.h @@ -136,55 +136,72 @@ mono_w32process_get_path (pid_t pid); #endif +ICALL_EXPORT gpointer ves_icall_System_Diagnostics_Process_GetProcess_internal (guint32 pid); +ICALL_EXPORT MonoArray* ves_icall_System_Diagnostics_Process_GetProcesses_internal (void); +ICALL_EXPORT MonoArray* ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject *this_obj, gpointer process); +ICALL_EXPORT void ves_icall_System_Diagnostics_FileVersionInfo_GetVersionInfo_internal (MonoObject *this_obj, MonoString *filename); +ICALL_EXPORT MonoBoolean ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoW32ProcessStartInfoHandle proc_start_info, MonoW32ProcessInfo *process_info, MonoError *error); +ICALL_EXPORT MonoBoolean ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoW32ProcessStartInfoHandle proc_start_info, gpointer stdin_handle, gpointer stdout_handle, gpointer stderr_handle, MonoW32ProcessInfo *process_handle, MonoError *error); +ICALL_EXPORT MonoString* ves_icall_System_Diagnostics_Process_ProcessName_internal (gpointer process); +ICALL_EXPORT gint64 ves_icall_System_Diagnostics_Process_GetProcessData (int pid, gint32 data_type, gint32 *error); +ICALL_EXPORT gpointer ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcess (MonoError *error); +ICALL_EXPORT MonoBoolean ves_icall_Microsoft_Win32_NativeMethods_GetExitCodeProcess (gpointer handle, gint32 *exitcode, MonoError *error); +ICALL_EXPORT MonoBoolean ves_icall_Microsoft_Win32_NativeMethods_CloseProcess (gpointer handle, MonoError *error); +ICALL_EXPORT MonoBoolean ves_icall_Microsoft_Win32_NativeMethods_TerminateProcess (gpointer handle, gint32 exitcode, MonoError *error); +ICALL_EXPORT MonoBoolean ves_icall_Microsoft_Win32_NativeMethods_GetProcessWorkingSetSize (gpointer handle, gsize *min, gsize *max, MonoError *error); +ICALL_EXPORT MonoBoolean ves_icall_Microsoft_Win32_NativeMethods_SetProcessWorkingSetSize (gpointer handle, gsize min, gsize max, MonoError *error); +ICALL_EXPORT gint32 ves_icall_Microsoft_Win32_NativeMethods_GetPriorityClass (gpointer handle, MonoError *error); +ICALL_EXPORT MonoBoolean ves_icall_Microsoft_Win32_NativeMethods_SetPriorityClass (gpointer handle, gint32 priorityClass, MonoError *error); +ICALL_EXPORT MonoBoolean ves_icall_Microsoft_Win32_NativeMethods_GetProcessTimes (gpointer handle, gint64 *creationtime, gint64 *exittime, gint64 *kerneltime, gint64 *usertime, MonoError *error); diff --git a/mono/metadata/w32socket-internals.h b/mono/metadata/w32socket-internals.h index 62e2eb154c..6cdb94063b 100644 --- a/mono/metadata/w32socket-internals.h +++ b/mono/metadata/w32socket-internals.h @@ -76,7 +76,7 @@ int mono_w32socket_recvbuffers (SOCKET s, LPWSABUF lpBuffers, guint32 dwBufferCount, guint32 *lpNumberOfBytesRecvd, guint32 *lpFlags, gpointer lpOverlapped, gpointer lpCompletionRoutine, gboolean blocking); int -mono_w32socket_send (SOCKET s, char *buf, int len, int flags, gboolean blocking); +mono_w32socket_send (SOCKET s, void *buf, int len, int flags, gboolean blocking); int mono_w32socket_sendto (SOCKET s, const char *buf, int len, int flags, const struct sockaddr *to, int tolen, gboolean blocking); @@ -109,7 +109,7 @@ gint mono_w32socket_getsockopt (SOCKET sock, gint level, gint optname, gpointer optval, socklen_t *optlen); gint -mono_w32socket_setsockopt (SOCKET sock, gint level, gint optname, const gpointer optval, socklen_t optlen); +mono_w32socket_setsockopt (SOCKET sock, gint level, gint optname, gconstpointer optval, socklen_t optlen); gint mono_w32socket_listen (SOCKET sock, gint backlog); diff --git a/mono/metadata/w32socket-unix.c b/mono/metadata/w32socket-unix.c index c5bf6f1cbe..0ce7845f82 100644 --- a/mono/metadata/w32socket-unix.c +++ b/mono/metadata/w32socket-unix.c @@ -438,7 +438,7 @@ mono_w32socket_recvbuffers (SOCKET sock, WSABUF *buffers, guint32 count, guint32 } int -mono_w32socket_send (SOCKET sock, char *buf, int len, int flags, gboolean blocking) +mono_w32socket_send (SOCKET sock, void *buf, int len, int flags, gboolean blocking) { SocketHandle *sockethandle; int ret; @@ -582,18 +582,18 @@ mono_w32socket_transmit_file (SOCKET sock, gpointer file_handle, TRANSMIT_FILE_B #if defined(HAVE_SENDFILE) && (defined(__linux__) || defined(DARWIN)) struct stat statbuf; #else - gchar *buffer; + gpointer buffer; #endif if (!mono_fdhandle_lookup_and_ref(sock, (MonoFDHandle**) &sockethandle)) { mono_w32error_set_last (WSAENOTSOCK); - return SOCKET_ERROR; + return FALSE; } if (((MonoFDHandle*) sockethandle)->type != MONO_FDTYPE_SOCKET) { mono_fdhandle_unref ((MonoFDHandle*) sockethandle); mono_w32error_set_last (WSAENOTSOCK); - return SOCKET_ERROR; + return FALSE; } /* Write the header */ @@ -617,7 +617,7 @@ mono_w32socket_transmit_file (SOCKET sock, gpointer file_handle, TRANSMIT_FILE_B gint errnum = errno; mono_w32socket_set_last_error (mono_w32socket_convert_error (errnum)); mono_fdhandle_unref ((MonoFDHandle*) sockethandle); - return SOCKET_ERROR; + return FALSE; } do { @@ -723,7 +723,8 @@ retry_socket: * https://bugzilla.novell.com/show_bug.cgi?id=MONO53992 */ { - int ret, true_ = 1; + int ret; + const int true_ = 1; MONO_ENTER_GC_SAFE; ret = setsockopt (((MonoFDHandle*) sockethandle)->fd, SOL_SOCKET, SO_REUSEADDR, &true_, sizeof (true_)); @@ -901,11 +902,11 @@ mono_w32socket_getsockopt (SOCKET sock, gint level, gint optname, gpointer optva } gint -mono_w32socket_setsockopt (SOCKET sock, gint level, gint optname, const gpointer optval, socklen_t optlen) +mono_w32socket_setsockopt (SOCKET sock, gint level, gint optname, gconstpointer optval, socklen_t optlen) { SocketHandle *sockethandle; gint ret; - gpointer tmp_val; + gconstpointer tmp_val; #if defined (__linux__) /* This has its address taken so it cannot be moved to the if block which uses it */ gint bufsize = 0; @@ -1129,12 +1130,13 @@ extension_transmit_file (SOCKET sock, gpointer file_handle, guint32 bytes_to_wri return ret; } +const static struct { GUID guid; gpointer func; } extension_functions[] = { - { {0x7fda2e11,0x8630,0x436f,{0xa0,0x31,0xf5,0x36,0xa6,0xee,0xc1,0x57}} /* WSAID_DISCONNECTEX */, extension_disconect }, - { {0xb5367df0,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}} /* WSAID_TRANSMITFILE */, extension_transmit_file }, + { {0x7fda2e11,0x8630,0x436f,{0xa0,0x31,0xf5,0x36,0xa6,0xee,0xc1,0x57}} /* WSAID_DISCONNECTEX */, (gpointer)extension_disconect }, + { {0xb5367df0,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}} /* WSAID_TRANSMITFILE */, (gpointer)extension_transmit_file }, { {0} , NULL }, }; @@ -1143,7 +1145,7 @@ mono_w32socket_ioctl (SOCKET sock, gint32 command, gchar *input, gint inputlen, { SocketHandle *sockethandle; gint ret; - gchar *buffer; + gpointer buffer; if (!mono_fdhandle_lookup_and_ref(sock, (MonoFDHandle**) &sockethandle)) { mono_w32error_set_last (WSAENOTSOCK); diff --git a/mono/metadata/w32socket-win32.c b/mono/metadata/w32socket-win32.c index af677cc4cd..b170804367 100644 --- a/mono/metadata/w32socket-win32.c +++ b/mono/metadata/w32socket-win32.c @@ -66,7 +66,7 @@ static DWORD get_socket_timeout (SOCKET sock, int optname) */ static gboolean alertable_socket_wait (SOCKET sock, int event_bit) { - static char *EVENT_NAMES[] = { "FD_READ", "FD_WRITE", NULL /*FD_OOB*/, "FD_ACCEPT", "FD_CONNECT", "FD_CLOSE" }; + static char const * const EVENT_NAMES[] = { "FD_READ", "FD_WRITE", NULL /*FD_OOB*/, "FD_ACCEPT", "FD_CONNECT", "FD_CLOSE" }; gboolean success = FALSE; int error = -1; DWORD timeout = WSA_INFINITE; @@ -177,16 +177,16 @@ int mono_w32socket_recvbuffers (SOCKET s, WSABUF *lpBuffers, guint32 dwBufferCou { int ret = SOCKET_ERROR; MONO_ENTER_GC_SAFE; - ALERTABLE_SOCKET_CALL (FD_READ_BIT, blocking, TRUE, ret, WSARecv, s, lpBuffers, dwBufferCount, (PDWORD)lpNumberOfBytesRecvd, (PDWORD)lpFlags, lpOverlapped, lpCompletionRoutine); + ALERTABLE_SOCKET_CALL (FD_READ_BIT, blocking, TRUE, ret, WSARecv, s, lpBuffers, dwBufferCount, (PDWORD)lpNumberOfBytesRecvd, (PDWORD)lpFlags, (LPWSAOVERLAPPED)lpOverlapped, (LPWSAOVERLAPPED_COMPLETION_ROUTINE)lpCompletionRoutine); MONO_EXIT_GC_SAFE; return ret; } -int mono_w32socket_send (SOCKET s, char *buf, int len, int flags, gboolean blocking) +int mono_w32socket_send (SOCKET s, void *buf, int len, int flags, gboolean blocking) { int ret = SOCKET_ERROR; MONO_ENTER_GC_SAFE; - ALERTABLE_SOCKET_CALL (FD_WRITE_BIT, blocking, TRUE, ret, send, s, buf, len, flags); + ALERTABLE_SOCKET_CALL (FD_WRITE_BIT, blocking, TRUE, ret, send, s, (char*)buf, len, flags); MONO_EXIT_GC_SAFE; return ret; } @@ -204,7 +204,7 @@ int mono_w32socket_sendbuffers (SOCKET s, WSABUF *lpBuffers, guint32 dwBufferCou { int ret = SOCKET_ERROR; MONO_ENTER_GC_SAFE; - ALERTABLE_SOCKET_CALL (FD_WRITE_BIT, blocking, TRUE, ret, WSASend, s, lpBuffers, dwBufferCount, (PDWORD)lpNumberOfBytesRecvd, lpFlags, lpOverlapped, lpCompletionRoutine); + ALERTABLE_SOCKET_CALL (FD_WRITE_BIT, blocking, TRUE, ret, WSASend, s, lpBuffers, dwBufferCount, (PDWORD)lpNumberOfBytesRecvd, lpFlags, (LPWSAOVERLAPPED)lpOverlapped, (LPWSAOVERLAPPED_COMPLETION_ROUTINE)lpCompletionRoutine); MONO_EXIT_GC_SAFE; return ret; } @@ -285,6 +285,7 @@ mono_w32socket_disconnect (SOCKET sock, gboolean reuse) * managed objects that still works on 64bit platforms. */ GUID disconnect_guid = WSAID_DISCONNECTEX; + GUID transmit_file_guid = WSAID_TRANSMITFILE; ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER, &disconnect_guid, sizeof (GUID), &disconnect, sizeof (LPFN_DISCONNECTEX), &output_bytes, NULL, NULL); if (ret == 0) { if (!disconnect (sock, NULL, reuse ? TF_REUSE_SOCKET : 0, 0)) { @@ -296,7 +297,6 @@ mono_w32socket_disconnect (SOCKET sock, gboolean reuse) goto done; } - GUID transmit_file_guid = WSAID_TRANSMITFILE; ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER, &transmit_file_guid, sizeof (GUID), &transmit_file, sizeof (LPFN_TRANSMITFILE), &output_bytes, NULL, NULL); if (ret == 0) { if (!transmit_file (sock, NULL, 0, 0, NULL, NULL, TF_DISCONNECT | (reuse ? TF_REUSE_SOCKET : 0))) { diff --git a/mono/metadata/w32socket.c b/mono/metadata/w32socket.c index bd722f8299..789b14380d 100644 --- a/mono/metadata/w32socket.c +++ b/mono/metadata/w32socket.c @@ -58,6 +58,7 @@ /* FIXME change this code to not mess so much with the internals */ #include #include +#include #include #include #include @@ -158,17 +159,17 @@ mono_w32socket_getsockopt (SOCKET sock, gint level, gint optname, gpointer optva { gint ret; MONO_ENTER_GC_SAFE; - ret = getsockopt (sock, level, optname, optval, optlen); + ret = getsockopt (sock, level, optname, (char*)optval, optlen); MONO_EXIT_GC_SAFE; return ret; } static gint -mono_w32socket_setsockopt (SOCKET sock, gint level, gint optname, const gpointer optval, socklen_t optlen) +mono_w32socket_setsockopt (SOCKET sock, gint level, gint optname, gconstpointer optval, socklen_t optlen) { gint ret; MONO_ENTER_GC_SAFE; - ret = setsockopt (sock, level, optname, optval, optlen); + ret = setsockopt (sock, level, optname, (const char*)optval, optlen); MONO_EXIT_GC_SAFE; return ret; } @@ -194,7 +195,7 @@ mono_w32socket_shutdown (SOCKET sock, gint how) } static gint -mono_w32socket_ioctl (SOCKET sock, gint32 command, gchar *input, gint inputlen, gchar *output, gint outputlen, glong *written) +mono_w32socket_ioctl (SOCKET sock, gint32 command, gchar *input, gint inputlen, gchar *output, gint outputlen, DWORD *written) { gint ret; MONO_ENTER_GC_SAFE; @@ -709,7 +710,7 @@ get_socket_assembly (void) if (domain->socket_assembly == NULL) { MonoImage *socket_assembly; - socket_assembly = mono_image_loaded ("System"); + socket_assembly = mono_image_loaded_internal ("System", FALSE); if (!socket_assembly) { MonoAssembly *sa = mono_assembly_open_predicate ("System.dll", MONO_ASMCTX_DEFAULT, NULL, NULL, NULL, NULL); @@ -1027,70 +1028,54 @@ get_sockaddr_size (int family) return size; } -MonoObjectHandle -ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal (gsize sock, gint32 af, gint32 *werror, MonoError *error) +static MonoObjectHandle +mono_w32socket_getname (gsize sock, gint32 af, gboolean local, gint32 *werror, MonoError *error) { - gchar *sa; - socklen_t salen; + gpointer sa = NULL; + socklen_t salen = 0; int ret; - + MonoObjectHandle result = NULL_HANDLE; + *werror = 0; salen = get_sockaddr_size (convert_family ((MonoAddressFamily)af)); if (salen == 0) { *werror = WSAEAFNOSUPPORT; - return NULL_HANDLE; + goto exit; + } + if (salen <= 128) { + sa = g_alloca (salen); + memset (sa, 0, salen); + } else { + sa = g_malloc0 (salen); } - sa = (salen <= 128) ? (gchar *)alloca (salen) : (gchar *)g_malloc0 (salen); - ret = mono_w32socket_getsockname (sock, (struct sockaddr *)sa, &salen); + /* Note: linux returns just 2 for AF_UNIX. Always. */ + ret = (local ? mono_w32socket_getsockname : mono_w32socket_getpeername) (sock, (struct sockaddr *)sa, &salen); if (ret == SOCKET_ERROR) { *werror = mono_w32socket_get_last_error (); - if (salen > 128) - g_free (sa); - return NULL_HANDLE; + goto exit; } - LOGDEBUG (g_message("%s: bound to %s port %d", __func__, inet_ntoa (((struct sockaddr_in *)&sa)->sin_addr), ntohs (((struct sockaddr_in *)&sa)->sin_port))); + LOGDEBUG (g_message("%s: %s to %s port %d", __func__, local ? "bound" : "connected", inet_ntoa (((struct sockaddr_in *)&sa)->sin_addr), ntohs (((struct sockaddr_in *)&sa)->sin_port))); - MonoObjectHandle result = create_object_handle_from_sockaddr ((struct sockaddr *)sa, salen, werror, error); + result = create_object_handle_from_sockaddr ((struct sockaddr *)sa, salen, werror, error); +exit: if (salen > 128) g_free (sa); return result; } +MonoObjectHandle +ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal (gsize sock, gint32 af, gint32 *werror, MonoError *error) +{ + return mono_w32socket_getname (sock, af, TRUE, werror, error); +} + MonoObjectHandle ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal (gsize sock, gint32 af, gint32 *werror, MonoError *error) { - gchar *sa; - socklen_t salen; - int ret; - - error_init (error); - *werror = 0; - - salen = get_sockaddr_size (convert_family ((MonoAddressFamily)af)); - if (salen == 0) { - *werror = WSAEAFNOSUPPORT; - return MONO_HANDLE_NEW (MonoObject, NULL); - } - sa = (salen <= 128) ? (gchar *)alloca (salen) : (gchar *)g_malloc0 (salen); - /* Note: linux returns just 2 for AF_UNIX. Always. */ - - ret = mono_w32socket_getpeername (sock, (struct sockaddr *)sa, &salen); - if (ret == SOCKET_ERROR) { - *werror = mono_w32socket_get_last_error (); - if (salen > 128) - g_free (sa); - return MONO_HANDLE_NEW (MonoObject, NULL); - } - - LOGDEBUG (g_message("%s: connected to %s port %d", __func__, inet_ntoa (((struct sockaddr_in *)&sa)->sin_addr), ntohs (((struct sockaddr_in *)&sa)->sin_port))); - - MonoObjectHandle result = create_object_handle_from_sockaddr ((struct sockaddr *)sa, salen, werror, error); - if (salen > 128) - g_free (sa); - return result; + return mono_w32socket_getname (sock, af, FALSE, werror, error); } static struct sockaddr* @@ -1257,6 +1242,7 @@ ves_icall_System_Net_Sockets_Socket_Poll_internal (gsize sock, gint mode, mono_pollfd *pfds; int ret; time_t start; + gint rtimeout; error_init (error); *werror = 0; @@ -1277,6 +1263,7 @@ ves_icall_System_Net_Sockets_Socket_Poll_internal (gsize sock, gint mode, } timeout = (timeout >= 0) ? (timeout / 1000) : -1; + rtimeout = timeout; start = time (NULL); do { @@ -1290,7 +1277,7 @@ ves_icall_System_Net_Sockets_Socket_Poll_internal (gsize sock, gint mode, int err = errno; int sec = time (NULL) - start; - timeout -= sec * 1000; + timeout = rtimeout - sec * 1000; if (timeout < 0) { timeout = 0; } @@ -1566,7 +1553,7 @@ Socket_to_SOCKET (MonoObjectHandle sockobj) if (MONO_HANDLE_IS_NULL (safe_handle)) return -1; - return (SOCKET)MONO_HANDLE_GETVAL (safe_handle, handle); + return (SOCKET)(gsize)MONO_HANDLE_GETVAL (safe_handle, handle); } #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL) @@ -1636,6 +1623,7 @@ ves_icall_System_Net_Sockets_Socket_Select_internal (MonoArrayHandle sockets, gi MonoClass *sock_arr_class; time_t start; uintptr_t socks_size; + gint32 rtimeout; error_init (error); *werror = 0; @@ -1655,6 +1643,7 @@ ves_icall_System_Net_Sockets_Socket_Select_internal (MonoArrayHandle sockets, gi } timeout = (timeout >= 0) ? (timeout / 1000) : -1; + rtimeout = timeout; start = time (NULL); do { MONO_ENTER_GC_SAFE; @@ -1667,7 +1656,7 @@ ves_icall_System_Net_Sockets_Socket_Select_internal (MonoArrayHandle sockets, gi int err = errno; int sec = time (NULL) - start; - timeout -= sec * 1000; + timeout = rtimeout - sec * 1000; if (timeout < 0) timeout = 0; errno = err; @@ -1781,7 +1770,7 @@ ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal (gsize sock, gi case SocketOptionName_SendTimeout: case SocketOptionName_ReceiveTimeout: - ret = mono_w32socket_getsockopt (sock, system_level, system_name, (char *)&time_ms, &time_ms_size); + ret = mono_w32socket_getsockopt (sock, system_level, system_name, &time_ms, &time_ms_size); break; #ifdef SO_PEERCRED @@ -1846,7 +1835,7 @@ ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal (gsize sock, gi static MonoImage *mono_posix_image = NULL; if (mono_posix_image == NULL) { - mono_posix_image = mono_image_loaded ("Mono.Posix"); + mono_posix_image = mono_image_loaded_internal ("Mono.Posix", FALSE); if (!mono_posix_image) { MonoAssembly *sa = mono_assembly_open_predicate ("Mono.Posix.dll", MONO_ASMCTX_DEFAULT, NULL, NULL, NULL, NULL); if (!sa) { @@ -2178,14 +2167,14 @@ ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal (gsize sock, gint32 /* int_val is interface index */ struct ip_mreqn mreq = {{0}}; mreq.imr_ifindex = int_val; - ret = mono_w32socket_setsockopt (sock, system_level, system_name, (char *) &mreq, sizeof (mreq)); + ret = mono_w32socket_setsockopt (sock, system_level, system_name, &mreq, sizeof (mreq)); break; } int_val = GUINT32_TO_BE (int_val); #endif /* HAVE_STRUCT_IP_MREQN */ #endif /* HOST_WIN32 */ /* int_val is in_addr */ - ret = mono_w32socket_setsockopt (sock, system_level, system_name, (char *) &int_val, sizeof (int_val)); + ret = mono_w32socket_setsockopt (sock, system_level, system_name, &int_val, sizeof (int_val)); break; case SocketOptionName_DontFragment: #ifdef HAVE_IP_MTU_DISCOVER @@ -2198,7 +2187,7 @@ ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal (gsize sock, gint32 #endif default: - ret = mono_w32socket_setsockopt (sock, system_level, system_name, (char *) &int_val, sizeof (int_val)); + ret = mono_w32socket_setsockopt (sock, system_level, system_name, &int_val, sizeof (int_val)); } } @@ -2255,10 +2244,15 @@ ves_icall_System_Net_Sockets_Socket_Shutdown_internal (gsize sock, gint32 how, g gint ves_icall_System_Net_Sockets_Socket_IOControl_internal (gsize sock, gint32 code, MonoArrayHandle input, MonoArrayHandle output, gint32 *werror, MonoError *error) { +#ifdef HOST_WIN32 + DWORD output_bytes = 0; +#else glong output_bytes = 0; +#endif gchar *i_buffer, *o_buffer; gint i_len, o_len; - uint32_t i_gchandle, o_gchandle; + uint32_t i_gchandle = 0; + uint32_t o_gchandle = 0; gint ret; error_init (error); @@ -2288,10 +2282,8 @@ ves_icall_System_Net_Sockets_Socket_IOControl_internal (gsize sock, gint32 code, ret = mono_w32socket_ioctl (sock, code, i_buffer, i_len, o_buffer, o_len, &output_bytes); - if (i_gchandle) - mono_gchandle_free (i_gchandle); - if (o_gchandle) - mono_gchandle_free (o_gchandle); + mono_gchandle_free (i_gchandle); + mono_gchandle_free (o_gchandle); if (ret == SOCKET_ERROR) { *werror = mono_w32socket_get_last_error (); @@ -2385,18 +2377,21 @@ addrinfo_to_IPHostEntry_handles (MonoAddressInfo *info, MonoStringHandleOut h_na goto leave; } - gint32 count = 0; + gint32 count; + count = 0; for (ai = info->entries; ai != NULL; ai = ai->next) { if (ai->family != AF_INET && ai->family != AF_INET6) continue; count++; } - int addr_index = 0; + int addr_index; + addr_index = 0; MONO_HANDLE_ASSIGN (h_addr_list, mono_array_new_handle (domain, mono_get_string_class (), count, error)); goto_if_nok (error, leave); - gboolean name_assigned = FALSE; + gboolean name_assigned; + name_assigned = FALSE; for (ai = info->entries; ai != NULL; ai = ai->next) { MonoAddress maddr; char buffer [INET6_ADDRSTRLEN]; /* Max. size for IPv6 */ @@ -2631,7 +2626,7 @@ mono_network_cleanup (void) mono_networking_shutdown (); } -void +ICALL_EXPORT void ves_icall_cancel_blocking_socket_operation (MonoThreadObjectHandle thread, MonoError *error) { error_init (error); diff --git a/mono/metadata/w32socket.h b/mono/metadata/w32socket.h index 67c8d30d04..b2c9e3d1f6 100644 --- a/mono/metadata/w32socket.h +++ b/mono/metadata/w32socket.h @@ -303,7 +303,7 @@ ves_icall_System_Net_Sockets_Socket_SendFile_internal (gsize sock, MonoStringHan MonoArrayHandle pre_buffer, MonoArrayHandle post_buffer, gint flags, gint32 *werror, gboolean blocking, MonoError *error); -void +ICALL_EXPORT void ves_icall_cancel_blocking_socket_operation (MonoThreadObjectHandle thread, MonoError *error); ICALL_EXPORT diff --git a/mono/mini/Makefile.am b/mono/mini/Makefile.am index 4f3ef2faba..6c840f88b8 100644 --- a/mono/mini/Makefile.am +++ b/mono/mini/Makefile.am @@ -169,6 +169,14 @@ endif noinst_LTLIBRARIES = $(mini_common_lib) +noinst_LIBRARIES = libmain.a + +libmain_a_SOURCES = main-sgen.c +if SUPPORT_BOEHM +libmain_a_SOURCES += main.c +endif +libmain_a_CFLAGS = $(AM_CFLAGS) @CXX_ADD_CFLAGS@ + if LOADED_LLVM lib_LTLIBRARIES += libmono-llvm.la libmono_llvm_la_SOURCES = mini-llvm.c mini-llvm-cpp.cpp llvm-jit.cpp @@ -179,35 +187,29 @@ libmono_llvm_la_LDFLAGS=-Wl,-undefined -Wl,suppress -Wl,-flat_namespace endif endif -mono_boehm_SOURCES = \ - main.c +# we need this to prevent automake from generating a default mono_SOURCES = mono.c +mono_SOURCES = -mono_CFLAGS = $(AM_CFLAGS) - -mono_boehm_CFLAGS = $(AM_CFLAGS) +mono_boehm_SOURCES = +mono_boehm_CFLAGS = $(AM_CFLAGS) @CXX_REMOVE_CFLAGS@ AM_CPPFLAGS = $(LIBGC_CPPFLAGS) -mono_sgen_SOURCES = \ - main-sgen.c - -mono_SOURCES = \ - main-sgen.c - -mono_sgen_CFLAGS = $(AM_CFLAGS) +mono_sgen_SOURCES = +mono_sgen_CFLAGS = $(AM_CFLAGS) @CXX_REMOVE_CFLAGS@ # We build this after libmono was built so it contains the date when the final # link was done if SUPPORT_BOEHM buildver-boehm.h: libmini.la $(monodir)/mono/metadata/libmonoruntime.la @echo "const char *build_date = \"`date`\";" > buildver-boehm.h -mono_boehm-main.$(OBJEXT): buildver-boehm.h +libmain_a-main.$(OBJEXT): buildver-boehm.h endif buildver-sgen.h: libmini.la $(monodir)/mono/metadata/libmonoruntimesgen.la $(monodir)/mono/sgen/libmonosgen.la @echo "const char *build_date = \"`date`\";" > buildver-sgen.h -mono_sgen-main-sgen.$(OBJEXT): buildver-sgen.h -main-sgen.$(OBJEXT): buildver-sgen.h + +libmain_a-main-sgen.$(OBJEXT): buildver-sgen.h if DTRACE_G_REQUIRED LIBMONO_DTRACE_OBJECT = .libs/mono-dtrace.$(OBJEXT) @@ -238,6 +240,7 @@ LLVMMONOF=$(LLVM_LIBS) $(LLVM_LDFLAGS) endif mono_boehm_LDADD = \ + libmain_a-main.$(OBJEXT) \ $(MONO_LIB) \ $(glib_libs) \ $(LLVMMONOF) \ @@ -248,6 +251,7 @@ mono_boehm_LDFLAGS = \ $(static_flags) $(monobinldflags) $(monobin_platform_ldflags) mono_sgen_LDADD = \ + libmain_a-main-sgen.$(OBJEXT) \ $(MONO_SGEN_LIB) \ $(glib_libs) \ $(LLVMMONOF) \ @@ -386,7 +390,6 @@ endif endif interp_sources = \ - interp/hacks.h \ interp/interp.h \ interp/interp-internals.h \ interp/interp.c \ @@ -642,11 +645,10 @@ endif if MONO_JEMALLOC_ENABLED libmonoldflags += $(JEMALLOC_LDFLAGS) -mono_CFLAGS += $(JEMALLOC_CFLAGS) endif libmono_ee_interp_la_SOURCES = $(interp_sources) -libmono_ee_interp_la_CFLAGS = $(mono_CFLAGS) +libmono_ee_interp_la_CFLAGS = $(AM_CFLAGS) @CXX_ADD_CFLAGS@ if BITCODE libmono_ee_interp_la_LDFLAGS = $(libmonoldflags) if DISABLE_INTERPRETER @@ -659,7 +661,7 @@ extra_libmono_dbg_source = debugger-engine.c endif libmono_dbg_la_SOURCES = debugger-agent.c debugger-state-machine.c $(extra_libmono_dbg_source) -libmono_dbg_la_CFLAGS = $(mono_CFLAGS) +libmono_dbg_la_CFLAGS = $(AM_CFLAGS) @CXX_ADD_CFLAGS@ if BITCODE if DISABLE_DEBUGGER_AGENT libmono_dbg_la_LIBADD = libmonosgen-2.0.la @@ -682,15 +684,17 @@ endif # compile time dependencies on boehm/sgen. # libmini_la_SOURCES = $(common_sources) $(llvm_sources) $(llvm_runtime_sources) $(arch_sources) $(os_sources) -libmini_la_CFLAGS = $(mono_CFLAGS) +libmini_la_CFLAGS = $(AM_CFLAGS) @CXX_ADD_CFLAGS@ libmonoboehm_2_0_la_SOURCES = -libmonoboehm_2_0_la_CFLAGS = $(mono_boehm_CFLAGS) +libmonoboehm_2_0_la_CFLAGS = $(mono_boehm_CFLAGS) @CXX_ADD_CFLAGS@ + libmonoboehm_2_0_la_LIBADD = libmini.la $(interp_libs_with_mini) $(dbg_libs_with_mini) $(boehm_libs) $(LIBMONO_DTRACE_OBJECT) $(LLVMMONOF) libmonoboehm_2_0_la_LDFLAGS = $(libmonoldflags) $(monobin_platform_ldflags) libmonosgen_2_0_la_SOURCES = -libmonosgen_2_0_la_CFLAGS = $(mono_sgen_CFLAGS) +libmonosgen_2_0_la_CFLAGS = $(mono_sgen_CFLAGS) @CXX_ADD_CFLAGS@ + libmonosgen_2_0_la_LIBADD = libmini.la $(interp_libs_with_mini) $(dbg_libs_with_mini) $(sgen_libs) $(LIBMONO_DTRACE_OBJECT) $(LLVMMONOF) libmonosgen_2_0_la_LDFLAGS = $(libmonoldflags) $(monobin_platform_ldflags) @@ -803,8 +807,8 @@ check-seq-points: else check-seq-points: mono $(regtests) rm -f TestResult-op_il_seq_point.xml - for i in $(regtests); do $(srcdir)/test_op_il_seq_point.sh $$i || ($(srcdir)/test_op_il_seq_point_headerfooter.sh; exit 1) || exit 1; done - for i in $(regtests); do $(srcdir)/test_op_il_seq_point.sh $$i --aot || ($(srcdir)/test_op_il_seq_point_headerfooter.sh; exit 1) || exit 1; done + for i in $(regtests); do $(srcdir)/test_op_il_seq_point.sh $(DEFAULT_PROFILE) $$i || ($(srcdir)/test_op_il_seq_point_headerfooter.sh; exit 1) || exit 1; done + for i in $(regtests); do $(srcdir)/test_op_il_seq_point.sh $(DEFAULT_PROFILE) $$i --aot || ($(srcdir)/test_op_il_seq_point_headerfooter.sh; exit 1) || exit 1; done $(srcdir)/test_op_il_seq_point_headerfooter.sh endif @@ -1009,4 +1013,5 @@ Makefile.am: Makefile.am.in endif -CFLAGS := $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) @CXX_ADD_CFLAGS@ +# Per-library because linking doesn't like -xc++, it treats libraries as C++. +CFLAGS := $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) diff --git a/mono/mini/Makefile.am.in b/mono/mini/Makefile.am.in index 4f3ef2faba..6c840f88b8 100755 --- a/mono/mini/Makefile.am.in +++ b/mono/mini/Makefile.am.in @@ -169,6 +169,14 @@ endif noinst_LTLIBRARIES = $(mini_common_lib) +noinst_LIBRARIES = libmain.a + +libmain_a_SOURCES = main-sgen.c +if SUPPORT_BOEHM +libmain_a_SOURCES += main.c +endif +libmain_a_CFLAGS = $(AM_CFLAGS) @CXX_ADD_CFLAGS@ + if LOADED_LLVM lib_LTLIBRARIES += libmono-llvm.la libmono_llvm_la_SOURCES = mini-llvm.c mini-llvm-cpp.cpp llvm-jit.cpp @@ -179,35 +187,29 @@ libmono_llvm_la_LDFLAGS=-Wl,-undefined -Wl,suppress -Wl,-flat_namespace endif endif -mono_boehm_SOURCES = \ - main.c +# we need this to prevent automake from generating a default mono_SOURCES = mono.c +mono_SOURCES = -mono_CFLAGS = $(AM_CFLAGS) - -mono_boehm_CFLAGS = $(AM_CFLAGS) +mono_boehm_SOURCES = +mono_boehm_CFLAGS = $(AM_CFLAGS) @CXX_REMOVE_CFLAGS@ AM_CPPFLAGS = $(LIBGC_CPPFLAGS) -mono_sgen_SOURCES = \ - main-sgen.c - -mono_SOURCES = \ - main-sgen.c - -mono_sgen_CFLAGS = $(AM_CFLAGS) +mono_sgen_SOURCES = +mono_sgen_CFLAGS = $(AM_CFLAGS) @CXX_REMOVE_CFLAGS@ # We build this after libmono was built so it contains the date when the final # link was done if SUPPORT_BOEHM buildver-boehm.h: libmini.la $(monodir)/mono/metadata/libmonoruntime.la @echo "const char *build_date = \"`date`\";" > buildver-boehm.h -mono_boehm-main.$(OBJEXT): buildver-boehm.h +libmain_a-main.$(OBJEXT): buildver-boehm.h endif buildver-sgen.h: libmini.la $(monodir)/mono/metadata/libmonoruntimesgen.la $(monodir)/mono/sgen/libmonosgen.la @echo "const char *build_date = \"`date`\";" > buildver-sgen.h -mono_sgen-main-sgen.$(OBJEXT): buildver-sgen.h -main-sgen.$(OBJEXT): buildver-sgen.h + +libmain_a-main-sgen.$(OBJEXT): buildver-sgen.h if DTRACE_G_REQUIRED LIBMONO_DTRACE_OBJECT = .libs/mono-dtrace.$(OBJEXT) @@ -238,6 +240,7 @@ LLVMMONOF=$(LLVM_LIBS) $(LLVM_LDFLAGS) endif mono_boehm_LDADD = \ + libmain_a-main.$(OBJEXT) \ $(MONO_LIB) \ $(glib_libs) \ $(LLVMMONOF) \ @@ -248,6 +251,7 @@ mono_boehm_LDFLAGS = \ $(static_flags) $(monobinldflags) $(monobin_platform_ldflags) mono_sgen_LDADD = \ + libmain_a-main-sgen.$(OBJEXT) \ $(MONO_SGEN_LIB) \ $(glib_libs) \ $(LLVMMONOF) \ @@ -386,7 +390,6 @@ endif endif interp_sources = \ - interp/hacks.h \ interp/interp.h \ interp/interp-internals.h \ interp/interp.c \ @@ -642,11 +645,10 @@ endif if MONO_JEMALLOC_ENABLED libmonoldflags += $(JEMALLOC_LDFLAGS) -mono_CFLAGS += $(JEMALLOC_CFLAGS) endif libmono_ee_interp_la_SOURCES = $(interp_sources) -libmono_ee_interp_la_CFLAGS = $(mono_CFLAGS) +libmono_ee_interp_la_CFLAGS = $(AM_CFLAGS) @CXX_ADD_CFLAGS@ if BITCODE libmono_ee_interp_la_LDFLAGS = $(libmonoldflags) if DISABLE_INTERPRETER @@ -659,7 +661,7 @@ extra_libmono_dbg_source = debugger-engine.c endif libmono_dbg_la_SOURCES = debugger-agent.c debugger-state-machine.c $(extra_libmono_dbg_source) -libmono_dbg_la_CFLAGS = $(mono_CFLAGS) +libmono_dbg_la_CFLAGS = $(AM_CFLAGS) @CXX_ADD_CFLAGS@ if BITCODE if DISABLE_DEBUGGER_AGENT libmono_dbg_la_LIBADD = libmonosgen-2.0.la @@ -682,15 +684,17 @@ endif # compile time dependencies on boehm/sgen. # libmini_la_SOURCES = $(common_sources) $(llvm_sources) $(llvm_runtime_sources) $(arch_sources) $(os_sources) -libmini_la_CFLAGS = $(mono_CFLAGS) +libmini_la_CFLAGS = $(AM_CFLAGS) @CXX_ADD_CFLAGS@ libmonoboehm_2_0_la_SOURCES = -libmonoboehm_2_0_la_CFLAGS = $(mono_boehm_CFLAGS) +libmonoboehm_2_0_la_CFLAGS = $(mono_boehm_CFLAGS) @CXX_ADD_CFLAGS@ + libmonoboehm_2_0_la_LIBADD = libmini.la $(interp_libs_with_mini) $(dbg_libs_with_mini) $(boehm_libs) $(LIBMONO_DTRACE_OBJECT) $(LLVMMONOF) libmonoboehm_2_0_la_LDFLAGS = $(libmonoldflags) $(monobin_platform_ldflags) libmonosgen_2_0_la_SOURCES = -libmonosgen_2_0_la_CFLAGS = $(mono_sgen_CFLAGS) +libmonosgen_2_0_la_CFLAGS = $(mono_sgen_CFLAGS) @CXX_ADD_CFLAGS@ + libmonosgen_2_0_la_LIBADD = libmini.la $(interp_libs_with_mini) $(dbg_libs_with_mini) $(sgen_libs) $(LIBMONO_DTRACE_OBJECT) $(LLVMMONOF) libmonosgen_2_0_la_LDFLAGS = $(libmonoldflags) $(monobin_platform_ldflags) @@ -803,8 +807,8 @@ check-seq-points: else check-seq-points: mono $(regtests) rm -f TestResult-op_il_seq_point.xml - for i in $(regtests); do $(srcdir)/test_op_il_seq_point.sh $$i || ($(srcdir)/test_op_il_seq_point_headerfooter.sh; exit 1) || exit 1; done - for i in $(regtests); do $(srcdir)/test_op_il_seq_point.sh $$i --aot || ($(srcdir)/test_op_il_seq_point_headerfooter.sh; exit 1) || exit 1; done + for i in $(regtests); do $(srcdir)/test_op_il_seq_point.sh $(DEFAULT_PROFILE) $$i || ($(srcdir)/test_op_il_seq_point_headerfooter.sh; exit 1) || exit 1; done + for i in $(regtests); do $(srcdir)/test_op_il_seq_point.sh $(DEFAULT_PROFILE) $$i --aot || ($(srcdir)/test_op_il_seq_point_headerfooter.sh; exit 1) || exit 1; done $(srcdir)/test_op_il_seq_point_headerfooter.sh endif @@ -1009,4 +1013,5 @@ Makefile.am: Makefile.am.in endif -CFLAGS := $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) @CXX_ADD_CFLAGS@ +# Per-library because linking doesn't like -xc++, it treats libraries as C++. +CFLAGS := $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) diff --git a/mono/mini/Makefile.in.REMOVED.git-id b/mono/mini/Makefile.in.REMOVED.git-id index a392a2adb6..c6b803efe2 100644 --- a/mono/mini/Makefile.in.REMOVED.git-id +++ b/mono/mini/Makefile.in.REMOVED.git-id @@ -1 +1 @@ -cfcdf92817611f6e9e66a79b7e24b5a46d448c19 \ No newline at end of file +837d0ba54d6b679fba185ee7860b2765e5761338 \ No newline at end of file diff --git a/mono/mini/aot-compiler.c.REMOVED.git-id b/mono/mini/aot-compiler.c.REMOVED.git-id index ab1e9f3d2d..013394178d 100644 --- a/mono/mini/aot-compiler.c.REMOVED.git-id +++ b/mono/mini/aot-compiler.c.REMOVED.git-id @@ -1 +1 @@ -4796fa7f1fed00eb377c87f438cca3a801d76167 \ No newline at end of file +9d01f833f93a9f1f321d8b5be1ef260422af9679 \ No newline at end of file diff --git a/mono/mini/aot-compiler.h b/mono/mini/aot-compiler.h index 9de33cc9d4..643322280a 100644 --- a/mono/mini/aot-compiler.h +++ b/mono/mini/aot-compiler.h @@ -15,7 +15,6 @@ gboolean mono_aot_is_shared_got_offset (int offset) MONO_LLVM_INTERNAL; guint32 mono_aot_get_got_offset (MonoJumpInfo *ji) MONO_LLVM_INTERNAL; char* mono_aot_get_method_name (MonoCompile *cfg) MONO_LLVM_INTERNAL; char* mono_aot_get_mangled_method_name (MonoMethod *method) MONO_LLVM_INTERNAL; -gboolean mono_aot_is_linkonce_method (MonoMethod *method) MONO_LLVM_INTERNAL; gboolean mono_aot_is_direct_callable (MonoJumpInfo *patch_info) MONO_LLVM_INTERNAL; void mono_aot_mark_unused_llvm_plt_entry(MonoJumpInfo *patch_info) MONO_LLVM_INTERNAL; char* mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data) MONO_LLVM_INTERNAL; diff --git a/mono/mini/aot-runtime.c.REMOVED.git-id b/mono/mini/aot-runtime.c.REMOVED.git-id index 5a66efc0e1..0e1b0efa1b 100644 --- a/mono/mini/aot-runtime.c.REMOVED.git-id +++ b/mono/mini/aot-runtime.c.REMOVED.git-id @@ -1 +1 @@ -c7d9df96dfb0bd639be4e4db5009436028c459de \ No newline at end of file +d5e52bc3fb391f69b506b5747e78c7ac14d0d127 \ No newline at end of file diff --git a/mono/mini/aot-runtime.h b/mono/mini/aot-runtime.h index b559cdc293..85c933cbac 100644 --- a/mono/mini/aot-runtime.h +++ b/mono/mini/aot-runtime.h @@ -139,7 +139,7 @@ typedef struct MonoAotFileInfo * The runtime version string for AOT images generated using 'bind-to-runtime-version', * NULL otherwise. */ - gpointer runtime_version; + char *runtime_version; /* Blocks of various kinds of trampolines */ gpointer specific_trampolines; gpointer static_rgctx_trampolines; @@ -247,11 +247,21 @@ void mono_aot_set_make_unreadable (gboolean unreadable); gboolean mono_aot_is_pagefault (void *ptr); void mono_aot_handle_pagefault (void *ptr); void mono_aot_register_jit_icall (const char *name, gpointer addr); + +#ifdef __cplusplus +template +inline void +mono_aot_register_jit_icall (const char *name, T addr) +{ + mono_aot_register_jit_icall (name, (gpointer)addr); +} +#endif // __cplusplus + guint32 mono_aot_find_method_index (MonoMethod *method); -void mono_aot_init_llvm_method (gpointer aot_module, guint32 method_index); -void mono_aot_init_gshared_method_this (gpointer aot_module, guint32 method_index, MonoObject *this_ins); -void mono_aot_init_gshared_method_mrgctx (gpointer aot_module, guint32 method_index, MonoMethodRuntimeGenericContext *rgctx); -void mono_aot_init_gshared_method_vtable (gpointer aot_module, guint32 method_index, MonoVTable *vtable); +G_EXTERN_C void mono_aot_init_llvm_method (gpointer aot_module, guint32 method_index); +G_EXTERN_C void mono_aot_init_gshared_method_this (gpointer aot_module, guint32 method_index, MonoObject *this_ins); +G_EXTERN_C void mono_aot_init_gshared_method_mrgctx (gpointer aot_module, guint32 method_index, MonoMethodRuntimeGenericContext *rgctx); +G_EXTERN_C void mono_aot_init_gshared_method_vtable (gpointer aot_module, guint32 method_index, MonoVTable *vtable); GHashTable *mono_aot_get_weak_field_indexes (MonoImage *image); /* This is an exported function */ diff --git a/mono/mini/aot-tests.cs b/mono/mini/aot-tests.cs index fa71ae8281..61d6ff40ee 100644 --- a/mono/mini/aot-tests.cs +++ b/mono/mini/aot-tests.cs @@ -441,7 +441,6 @@ class Tests } [Category ("DYNCALL")] - [Category ("!WASM")] //Interp fails public static int test_0_arm64_dyncall_vtypebyrefonstack () { var s = new LargeStruct () { a = 1, b = 2, c = 3, d = 4 }; diff --git a/mono/mini/cpu-amd64.md b/mono/mini/cpu-amd64.md index 92e09955cf..f5dd9fb0c1 100644 --- a/mono/mini/cpu-amd64.md +++ b/mono/mini/cpu-amd64.md @@ -121,7 +121,7 @@ long_conv_to_u2: dest:i src1:i len:4 long_conv_to_u1: dest:i src1:i len:4 zext_i4: dest:i src1:i len:4 -long_mul_imm: dest:i src1:i clob:1 len:12 +long_mul_imm: dest:i src1:i clob:1 len:16 long_min: dest:i src1:i src2:i len:16 clob:1 long_min_un: dest:i src1:i src2:i len:16 clob:1 long_max: dest:i src1:i src2:i len:16 clob:1 @@ -813,6 +813,8 @@ expand_i8: dest:x src1:i len:11 expand_r4: dest:x src1:f len:16 expand_r8: dest:x src1:f len:13 +roundpd: dest:x src1:x len:10 + liverange_start: len:0 liverange_end: len:0 gc_liveness_def: len:0 diff --git a/mono/mini/debugger-agent.c.REMOVED.git-id b/mono/mini/debugger-agent.c.REMOVED.git-id index 013690cd6c..4f6bb25077 100644 --- a/mono/mini/debugger-agent.c.REMOVED.git-id +++ b/mono/mini/debugger-agent.c.REMOVED.git-id @@ -1 +1 @@ -ab6ba3420956c21d329bdb767fc76f3544561763 \ No newline at end of file +95f6bf6807954c1b4ad911063f17c1752876dbbb \ No newline at end of file diff --git a/mono/mini/debugger-engine.c b/mono/mini/debugger-engine.c index fd9a5ce950..4ec9d48055 100644 --- a/mono/mini/debugger-engine.c +++ b/mono/mini/debugger-engine.c @@ -442,12 +442,12 @@ mono_de_set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, M mono_loader_lock (); - CollectDomainData user_data = { - .bp = bp, - .methods = methods, - .method_domains = method_domains, - .method_seq_points = method_seq_points - }; + CollectDomainData user_data; + memset (&user_data, 0, sizeof (user_data)); + user_data.bp = bp; + user_data.methods = methods; + user_data.method_domains = method_domains; + user_data.method_seq_points = method_seq_points; mono_de_foreach_domain (collect_domain_bp, &user_data); for (i = 0; i < methods->len; ++i) { @@ -473,6 +473,17 @@ mono_de_set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, M return bp; } +MonoBreakpoint * +mono_de_get_breakpoint_by_id (int id) +{ + for (int i = 0; i < breakpoints->len; ++i) { + MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i); + if (bp->req->id == id) + return bp; + } + return NULL; +} + void mono_de_clear_breakpoint (MonoBreakpoint *bp) { @@ -920,7 +931,7 @@ mono_de_ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, void *tls, return FALSE; } - if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) { + if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && !(sp->flags & MONO_SEQ_POINT_FLAG_NESTED_CALL)) { /* * These seq points are inserted by the JIT after calls, step over needs to skip them. */ @@ -943,7 +954,7 @@ mono_de_ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, void *tls, } } - if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && req->start_method) { + if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && !(sp->flags & MONO_SEQ_POINT_FLAG_NESTED_CALL) && req->start_method) { int nframes; rt_callbacks.ss_calculate_framecount (tls, ctx, FALSE, NULL, &nframes); if (req->start_method == method && req->nframes && nframes == req->nframes) { //Check also frame count(could be recursion) @@ -1002,7 +1013,6 @@ mono_de_process_breakpoint (void *void_tls, gboolean from_signal) guint8 *ip; int i; guint32 native_offset; - MonoBreakpoint *bp; GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs; EventKind kind = EVENT_KIND_BREAKPOINT; MonoContext *ctx = rt_callbacks.tls_get_restore_state (tls); @@ -1050,7 +1060,6 @@ mono_de_process_breakpoint (void *void_tls, gboolean from_signal) mono_debugger_log_bp_hit (tls, method, sp.il_offset); - bp = NULL; mono_de_collect_breakpoints_by_sp (&sp, ji, ss_reqs_orig, bp_reqs); if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) { @@ -1140,7 +1149,7 @@ static gboolean ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset) { if (ss_req_bp_cache) { - MonoBreakpoint dummy = {method, il_offset, NULL, NULL}; + MonoBreakpoint dummy = {method, (long)il_offset, NULL, NULL}; return !g_hash_table_lookup (ss_req_bp_cache, &dummy); } for (GSList *l = bps; l; l = l->next) { @@ -1218,7 +1227,7 @@ is_last_non_empty (SeqPoint* sp, MonoSeqPointInfo *info) SeqPoint* next = g_new (SeqPoint, sp->next_len); mono_seq_point_init_next (info, *sp, next); for (int i = 0; i < sp->next_len; i++) { - if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) { + if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK && !(next [i].flags & MONO_SEQ_POINT_FLAG_NESTED_CALL)) { if (!is_last_non_empty (&next [i], info)) { g_free (next); return FALSE; diff --git a/mono/mini/debugger-engine.h b/mono/mini/debugger-engine.h index 12952b6445..5b2434aad0 100644 --- a/mono/mini/debugger-engine.h +++ b/mono/mini/debugger-engine.h @@ -253,6 +253,7 @@ void mono_de_collect_breakpoints_by_sp (SeqPoint *sp, MonoJitInfo *ji, GPtrArray void mono_de_clear_breakpoints_for_domain (MonoDomain *domain); void mono_de_add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji); void mono_de_clear_all_breakpoints (void); +MonoBreakpoint * mono_de_get_breakpoint_by_id (int id); //single stepping void mono_de_start_single_stepping (void); diff --git a/mono/mini/debugger-state-machine.c b/mono/mini/debugger-state-machine.c index 88cdbab467..1788815f0f 100644 --- a/mono/mini/debugger-state-machine.c +++ b/mono/mini/debugger-state-machine.c @@ -85,7 +85,7 @@ void mono_debugger_log_free (void) { MonoFlightRecorder *log = debugger_log; - debugger_log = GINT_TO_POINTER (MONO_DEBUGGER_LOG_FREED); + debugger_log = (MonoFlightRecorder*)GINT_TO_POINTER (MONO_DEBUGGER_LOG_FREED); mono_memory_barrier (); mono_flight_recorder_free (log); diff --git a/mono/mini/decompose.c b/mono/mini/decompose.c index d522d7e01e..400f56270d 100644 --- a/mono/mini/decompose.c +++ b/mono/mini/decompose.c @@ -18,6 +18,8 @@ #include #include #include +#define MONO_MATH_DECLARE_ALL 1 +#include #ifndef DISABLE_JIT @@ -1868,7 +1870,7 @@ mono_decompose_soft_float (MonoCompile *cfg) MONO_INST_NEW (cfg, iargs [0], OP_ARG); iargs [0]->dreg = ins->sreg1; - call = mono_emit_jit_icall (cfg, mono_isfinite, iargs); + call = mono_emit_jit_icall (cfg, mono_isfinite_double, iargs); MONO_INST_NEW (cfg, cmp, OP_ICOMPARE_IMM); cmp->sreg1 = call->dreg; diff --git a/mono/mini/driver.c b/mono/mini/driver.c index ad690317a2..a88d8bfd3d 100644 --- a/mono/mini/driver.c +++ b/mono/mini/driver.c @@ -54,6 +54,7 @@ #include "mono/utils/mono-logger-internals.h" #include "mono/metadata/w32handle.h" #include "mono/metadata/callspec.h" +#include "mono/metadata/custom-attrs-internals.h" #include "mini.h" #include "jit.h" @@ -101,7 +102,7 @@ static const struct msgstr_t { #undef OPTFLAG }; static const gint16 opt_names [] = { -#define OPTFLAG(id,shift,name,desc) [(shift)] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)), +#define OPTFLAG(id,shift,name,desc) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)), #include "optflags-def.h" #undef OPTFLAG }; @@ -350,6 +351,96 @@ domain_dump_native_code (MonoDomain *domain) { } #endif +static gboolean do_regression_retries; +static int regression_test_skip_index; + + +static gboolean +method_should_be_regression_tested (MonoMethod *method, gboolean interp) +{ + ERROR_DECL (error); + + if (strncmp (method->name, "test_", 5) != 0) + return FALSE; + + if (interp) { + static gboolean filter_method_init = FALSE; + static const char *filter_method = NULL; + + if (!filter_method_init) { + filter_method = g_getenv ("INTERP_FILTER_METHOD"); + filter_method_init = TRUE; + } + + if (filter_method) { + const char *name = filter_method; + + if ((strchr (name, '.') > name) || strchr (name, ':')) { + MonoMethodDesc *desc = mono_method_desc_new (name, TRUE); + gboolean res = mono_method_desc_full_match (desc, method); + mono_method_desc_free (desc); + return res; + } else { + return strcmp (method->name, name) == 0; + } + } + } + + MonoCustomAttrInfo* ainfo = mono_custom_attrs_from_method_checked (method, error); + mono_error_cleanup (error); + if (!ainfo) + return TRUE; + + int j; + for (j = 0; j < ainfo->num_attrs; ++j) { + MonoCustomAttrEntry *centry = &ainfo->attrs [j]; + if (centry->ctor == NULL) + continue; + + MonoClass *klass = centry->ctor->klass; + if (strcmp (m_class_get_name (klass), "CategoryAttribute") || mono_method_signature (centry->ctor)->param_count != 1) + continue; + + gpointer *typed_args, *named_args; + int num_named_args; + CattrNamedArg *arginfo; + + mono_reflection_create_custom_attr_data_args_noalloc ( + mono_defaults.corlib, centry->ctor, centry->data, centry->data_size, + &typed_args, &named_args, &num_named_args, &arginfo, error); + if (!is_ok (error)) + continue; + + char *utf8_str = (char*)(void*)typed_args[0]; //this points into image memory that is constant + g_free (typed_args); + g_free (named_args); + g_free (arginfo); + + if (interp && !strcmp (utf8_str, "!INTERPRETER")) { + g_print ("skip %s...\n", method->name); + return FALSE; + } + +#if HOST_WASM + if (!strcmp (utf8_str, "!WASM")) { + g_print ("skip %s...\n", method->name); + return FALSE; + } +#endif + if (mono_aot_mode == MONO_AOT_MODE_FULL && !strcmp (utf8_str, "!FULLAOT")) { + g_print ("skip %s...\n", method->name); + return FALSE; + } + + if ((mono_aot_mode == MONO_AOT_MODE_INTERP_LLVMONLY || mono_aot_mode == MONO_AOT_MODE_LLVMONLY) && !strcmp (utf8_str, "!BITCODE")) { + g_print ("skip %s...\n", method->name); + return FALSE; + } + } + + return TRUE; +} + static void mini_regression_step (MonoImage *image, int verbose, int *total_run, int *total, guint32 opt_flags, @@ -367,6 +458,7 @@ mini_regression_step (MonoImage *image, int verbose, int *total_run, int *total, g_free (n); cfailed = failed = run = code_size = 0; comp_time = elapsed = 0.0; + int local_skip_index = 0; /* fixme: ugly hack - delete all previously compiled methods */ if (domain_jit_info (domain)) { @@ -386,18 +478,27 @@ mini_regression_step (MonoImage *image, int verbose, int *total_run, int *total, mono_error_cleanup (error); /* FIXME don't swallow the error */ continue; } - if (strncmp (method->name, "test_", 5) == 0) { - MonoCompile *cfg; + if (method_should_be_regression_tested (method, FALSE)) { + MonoCompile *cfg = NULL; expected = atoi (method->name + 5); run++; start_time = g_timer_elapsed (timer, NULL); + +#ifdef DISABLE_JIT +#ifdef MONO_USE_AOT_COMPILER + ERROR_DECL (error); + func = (TestMethod)mono_aot_get_method (mono_get_root_domain (), method, error); + mono_error_cleanup (error); +#else + g_error ("No JIT or AOT available, regression testing not possible!") +#endif + +#else comp_time -= start_time; cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, opt_flags), mono_get_root_domain (), JIT_FLAG_RUN_CCTORS, 0, -1); comp_time += g_timer_elapsed (timer, NULL); if (cfg->exception_type == MONO_EXCEPTION_NONE) { - if (verbose >= 2) - g_print ("Running '%s' ...\n", method->name); #ifdef MONO_USE_AOT_COMPILER ERROR_DECL (error); func = (TestMethod)mono_aot_get_method (mono_get_root_domain (), method, error); @@ -407,15 +508,37 @@ mini_regression_step (MonoImage *image, int verbose, int *total_run, int *total, #else func = (TestMethod)(gpointer)cfg->native_code; #endif - func = (TestMethod)mono_create_ftnptr (mono_get_root_domain (), func); + func = (TestMethod)mono_create_ftnptr (mono_get_root_domain (), (gpointer)func); + } +#endif + + if (func) { + if (do_regression_retries) { + ++local_skip_index; + + if(local_skip_index <= regression_test_skip_index) + continue; + ++regression_test_skip_index; + } + + if (verbose >= 2) + g_print ("Running '%s' ...\n", method->name); + +#if HOST_WASM + //WASM AOT injects dummy args and we must call with exact signatures + int (*func_2)(int) = (int (*)(int))(void*)func; + result = func_2 (-1); +#else result = func (); +#endif if (result != expected) { failed++; g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected); } - code_size += cfg->code_len; - mono_destroy_compile (cfg); - + if (cfg) { + code_size += cfg->code_len; + mono_destroy_compile (cfg); + } } else { cfailed++; g_print ("Test '%s' failed compilation.\n", method->name); @@ -529,6 +652,11 @@ mini_regression (MonoImage *image, int verbose, int *total_run) if (!(opt_sets [opt] & MONO_OPT_INTRINS)) continue; + //we running in AOT only, it makes no sense to try multiple flags + if ((mono_aot_mode == MONO_AOT_MODE_FULL || mono_aot_mode == MONO_AOT_MODE_LLVMONLY) && opt_sets [opt] != DEFAULT_OPTIMIZATIONS) { + continue; + } + mini_regression_step (image, verbose, total_run, &total, opt_sets [opt] & ~exclude, timer, domain); @@ -578,8 +706,7 @@ interp_regression_step (MonoImage *image, int verbose, int *total_run, int *tota double elapsed, transform_time; int i; MonoObject *result_obj; - static gboolean filter_method_init = FALSE; - static const char *filter_method = NULL; + int local_skip_index = 0; g_print ("Test run: image=%s\n", mono_image_get_filename (image)); cfailed = failed = run = 0; @@ -587,7 +714,6 @@ interp_regression_step (MonoImage *image, int verbose, int *total_run, int *tota g_timer_start (timer); for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) { - MonoObject *exc = NULL; ERROR_DECL (error); MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error); if (!method) { @@ -595,62 +721,18 @@ interp_regression_step (MonoImage *image, int verbose, int *total_run, int *tota continue; } - if (!filter_method_init) { - filter_method = g_getenv ("INTERP_FILTER_METHOD"); - filter_method_init = TRUE; - } - gboolean filter = FALSE; - if (filter_method) { - const char *name = filter_method; - - if ((strchr (name, '.') > name) || strchr (name, ':')) { - MonoMethodDesc *desc = mono_method_desc_new (name, TRUE); - filter = mono_method_desc_full_match (desc, method); - mono_method_desc_free (desc); - } else { - filter = strcmp (method->name, name) == 0; - } - } else { /* no filter, check for `Category' attribute on method */ - filter = TRUE; - MonoCustomAttrInfo* ainfo = mono_custom_attrs_from_method_checked (method, error); - mono_error_cleanup (error); - - if (ainfo) { - int j; - for (j = 0; j < ainfo->num_attrs && filter; ++j) { - MonoCustomAttrEntry *centry = &ainfo->attrs [j]; - if (centry->ctor == NULL) - continue; - - MonoClass *klass = centry->ctor->klass; - if (strcmp (m_class_get_name (klass), "CategoryAttribute")) - continue; - - MonoObject *obj = mono_custom_attrs_get_attr_checked (ainfo, klass, error); - /* FIXME: there is an ordering problem if there're multiple attributes, do this instead: - * MonoObject *obj = create_custom_attr (ainfo->image, centry->ctor, centry->data, centry->data_size, error); */ - mono_error_cleanup (error); - error_init (error); - MonoMethod *getter = mono_class_get_method_from_name_checked (klass, "get_Category", -1, 0, error); - mono_error_cleanup (error); - error_init (error); - MonoObject *str = mini_get_interp_callbacks ()->runtime_invoke (getter, obj, NULL, &exc, error); - mono_error_cleanup (error); - error_init (error); - char *utf8_str = mono_string_to_utf8_checked ((MonoString *) str, error); - mono_error_cleanup (error); - error_init (error); - if (!strcmp (utf8_str, "!INTERPRETER")) { - g_print ("skip %s...\n", method->name); - filter = FALSE; - } - } - } - } - if (strncmp (method->name, "test_", 5) == 0 && filter) { + if (method_should_be_regression_tested (method, TRUE)) { ERROR_DECL_VALUE (interp_error); MonoObject *exc = NULL; + if (do_regression_retries) { + ++local_skip_index; + + if(local_skip_index <= regression_test_skip_index) + continue; + ++regression_test_skip_index; + } + result_obj = mini_get_interp_callbacks ()->runtime_invoke (method, NULL, NULL, &exc, &interp_error); if (!mono_error_ok (&interp_error)) { cfailed++; @@ -906,8 +988,9 @@ free_jit_info_data (ThreadData *td, JitInfoData *free) #define MODE_FREE 2 static void -test_thread_func (ThreadData *td) +test_thread_func (gpointer void_arg) { + ThreadData* td = (ThreadData*)void_arg; int mode = MODE_ALLOC; int i = 0; gulong lookup_successes = 0, lookup_failures = 0; @@ -947,7 +1030,7 @@ test_thread_func (ThreadData *td) } } else { int pos = random () % MAX_ADDR; - char *addr = (char*)(gulong) pos; + char *addr = (char*)(uintptr_t)pos; MonoJitInfo *ji; ji = mono_jit_info_table_find (domain, addr); @@ -1056,7 +1139,7 @@ jit_info_table_test (MonoDomain *domain) */ for (i = 0; i < num_threads; ++i) { - mono_thread_create_checked (domain, test_thread_func, &thread_datas [i], error); + mono_thread_create_checked (domain, (gpointer)test_thread_func, &thread_datas [i], error); mono_error_assert_ok (error); } } @@ -1144,8 +1227,9 @@ compile_all_methods_thread_main_inner (CompileAllThreadArgs *args) } static void -compile_all_methods_thread_main (CompileAllThreadArgs *args) +compile_all_methods_thread_main (gpointer void_args) { + CompileAllThreadArgs *args = (CompileAllThreadArgs*)void_args; guint32 i; for (i = 0; i < args->recompilation_times; ++i) compile_all_methods_thread_main_inner (args); @@ -1166,7 +1250,7 @@ compile_all_methods (MonoAssembly *ass, int verbose, guint32 opts, guint32 recom * Need to create a mono thread since compilation might trigger * running of managed code. */ - mono_thread_create_checked (mono_domain_get (), compile_all_methods_thread_main, &args, error); + mono_thread_create_checked (mono_domain_get (), (gpointer)compile_all_methods_thread_main, &args, error); mono_error_assert_ok (error); mono_thread_manage (); @@ -1813,6 +1897,44 @@ mono_enable_interp (const char *opts) } +static int +mono_exec_regression_internal (int verbose_level, int count, char *images [], gboolean single_method) +{ + mono_do_single_method_regression = single_method; + if (mono_use_interpreter) { + if (mono_interp_regression_list (verbose_level, count, images)) { + g_print ("Regression ERRORS!\n"); + return 1; + } + return 0; + } + if (mini_regression_list (verbose_level, count, images)) { + g_print ("Regression ERRORS!\n"); + return 1; + } + return 0; +} + + +/** + * Returns TRUE for success, FALSE for failure. + */ +gboolean +mono_regression_test_step (int verbose_level, const char *image, const char *method_name) +{ + if (method_name) { + //TODO + } else { + do_regression_retries = TRUE; + } + + char *images[] = { + (char*)image, + NULL + }; + + return mono_exec_regression_internal (verbose_level, 1, images, FALSE) == 0; +} /** * mono_main: * \param argc number of arguments in the argv array @@ -2234,7 +2356,20 @@ mono_main (int argc, char* argv[]) return 1; } -#if !defined(HOST_WIN32) && defined(HAVE_UNISTD_H) +/* + * XXX: verify if other OSes need it; many platforms seem to have it so that + * mono_w32process_get_path -> mono_w32process_get_name, and the name is not + * necessarily a path instead of just the program name + */ +#if defined (_AIX) + /* + * mono_w32process_get_path on these can only return a name, not a path; + * which may not be good for us if the mono command name isn't on $PATH, + * like in CI scenarios. chances are argv based is fine if we inherited + * the environment variables. + */ + mono_w32process_set_cli_launcher (argv [0]); +#elif !defined(HOST_WIN32) && defined(HAVE_UNISTD_H) /* * If we are not embedded, use the mono runtime executable to run managed exe's. */ @@ -2334,24 +2469,9 @@ mono_main (int argc, char* argv[]) switch (action) { case DO_SINGLE_METHOD_REGRESSION: - mono_do_single_method_regression = TRUE; case DO_REGRESSION: - if (mono_use_interpreter) { - if (mono_interp_regression_list (2, argc -i, argv + i)) { - g_print ("Regression ERRORS!\n"); - // mini_cleanup (domain); - return 1; - } - // mini_cleanup (domain); - return 0; - } - if (mini_regression_list (mini_verbose, argc -i, argv + i)) { - g_print ("Regression ERRORS!\n"); - mini_cleanup (domain); - return 1; - } - mini_cleanup (domain); - return 0; + return mono_exec_regression_internal (mini_verbose, argc -i, argv + i, action == DO_SINGLE_METHOD_REGRESSION); + case DO_BENCH: if (argc - i != 1 || mname == NULL) { g_print ("Usage: mini --ncompile num --compile method assembly\n"); @@ -2420,7 +2540,7 @@ mono_main (int argc, char* argv[]) #if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) /* Detach console when executing IMAGE_SUBSYSTEM_WINDOWS_GUI on win32 */ - if (!enable_debugging && !mono_compile_aot && ((MonoCLIImageInfo*)(mono_assembly_get_image_internal (assembly)->image_info))->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI) + if (!enable_debugging && !mono_compile_aot && mono_assembly_get_image_internal (assembly)->image_info->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI) FreeConsole (); #endif @@ -2430,12 +2550,8 @@ mono_main (int argc, char* argv[]) main_args.argv = argv + i; main_args.opts = opt; main_args.aot_options = aot_options; -#if RUN_IN_SUBTHREAD - mono_runtime_exec_managed_code (domain, main_thread_handler, &main_args); -#else main_thread_handler (&main_args); mono_thread_manage (); -#endif mini_cleanup (domain); @@ -2660,6 +2776,7 @@ mono_runtime_set_execution_mode (MonoEEMode mode) break; case MONO_AOT_MODE_NORMAL: + case MONO_AOT_MODE_NONE: break; default: @@ -2674,11 +2791,13 @@ void mono_jit_set_aot_mode (MonoAotMode mode) { /* we don't want to set mono_aot_mode twice */ - g_assert (mono_aot_mode == MONO_AOT_MODE_NONE); + static gboolean inited; + + g_assert (!inited); mono_aot_mode = mode; + inited = TRUE; mono_runtime_set_execution_mode ((MonoEEMode)mode); - } mono_bool diff --git a/mono/mini/ee.h b/mono/mini/ee.h index be694cd070..57e87d2f8a 100644 --- a/mono/mini/ee.h +++ b/mono/mini/ee.h @@ -15,7 +15,7 @@ #ifndef __MONO_EE_H__ #define __MONO_EE_H__ -#define MONO_EE_API_VERSION 0x50009 +#define MONO_EE_API_VERSION 0x60010 typedef struct _MonoInterpStackIter MonoInterpStackIter; @@ -35,8 +35,8 @@ struct _MonoEECallbacks { void (*delegate_ctor) (MonoObjectHandle this_obj, MonoObjectHandle target, gpointer addr, MonoError *error); gpointer (*get_remoting_invoke) (gpointer imethod, MonoError *error); void (*set_resume_state) (MonoJitTlsData *jit_tls, MonoException *ex, MonoJitExceptionInfo *ei, MonoInterpFrameHandle interp_frame, gpointer handler_ip); - gboolean (*run_finally) (StackFrameInfo *frame, int clause_index, gpointer handler_ip); - gboolean (*run_filter) (StackFrameInfo *frame, MonoException *ex, int clause_index, gpointer handler_ip); + gboolean (*run_finally) (StackFrameInfo *frame, int clause_index, gpointer handler_ip, gpointer handler_ip_end); + gboolean (*run_filter) (StackFrameInfo *frame, MonoException *ex, int clause_index, gpointer handler_ip, gpointer handler_ip_end); void (*frame_iter_init) (MonoInterpStackIter *iter, gpointer interp_exit_data); gboolean (*frame_iter_next) (MonoInterpStackIter *iter, StackFrameInfo *frame); MonoJitInfo* (*find_jit_info) (MonoDomain *domain, MonoMethod *method); diff --git a/mono/mini/exceptions-amd64.c b/mono/mini/exceptions-amd64.c index b4dfca90df..8a01f49766 100644 --- a/mono/mini/exceptions-amd64.c +++ b/mono/mini/exceptions-amd64.c @@ -195,7 +195,7 @@ static LONG CALLBACK seh_vectored_exception_handler(EXCEPTION_POINTERS* ep) void win32_seh_init() { if (!mono_aot_only) - restore_stack = get_win32_restore_stack (); + restore_stack = (void (*) (void))get_win32_restore_stack (); mono_old_win_toplevel_exception_filter = SetUnhandledExceptionFilter(seh_unhandled_exception_filter); mono_win_vectored_exception_handle = AddVectoredExceptionHandler (1, seh_vectored_exception_handler); @@ -730,7 +730,7 @@ mono_arch_unwind_frame (MonoDomain *domain, MonoJitTlsData *jit_tls, static void handle_signal_exception (gpointer obj) { - MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls (); + MonoJitTlsData *jit_tls = mono_tls_get_jit_tls (); MonoContext ctx; memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext)); @@ -776,7 +776,7 @@ mono_arch_handle_exception (void *sigctx, gpointer obj) * signal is disabled, and we could run arbitrary code though the debugger. So * resume into the normal stack and do most work there if possible. */ - MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls (); + MonoJitTlsData *jit_tls = mono_tls_get_jit_tls (); /* Pass the ctx parameter in TLS */ mono_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx); @@ -807,17 +807,17 @@ mono_arch_ip_from_context (void *sigctx) return (gpointer)UCONTEXT_REG_RIP (ctx); #elif defined(HOST_WIN32) - return ((CONTEXT*)sigctx)->Rip; + return (gpointer)(((CONTEXT*)sigctx)->Rip); #else - MonoContext *ctx = sigctx; + MonoContext *ctx = (MonoContext*)sigctx; return (gpointer)ctx->gregs [AMD64_RIP]; #endif } static MonoObject* -restore_soft_guard_pages () +restore_soft_guard_pages (void) { - MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls (); + MonoJitTlsData *jit_tls = mono_tls_get_jit_tls (); if (jit_tls->stack_ovf_guard_base) mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE); @@ -861,7 +861,7 @@ altstack_handle_and_restore (MonoContext *ctx, MonoObject *obj, gboolean stack_o mono_handle_exception (&mctx, obj); if (stack_ovf) { - MonoJitTlsData *jit_tls = (MonoJitTlsData *) mono_tls_get_jit_tls (); + MonoJitTlsData *jit_tls = mono_tls_get_jit_tls (); jit_tls->stack_ovf_pending = 1; prepare_for_guard_pages (&mctx); } @@ -1203,8 +1203,8 @@ fast_find_range_in_table_no_lock_ex (gsize begin_range, gsize end_range, gboolea // Fast path, look at boundaries. if (g_dynamic_function_table_begin != NULL) { - DynamicFunctionTableEntry *first_entry = g_dynamic_function_table_begin->data; - DynamicFunctionTableEntry *last_entry = (g_dynamic_function_table_end != NULL ) ? g_dynamic_function_table_end->data : first_entry; + DynamicFunctionTableEntry *first_entry = (DynamicFunctionTableEntry*)g_dynamic_function_table_begin->data; + DynamicFunctionTableEntry *last_entry = (g_dynamic_function_table_end != NULL ) ? (DynamicFunctionTableEntry*)g_dynamic_function_table_end->data : first_entry; // Sorted in descending order based on begin_range, check first item, that is the entry with highest range. if (first_entry != NULL && first_entry->begin_range <= begin_range && first_entry->end_range >= end_range) { @@ -1749,7 +1749,7 @@ initialize_unwind_info_internal (GSList *unwind_ops) { PUNWIND_INFO unwindinfo; - mono_arch_unwindinfo_create (&unwindinfo); + mono_arch_unwindinfo_create ((gpointer*)&unwindinfo); initialize_unwind_info_internal_ex (unwind_ops, unwindinfo); return unwindinfo; diff --git a/mono/mini/exceptions-arm.c b/mono/mini/exceptions-arm.c index a447faa60b..a4917d5903 100644 --- a/mono/mini/exceptions-arm.c +++ b/mono/mini/exceptions-arm.c @@ -378,7 +378,7 @@ mono_arm_get_exception_trampolines (gboolean aot) void mono_arch_exceptions_init (void) { - guint8 *tramp; + gpointer tramp; GSList *tramps, *l; if (mono_aot_only) { @@ -391,7 +391,7 @@ mono_arch_exceptions_init (void) } else { tramps = mono_arm_get_exception_trampolines (FALSE); for (l = tramps; l; l = l->next) { - MonoTrampInfo *info = l->data; + MonoTrampInfo *info = (MonoTrampInfo*)l->data; mono_register_jit_icall (info->code, g_strdup (info->name), NULL, TRUE); mono_tramp_info_register (info, NULL); @@ -446,9 +446,9 @@ mono_arch_unwind_frame (MonoDomain *domain, MonoJitTlsData *jit_tls, regs [MONO_MAX_IREGS + i] = *(guint64*)&(new_ctx->fregs [8 + i]); #endif - gboolean success = mono_unwind_frame (unwind_info, unwind_info_len, ji->code_start, + gboolean success = mono_unwind_frame (unwind_info, unwind_info_len, (guint8*)ji->code_start, (guint8*)ji->code_start + ji->code_size, - ip, NULL, regs, MONO_MAX_IREGS + 8, + (guint8*)ip, NULL, regs, MONO_MAX_IREGS + 8, save_locations, MONO_MAX_IREGS, &cfa); if (!success) @@ -502,7 +502,7 @@ mono_arch_unwind_frame (MonoDomain *domain, MonoJitTlsData *jit_tls, /* we substract 1, so that the IP points into the call instruction */ new_ctx->pc--; - *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3); + *lmf = (MonoLMF*)(((gsize)(*lmf)->previous_lmf) & ~3); return TRUE; } @@ -523,7 +523,7 @@ handle_signal_exception (gpointer obj) memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext)); - mono_handle_exception (&ctx, obj); + mono_handle_exception (&ctx, (MonoObject*)obj); mono_restore_context (&ctx); } @@ -535,7 +535,7 @@ handle_signal_exception (gpointer obj) static MONO_NEVER_INLINE gpointer get_handle_signal_exception_addr (void) { - return handle_signal_exception; + return (gpointer)handle_signal_exception; } /* @@ -547,7 +547,7 @@ mono_arch_handle_exception (void *ctx, gpointer obj) #if defined(MONO_CROSS_COMPILE) || !defined(MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX) g_assert_not_reached (); #elif defined(MONO_ARCH_USE_SIGACTION) - arm_ucontext *sigctx = ctx; + arm_ucontext *sigctx = (arm_ucontext*)ctx; /* * Handling the exception in the signal handler is problematic, since the original * signal is disabled, and we could run arbitrary code though the debugger. So @@ -597,7 +597,7 @@ mono_arch_ip_from_context (void *sigctx) #ifdef MONO_CROSS_COMPILE g_assert_not_reached (); #else - arm_ucontext *my_uc = sigctx; + arm_ucontext *my_uc = (arm_ucontext*)sigctx; return (void*) UCONTEXT_REG_PC (my_uc); #endif } @@ -614,7 +614,7 @@ mono_arch_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), g sp -= 16; MONO_CONTEXT_SET_SP (ctx, sp); - mono_arch_setup_resume_sighandler_ctx (ctx, async_cb); + mono_arch_setup_resume_sighandler_ctx (ctx, (gpointer)async_cb); } /* diff --git a/mono/mini/exceptions-arm64.c b/mono/mini/exceptions-arm64.c index f74fced3cd..219b0e1b96 100644 --- a/mono/mini/exceptions-arm64.c +++ b/mono/mini/exceptions-arm64.c @@ -237,9 +237,9 @@ get_throw_trampoline (int size, gboolean corlib, gboolean rethrow, gboolean llvm gpointer icall_func; if (resume_unwind) - icall_func = mono_arm_resume_unwind; + icall_func = (gpointer)mono_arm_resume_unwind; else - icall_func = mono_arm_throw_exception; + icall_func = (gpointer)mono_arm_throw_exception; code = mono_arm_emit_imm64 (code, ARMREG_LR, (guint64)icall_func); } @@ -343,7 +343,7 @@ mono_arm_get_exception_trampolines (gboolean aot) void mono_arch_exceptions_init (void) { - guint8 *tramp; + gpointer tramp; GSList *tramps, *l; if (mono_aot_only) { @@ -356,7 +356,7 @@ mono_arch_exceptions_init (void) } else { tramps = mono_arm_get_exception_trampolines (FALSE); for (l = tramps; l; l = l->next) { - MonoTrampInfo *info = l->data; + MonoTrampInfo *info = (MonoTrampInfo*)l->data; mono_register_jit_icall (info->code, g_strdup (info->name), NULL, TRUE); mono_tramp_info_register (info, NULL); @@ -380,7 +380,7 @@ mono_arm_throw_exception (gpointer arg, mgreg_t pc, mgreg_t *int_regs, gdouble * guint32 ex_token_index, ex_token; if (!corlib) - exc = arg; + exc = (MonoObject*)arg; else { ex_token_index = (guint64)arg; ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index; @@ -469,10 +469,10 @@ mono_arch_unwind_frame (MonoDomain *domain, MonoJitTlsData *jit_tls, for (int i = 0; i < 8; i++) (regs + MONO_MAX_IREGS) [i] = *((mgreg_t*)&new_ctx->fregs [8 + i]); - gboolean success = mono_unwind_frame (unwind_info, unwind_info_len, ji->code_start, + gboolean success = mono_unwind_frame (unwind_info, unwind_info_len, (guint8*)ji->code_start, (guint8*)ji->code_start + ji->code_size, - ip, NULL, regs, MONO_MAX_IREGS + 8, - save_locations, MONO_MAX_IREGS, &cfa); + (guint8*)ip, NULL, regs, MONO_MAX_IREGS + 8, + save_locations, MONO_MAX_IREGS, (guint8**)&cfa); if (!success) return FALSE; @@ -487,7 +487,7 @@ mono_arch_unwind_frame (MonoDomain *domain, MonoJitTlsData *jit_tls, if (*lmf && (*lmf)->gregs [MONO_ARCH_LMF_REG_SP] && (MONO_CONTEXT_GET_SP (ctx) >= (gpointer)(*lmf)->gregs [MONO_ARCH_LMF_REG_SP])) { /* remove any unused lmf */ - *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3); + *lmf = (MonoLMF*)(((gsize)(*lmf)->previous_lmf) & ~3); } /* we substract 1, so that the IP points into the call instruction */ @@ -512,7 +512,7 @@ mono_arch_unwind_frame (MonoDomain *domain, MonoJitTlsData *jit_tls, /* we substract 1, so that the IP points into the call instruction */ new_ctx->pc--; - *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3); + *lmf = (MonoLMF*)(((gsize)(*lmf)->previous_lmf) & ~3); return TRUE; } @@ -533,7 +533,7 @@ handle_signal_exception (gpointer obj) memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext)); - mono_handle_exception (&ctx, obj); + mono_handle_exception (&ctx, (MonoObject*)obj); mono_restore_context (&ctx); } @@ -590,7 +590,7 @@ mono_arch_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), g sp -= 32; MONO_CONTEXT_SET_SP (ctx, sp); - mono_arch_setup_resume_sighandler_ctx (ctx, async_cb); + mono_arch_setup_resume_sighandler_ctx (ctx, (gpointer)async_cb); } /* diff --git a/mono/mini/exceptions-wasm.c b/mono/mini/exceptions-wasm.c index 9c7d26048e..07abc7a10e 100644 --- a/mono/mini/exceptions-wasm.c +++ b/mono/mini/exceptions-wasm.c @@ -54,7 +54,7 @@ mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot) { if (info) *info = mono_tramp_info_create ("call_filter", (guint8*)wasm_call_filter, 1, NULL, NULL); - return wasm_call_filter; + return (gpointer)wasm_call_filter; } gpointer @@ -62,14 +62,14 @@ mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot) { if (info) *info = mono_tramp_info_create ("restore_context", (guint8*)wasm_restore_context, 1, NULL, NULL); - return wasm_restore_context; + return (gpointer)wasm_restore_context; } gpointer mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot) { if (info) *info = mono_tramp_info_create ("throw_corlib_exception", (guint8*)wasm_throw_corlib_exception, 1, NULL, NULL); - return wasm_throw_corlib_exception; + return (gpointer)wasm_throw_corlib_exception; } gpointer @@ -77,7 +77,7 @@ mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot) { if (info) *info = mono_tramp_info_create ("rethrow_exception", (guint8*)wasm_rethrow_exception, 1, NULL, NULL); - return wasm_rethrow_exception; + return (gpointer)wasm_rethrow_exception; } gpointer @@ -85,10 +85,16 @@ mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot) { if (info) *info = mono_tramp_info_create ("throw_exception", (guint8*)wasm_throw_exception, 1, NULL, NULL); - return wasm_throw_exception; + return (gpointer)wasm_throw_exception; } void mono_arch_undo_ip_adjustment (MonoContext *ctx) { } + +gboolean +mono_arch_handle_exception (void *sigctx, gpointer obj) +{ + g_error ("mono_arch_handle_exception"); +} diff --git a/mono/mini/exceptions-x86.c b/mono/mini/exceptions-x86.c index 6f9ec69536..26e147dc11 100644 --- a/mono/mini/exceptions-x86.c +++ b/mono/mini/exceptions-x86.c @@ -135,7 +135,7 @@ mono_win32_get_handle_stackoverflow (void) * - done */ static void -win32_handle_stack_overflow (EXCEPTION_POINTERS* ep, struct sigcontext *sctx) +win32_handle_stack_overflow (EXCEPTION_POINTERS* ep, CONTEXT *sctx) { SYSTEM_INFO si; DWORD page_size; @@ -249,7 +249,7 @@ void win32_seh_init() { /* install restore stack helper */ if (!restore_stack) - restore_stack = mono_win32_get_handle_stackoverflow (); + restore_stack = (void (*) (void*))mono_win32_get_handle_stackoverflow (); mono_old_win_toplevel_exception_filter = SetUnhandledExceptionFilter(seh_unhandled_exception_filter); mono_win_vectored_exception_handle = AddVectoredExceptionHandler (1, seh_vectored_exception_handler); @@ -733,17 +733,18 @@ mono_arch_exceptions_init (void) * or (eventually) Windows 7 SP1. */ #ifdef TARGET_WIN32 - DWORD flags; - FARPROC getter; - FARPROC setter; HMODULE kernel32 = LoadLibraryW (L"kernel32.dll"); - if (kernel32) { - getter = GetProcAddress (kernel32, "GetProcessUserModeExceptionPolicy"); - setter = GetProcAddress (kernel32, "SetProcessUserModeExceptionPolicy"); - if (getter && setter) { - if (getter (&flags)) - setter (flags & ~PROCESS_CALLBACK_FILTER_ENABLED); + typedef BOOL (WINAPI * SetProcessUserModeExceptionPolicy_t) (DWORD dwFlags); + typedef BOOL (WINAPI * GetProcessUserModeExceptionPolicy_t) (PDWORD dwFlags); + GetProcessUserModeExceptionPolicy_t const getter = (GetProcessUserModeExceptionPolicy_t)GetProcAddress (kernel32, "GetProcessUserModeExceptionPolicy"); + if (getter) { + SetProcessUserModeExceptionPolicy_t const setter = (SetProcessUserModeExceptionPolicy_t)GetProcAddress (kernel32, "SetProcessUserModeExceptionPolicy"); + if (setter) { + DWORD flags = 0; + if (getter (&flags)) + setter (flags & ~PROCESS_CALLBACK_FILTER_ENABLED); + } } } #endif @@ -820,9 +821,9 @@ mono_arch_unwind_frame (MonoDomain *domain, MonoJitTlsData *jit_tls, regs [X86_EDI] = new_ctx->edi; regs [X86_NREG] = new_ctx->eip; - gboolean success = mono_unwind_frame (unwind_info, unwind_info_len, ji->code_start, + gboolean success = mono_unwind_frame ((guint8*)unwind_info, unwind_info_len, (guint8*)ji->code_start, (guint8*)ji->code_start + ji->code_size, - ip, NULL, regs, MONO_MAX_IREGS + 1, + (guint8*)ip, NULL, regs, MONO_MAX_IREGS + 1, save_locations, MONO_MAX_IREGS, &cfa); if (!success) @@ -877,7 +878,7 @@ mono_arch_unwind_frame (MonoDomain *domain, MonoJitTlsData *jit_tls, * expression points to a stack location which can be used as ESP */ new_ctx->esp = (unsigned long)&((*lmf)->eip); - *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3); + *lmf = (MonoLMF*)(((gsize)(*lmf)->previous_lmf) & ~3); return TRUE; } @@ -898,7 +899,7 @@ mono_arch_ip_from_context (void *sigctx) ucontext_t *ctx = (ucontext_t*)sigctx; return (gpointer)UCONTEXT_REG_EIP (ctx); #elif defined(HOST_WIN32) - return ((CONTEXT*)sigctx)->Eip; + return (gpointer)((CONTEXT*)sigctx)->Eip; #else struct sigcontext *ctx = sigctx; return (gpointer)ctx->SC_EIP; @@ -918,7 +919,7 @@ handle_signal_exception (gpointer obj) memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext)); - mono_handle_exception (&ctx, obj); + mono_handle_exception (&ctx, (MonoObject*)obj); mono_restore_context (&ctx); } @@ -1018,7 +1019,6 @@ mono_arch_handle_exception (void *sigctx, gpointer obj) #elif defined (TARGET_WIN32) MonoContext mctx; MonoJitTlsData *jit_tls = mono_tls_get_jit_tls (); - struct sigcontext *ctx = (struct sigcontext *)sigctx; mono_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx); @@ -1066,7 +1066,7 @@ static void prepare_for_guard_pages (MonoContext *mctx) { gpointer *sp; - sp = (gpointer)(mctx->esp); + sp = (gpointer*)(mctx->esp); sp -= 1; /* the return addr */ sp [0] = (gpointer)(mctx->eip); @@ -1082,9 +1082,9 @@ altstack_handle_and_restore (MonoContext *ctx, gpointer obj, gboolean stack_ovf) mctx = *ctx; - mono_handle_exception (&mctx, obj); + mono_handle_exception (&mctx, (MonoObject*)obj); if (stack_ovf) { - MonoJitTlsData *jit_tls = (MonoJitTlsData *) mono_tls_get_jit_tls (); + MonoJitTlsData *jit_tls = mono_tls_get_jit_tls (); jit_tls->stack_ovf_pending = 1; prepare_for_guard_pages (&mctx); } @@ -1106,7 +1106,7 @@ mono_arch_handle_altstack_exception (void *sigctx, MONO_SIG_HANDLER_INFO_TYPE *s * we try the lookup again with the return address pushed on the stack */ if (!ji && fault_addr == (gpointer)UCONTEXT_REG_EIP (ctx)) { - glong *sp = (gpointer)UCONTEXT_REG_ESP (ctx); + glong *sp = (glong*)UCONTEXT_REG_ESP (ctx); ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)sp [0], NULL); if (ji) UCONTEXT_REG_EIP (ctx) = sp [0]; @@ -1130,8 +1130,8 @@ mono_arch_handle_altstack_exception (void *sigctx, MONO_SIG_HANDLER_INFO_TYPE *s frame_size = sizeof (MonoContext) + sizeof (gpointer) * 4; frame_size += 15; frame_size &= ~15; - sp = (gpointer)(UCONTEXT_REG_ESP (ctx) & ~15); - sp = (gpointer)((char*)sp - frame_size); + sp = (gpointer*)(UCONTEXT_REG_ESP (ctx) & ~15); + sp = (gpointer*)((char*)sp - frame_size); /* the incoming arguments are aligned to 16 bytes boundaries, so the return address IP * goes at sp [-1] */ diff --git a/mono/mini/gshared.cs b/mono/mini/gshared.cs index 1a7062190d..06e1865722 100644 --- a/mono/mini/gshared.cs +++ b/mono/mini/gshared.cs @@ -1350,6 +1350,8 @@ public class Tests // FIXME: The runtime-invoke wrapper used by BeginInvoke is not found [Category ("!FULLAOT")] + // FIXME: Wasm is single threaded and can't handle blocking waits + [Category ("!WASM")] public static int test_0_begin_end_invoke () { IFace6 o = new Class6 (); var arr1 = o.Del (1); diff --git a/mono/mini/helpers.c b/mono/mini/helpers.c index 1e37c6a3e4..3cafc343df 100644 --- a/mono/mini/helpers.c +++ b/mono/mini/helpers.c @@ -43,8 +43,8 @@ static const struct msgstr_t { #undef MINI_OP3 }; static const gint16 opidx [] = { -#define MINI_OP(a,b,dest,src1,src2) [a - OP_LOAD] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)), -#define MINI_OP3(a,b,dest,src1,src2,src3) [a - OP_LOAD] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)), +#define MINI_OP(a,b,dest,src1,src2) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)), +#define MINI_OP3(a,b,dest,src1,src2,src3) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)), #include "mini-ops.h" #undef MINI_OP #undef MINI_OP3 diff --git a/mono/mini/image-writer.c b/mono/mini/image-writer.c index 94cc996dbb..5e51a891aa 100644 --- a/mono/mini/image-writer.c +++ b/mono/mini/image-writer.c @@ -74,7 +74,7 @@ #define AS_INT32_DIRECTIVE ".long" #define AS_INT64_DIRECTIVE ".quad" -#if (defined(TARGET_AMD64) || defined(TARGET_POWERPC64)) && !defined(__mono_ilp32__) +#if (defined(TARGET_AMD64) || defined(TARGET_POWERPC64)) && !defined(MONO_ARCH_ILP32) #define AS_POINTER_DIRECTIVE ".quad" #elif defined(TARGET_ARM64) diff --git a/mono/mini/interp-stubs.c b/mono/mini/interp-stubs.c index 81eee0d1dc..83aa8520d6 100644 --- a/mono/mini/interp-stubs.c +++ b/mono/mini/interp-stubs.c @@ -81,13 +81,13 @@ stub_set_resume_state (MonoJitTlsData *jit_tls, MonoException *ex, MonoJitExcept } static gboolean -stub_run_finally (StackFrameInfo *frame, int clause_index, gpointer handler_ip) +stub_run_finally (StackFrameInfo *frame, int clause_index, gpointer handler_ip, gpointer handler_ip_end) { g_assert_not_reached (); } static gboolean -stub_run_filter (StackFrameInfo *frame, MonoException *ex, int clause_index, gpointer handler_ip) +stub_run_filter (StackFrameInfo *frame, MonoException *ex, int clause_index, gpointer handler_ip, gpointer handler_ip_end) { g_assert_not_reached (); return FALSE; @@ -133,12 +133,6 @@ stub_get_remoting_invoke (gpointer imethod, MonoError *error) return NULL; } -static void -stub_walk_stack_with_ctx (MonoInternalStackWalk func, MonoContext *ctx, MonoUnwindOptions options, void *user_data) -{ - g_assert_not_reached (); -} - static void stub_delegate_ctor (MonoObjectHandle this_obj, MonoObjectHandle target, gpointer addr, MonoError *error) { diff --git a/mono/mini/interp/hacks.h b/mono/mini/interp/hacks.h deleted file mode 100644 index 0499e04518..0000000000 --- a/mono/mini/interp/hacks.h +++ /dev/null @@ -1,82 +0,0 @@ -/** - * \file - */ - -/* we need some special math function */ -#ifndef _ISOC99_SOURCE -#define _ISOC99_SOURCE -#endif -#include - -/* which are not defined on FreeBSD */ -#ifdef __GNUC__ - -#ifndef isunordered -# define isunordered(u, v) \ - (__extension__ \ - ({ __typeof__(u) __u = (u); __typeof__(v) __v = (v); \ - isnan(__u) || isnan(__v); })) -#endif - -#ifndef islessgreater -# define islessgreater(x, u) \ - (__extension__ \ - ({ __typeof__(x) __x = (x); __typeof__(y) __y = (y); \ - !isunordered (__x, __y) && (__x < __y) || (__y < __x); })) -#endif - -#ifndef islessequal -# define islessequal(x, y) \ - (__extension__ \ - ({ __typeof__(x) __x = (x); __typeof__(y) __y = (y); \ - !isunordered(__x, __y) && __x <= __y; })) -#endif - -#ifndef isless -# define isless(x, y) \ - (__extension__ \ - ({ __typeof__(x) __x = (x); __typeof__(y) __y = (y); \ - !isunordered(__x, __y) && __x < __y; })) -#endif - -#ifndef isgreater -# define isgreater(x, y) \ - (__extension__ \ - ({ __typeof__(x) __x = (x); __typeof__(y) __y = (y); \ - !isunordered(__x, __y) && __x > __y; })) -#endif - -#else - -/* isunordered seems to crash on HPUX when built 64 bits - so use generic implementation. -*/ -#if defined(__hpux) && SIZEOF_VOID_P == 8 -#undef isunordered -#undef islessgreater -#undef islessequal -#undef isless -#undef isgreater -#endif - -#ifndef isunordered -# define isunordered(u, v) (isnan(u) || isnan(v)) -#endif - -#ifndef islessgreater -# define islessgreater(x, u) (!isunordered (x, y) && (x < y) || (y < x)) -#endif - -#ifndef islessequal -# define islessequal(x, y) (!isunordered(x, y) && x <= y) -#endif - -#ifndef isless -# define isless(x, y) (!isunordered(x, y) && x < y) -#endif - -#ifndef isgreater -# define isgreater(x, y) (!isunordered(x, y) && x > y) -#endif - -#endif diff --git a/mono/mini/interp/interp-internals.h b/mono/mini/interp/interp-internals.h index 9839ea5f8e..cda481539b 100644 --- a/mono/mini/interp/interp-internals.h +++ b/mono/mini/interp/interp-internals.h @@ -146,7 +146,7 @@ typedef struct { /* Frame to resume execution at */ InterpFrame *handler_frame; /* IP to resume execution at */ - gpointer handler_ip; + guint16 *handler_ip; /* Clause that we are resuming to */ MonoJitExceptionInfo *handler_ei; } ThreadContext; diff --git a/mono/mini/interp/interp.c.REMOVED.git-id b/mono/mini/interp/interp.c.REMOVED.git-id index 4087ea5ae8..e433546f57 100644 --- a/mono/mini/interp/interp.c.REMOVED.git-id +++ b/mono/mini/interp/interp.c.REMOVED.git-id @@ -1 +1 @@ -066fc9252ced717afe366726964927f11e0e2cb3 \ No newline at end of file +5aae1e15aa2e5c42694fa32721be0373be769220 \ No newline at end of file diff --git a/mono/mini/interp/transform.c.REMOVED.git-id b/mono/mini/interp/transform.c.REMOVED.git-id index fba1bae61d..5ed4b72a14 100644 --- a/mono/mini/interp/transform.c.REMOVED.git-id +++ b/mono/mini/interp/transform.c.REMOVED.git-id @@ -1 +1 @@ -2a7a249617188d9e97b8e106452394a3e4f6930e \ No newline at end of file +ad08a3f5d44aded67a94f61f650dd8e30aeecea2 \ No newline at end of file diff --git a/mono/mini/intrinsics.c b/mono/mini/intrinsics.c index 4d94c455be..48cb57a6c8 100644 --- a/mono/mini/intrinsics.c +++ b/mono/mini/intrinsics.c @@ -124,7 +124,7 @@ llvm_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSign if (opcode) { MONO_INST_NEW (cfg, ins, opcode); ins->type = STACK_R8; - ins->dreg = mono_alloc_dreg (cfg, ins->type); + ins->dreg = mono_alloc_dreg (cfg, (MonoStackType)ins->type); ins->sreg1 = args [0]->dreg; if (fsig->param_count == 2) ins->sreg2 = args [1]->dreg; @@ -146,7 +146,7 @@ llvm_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSign if (opcode && fsig->param_count == 1) { MONO_INST_NEW (cfg, ins, opcode); ins->type = STACK_R8; - ins->dreg = mono_alloc_dreg (cfg, ins->type); + ins->dreg = mono_alloc_dreg (cfg, (MonoStackType)ins->type); ins->sreg1 = args [0]->dreg; MONO_ADD_INS (cfg->cbb, ins); } @@ -177,7 +177,7 @@ llvm_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSign if (opcode && fsig->param_count == 2) { MONO_INST_NEW (cfg, ins, opcode); ins->type = fsig->params [0]->type == MONO_TYPE_I4 ? STACK_I4 : STACK_I8; - ins->dreg = mono_alloc_dreg (cfg, ins->type); + ins->dreg = mono_alloc_dreg (cfg, (MonoStackType)ins->type); ins->sreg1 = args [0]->dreg; ins->sreg2 = args [1]->dreg; MONO_ADD_INS (cfg->cbb, ins); @@ -1390,4 +1390,23 @@ mini_emit_inst_for_sharable_method (MonoCompile *cfg, MonoMethod *cmethod, MonoM return NULL; } +MonoInst* +mini_emit_inst_for_field_load (MonoCompile *cfg, MonoClassField *field) +{ + MonoClass *klass = field->parent; + const char *klass_name_space = m_class_get_name_space (klass); + const char *klass_name = m_class_get_name (klass); + MonoImage *klass_image = m_class_get_image (klass); + gboolean in_corlib = klass_image == mono_defaults.corlib; + gboolean is_le; + MonoInst *ins; + + if (in_corlib && !strcmp (klass_name_space, "System") && !strcmp (klass_name, "BitConverter") && !strcmp (field->name, "IsLittleEndian")) { + is_le = (TARGET_BYTE_ORDER == G_LITTLE_ENDIAN); + EMIT_NEW_ICONST (cfg, ins, is_le); + return ins; + } + return NULL; +} + #endif diff --git a/mono/mini/ir-emit.h b/mono/mini/ir-emit.h index ea2a151af2..2c556688f1 100644 --- a/mono/mini/ir-emit.h +++ b/mono/mini/ir-emit.h @@ -233,8 +233,8 @@ alloc_dreg (MonoCompile *cfg, MonoStackType stack_type) #define NEW_PATCH_INFO(cfg,dest,el1,el2) do { \ MONO_INST_NEW ((cfg), (dest), OP_PATCH_INFO); \ - (dest)->inst_left = (gpointer)(el1); \ - (dest)->inst_right = (gpointer)(el2); \ + (dest)->inst_left = (MonoInst*)(el1); \ + (dest)->inst_right = (MonoInst*)(el2); \ } while (0) #define NEW_AOTCONST_GOT_VAR(cfg,dest,patch_type,cons) do { \ @@ -247,7 +247,7 @@ alloc_dreg (MonoCompile *cfg, MonoStackType stack_type) (dest)->inst_p1 = group; \ } else { \ (dest)->inst_p0 = (cons); \ - (dest)->inst_i1 = (gpointer)(patch_type); \ + (dest)->inst_i1 = (MonoInst*)(patch_type); \ } \ (dest)->type = STACK_PTR; \ (dest)->dreg = alloc_dreg ((cfg), STACK_PTR); \ @@ -324,7 +324,7 @@ alloc_dreg (MonoCompile *cfg, MonoStackType stack_type) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_METHOD_RGCTX, (method)); \ } else { \ MonoMethodRuntimeGenericContext *mrgctx; \ - mrgctx = mini_method_get_rgctx ((method)); \ + mrgctx = (MonoMethodRuntimeGenericContext*)mini_method_get_rgctx ((method)); \ NEW_PCONST ((cfg), (dest), (mrgctx)); \ } \ } while (0) @@ -700,7 +700,7 @@ handle_gsharedvt_ldaddr (MonoCompile *cfg) MONO_INST_NEW ((cfg), (inst), (op)); \ inst->dreg = dr; \ inst->sreg1 = sr; \ - inst->inst_imm = (mgreg_t)(imm); \ + inst->inst_imm = (target_mgreg_t)(imm); \ MONO_ADD_INS (cfg->cbb, inst); \ } while (0) diff --git a/mono/mini/jit-icalls.c b/mono/mini/jit-icalls.c index b93f0e192a..68739ce394 100644 --- a/mono/mini/jit-icalls.c +++ b/mono/mini/jit-icalls.c @@ -26,6 +26,7 @@ #include #include #include +#include #ifdef ENABLE_LLVM #include "mini-llvm-cpp.h" @@ -666,17 +667,6 @@ mono_fclt_un (double a, double b) return isunordered (a, b) || a < b; } -gboolean -mono_isfinite (double a) -{ -#ifdef HAVE_ISFINITE - return isfinite (a); -#else - g_assert_not_reached (); - return TRUE; -#endif -} - double mono_fload_r4 (float *ptr) { @@ -717,14 +707,14 @@ mono_array_new_va (MonoMethod *cm, ...) va_start (ap, cm); - lengths = (uintptr_t *)alloca (sizeof (uintptr_t) * pcount); + lengths = g_newa (uintptr_t, pcount); for (i = 0; i < pcount; ++i) lengths [i] = d = va_arg(ap, int); if (rank == pcount) { /* Only lengths provided. */ if (m_class_get_byval_arg (cm->klass)->type == MONO_TYPE_ARRAY) { - lower_bounds = (intptr_t *)alloca (sizeof (intptr_t) * rank); + lower_bounds = g_newa (intptr_t, rank); memset (lower_bounds, 0, sizeof (intptr_t) * rank); } else { lower_bounds = NULL; @@ -767,7 +757,7 @@ mono_array_new_1 (MonoMethod *cm, guint32 length) g_assert (rank == pcount); if (m_class_get_byval_arg (cm->klass)->type == MONO_TYPE_ARRAY) { - lower_bounds = (intptr_t *)alloca (sizeof (intptr_t) * rank); + lower_bounds = g_newa (intptr_t, rank); memset (lower_bounds, 0, sizeof (intptr_t) * rank); } else { lower_bounds = NULL; @@ -803,7 +793,7 @@ mono_array_new_2 (MonoMethod *cm, guint32 length1, guint32 length2) g_assert (rank == pcount); if (m_class_get_byval_arg (cm->klass)->type == MONO_TYPE_ARRAY) { - lower_bounds = (intptr_t *)alloca (sizeof (intptr_t) * rank); + lower_bounds = g_newa (intptr_t, rank); memset (lower_bounds, 0, sizeof (intptr_t) * rank); } else { lower_bounds = NULL; @@ -840,7 +830,7 @@ mono_array_new_3 (MonoMethod *cm, guint32 length1, guint32 length2, guint32 leng g_assert (rank == pcount); if (m_class_get_byval_arg (cm->klass)->type == MONO_TYPE_ARRAY) { - lower_bounds = (intptr_t *)alloca (sizeof (intptr_t) * rank); + lower_bounds = g_newa (intptr_t, rank); memset (lower_bounds, 0, sizeof (intptr_t) * rank); } else { lower_bounds = NULL; @@ -878,7 +868,7 @@ mono_array_new_4 (MonoMethod *cm, guint32 length1, guint32 length2, guint32 leng g_assert (rank == pcount); if (m_class_get_byval_arg (cm->klass)->type == MONO_TYPE_ARRAY) { - lower_bounds = (intptr_t *)alloca (sizeof (intptr_t) * rank); + lower_bounds = g_newa (intptr_t, rank); memset (lower_bounds, 0, sizeof (intptr_t) * rank); } else { lower_bounds = NULL; @@ -990,31 +980,17 @@ guint32 mono_fconv_u4 (double v) { /* MS.NET behaves like this for some reason */ -#ifdef HAVE_ISINF - if (isinf (v) || isnan (v)) + if (mono_isinf (v) || mono_isnan (v)) return 0; -#endif - return (guint32)v; } -#ifndef HAVE_TRUNC -/* Solaris doesn't have trunc */ -#ifdef HAVE_AINTL -extern long double aintl (long double); -#define trunc aintl -#else -/* FIXME: This means we will never throw overflow exceptions */ -#define trunc(v) res -#endif -#endif /* HAVE_TRUNC */ - gint64 mono_fconv_ovf_i8 (double v) { const gint64 res = (gint64)v; - if (isnan(v) || trunc (v) != res) { + if (mono_isnan (v) || mono_trunc (v) != res) { ERROR_DECL (error); mono_error_set_overflow (error); mono_error_set_pending_exception (error); @@ -1038,7 +1014,7 @@ mono_fconv_ovf_u8 (double v) * To work around this issue we test for value boundaries instead. */ #if defined(__arm__) && defined(MONO_ARCH_SOFT_FLOAT_FALLBACK) - if (isnan (v) || !(v >= -0.5 && v <= ULLONG_MAX+0.5)) { + if (mono_isnan (v) || !(v >= -0.5 && v <= ULLONG_MAX+0.5)) { ERROR_DECL (error); mono_error_set_overflow (error); mono_error_set_pending_exception (error); @@ -1047,7 +1023,7 @@ mono_fconv_ovf_u8 (double v) res = (guint64)v; #else res = (guint64)v; - if (isnan(v) || trunc (v) != res) { + if (mono_isnan (v) || mono_trunc (v) != res) { ERROR_DECL (error); mono_error_set_overflow (error); mono_error_set_pending_exception (error); @@ -1070,7 +1046,7 @@ mono_rconv_ovf_i8 (float v) { const gint64 res = (gint64)v; - if (isnan(v) || trunc (v) != res) { + if (mono_isnan (v) || mono_trunc (v) != res) { ERROR_DECL (error); mono_error_set_overflow (error); mono_error_set_pending_exception (error); @@ -1085,7 +1061,7 @@ mono_rconv_ovf_u8 (float v) guint64 res; res = (guint64)v; - if (isnan(v) || trunc (v) != res) { + if (mono_isnan (v) || mono_trunc (v) != res) { ERROR_DECL (error); mono_error_set_overflow (error); mono_error_set_pending_exception (error); @@ -1254,7 +1230,7 @@ mono_object_castclass_unbox (MonoObject *obj, MonoClass *klass) MonoClass *oklass; if (mini_get_debug_options ()->better_cast_details) { - jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls (); + jit_tls = mono_tls_get_jit_tls (); jit_tls->class_cast_from = NULL; } @@ -1288,7 +1264,7 @@ mono_object_castclass_with_cache (MonoObject *obj, MonoClass *klass, gpointer *c gpointer cached_vtable, obj_vtable; if (mini_get_debug_options ()->better_cast_details) { - jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls (); + jit_tls = mono_tls_get_jit_tls (); jit_tls->class_cast_from = NULL; } @@ -1577,7 +1553,7 @@ static gpointer resolve_iface_call (MonoObject *this_obj, int imt_slot, MonoMethod *imt_method, gpointer *out_arg, gboolean caller_gsharedvt, MonoError *error) { MonoVTable *vt; - gpointer *imt, *vtable_slot; + gpointer *imt; MonoMethod *impl_method, *generic_virtual = NULL, *variant_iface = NULL; gpointer addr, compiled_method, aot_addr; gboolean need_rgctx_tramp = FALSE, need_unbox_tramp = FALSE; @@ -1590,7 +1566,7 @@ resolve_iface_call (MonoObject *this_obj, int imt_slot, MonoMethod *imt_method, vt = this_obj->vtable; imt = (gpointer*)vt - MONO_IMT_SIZE; - vtable_slot = mini_resolve_imt_method (vt, imt + imt_slot, imt_method, &impl_method, &aot_addr, &need_rgctx_tramp, &variant_iface, error); + mini_resolve_imt_method (vt, imt + imt_slot, imt_method, &impl_method, &aot_addr, &need_rgctx_tramp, &variant_iface, error); return_val_if_nok (error, NULL); // FIXME: This can throw exceptions @@ -1915,7 +1891,7 @@ mono_llvmonly_init_delegate (MonoDelegate *del) ftndesc = mini_create_llvmonly_ftndesc (mono_domain_get (), addr, arg); mono_memory_barrier (); - *del->method_code = (gpointer)ftndesc; + *del->method_code = (guint8*)ftndesc; } del->method_ptr = ftndesc->addr; del->extra_arg = ftndesc->arg; @@ -1963,7 +1939,7 @@ mono_get_method_object (MonoMethod *method) double mono_ckfinite (double d) { - if (isinf (d) || isnan (d)) + if (mono_isinf (d) || mono_isnan (d)) mono_set_pending_exception (mono_get_exception_arithmetic ()); return d; } diff --git a/mono/mini/jit-icalls.h b/mono/mini/jit-icalls.h index c41cf78bf8..552485e1bd 100644 --- a/mono/mini/jit-icalls.h +++ b/mono/mini/jit-icalls.h @@ -9,189 +9,185 @@ #include "mini.h" #include -void* mono_ldftn (MonoMethod *method); +G_EXTERN_C void* mono_ldftn (MonoMethod *method); -void* mono_ldvirtfn (MonoObject *obj, MonoMethod *method); +G_EXTERN_C void* mono_ldvirtfn (MonoObject *obj, MonoMethod *method); -void* mono_ldvirtfn_gshared (MonoObject *obj, MonoMethod *method); +G_EXTERN_C void* mono_ldvirtfn_gshared (MonoObject *obj, MonoMethod *method); -void mono_helper_stelem_ref_check (MonoArray *array, MonoObject *val); +G_EXTERN_C void mono_helper_stelem_ref_check (MonoArray *array, MonoObject *val); -gint64 mono_llmult (gint64 a, gint64 b); +G_EXTERN_C gint64 mono_llmult (gint64 a, gint64 b); -guint64 mono_llmult_ovf_un (guint64 a, guint64 b); +G_EXTERN_C guint64 mono_llmult_ovf_un (guint64 a, guint64 b); -guint64 mono_llmult_ovf (gint64 a, gint64 b); +G_EXTERN_C guint64 mono_llmult_ovf (gint64 a, gint64 b); -gint32 mono_idiv (gint32 a, gint32 b); +G_EXTERN_C gint32 mono_idiv (gint32 a, gint32 b); -guint32 mono_idiv_un (guint32 a, guint32 b); +G_EXTERN_C guint32 mono_idiv_un (guint32 a, guint32 b); -gint32 mono_irem (gint32 a, gint32 b); +G_EXTERN_C gint32 mono_irem (gint32 a, gint32 b); -guint32 mono_irem_un (guint32 a, guint32 b); +G_EXTERN_C guint32 mono_irem_un (guint32 a, guint32 b); -gint32 mono_imul (gint32 a, gint32 b); +G_EXTERN_C gint32 mono_imul (gint32 a, gint32 b); -gint32 mono_imul_ovf (gint32 a, gint32 b); +G_EXTERN_C gint32 mono_imul_ovf (gint32 a, gint32 b); -gint32 mono_imul_ovf_un (guint32 a, guint32 b); +G_EXTERN_C gint32 mono_imul_ovf_un (guint32 a, guint32 b); -double mono_fdiv (double a, double b); +G_EXTERN_C double mono_fdiv (double a, double b); -gint64 mono_lldiv (gint64 a, gint64 b); +G_EXTERN_C gint64 mono_lldiv (gint64 a, gint64 b); -gint64 mono_llrem (gint64 a, gint64 b); +G_EXTERN_C gint64 mono_llrem (gint64 a, gint64 b); -guint64 mono_lldiv_un (guint64 a, guint64 b); +G_EXTERN_C guint64 mono_lldiv_un (guint64 a, guint64 b); -guint64 mono_llrem_un (guint64 a, guint64 b); +G_EXTERN_C guint64 mono_llrem_un (guint64 a, guint64 b); -guint64 mono_lshl (guint64 a, gint32 shamt); +G_EXTERN_C guint64 mono_lshl (guint64 a, gint32 shamt); -guint64 mono_lshr_un (guint64 a, gint32 shamt); +G_EXTERN_C guint64 mono_lshr_un (guint64 a, gint32 shamt); -gint64 mono_lshr (gint64 a, gint32 shamt); +G_EXTERN_C gint64 mono_lshr (gint64 a, gint32 shamt); -MonoArray *mono_array_new_va (MonoMethod *cm, ...); +G_EXTERN_C MonoArray *mono_array_new_va (MonoMethod *cm, ...); -MonoArray *mono_array_new_1 (MonoMethod *cm, guint32 length); +G_EXTERN_C MonoArray *mono_array_new_1 (MonoMethod *cm, guint32 length); -MonoArray *mono_array_new_2 (MonoMethod *cm, guint32 length1, guint32 length2); +G_EXTERN_C MonoArray *mono_array_new_2 (MonoMethod *cm, guint32 length1, guint32 length2); -MonoArray *mono_array_new_3 (MonoMethod *cm, guint32 length1, guint32 length2, guint32 length3); +G_EXTERN_C MonoArray *mono_array_new_3 (MonoMethod *cm, guint32 length1, guint32 length2, guint32 length3); -MonoArray *mono_array_new_4 (MonoMethod *cm, guint32 length1, guint32 length2, guint32 length3, guint32 length4); +G_EXTERN_C MonoArray *mono_array_new_4 (MonoMethod *cm, guint32 length1, guint32 length2, guint32 length3, guint32 length4); -gpointer mono_class_static_field_address (MonoDomain *domain, MonoClassField *field); +G_EXTERN_C gpointer mono_class_static_field_address (MonoDomain *domain, MonoClassField *field); -gpointer mono_ldtoken_wrapper (MonoImage *image, int token, MonoGenericContext *context); +G_EXTERN_C gpointer mono_ldtoken_wrapper (MonoImage *image, int token, MonoGenericContext *context); -gpointer mono_ldtoken_wrapper_generic_shared (MonoImage *image, int token, MonoMethod *method); +G_EXTERN_C gpointer mono_ldtoken_wrapper_generic_shared (MonoImage *image, int token, MonoMethod *method); -guint64 mono_fconv_u8 (double v); +G_EXTERN_C guint64 mono_fconv_u8 (double v); -guint64 mono_rconv_u8 (float v); +G_EXTERN_C guint64 mono_rconv_u8 (float v); -gint64 mono_fconv_i8 (double v); +G_EXTERN_C gint64 mono_fconv_i8 (double v); -guint32 mono_fconv_u4 (double v); +G_EXTERN_C guint32 mono_fconv_u4 (double v); -gint64 mono_fconv_ovf_i8 (double v); +G_EXTERN_C gint64 mono_fconv_ovf_i8 (double v); -guint64 mono_fconv_ovf_u8 (double v); +G_EXTERN_C guint64 mono_fconv_ovf_u8 (double v); -gint64 mono_rconv_i8 (float v); +G_EXTERN_C gint64 mono_rconv_i8 (float v); -gint64 mono_rconv_ovf_i8 (float v); +G_EXTERN_C gint64 mono_rconv_ovf_i8 (float v); -guint64 mono_rconv_ovf_u8 (float v); +G_EXTERN_C guint64 mono_rconv_ovf_u8 (float v); -double mono_lconv_to_r8 (gint64 a); +G_EXTERN_C double mono_lconv_to_r8 (gint64 a); -double mono_conv_to_r8 (gint32 a); +G_EXTERN_C double mono_conv_to_r8 (gint32 a); -double mono_conv_to_r4 (gint32 a); +G_EXTERN_C double mono_conv_to_r4 (gint32 a); -float mono_lconv_to_r4 (gint64 a); +G_EXTERN_C float mono_lconv_to_r4 (gint64 a); -double mono_conv_to_r8_un (guint32 a); +G_EXTERN_C double mono_conv_to_r8_un (guint32 a); -double mono_lconv_to_r8_un (guint64 a); +G_EXTERN_C double mono_lconv_to_r8_un (guint64 a); -gpointer mono_helper_compile_generic_method (MonoObject *obj, MonoMethod *method, gpointer *this_arg); +G_EXTERN_C gpointer mono_helper_compile_generic_method (MonoObject *obj, MonoMethod *method, gpointer *this_arg); ICALL_EXPORT MonoString* ves_icall_mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 idx); -MonoString *mono_helper_ldstr (MonoImage *image, guint32 idx); +G_EXTERN_C MonoString *mono_helper_ldstr (MonoImage *image, guint32 idx); -MonoString *mono_helper_ldstr_mscorlib (guint32 idx); +G_EXTERN_C MonoString *mono_helper_ldstr_mscorlib (guint32 idx); -MonoObject *mono_helper_newobj_mscorlib (guint32 idx); +G_EXTERN_C MonoObject *mono_helper_newobj_mscorlib (guint32 idx); -double mono_fsub (double a, double b); +G_EXTERN_C double mono_fsub (double a, double b); -double mono_fadd (double a, double b); +G_EXTERN_C double mono_fadd (double a, double b); -double mono_fmul (double a, double b); +G_EXTERN_C double mono_fmul (double a, double b); -double mono_fneg (double a); +G_EXTERN_C double mono_fneg (double a); -double mono_fconv_r4 (double a); +G_EXTERN_C double mono_fconv_r4 (double a); -gint8 mono_fconv_i1 (double a); +G_EXTERN_C gint8 mono_fconv_i1 (double a); -gint16 mono_fconv_i2 (double a); +G_EXTERN_C gint16 mono_fconv_i2 (double a); -gint32 mono_fconv_i4 (double a); +G_EXTERN_C gint32 mono_fconv_i4 (double a); -guint8 mono_fconv_u1 (double a); +G_EXTERN_C guint8 mono_fconv_u1 (double a); -guint16 mono_fconv_u2 (double a); +G_EXTERN_C guint16 mono_fconv_u2 (double a); -gboolean mono_fcmp_eq (double a, double b); +G_EXTERN_C gboolean mono_fcmp_eq (double a, double b); -gboolean mono_fcmp_ge (double a, double b); +G_EXTERN_C gboolean mono_fcmp_ge (double a, double b); -gboolean mono_fcmp_gt (double a, double b); +G_EXTERN_C gboolean mono_fcmp_gt (double a, double b); -gboolean mono_fcmp_le (double a, double b); +G_EXTERN_C gboolean mono_fcmp_le (double a, double b); -gboolean mono_fcmp_lt (double a, double b); +G_EXTERN_C gboolean mono_fcmp_lt (double a, double b); -gboolean mono_fcmp_ne_un (double a, double b); +G_EXTERN_C gboolean mono_fcmp_ne_un (double a, double b); -gboolean mono_fcmp_ge_un (double a, double b); +G_EXTERN_C gboolean mono_fcmp_ge_un (double a, double b); -gboolean mono_fcmp_gt_un (double a, double b); +G_EXTERN_C gboolean mono_fcmp_gt_un (double a, double b); -gboolean mono_fcmp_le_un (double a, double b); +G_EXTERN_C gboolean mono_fcmp_le_un (double a, double b); -gboolean mono_fcmp_lt_un (double a, double b); +G_EXTERN_C gboolean mono_fcmp_lt_un (double a, double b); -gboolean mono_fceq (double a, double b); +G_EXTERN_C gboolean mono_fceq (double a, double b); -gboolean mono_fcgt (double a, double b); +G_EXTERN_C gboolean mono_fcgt (double a, double b); -gboolean mono_fcgt_un (double a, double b); +G_EXTERN_C gboolean mono_fcgt_un (double a, double b); -gboolean mono_fclt (double a, double b); +G_EXTERN_C gboolean mono_fclt (double a, double b); -gboolean mono_fclt_un (double a, double b); +G_EXTERN_C gboolean mono_fclt_un (double a, double b); -gboolean mono_isfinite (double a); +G_EXTERN_C double mono_fload_r4 (float *ptr); -double mono_fload_r4 (float *ptr); +G_EXTERN_C void mono_fstore_r4 (double val, float *ptr); -void mono_fstore_r4 (double val, float *ptr); +G_EXTERN_C guint32 mono_fload_r4_arg (double val); -guint32 mono_fload_r4_arg (double val); +G_EXTERN_C void mono_break (void); -void mono_break (void); +G_EXTERN_C MonoException *mono_create_corlib_exception_0 (guint32 token); -MonoException *mono_create_corlib_exception_0 (guint32 token); +G_EXTERN_C MonoException *mono_create_corlib_exception_1 (guint32 token, MonoString *arg); -MonoException *mono_create_corlib_exception_1 (guint32 token, MonoString *arg); +G_EXTERN_C MonoException *mono_create_corlib_exception_2 (guint32 token, MonoString *arg1, MonoString *arg2); -MonoException *mono_create_corlib_exception_2 (guint32 token, MonoString *arg1, MonoString *arg2); +G_EXTERN_C MonoObject* mono_object_castclass_unbox (MonoObject *obj, MonoClass *klass); -MonoObject* mono_object_castclass_unbox (MonoObject *obj, MonoClass *klass); +G_EXTERN_C gpointer mono_get_native_calli_wrapper (MonoImage *image, MonoMethodSignature *sig, gpointer func); -gpointer mono_get_native_calli_wrapper (MonoImage *image, MonoMethodSignature *sig, gpointer func); +G_EXTERN_C MonoObject* mono_object_isinst_with_cache (MonoObject *obj, MonoClass *klass, gpointer *cache); -MonoObject* -mono_object_isinst_with_cache (MonoObject *obj, MonoClass *klass, gpointer *cache); - -MonoObject* -mono_object_castclass_with_cache (MonoObject *obj, MonoClass *klass, gpointer *cache); +G_EXTERN_C MonoObject* mono_object_castclass_with_cache (MonoObject *obj, MonoClass *klass, gpointer *cache); ICALL_EXPORT void ves_icall_runtime_class_init (MonoVTable *vtable); -void +G_EXTERN_C void mono_generic_class_init (MonoVTable *vtable); ICALL_EXPORT @@ -202,37 +198,36 @@ ICALL_EXPORT void ves_icall_mono_delegate_ctor_interp (MonoObject *this_obj, MonoObject *target, gpointer addr); -MonoObject* -mono_gsharedvt_constrained_call (gpointer mp, MonoMethod *cmethod, MonoClass *klass, gboolean deref_arg, gpointer *args); +G_EXTERN_C MonoObject* mono_gsharedvt_constrained_call (gpointer mp, MonoMethod *cmethod, MonoClass *klass, gboolean deref_arg, gpointer *args); -void mono_gsharedvt_value_copy (gpointer dest, gpointer src, MonoClass *klass); +G_EXTERN_C void mono_gsharedvt_value_copy (gpointer dest, gpointer src, MonoClass *klass); -gpointer mono_fill_class_rgctx (MonoVTable *vtable, int index); +G_EXTERN_C gpointer mono_fill_class_rgctx (MonoVTable *vtable, int index); -gpointer mono_fill_method_rgctx (MonoMethodRuntimeGenericContext *mrgctx, int index); +G_EXTERN_C gpointer mono_fill_method_rgctx (MonoMethodRuntimeGenericContext *mrgctx, int index); -gpointer mono_resolve_iface_call_gsharedvt (MonoObject *this_obj, int imt_slot, MonoMethod *imt_method, gpointer *out_arg); +G_EXTERN_C gpointer mono_resolve_iface_call_gsharedvt (MonoObject *this_obj, int imt_slot, MonoMethod *imt_method, gpointer *out_arg); -gpointer mono_resolve_vcall_gsharedvt (MonoObject *this_obj, int imt_slot, MonoMethod *imt_method, gpointer *out_arg); +G_EXTERN_C gpointer mono_resolve_vcall_gsharedvt (MonoObject *this_obj, int imt_slot, MonoMethod *imt_method, gpointer *out_arg); -MonoFtnDesc* mono_resolve_generic_virtual_call (MonoVTable *vt, int slot, MonoMethod *imt_method); +G_EXTERN_C MonoFtnDesc* mono_resolve_generic_virtual_call (MonoVTable *vt, int slot, MonoMethod *imt_method); -MonoFtnDesc* mono_resolve_generic_virtual_iface_call (MonoVTable *vt, int imt_slot, MonoMethod *imt_method); +G_EXTERN_C MonoFtnDesc* mono_resolve_generic_virtual_iface_call (MonoVTable *vt, int imt_slot, MonoMethod *imt_method); -gpointer mono_init_vtable_slot (MonoVTable *vtable, int slot); +G_EXTERN_C gpointer mono_init_vtable_slot (MonoVTable *vtable, int slot); -void mono_llvmonly_init_delegate (MonoDelegate *del); +G_EXTERN_C void mono_llvmonly_init_delegate (MonoDelegate *del); -void mono_llvmonly_init_delegate_virtual (MonoDelegate *del, MonoObject *target, MonoMethod *method); +G_EXTERN_C void mono_llvmonly_init_delegate_virtual (MonoDelegate *del, MonoObject *target, MonoMethod *method); -MonoObject* mono_get_assembly_object (MonoImage *image); +G_EXTERN_C MonoObject* mono_get_assembly_object (MonoImage *image); -MonoObject* mono_get_method_object (MonoMethod *method); +G_EXTERN_C MonoObject* mono_get_method_object (MonoMethod *method); -double mono_ckfinite (double d); +G_EXTERN_C double mono_ckfinite (double d); -void mono_throw_method_access (MonoMethod *caller, MonoMethod *callee); +G_EXTERN_C void mono_throw_method_access (MonoMethod *caller, MonoMethod *callee); -void mono_dummy_jit_icall (void); +G_EXTERN_C void mono_dummy_jit_icall (void); #endif /* __MONO_JIT_ICALLS_H__ */ diff --git a/mono/mini/liveness.c b/mono/mini/liveness.c index 4975c0bea7..65a1facc65 100644 --- a/mono/mini/liveness.c +++ b/mono/mini/liveness.c @@ -42,7 +42,10 @@ static void mono_analyze_liveness2 (MonoCompile *cfg); typedef struct { int capacity; - gpointer data [INLINE_SIZE]; + union { + gpointer data [INLINE_SIZE]; + GHashTable *hashtable; + }; } MonoPtrSet; static void @@ -55,7 +58,7 @@ static void mono_ptrset_destroy (MonoPtrSet *set) { if (set->capacity > INLINE_SIZE) - g_hash_table_destroy (set->data [0]); + g_hash_table_destroy (set->hashtable); } static void @@ -66,12 +69,12 @@ mono_ptrset_add (MonoPtrSet *set, gpointer val) GHashTable *tmp = g_hash_table_new (NULL, NULL); for (int i = 0; i < INLINE_SIZE; ++i) g_hash_table_insert (tmp, set->data [i], set->data [i]); - set->data [0] = tmp; + set->hashtable = tmp; ++set->capacity; } if (set->capacity > INLINE_SIZE) { - g_hash_table_insert (set->data [0], val, val); + g_hash_table_insert (set->hashtable, val, val); } else { set->data [set->capacity] = val; ++set->capacity; @@ -89,7 +92,7 @@ mono_ptrset_contains (MonoPtrSet *set, gpointer val) return FALSE; } - return g_hash_table_lookup (set->data [0], val) != NULL; + return g_hash_table_lookup (set->hashtable, val) != NULL; } diff --git a/mono/mini/lldb.c b/mono/mini/lldb.c index 3e44b35bf6..580a3d7063 100644 --- a/mono/mini/lldb.c +++ b/mono/mini/lldb.c @@ -125,6 +125,8 @@ static int num_entries; #define lldb_lock() mono_os_mutex_lock (&mutex) #define lldb_unlock() mono_os_mutex_unlock (&mutex) +G_BEGIN_DECLS + void MONO_NEVER_INLINE __mono_jit_debug_register_code (void); /* The native debugger puts a breakpoint in this function. */ @@ -137,6 +139,8 @@ __mono_jit_debug_register_code (void) #endif } +G_END_DECLS + /* * Functions to encode protocol data */ @@ -257,7 +261,7 @@ typedef struct { static int find_code_region (void *data, int csize, int size, void *user_data) { - UserData *ud = user_data; + UserData *ud = (UserData*)user_data; if ((char*)ud->code >= (char*)data && (char*)ud->code < (char*)data + csize) { ud->region_start = data; @@ -373,7 +377,7 @@ emit_unwind_info (GSList *unwind_ops, Buffer *buf) /* We use the unencoded version of the unwind info to make it easier to decode */ nunwind_ops = 0; for (l = unwind_ops; l; l = l->next) { - MonoUnwindOp *op = l->data; + MonoUnwindOp *op = (MonoUnwindOp*)l->data; /* lldb can't handle these */ if (op->op == DW_CFA_mono_advance_loc) @@ -384,7 +388,7 @@ emit_unwind_info (GSList *unwind_ops, Buffer *buf) buffer_add_byte (buf, ret_reg); buffer_add_int (buf, nunwind_ops); for (l = unwind_ops; l; l = l->next) { - MonoUnwindOp *op = l->data; + MonoUnwindOp *op = (MonoUnwindOp*)l->data; if (op->op == DW_CFA_mono_advance_loc) break; @@ -425,8 +429,8 @@ typedef struct static int compare_by_addr (const void *arg1, const void *arg2) { - const FullSeqPoint *sp1 = arg1; - const FullSeqPoint *sp2 = arg2; + const FullSeqPoint *sp1 = (const FullSeqPoint *)arg1; + const FullSeqPoint *sp2 = (const FullSeqPoint *)arg2; return sp1->native_offset - sp2->native_offset; } @@ -518,12 +522,6 @@ mono_lldb_save_method_info (MonoCompile *cfg) buffer_add_int (buf, n_il_offsets); for (i = 0; i < n_il_offsets; ++i) { MonoSymSeqPoint *sp = &locs [i].sp; - const char *srcfile = ""; - - if (source_files [i] != -1) { - MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]); - srcfile = sinfo->source_file; - } //printf ("%s %x %d %d\n", cfg->method->name, locs [i].native_offset, sp->il_offset, sp->line); buffer_add_int (buf, locs [i].native_offset); diff --git a/mono/mini/local-propagation.c b/mono/mini/local-propagation.c index bd2a98a2e5..fd78c5dc19 100644 --- a/mono/mini/local-propagation.c +++ b/mono/mini/local-propagation.c @@ -370,7 +370,7 @@ mono_strength_reduction_ins (MonoCompile *cfg, MonoInst *ins, const char **spec) } case OP_IDIV_UN_IMM: case OP_IDIV_IMM: { - if (!COMPILE_LLVM (cfg)) + if ((!COMPILE_LLVM (cfg)) && (!cfg->backend->optimized_div)) allocated_vregs = mono_strength_reduction_division (cfg, ins); break; } @@ -383,10 +383,8 @@ mono_strength_reduction_ins (MonoCompile *cfg, MonoInst *ins, const char **spec) ins->opcode = OP_ICONST; MONO_INST_NULLIFY_SREGS (ins); ins->inst_c0 = 0; -#if __s390__ - } -#else - } else if ((ins->inst_imm > 0) && (ins->inst_imm < (1LL << 32)) && (power != -1)) { + } else if ((ins->inst_imm > 0) && (ins->inst_imm < (1LL << 32)) && + (power != -1) && (!cfg->backend->optimized_div)) { gboolean is_long = ins->opcode == OP_LREM_IMM; int compensator_reg = alloc_ireg (cfg); int intermediate_reg; @@ -411,7 +409,6 @@ mono_strength_reduction_ins (MonoCompile *cfg, MonoInst *ins, const char **spec) allocated_vregs = TRUE; } -#endif break; } #if SIZEOF_REGISTER == 4 diff --git a/mono/mini/main.c b/mono/mini/main.c index a0c62afe88..7e1f521705 100644 --- a/mono/mini/main.c +++ b/mono/mini/main.c @@ -145,7 +145,7 @@ delete_bundled_libraries (void) GSList *list; for (list = bundle_library_paths; list != NULL; list = list->next){ - unlink (list->data); + unlink ((const char*)list->data); } rmdir (bundled_dylibrary_directory); } @@ -287,7 +287,8 @@ probe_embedded (const char *program, int *ref_argc, char **ref_argv []) for (i = 0; i < items; i++){ char *kind; int strsize = STREAM_INT (p); - uint64_t offset, item_size; + uint64_t offset; + uint32_t item_size; kind = p+4; p += 4 + strsize; offset = STREAM_LONG(p); @@ -297,7 +298,7 @@ probe_embedded (const char *program, int *ref_argc, char **ref_argv []) if (mapaddress == NULL) { char *error_message = NULL; - mapaddress = mono_file_map_error (directory_location - offset, MONO_MMAP_READ | MONO_MMAP_PRIVATE, + mapaddress = (guchar*)mono_file_map_error (directory_location - offset, MONO_MMAP_READ | MONO_MMAP_PRIVATE, fd, offset, &maphandle, program, &error_message); if (mapaddress == NULL) { if (error_message) diff --git a/mono/mini/memory-access.c b/mono/mini/memory-access.c index 3ce499d219..2b538acbf5 100644 --- a/mono/mini/memory-access.c +++ b/mono/mini/memory-access.c @@ -66,7 +66,8 @@ mini_emit_memset (MonoCompile *cfg, int destreg, int offset, int size, int val, //Unaligned offsets don't naturaly happen in the runtime, so it's ok to be conservative in how we copy //We assume that input src and dest are be aligned to `align` so offset just worsen it - int offsets_mask = offset & 0x7; //we only care about the misalignment part + int offsets_mask; + offsets_mask = offset & 0x7; //we only care about the misalignment part if (offsets_mask) { if (offsets_mask % 2 == 1) goto set_1; @@ -126,7 +127,8 @@ mini_emit_memcpy (MonoCompile *cfg, int destreg, int doffset, int srcreg, int so //Unaligned offsets don't naturaly happen in the runtime, so it's ok to be conservative in how we copy //We assume that input src and dest are be aligned to `align` so offset just worsen it - int offsets_mask = (doffset | soffset) & 0x7; //we only care about the misalignment part + int offsets_mask; + offsets_mask = (doffset | soffset) & 0x7; //we only care about the misalignment part if (offsets_mask) { if (offsets_mask % 2 == 1) goto copy_1; diff --git a/mono/mini/method-to-ir.c.REMOVED.git-id b/mono/mini/method-to-ir.c.REMOVED.git-id index 2775c72a26..303762dcbc 100644 --- a/mono/mini/method-to-ir.c.REMOVED.git-id +++ b/mono/mini/method-to-ir.c.REMOVED.git-id @@ -1 +1 @@ -553eed9e186f93fc74e6a7ca8190ca2ade6791ac \ No newline at end of file +54cd6484f7ed21b57fff42f51598ceece4420a1a \ No newline at end of file diff --git a/mono/mini/mini-amd64.c.REMOVED.git-id b/mono/mini/mini-amd64.c.REMOVED.git-id index 4e9611f8d1..8ccfd5e777 100644 --- a/mono/mini/mini-amd64.c.REMOVED.git-id +++ b/mono/mini/mini-amd64.c.REMOVED.git-id @@ -1 +1 @@ -d5cc9fdbaee8aae90616f2abbaa18f6e84d2c914 \ No newline at end of file +dd89c329aa276333966129a913f446acfe56604d \ No newline at end of file diff --git a/mono/mini/mini-amd64.h b/mono/mini/mini-amd64.h index 11ad02ba91..625dbfd407 100644 --- a/mono/mini/mini-amd64.h +++ b/mono/mini/mini-amd64.h @@ -209,17 +209,18 @@ typedef struct MonoCompileArch { gint32 stack_alloc_size; gint32 sp_fp_offset; guint32 saved_iregs; - gboolean omit_fp, omit_fp_computed; - gpointer cinfo; + gboolean omit_fp; + gboolean omit_fp_computed; + CallInfo *cinfo; gint32 async_point_count; - gpointer vret_addr_loc; + MonoInst *vret_addr_loc; + MonoInst *seq_point_info_var; + MonoInst *ss_tramp_var; + MonoInst *bp_tramp_var; + MonoInst *lmf_var; #ifdef HOST_WIN32 struct _UNWIND_INFO* unwindinfo; #endif - gpointer seq_point_info_var; - gpointer ss_tramp_var; - gpointer bp_tramp_var; - gpointer lmf_var; } MonoCompileArch; #ifdef TARGET_WIN32 @@ -275,10 +276,10 @@ typedef struct { } GSharedVtCallInfo; /* Structure used by the sequence points in AOTed code */ -typedef struct { +struct SeqPointInfo { gpointer ss_tramp_addr; gpointer bp_addrs [MONO_ZERO_LEN_ARRAY]; -} SeqPointInfo; +}; typedef struct { mgreg_t res; @@ -324,7 +325,7 @@ typedef struct { guint8 pass_empty_struct : 1; // Set in scenarios when empty structs needs to be represented as argument. } ArgInfo; -typedef struct { +struct CallInfo { int nargs; guint32 stack_usage; guint32 reg_usage; @@ -336,7 +337,7 @@ typedef struct { ArgInfo ret; ArgInfo sig_cookie; ArgInfo args [1]; -} CallInfo; +}; typedef struct { /* General registers */ @@ -357,7 +358,6 @@ typedef struct { #define MONO_INIT_CONTEXT_FROM_FUNC(ctx, start_func) do { \ guint64 stackptr; \ - mono_arch_flush_register_windows (); \ stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));\ MONO_CONTEXT_SET_IP ((ctx), (start_func)); \ MONO_CONTEXT_SET_BP ((ctx), stackptr); \ @@ -373,7 +373,6 @@ typedef struct { #define MONO_INIT_CONTEXT_FROM_FUNC(ctx,start_func) do { \ int tmp; \ guint64 stackptr = (guint64)&tmp; \ - mono_arch_flush_register_windows (); \ MONO_CONTEXT_SET_IP ((ctx), (start_func)); \ MONO_CONTEXT_SET_BP ((ctx), stackptr); \ MONO_CONTEXT_SET_SP ((ctx), stackptr); \ diff --git a/mono/mini/mini-arm.c.REMOVED.git-id b/mono/mini/mini-arm.c.REMOVED.git-id index 801ede37fe..999a9f01e6 100644 --- a/mono/mini/mini-arm.c.REMOVED.git-id +++ b/mono/mini/mini-arm.c.REMOVED.git-id @@ -1 +1 @@ -ba93c5047326f96acd6d3d4aa2390cf12bbddd8c \ No newline at end of file +03945b843955a3347bf14841c37bf3252be811b7 \ No newline at end of file diff --git a/mono/mini/mini-arm.h b/mono/mini/mini-arm.h index a05f7922c3..477ed1922e 100644 --- a/mono/mini/mini-arm.h +++ b/mono/mini/mini-arm.h @@ -168,7 +168,8 @@ typedef struct { int gsharedvt_in; /* Whenever this call uses fp registers */ int have_fregs; - gpointer caller_cinfo, callee_cinfo; + CallInfo *caller_cinfo; + CallInfo *callee_cinfo; /* Maps stack slots/registers in the caller to the stack slots/registers in the callee */ /* A negative value means a register, i.e. -1=r0, -2=r1 etc. */ int map [MONO_ZERO_LEN_ARRAY]; @@ -212,7 +213,7 @@ typedef struct { guint8 size : 4; /* 1, 2, 4, 8, or regs used by RegTypeStructByVal */ } ArgInfo; -typedef struct { +struct CallInfo { int nargs; guint32 stack_usage; /* The index of the vret arg in the argument list for RegTypeStructByAddr */ @@ -220,7 +221,7 @@ typedef struct { ArgInfo ret; ArgInfo sig_cookie; ArgInfo args [1]; -} CallInfo; +}; #define PARAM_REGS 4 #define FP_PARAM_REGS 8 @@ -236,12 +237,12 @@ typedef struct { } CallContext; /* Structure used by the sequence points in AOTed code */ -typedef struct { +struct SeqPointInfo { gpointer ss_trigger_page; gpointer bp_trigger_page; gpointer ss_tramp_addr; guint8* bp_addrs [MONO_ZERO_LEN_ARRAY]; -} SeqPointInfo; +}; typedef struct { double fpregs [FP_PARAM_REGS]; @@ -294,13 +295,15 @@ struct MonoLMF { }; typedef struct MonoCompileArch { - gpointer seq_point_info_var, ss_trigger_page_var; - gpointer seq_point_ss_method_var; - gpointer seq_point_bp_method_var; - gpointer vret_addr_loc; - gboolean omit_fp, omit_fp_computed; - gpointer cinfo; - gpointer *vfp_scratch_slots [2]; + MonoInst *seq_point_info_var; + MonoInst *ss_trigger_page_var; + MonoInst *seq_point_ss_method_var; + MonoInst *seq_point_bp_method_var; + MonoInst *vret_addr_loc; + gboolean omit_fp; + gboolean omit_fp_computed; + CallInfo *cinfo; + MonoInst *vfp_scratch_slots [2]; int atomic_tmp_offset; guint8 *thunks; int thunks_size; diff --git a/mono/mini/mini-arm64.c.REMOVED.git-id b/mono/mini/mini-arm64.c.REMOVED.git-id index 29f2348f5c..b6961dd951 100644 --- a/mono/mini/mini-arm64.c.REMOVED.git-id +++ b/mono/mini/mini-arm64.c.REMOVED.git-id @@ -1 +1 @@ -55f7125c34f2e264f2e831a6b63f0f62a7c548d2 \ No newline at end of file +b215d7448c3b30d6cdd13539ac3f1894e4ece6b8 \ No newline at end of file diff --git a/mono/mini/mini-arm64.h b/mono/mini/mini-arm64.h index 984dfa3c7d..68bdd12e5d 100644 --- a/mono/mini/mini-arm64.h +++ b/mono/mini/mini-arm64.h @@ -78,12 +78,12 @@ struct MonoLMF { }; /* Structure used by the sequence points in AOTed code */ -typedef struct { +struct SeqPointInfo { gpointer ss_trigger_page; gpointer bp_trigger_page; gpointer ss_tramp_addr; guint8* bp_addrs [MONO_ZERO_LEN_ARRAY]; -} SeqPointInfo; +}; #define PARAM_REGS 8 #define FP_PARAM_REGS 8 @@ -99,23 +99,37 @@ typedef struct { } DynCallArgs; typedef struct { - gpointer cinfo; + CallInfo *cinfo; int saved_gregs_offset; /* Points to arguments received on the stack */ int args_reg; gboolean cond_branch_islands; - gpointer vret_addr_loc; - gpointer seq_point_info_var; - gpointer ss_tramp_var; - gpointer bp_tramp_var; + MonoInst *vret_addr_loc; + MonoInst *seq_point_info_var; + MonoInst *ss_tramp_var; + MonoInst *bp_tramp_var; guint8 *thunks; int thunks_size; } MonoCompileArch; -#define MONO_ARCH_EMULATE_FREM 1 -#define MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS 1 -#define MONO_ARCH_EMULATE_LONG_MUL_OVF_OPTS 1 +#ifdef MONO_ARCH_ILP32 +/* For the watch (starting with series 4), a new ABI is introduced: arm64_32. + * We can still use the older AOT compiler to produce bitcode, because it's + * "offset compatible". However, since it is targeting arm7k, it makes certain + * assumptions that we need to align here. */ +#define MONO_ARCH_EMULATE_FCONV_TO_I8 1 +#define MONO_ARCH_EMULATE_LCONV_TO_R8 1 +#define MONO_ARCH_EMULATE_LCONV_TO_R4 1 +#define MONO_ARCH_EMULATE_LCONV_TO_R8_UN 1 +#define MONO_ARCH_EMULATE_DIV 1 +#define MONO_ARCH_EMULATE_CONV_R8_UN 1 +#else #define MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS 1 +#define MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS 1 +#endif + +#define MONO_ARCH_EMULATE_FREM 1 +#define MONO_ARCH_EMULATE_LONG_MUL_OVF_OPTS 1 #define MONO_ARCH_NEED_DIV_CHECK 1 #define MONO_ARCH_EMULATE_MUL_OVF 1 #define MONO_ARCH_HAVE_OP_TAILCALL_MEMBASE 1 @@ -224,14 +238,14 @@ typedef struct { gboolean hfa; } ArgInfo; -typedef struct { +struct CallInfo { int nargs; int gr, fr, stack_usage; gboolean pinvoke; ArgInfo ret; ArgInfo sig_cookie; ArgInfo args [1]; -} CallInfo; +}; typedef struct { /* General registers + ARMREG_R8 for indirect returns */ diff --git a/mono/mini/mini-darwin.c b/mono/mini/mini-darwin.c index 05962a0717..b0d2a4d674 100644 --- a/mono/mini/mini-darwin.c +++ b/mono/mini/mini-darwin.c @@ -101,10 +101,6 @@ mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo kern_return_t ret; mach_msg_type_number_t num_state, num_fpstate; thread_state_t state, fpstate; - MonoJitTlsData *jit_tls; - void *domain; - MonoLMF *lmf = NULL; - gpointer *addr; g_assert (info); /*Zero enough state to make sure the caller doesn't confuse itself*/ @@ -125,9 +121,9 @@ mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo mono_mach_arch_thread_states_to_mono_context (state, fpstate, &tctx->ctx); /* mono_set_jit_tls () sets this */ - jit_tls = mono_thread_info_tls_get (info, TLS_KEY_JIT_TLS); + void *jit_tls = mono_thread_info_tls_get (info, TLS_KEY_JIT_TLS); /* SET_APPDOMAIN () sets this */ - domain = mono_thread_info_tls_get (info, TLS_KEY_DOMAIN); + void *domain = mono_thread_info_tls_get (info, TLS_KEY_DOMAIN); /*Thread already started to cleanup, can no longer capture unwind state*/ if (!jit_tls || !domain) @@ -139,11 +135,11 @@ mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo * can be accessed through MonoThreadInfo. */ /* mono_set_lmf_addr () sets this */ - addr = mono_thread_info_tls_get (info, TLS_KEY_LMF_ADDR); + MonoLMF *lmf = NULL; + MonoLMF **addr = (MonoLMF**)mono_thread_info_tls_get (info, TLS_KEY_LMF_ADDR); if (addr) lmf = *addr; - tctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = domain; tctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls; tctx->unwind_data [MONO_UNWIND_DATA_LMF] = lmf; diff --git a/mono/mini/mini-exceptions.c.REMOVED.git-id b/mono/mini/mini-exceptions.c.REMOVED.git-id index 86c87ce3f1..d420bd5d2f 100644 --- a/mono/mini/mini-exceptions.c.REMOVED.git-id +++ b/mono/mini/mini-exceptions.c.REMOVED.git-id @@ -1 +1 @@ -9a3c687e45c6b1c31791b76e54cf9cc8d6ce38f6 \ No newline at end of file +5d2cdc457b989d21bce22f039a63e9a0b790994f \ No newline at end of file diff --git a/mono/mini/mini-generic-sharing.c.REMOVED.git-id b/mono/mini/mini-generic-sharing.c.REMOVED.git-id index aaadb44a46..6f31073565 100644 --- a/mono/mini/mini-generic-sharing.c.REMOVED.git-id +++ b/mono/mini/mini-generic-sharing.c.REMOVED.git-id @@ -1 +1 @@ -0cfb58a181a0d89acc2da3bf5d0de5c68e42fdc1 \ No newline at end of file +ed6f3fdf21f1385753c6e380832da216d0748168 \ No newline at end of file diff --git a/mono/mini/mini-llvm-cpp.h b/mono/mini/mini-llvm-cpp.h index c6b9024547..72b64bd0b7 100644 --- a/mono/mini/mini-llvm-cpp.h +++ b/mono/mini/mini-llvm-cpp.h @@ -116,8 +116,7 @@ void mono_llvm_add_instr_attr (LLVMValueRef val, int index, AttrKind kind); #if defined(ENABLE_LLVM) && defined(HAVE_UNWIND_H) -_Unwind_Reason_Code -mono_debug_personality (int a, _Unwind_Action b, +G_EXTERN_C _Unwind_Reason_Code mono_debug_personality (int a, _Unwind_Action b, uint64_t c, struct _Unwind_Exception *d, struct _Unwind_Context *e); #endif diff --git a/mono/mini/mini-llvm.c.REMOVED.git-id b/mono/mini/mini-llvm.c.REMOVED.git-id index 513be939e4..cd01322e7e 100644 --- a/mono/mini/mini-llvm.c.REMOVED.git-id +++ b/mono/mini/mini-llvm.c.REMOVED.git-id @@ -1 +1 @@ -589a92de939fc398f6106ee3d354acdba0c6c377 \ No newline at end of file +5d6dcdc19f7da66ae99c6a7f4615f604ef1a49fc \ No newline at end of file diff --git a/mono/mini/mini-mips.c.REMOVED.git-id b/mono/mini/mini-mips.c.REMOVED.git-id index e4b8a9b43e..c9b04bb37b 100644 --- a/mono/mini/mini-mips.c.REMOVED.git-id +++ b/mono/mini/mini-mips.c.REMOVED.git-id @@ -1 +1 @@ -dc51e2bd7ede042390322b765af38ba18c345c2d \ No newline at end of file +3e321d0017d0d7a5576f0a6a7f007d96c652a4ab \ No newline at end of file diff --git a/mono/mini/mini-mips.h b/mono/mini/mini-mips.h index 223fdd430f..8c15a49444 100644 --- a/mono/mini/mini-mips.h +++ b/mono/mini/mini-mips.h @@ -216,7 +216,7 @@ struct MonoLMF { }; typedef struct MonoCompileArch { - gpointer cinfo; + CallInfo *cinfo; guint iregs_offset; guint lmf_offset; guint local_alloc_offset; diff --git a/mono/mini/mini-native-types.c b/mono/mini/mini-native-types.c index 165d075308..a3889a4f5f 100644 --- a/mono/mini/mini-native-types.c +++ b/mono/mini/mini-native-types.c @@ -24,9 +24,15 @@ typedef struct { typedef struct { short op_index; +#ifdef __cplusplus + MonoStackType big_stack_type : 16; + MonoStackType small_stack_type : 16; + MonoStackType stack_type : 16; +#else short big_stack_type; short small_stack_type; short stack_type; +#endif short conv_4_to_8; short conv_8_to_4; short move; @@ -154,7 +160,7 @@ emit_narrow (MonoCompile *cfg, const MagicTypeInfo *info, int sreg) ins->type = cfg->r4_stack_type; else ins->type = info->small_stack_type; - ins->dreg = alloc_dreg (cfg, ins->type); + ins->dreg = alloc_dreg (cfg, (MonoStackType)ins->type); MONO_ADD_INS (cfg->cbb, ins); return mono_decompose_opcode (cfg, ins); } @@ -181,7 +187,8 @@ emit_intrinsics (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsi int i = 0; const char *name = cmethod->name; MonoInst *ins; - int type_index, stack_type; + int type_index; + MonoStackType stack_type; if (info->op_index == 2 && cfg->r4fp && TARGET_SIZEOF_VOID_P == 4) { type_index = 3; @@ -250,7 +257,7 @@ emit_intrinsics (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsi /* We have IR for inc/dec */ MONO_INST_NEW (cfg, ins, inc ? info->inc_op : info->dec_op); - ins->dreg = alloc_dreg (cfg, info->stack_type); + ins->dreg = alloc_dreg (cfg, (MonoStackType)info->stack_type); ins->sreg1 = args [0]->dreg; ins->inst_imm = 1; ins->type = info->stack_type; diff --git a/mono/mini/mini-ops.h b/mono/mini/mini-ops.h index ee347017ca..dd19d5f3d2 100644 --- a/mono/mini/mini-ops.h +++ b/mono/mini/mini-ops.h @@ -966,6 +966,11 @@ MINI_OP(OP_CVTTPS2DQ, "cvttps2dq", XREG, XREG, NONE) /* multiply all 4 single precision float elements, add them together, and store the result to the lowest element */ MINI_OP(OP_DPPS, "dpps", XREG, XREG, XREG) +/* sse 4.1 */ + +/* inst_c0 is the rounding mode: 0 = round, 1 = floor, 2 = ceiling */ +MINI_OP(OP_SSE41_ROUNDPD, "roundpd", XREG, XREG, NONE) + #endif MINI_OP(OP_XMOVE, "xmove", XREG, XREG, NONE) diff --git a/mono/mini/mini-posix.c b/mono/mini/mini-posix.c index 9af6f0d0f3..189d85dc38 100644 --- a/mono/mini/mini-posix.c +++ b/mono/mini/mini-posix.c @@ -153,7 +153,7 @@ get_saved_signal_handler (int signo, gboolean remove) { if (mono_saved_signal_handlers) { /* The hash is only modified during startup, so no need for locking */ - struct sigaction *handler = g_hash_table_lookup (mono_saved_signal_handlers, GINT_TO_POINTER (signo)); + struct sigaction *handler = (struct sigaction*)g_hash_table_lookup (mono_saved_signal_handlers, GINT_TO_POINTER (signo)); if (remove && handler) g_hash_table_remove (mono_saved_signal_handlers, GINT_TO_POINTER (signo)); return handler; @@ -296,7 +296,7 @@ MONO_SIG_HANDLER_FUNC (static, profiler_signal_handler) mono_thread_info_set_is_async_context (TRUE); - MONO_PROFILER_RAISE (sample_hit, (mono_arch_ip_from_context (ctx), ctx)); + MONO_PROFILER_RAISE (sample_hit, ((const mono_byte*)mono_arch_ip_from_context (ctx), ctx)); mono_thread_info_set_is_async_context (FALSE); @@ -332,14 +332,16 @@ MONO_SIG_HANDLER_FUNC (static, sigusr2_signal_handler) mono_chain_signal (MONO_SIG_HANDLER_PARAMS); } +typedef void MONO_SIG_HANDLER_SIGNATURE ((*MonoSignalHandler)); + static void -add_signal_handler (int signo, gpointer handler, int flags) +add_signal_handler (int signo, MonoSignalHandler handler, int flags) { struct sigaction sa; struct sigaction previous_sa; #ifdef MONO_ARCH_USE_SIGACTION - sa.sa_sigaction = (void (*)(int, siginfo_t *, void *))handler; + sa.sa_sigaction = handler; sigemptyset (&sa.sa_mask); sa.sa_flags = SA_SIGINFO | flags; #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK @@ -370,7 +372,7 @@ add_signal_handler (int signo, gpointer handler, int flags) sigemptyset (&block_mask); } #else - sa.sa_handler = handler; + sa.sa_handler = (void (*)(int))handler; sigemptyset (&sa.sa_mask); sa.sa_flags = flags; #endif @@ -711,7 +713,9 @@ sampling_thread_func (gpointer unused) * to do our work, the kernel may knock us back down to the normal thread * scheduling policy without telling us. */ - struct sched_param sched = { .sched_priority = sched_get_priority_max (SCHED_FIFO) }; + struct sched_param sched; + memset (&sched, 0, sizeof (sched)); + sched.sched_priority = sched_get_priority_max (SCHED_FIFO); pthread_setschedparam (pthread_self (), SCHED_FIFO, &sched); MonoProfilerSampleMode mode; @@ -856,7 +860,7 @@ mono_runtime_setup_stat_profiler (void) mono_atomic_store_i32 (&sampling_thread_running, 1); MonoError error; - MonoInternalThread *thread = mono_thread_create_internal (mono_get_root_domain (), sampling_thread_func, NULL, MONO_THREAD_CREATE_FLAGS_NONE, &error); + MonoInternalThread *thread = mono_thread_create_internal (mono_get_root_domain (), (gpointer)sampling_thread_func, NULL, MONO_THREAD_CREATE_FLAGS_NONE, &error); mono_error_assert_ok (&error); sampling_thread = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid); @@ -986,8 +990,9 @@ dump_native_stacktrace (const char *signal, void *ctx) pid_t pid; int status; pid_t crashed_pid = getpid (); - gchar *output = NULL; + MonoStackHash hashes; + gchar *output = NULL; #ifndef DISABLE_CRASH_REPORTING MonoStateMem merp_mem; @@ -996,7 +1001,6 @@ dump_native_stacktrace (const char *signal, void *ctx) if (!double_faulted) { gboolean leave = FALSE; gboolean dump_for_merp = FALSE; - #if defined(TARGET_OSX) dump_for_merp = mono_merp_enabled (); #endif @@ -1123,7 +1127,6 @@ dump_native_stacktrace (const char *signal, void *ctx) output = NULL; mono_state_free_mem (&merp_mem); #endif - } #endif #else diff --git a/mono/mini/mini-ppc.c.REMOVED.git-id b/mono/mini/mini-ppc.c.REMOVED.git-id index bd7bdcc5ed..28d777b8f5 100644 --- a/mono/mini/mini-ppc.c.REMOVED.git-id +++ b/mono/mini/mini-ppc.c.REMOVED.git-id @@ -1 +1 @@ -1aa44390c1dc2750287cd740c5361541ffcdb1e2 \ No newline at end of file +5c67d14b49529f763f2ade98cc28aa5e4f349fc3 \ No newline at end of file diff --git a/mono/mini/mini-runtime.c.REMOVED.git-id b/mono/mini/mini-runtime.c.REMOVED.git-id index b195605654..5c3fe490c7 100644 --- a/mono/mini/mini-runtime.c.REMOVED.git-id +++ b/mono/mini/mini-runtime.c.REMOVED.git-id @@ -1 +1 @@ -7a0baff28d8e75d42046f5b6695e8d5973c9dadc \ No newline at end of file +b4e48873ea9699ddedb859bf10b9ff0a47d61a45 \ No newline at end of file diff --git a/mono/mini/mini-runtime.h b/mono/mini/mini-runtime.h index b143bd99fa..45849cec85 100644 --- a/mono/mini/mini-runtime.h +++ b/mono/mini/mini-runtime.h @@ -73,6 +73,8 @@ typedef struct { int first_filter_idx, filter_idx; } ResumeState; +typedef void (*MonoAbortFunction)(MonoObject*); + struct MonoJitTlsData { gpointer end_of_stack; guint32 stack_size; @@ -85,7 +87,7 @@ struct MonoJitTlsData { guint32 stack_ovf_guard_size; guint stack_ovf_valloced : 1; guint stack_ovf_pending : 1; - void (*abort_func) (MonoObject *object); + MonoAbortFunction abort_func; /* Used to implement --debug=casts */ MonoClass *class_cast_from, *class_cast_to; @@ -395,6 +397,8 @@ 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_interp_stub_init (void); void mini_install_interp_callbacks (MonoEECallbacks *cbs); @@ -422,10 +426,12 @@ MONO_API int mono_parse_default_optimizations (const char* p); gboolean mono_running_on_valgrind (void); MonoLMF * mono_get_lmf (void); +#define mono_get_lmf_addr mono_tls_get_lmf_addr MonoLMF** mono_get_lmf_addr (void); void mono_set_lmf (MonoLMF *lmf); void mono_push_lmf (MonoLMFExt *ext); void mono_pop_lmf (MonoLMF *lmf); +#define mono_get_jit_tls mono_tls_get_jit_tls MonoJitTlsData* mono_get_jit_tls (void); MONO_API MONO_RT_EXTERNAL_ONLY MonoDomain* mono_jit_thread_attach (MonoDomain *domain); diff --git a/mono/mini/mini-s390x.c.REMOVED.git-id b/mono/mini/mini-s390x.c.REMOVED.git-id index b02eb92221..aa786806d5 100644 --- a/mono/mini/mini-s390x.c.REMOVED.git-id +++ b/mono/mini/mini-s390x.c.REMOVED.git-id @@ -1 +1 @@ -c66d6a485515096ce35adf3da1f12a0c160b0bb3 \ No newline at end of file +3de84975b2f0f458db76281336d8d718e43ece41 \ No newline at end of file diff --git a/mono/mini/mini-s390x.h b/mono/mini/mini-s390x.h index 464ddb1178..9323182c0c 100644 --- a/mono/mini/mini-s390x.h +++ b/mono/mini/mini-s390x.h @@ -65,6 +65,7 @@ typedef struct #define MONO_ARCH_HAVE_OP_GENERIC_CLASS_INIT 1 #define MONO_ARCH_HAVE_SETUP_ASYNC_CALLBACK 1 #define MONO_ARCH_HAVE_TRACK_FPREGS 1 +#define MONO_ARCH_HAVE_OPTIMIZED_DIV 1 #define S390_STACK_ALIGNMENT 8 #define S390_FIRST_ARG_REG s390_r2 diff --git a/mono/mini/mini-sparc.c.REMOVED.git-id b/mono/mini/mini-sparc.c.REMOVED.git-id index b9a80e9379..9a7e43f13e 100644 --- a/mono/mini/mini-sparc.c.REMOVED.git-id +++ b/mono/mini/mini-sparc.c.REMOVED.git-id @@ -1 +1 @@ -313f1694208b6763ed17c10be9084db6c82eb27e \ No newline at end of file +b1ddd698daff1675bda502e9e1596558e0aed99e \ No newline at end of file diff --git a/mono/mini/mini-sparc.h b/mono/mini/mini-sparc.h index 86e72c2fcd..2992a84c15 100644 --- a/mono/mini/mini-sparc.h +++ b/mono/mini/mini-sparc.h @@ -82,7 +82,6 @@ typedef struct MonoCompileArch { } MonoCompileArch; #define MONO_INIT_CONTEXT_FROM_FUNC(ctx,start_func) do { \ - mono_arch_flush_register_windows (); \ MONO_CONTEXT_SET_IP ((ctx), (start_func)); \ MONO_CONTEXT_SET_BP ((ctx), __builtin_frame_address (0)); \ MONO_CONTEXT_SET_SP ((ctx), __builtin_frame_address (0)); \ diff --git a/mono/mini/mini-trampolines.c b/mono/mini/mini-trampolines.c index 726ce3c4a2..d33e958709 100644 --- a/mono/mini/mini-trampolines.c +++ b/mono/mini/mini-trampolines.c @@ -191,7 +191,6 @@ mini_resolve_imt_method (MonoVTable *vt, gpointer *vtable_slot, MonoMethod *imt_ { MonoMethod *impl = NULL, *generic_virtual = NULL; gboolean lookup_aot, variance_used = FALSE, need_rgctx_tramp = FALSE; - gpointer addr; guint8 *aot_addr = NULL; int displacement = vtable_slot - ((gpointer*)vt); int interface_offset; @@ -214,7 +213,6 @@ mini_resolve_imt_method (MonoVTable *vt, gpointer *vtable_slot, MonoMethod *imt_ *variant_iface = imt_method; } - addr = NULL; /* We can only use the AOT compiled code if we don't require further processing */ lookup_aot = !generic_virtual & !variant_iface; @@ -442,7 +440,7 @@ gpointer mini_add_method_wrappers_llvmonly (MonoMethod *m, gpointer compiled_method, gboolean caller_gsharedvt, gboolean add_unbox_tramp, gpointer *out_arg) { gpointer addr; - gboolean callee_gsharedvt, callee_array_helper; + gboolean callee_gsharedvt; MonoMethod *jmethod = NULL; MonoJitInfo *ji; @@ -450,7 +448,6 @@ mini_add_method_wrappers_llvmonly (MonoMethod *m, gpointer compiled_method, gboo ji = mini_jit_info_table_find (mono_domain_get (), (char *)mono_get_addr_from_ftnptr (compiled_method), NULL); callee_gsharedvt = mini_jit_info_is_gsharedvt (ji); - callee_array_helper = FALSE; if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) { WrapperInfo *info = mono_marshal_get_wrapper_info (m); @@ -459,7 +456,6 @@ mini_add_method_wrappers_llvmonly (MonoMethod *m, gpointer compiled_method, gboo * Have to replace the wrappers with the original generic instances. */ if (info && info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) { - callee_array_helper = TRUE; m = info->d.generic_array_helper.method; } } else if (m->wrapper_type == MONO_WRAPPER_UNKNOWN) { @@ -1350,23 +1346,23 @@ mono_get_trampoline_func (MonoTrampolineType tramp_type) switch (tramp_type) { case MONO_TRAMPOLINE_JIT: case MONO_TRAMPOLINE_JUMP: - return mono_magic_trampoline; + return (gconstpointer)mono_magic_trampoline; case MONO_TRAMPOLINE_RGCTX_LAZY_FETCH: - return mono_rgctx_lazy_fetch_trampoline; + return (gconstpointer)mono_rgctx_lazy_fetch_trampoline; #ifdef MONO_ARCH_AOT_SUPPORTED case MONO_TRAMPOLINE_AOT: - return mono_aot_trampoline; + return (gconstpointer)mono_aot_trampoline; case MONO_TRAMPOLINE_AOT_PLT: - return mono_aot_plt_trampoline; + return (gconstpointer)mono_aot_plt_trampoline; #endif case MONO_TRAMPOLINE_DELEGATE: - return mono_delegate_trampoline; + return (gconstpointer)mono_delegate_trampoline; #ifndef DISABLE_REMOTING case MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING: - return mono_generic_virtual_remoting_trampoline; + return (gconstpointer)mono_generic_virtual_remoting_trampoline; #endif case MONO_TRAMPOLINE_VCALL: - return mono_vcall_trampoline; + return (gconstpointer)mono_vcall_trampoline; default: g_assert_not_reached (); return NULL; @@ -1389,8 +1385,12 @@ void mono_trampolines_init (void) { mono_os_mutex_init_recursive (&trampolines_mutex); + gboolean disable_tramps = FALSE; +#if TARGET_WASM + disable_tramps = TRUE; +#endif - if (mono_aot_only) + if (mono_aot_only || disable_tramps) return; mono_trampoline_code [MONO_TRAMPOLINE_JIT] = create_trampoline_code (MONO_TRAMPOLINE_JIT); @@ -1532,7 +1532,7 @@ mono_create_jit_trampoline (MonoDomain *domain, MonoMethod *method, MonoError *e if (mono_llvm_only) { if (method->wrapper_type == MONO_WRAPPER_PROXY_ISINST) /* These wrappers are not generated */ - return method_not_found; + return (gpointer)method_not_found; /* Methods are lazily initialized on first call, so this can't lead recursion */ code = mono_jit_compile_method (method, error); if (!mono_error_ok (error)) @@ -1639,7 +1639,7 @@ gpointer mono_create_delegate_trampoline (MonoDomain *domain, MonoClass *klass) { if (mono_llvm_only || (mono_use_interpreter && !mono_aot_only)) - return no_delegate_trampoline; + return (gpointer)no_delegate_trampoline; return mono_create_delegate_trampoline_info (domain, klass, NULL)->invoke_impl; } diff --git a/mono/mini/mini-wasm-debugger.c b/mono/mini/mini-wasm-debugger.c index e2613e852b..426a04eb4c 100644 --- a/mono/mini/mini-wasm-debugger.c +++ b/mono/mini/mini-wasm-debugger.c @@ -11,6 +11,8 @@ //XXX This is dirty, extend ee.h to support extracting info from MonoInterpFrameHandle #include +#ifdef HOST_WASM + #include @@ -19,7 +21,10 @@ static int log_level = 1; #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (stdout, __VA_ARGS__); } } while (0) //functions exported to be used by JS +G_BEGIN_DECLS + EMSCRIPTEN_KEEPALIVE int mono_wasm_set_breakpoint (const char *assembly_name, int method_token, int il_offset); +EMSCRIPTEN_KEEPALIVE int mono_wasm_remove_breakpoint (int bp_id); EMSCRIPTEN_KEEPALIVE int mono_wasm_current_bp_id (void); EMSCRIPTEN_KEEPALIVE void mono_wasm_enum_frames (void); EMSCRIPTEN_KEEPALIVE void mono_wasm_get_var_info (int scope, int pos); @@ -36,6 +41,8 @@ extern void mono_wasm_add_float_var (float); extern void mono_wasm_add_double_var (double); extern void mono_wasm_add_string_var (const char*); +G_END_DECLS + //FIXME move all of those fields to the profiler object static gboolean debugger_enabled; @@ -112,7 +119,7 @@ free_frame_state (void) if (frames) { int i; for (i = 0; i < frames->len; ++i) - free_frame (g_ptr_array_index (frames, i)); + free_frame ((DbgEngineStackFrame*)g_ptr_array_index (frames, i)); g_ptr_array_set_size (frames, 0); } } @@ -122,7 +129,7 @@ compute_frames (void) { if (frames) { int i; for (i = 0; i < frames->len; ++i) - free_frame (g_ptr_array_index (frames, i)); + free_frame ((DbgEngineStackFrame*)g_ptr_array_index (frames, i)); g_ptr_array_set_size (frames, 0); } else { frames = g_ptr_array_new (); @@ -220,7 +227,7 @@ create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *j static void process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offsets) { - BpEvents *evts = _evts; + BpEvents *evts = (BpEvents*)_evts; if (evts) { if (evts->is_ss) mono_de_cancel_ss (); @@ -255,7 +262,7 @@ ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *ss_args) return DBG_NOT_SUSPENDED; } - DbgEngineStackFrame *frame = g_ptr_array_index (frames, 0); + DbgEngineStackFrame *frame = (DbgEngineStackFrame*)g_ptr_array_index (frames, 0); ss_req->start_method = ss_args->method = frame->method; gboolean found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &ss_args->info, &ss_args->sp); if (!found_sp) @@ -427,6 +434,17 @@ mono_wasm_set_breakpoint (const char *assembly_name, int method_token, int il_of return req->id; } +EMSCRIPTEN_KEEPALIVE int +mono_wasm_remove_breakpoint (int bp_id) +{ + MonoBreakpoint *bp = mono_de_get_breakpoint_by_id (bp_id); + if (!bp) + return 0; + + mono_de_clear_breakpoint (bp); + return 1; +} + void mono_wasm_single_step_hit (void) { @@ -453,9 +471,9 @@ mono_wasm_current_bp_id (void) MonoLMFExt *ext = (MonoLMFExt*)lmf; g_assert (ext->kind == MONO_LMFEXT_INTERP_EXIT || ext->kind == MONO_LMFEXT_INTERP_EXIT_WITH_CTX); - MonoInterpFrameHandle *frame = ext->interp_exit_data; + MonoInterpFrameHandle *frame = (MonoInterpFrameHandle*)ext->interp_exit_data; MonoJitInfo *ji = mini_get_interp_callbacks ()->frame_get_jit_info (frame); - guint8 *ip = mini_get_interp_callbacks ()->frame_get_ip (frame); + guint8 *ip = (guint8*)mini_get_interp_callbacks ()->frame_get_ip (frame); g_assert (ji && !ji->is_trampoline); MonoMethod *method = jinfo_get_method (ji); @@ -546,7 +564,7 @@ describe_variable (MonoStackFrameInfo *info, MonoContext *ctx, gpointer ud) ERROR_DECL (error); MonoMethodHeader *header = NULL; - FrameDescData *data = ud; + FrameDescData *data = (FrameDescData*)ud; //skip wrappers if (info->type != FRAME_TYPE_MANAGED && info->type != FRAME_TYPE_INTERP) { @@ -558,7 +576,7 @@ describe_variable (MonoStackFrameInfo *info, MonoContext *ctx, gpointer ud) return FALSE; } - InterpFrame *frame = info->interp_frame; + InterpFrame *frame = (InterpFrame*)info->interp_frame; g_assert (frame); MonoMethod *method = frame->imethod->method; g_assert (method); @@ -655,3 +673,22 @@ mono_debugger_tls_thread_id (DebuggerTlsData *debuggerTlsData) { return 1; } + +#else // HOST_WASM + +void +mono_wasm_single_step_hit (void) +{ +} + +void +mono_wasm_breakpoint_hit (void) +{ +} + +void +mono_wasm_debugger_init (void) +{ +} + +#endif // HOST_WASM diff --git a/mono/mini/mini-wasm.c b/mono/mini/mini-wasm.c index f88a1f990f..2387e607d2 100644 --- a/mono/mini/mini-wasm.c +++ b/mono/mini/mini-wasm.c @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -11,13 +12,388 @@ //XXX This is dirty, extend ee.h to support extracting info from MonoInterpFrameHandle #include +#ifndef DISABLE_JIT + +#include "ir-emit.h" +#include "cpu-wasm.h" + + //FIXME figure out if we need to distingush between i,l,f,d types +typedef enum { + ArgOnStack, + ArgValuetypeAddrOnStack, + ArgGsharedVTOnStack, + ArgValuetypeAddrInIReg, + ArgInvalid, +} ArgStorage; + +typedef struct { + ArgStorage storage : 8; +} ArgInfo; + +struct CallInfo { + int nargs; + gboolean gsharedvt; + + ArgInfo ret; + ArgInfo args [1]; +}; + +static ArgStorage +get_storage (MonoType *type, gboolean is_return) +{ + switch (type->type) { + case MONO_TYPE_I1: + case MONO_TYPE_U1: + case MONO_TYPE_I2: + case MONO_TYPE_U2: + case MONO_TYPE_I4: + case MONO_TYPE_U4: + case MONO_TYPE_I: + case MONO_TYPE_U: + case MONO_TYPE_PTR: + case MONO_TYPE_FNPTR: + case MONO_TYPE_OBJECT: + return ArgOnStack; + + case MONO_TYPE_U8: + case MONO_TYPE_I8: + return ArgOnStack; + + case MONO_TYPE_R4: + return ArgOnStack; + + case MONO_TYPE_R8: + return ArgOnStack; + + case MONO_TYPE_GENERICINST: + if (!mono_type_generic_inst_is_valuetype (type)) + return ArgOnStack; + + if (mini_is_gsharedvt_type (type)) { + return ArgGsharedVTOnStack; + } + /* fall through */ + case MONO_TYPE_VALUETYPE: + case MONO_TYPE_TYPEDBYREF: { + return is_return ? ArgValuetypeAddrInIReg : ArgValuetypeAddrOnStack; + break; + } + case MONO_TYPE_VAR: + case MONO_TYPE_MVAR: + g_assert (mini_is_gsharedvt_type (type)); + return ArgGsharedVTOnStack; + break; + case MONO_TYPE_VOID: + g_assert (is_return); + break; + default: + g_error ("Can't handle as return value 0x%x", type->type); + } + return ArgInvalid; +} + +static CallInfo* +get_call_info (MonoMemPool *mp, MonoMethodSignature *sig) +{ + int n = sig->hasthis + sig->param_count; + CallInfo *cinfo; + + if (mp) + cinfo = (CallInfo *)mono_mempool_alloc0 (mp, sizeof (CallInfo) + (sizeof (ArgInfo) * n)); + else + cinfo = (CallInfo *)g_malloc0 (sizeof (CallInfo) + (sizeof (ArgInfo) * n)); + + cinfo->nargs = n; + cinfo->gsharedvt = mini_is_gsharedvt_variable_signature (sig); + + /* return value */ + cinfo->ret.storage = get_storage (mini_get_underlying_type (sig->ret), TRUE); + + if (sig->hasthis) + cinfo->args [0].storage = ArgOnStack; + + // not supported + g_assert (sig->call_convention != MONO_CALL_VARARG); + + int i; + for (i = 0; i < sig->param_count; ++i) + cinfo->args [i + sig->hasthis].storage = get_storage (mini_get_underlying_type (sig->params [i]), FALSE); + + return cinfo; +} + +gboolean +mono_arch_have_fast_tls (void) +{ + return FALSE; +} + +guint32 +mono_arch_get_patch_offset (guint8 *code) +{ + g_error ("mono_arch_get_patch_offset"); + return 0; +} +gpointer +mono_arch_ip_from_context (void *sigctx) +{ + g_error ("mono_arch_ip_from_context"); +} + +gboolean +mono_arch_is_inst_imm (int opcode, int imm_opcode, gint64 imm) +{ + return TRUE; +} + +void +mono_arch_lowering_pass (MonoCompile *cfg, MonoBasicBlock *bb) +{ +} + +gboolean +mono_arch_opcode_supported (int opcode) +{ + return FALSE; +} + +void +mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb) +{ + g_error ("mono_arch_output_basic_block"); +} + +void +mono_arch_peephole_pass_1 (MonoCompile *cfg, MonoBasicBlock *bb) +{ +} + +void +mono_arch_peephole_pass_2 (MonoCompile *cfg, MonoBasicBlock *bb) +{ +} + +guint32 +mono_arch_regalloc_cost (MonoCompile *cfg, MonoMethodVar *vmv) +{ + return 0; +} + +GList * +mono_arch_get_allocatable_int_vars (MonoCompile *cfg) +{ + g_error ("mono_arch_get_allocatable_int_vars"); +} + +GList * +mono_arch_get_global_int_regs (MonoCompile *cfg) +{ + g_error ("mono_arch_get_global_int_regs"); +} + +void +mono_arch_allocate_vars (MonoCompile *cfg) +{ + g_error ("mono_arch_allocate_vars"); +} + +void +mono_arch_create_vars (MonoCompile *cfg) +{ + MonoMethodSignature *sig; + CallInfo *cinfo; + MonoType *sig_ret; + + sig = mono_method_signature (cfg->method); + + if (!cfg->arch.cinfo) + cfg->arch.cinfo = get_call_info (cfg->mempool, sig); + cinfo = (CallInfo *)cfg->arch.cinfo; + + // if (cinfo->ret.storage == ArgValuetypeInReg) + // cfg->ret_var_is_local = TRUE; + + sig_ret = mini_get_underlying_type (sig->ret); + if (cinfo->ret.storage == ArgValuetypeAddrInIReg || cinfo->ret.storage == ArgGsharedVTOnStack) { + cfg->vret_addr = mono_compile_create_var (cfg, mono_get_int_type (), OP_ARG); + if (G_UNLIKELY (cfg->verbose_level > 1)) { + printf ("vret_addr = "); + mono_print_ins (cfg->vret_addr); + } + } + + if (cfg->gen_sdb_seq_points) + g_error ("gen_sdb_seq_points not supported"); + + if (cfg->method->save_lmf) + cfg->create_lmf_var = TRUE; + + if (cfg->method->save_lmf) + cfg->lmf_ir = TRUE; +} + +void +mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call) +{ + g_error ("mono_arch_emit_call"); +} + +void +mono_arch_emit_epilog (MonoCompile *cfg) +{ + g_error ("mono_arch_emit_epilog"); +} + +void +mono_arch_emit_exceptions (MonoCompile *cfg) +{ + g_error ("mono_arch_emit_exceptions"); +} + +MonoInst* +mono_arch_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args) +{ + return NULL; +} + +void +mono_arch_emit_outarg_vt (MonoCompile *cfg, MonoInst *ins, MonoInst *src) +{ + g_error ("mono_arch_emit_outarg_vt"); +} + +guint8 * +mono_arch_emit_prolog (MonoCompile *cfg) +{ + g_error ("mono_arch_emit_prolog"); +} + +void +mono_arch_emit_setret (MonoCompile *cfg, MonoMethod *method, MonoInst *val) +{ + MonoType *ret = mini_get_underlying_type (mono_method_signature (method)->ret); + + if (!ret->byref) { + if (ret->type == MONO_TYPE_R4) { + MONO_EMIT_NEW_UNALU (cfg, cfg->r4fp ? OP_RMOVE : OP_FMOVE, cfg->ret->dreg, val->dreg); + return; + } else if (ret->type == MONO_TYPE_R8) { + MONO_EMIT_NEW_UNALU (cfg, OP_FMOVE, cfg->ret->dreg, val->dreg); + return; + } else if (ret->type == MONO_TYPE_I8 || ret->type == MONO_TYPE_U8) { + MONO_EMIT_NEW_UNALU (cfg, OP_LMOVE, cfg->ret->dreg, val->dreg); + return; + } + } + MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->ret->dreg, val->dreg); +} + +void +mono_arch_flush_icache (guint8 *code, gint size) +{ +} + +const char* +mono_arch_fregname (int reg) +{ + return "freg0"; +} + +const char* +mono_arch_regname (int reg) +{ + return "r0"; +} + +LLVMCallInfo* +mono_arch_get_llvm_call_info (MonoCompile *cfg, MonoMethodSignature *sig) +{ + int i, n; + CallInfo *cinfo; + LLVMCallInfo *linfo; + + cinfo = get_call_info (cfg->mempool, sig); + n = cinfo->nargs; + + linfo = mono_mempool_alloc0 (cfg->mempool, sizeof (LLVMCallInfo) + (sizeof (LLVMArgInfo) * n)); + + if (mini_type_is_vtype (sig->ret)) { + /* Vtype returned using a hidden argument */ + linfo->ret.storage = LLVMArgVtypeRetAddr; + // linfo->vret_arg_index = cinfo->vret_arg_index; + } else { + if (sig->ret->type != MONO_TYPE_VOID) + linfo->ret.storage = LLVMArgNormal; + } + + for (i = 0; i < n; ++i) { + ArgInfo *ainfo = &cinfo->args[i]; + + switch (ainfo->storage) { + case ArgOnStack: + linfo->args [i].storage = LLVMArgNormal; + break; + case ArgValuetypeAddrOnStack: + linfo->args [i].storage = LLVMArgVtypeByRef; + break; + case ArgGsharedVTOnStack: + linfo->args [i].storage = LLVMArgGsharedvtVariable; + break; + case ArgValuetypeAddrInIReg: + g_error ("this is only valid for sig->ret"); + break; + } + } + + return linfo; +} + +gboolean +mono_arch_tailcall_supported (MonoCompile *cfg, MonoMethodSignature *caller_sig, MonoMethodSignature *callee_sig) +{ + return FALSE; +} + +#endif // DISABLE_JIT + +int +mono_arch_get_argument_info (MonoMethodSignature *csig, int param_count, MonoJitArgumentInfo *arg_info) +{ + g_error ("mono_arch_get_argument_info"); +} + +GSList* +mono_arch_get_delegate_invoke_impls (void) +{ + g_error ("mono_arch_get_delegate_invoke_impls"); +} + +gpointer +mono_arch_get_gsharedvt_call_info (gpointer addr, MonoMethodSignature *normal_sig, MonoMethodSignature *gsharedvt_sig, gboolean gsharedvt_in, gint32 vcall_offset, gboolean calli) +{ + g_error ("mono_arch_get_gsharedvt_call_info"); + return NULL; +} + +gpointer +mono_arch_get_delegate_invoke_impl (MonoMethodSignature *sig, gboolean has_target) +{ + g_error ("mono_arch_get_delegate_invoke_impl"); +} + +#ifdef HOST_WASM + #include //functions exported to be used by JS +G_BEGIN_DECLS EMSCRIPTEN_KEEPALIVE void mono_set_timeout_exec (int id); //JS functions imported that we use extern void mono_set_timeout (int t, int d); +G_END_DECLS + +#endif // HOST_WASM gpointer mono_arch_get_this_arg_from_call (mgreg_t *regs, guint8 *code) @@ -100,23 +476,11 @@ mono_arch_cpu_enumerate_simd_versions (void) guint32 mono_arch_cpu_optimizations (guint32 *exclude_mask) { + /* No arch specific passes yet */ + *exclude_mask = 0; return 0; } -GSList* -mono_arch_get_delegate_invoke_impls (void) -{ - g_error ("mono_arch_get_delegate_invoke_impls"); - return NULL; -} - -gpointer -mono_arch_get_delegate_invoke_impl (MonoMethodSignature *sig, gboolean has_target) -{ - g_error ("mono_arch_get_delegate_invoke_impl"); - return NULL; -} - mgreg_t mono_arch_context_get_int_reg (MonoContext *ctx, int reg) { @@ -124,13 +488,7 @@ mono_arch_context_get_int_reg (MonoContext *ctx, int reg) return 0; } -int -mono_arch_get_argument_info (MonoMethodSignature *csig, int param_count, MonoJitArgumentInfo *arg_info) -{ - g_error ("mono_arch_get_argument_info"); - return 0; - -} +#ifdef HOST_WASM void mono_runtime_setup_stat_profiler (void) @@ -177,7 +535,6 @@ mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo return FALSE; } - EMSCRIPTEN_KEEPALIVE void mono_set_timeout_exec (int id) { @@ -208,10 +565,14 @@ mono_set_timeout_exec (int id) } } +#endif + void mono_wasm_set_timeout (int timeout, int id) { +#ifdef HOST_WASM mono_set_timeout (timeout, id); +#endif } void @@ -226,10 +587,15 @@ mono_arch_patch_code_new (MonoCompile *cfg, MonoDomain *domain, guint8 *code, Mo g_error ("mono_arch_patch_code_new"); } +#ifdef HOST_WASM + /* The following functions don't belong here, but are due to laziness. */ gboolean mono_w32file_get_volume_information (const gunichar2 *path, gunichar2 *volumename, gint volumesize, gint *outserial, gint *maxcomp, gint *fsflags, gunichar2 *fsbuffer, gint fsbuffersize); + +G_BEGIN_DECLS + void * getgrnam (const char *name); void * getgrgid (gid_t gid); int inotify_init (void); @@ -237,6 +603,7 @@ int inotify_rm_watch (int fd, int wd); int inotify_add_watch (int fd, const char *pathname, uint32_t mask); int sem_timedwait (sem_t *sem, const struct timespec *abs_timeout); +G_END_DECLS //w32file-wasm.c gboolean @@ -257,6 +624,7 @@ mono_w32file_get_volume_information (const gunichar2 *path, gunichar2 *volumenam return status; } +G_BEGIN_DECLS //llvm builtin's that we should not have used in the first place @@ -276,13 +644,13 @@ pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *pa int -pthread_attr_getstacksize (const pthread_attr_t *restrict attr, size_t *restrict stacksize) +pthread_attr_getstacksize (const pthread_attr_t *attr, size_t *stacksize) { return 65536; //wasm page size } int -pthread_sigmask (int how, const sigset_t * restrict set, sigset_t * restrict oset) +pthread_sigmask (int how, const sigset_t *set, sigset_t *oset) { return 0; } @@ -340,3 +708,7 @@ sem_timedwait (sem_t *sem, const struct timespec *abs_timeout) return 0; } + +G_END_DECLS + +#endif // HOST_WASM diff --git a/mono/mini/mini-wasm.h b/mono/mini/mini-wasm.h index 7a8a188307..b5c9e1c979 100644 --- a/mono/mini/mini-wasm.h +++ b/mono/mini/mini-wasm.h @@ -11,6 +11,32 @@ #define WASM_REG_0 0 +#define MONO_ARCH_USE_FPSTACK FALSE + +// Does the ABI have a volatile non-parameter register, so tailcall +// can pass context to generics or interfaces? +#define MONO_ARCH_HAVE_VOLATILE_NON_PARAM_REGISTER 0 + +#define MONO_ARCH_AOT_SUPPORTED 1 +#define MONO_ARCH_LLVM_SUPPORTED 1 +#define MONO_ARCH_GSHARED_SUPPORTED 1 +#define MONO_ARCH_GSHAREDVT_SUPPORTED 1 +#define MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES 1 +#define MONO_ARCH_NEED_DIV_CHECK 1 + +#define MONO_ARCH_EMULATE_FREM 1 +#define MONO_ARCH_FLOAT32_SUPPORTED 1 + +//mini-codegen stubs - this doesn't do anything +#define MONO_ARCH_CALLEE_REGS (1 << 0) +#define MONO_ARCH_CALLEE_FREGS (1 << 1) +#define MONO_ARCH_CALLEE_SAVED_FREGS (1 << 2) +#define MONO_ARCH_CALLEE_SAVED_REGS (1 << 3) +#define MONO_ARCH_INST_FIXED_REG(desc) FALSE +#define MONO_ARCH_INST_IS_REGPAIR(desc) FALSE +#define MONO_ARCH_INST_REGPAIR_REG2(desc,hreg1) (-1) +#define MONO_ARCH_INST_SREG2_MASK(ins) 0 + struct MonoLMF { /* @@ -25,7 +51,7 @@ struct MonoLMF { }; typedef struct { - int dummy; + gpointer cinfo; } MonoCompileArch; #define MONO_ARCH_INIT_TOP_LMF_ENTRY(lmf) do { (lmf)->top_entry = TRUE; } while (0) @@ -47,6 +73,31 @@ typedef struct { /* must be at a power of 2 and >= 8 */ #define MONO_ARCH_FRAME_ALIGNMENT 16 +#define MONO_ARCH_USE_FPSTACK FALSE + +// Does the ABI have a volatile non-parameter register, so tailcall +// can pass context to generics or interfaces? +#define MONO_ARCH_HAVE_VOLATILE_NON_PARAM_REGISTER 0 + +#define MONO_ARCH_AOT_SUPPORTED 1 +#define MONO_ARCH_LLVM_SUPPORTED 1 +#define MONO_ARCH_GSHAREDVT_SUPPORTED 1 +#define MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES 1 + +#define MONO_ARCH_EMULATE_FREM 1 +#define MONO_ARCH_FLOAT32_SUPPORTED 1 + +//mini-codegen stubs - this doesn't do anything +#define MONO_ARCH_CALLEE_REGS (1 << 0) +#define MONO_ARCH_CALLEE_FREGS (1 << 1) +#define MONO_ARCH_CALLEE_SAVED_FREGS (1 << 2) +#define MONO_ARCH_CALLEE_SAVED_REGS (1 << 3) +#define MONO_ARCH_INST_FIXED_REG(desc) FALSE +#define MONO_ARCH_INST_IS_REGPAIR(desc) FALSE +#define MONO_ARCH_INST_REGPAIR_REG2(desc,hreg1) (-1) +#define MONO_ARCH_INST_SREG2_MASK(ins) 0 + + #define MONO_ARCH_INTERPRETER_SUPPORTED 1 #define MONO_ARCH_HAS_REGISTER_ICALL 1 #define MONO_ARCH_HAVE_PATCH_CODE_NEW 1 @@ -54,11 +105,15 @@ typedef struct { void mono_wasm_debugger_init (void); +G_BEGIN_DECLS // sdks/wasm/driver.c is C and uses this + void mono_wasm_enable_debugging (void); + +G_END_DECLS + void mono_wasm_breakpoint_hit (void); void mono_wasm_set_timeout (int timeout, int id); -void mono_sdb_single_step_trampoline (void); void mono_wasm_single_step_hit (void); void mono_wasm_breakpoint_hit (void); diff --git a/mono/mini/mini-windows-dlldac.c b/mono/mini/mini-windows-dlldac.c index 5d19a16354..0cdb9e0989 100644 --- a/mono/mini/mini-windows-dlldac.c +++ b/mono/mini/mini-windows-dlldac.c @@ -38,6 +38,7 @@ read_memory(PVOID user_context, LPCVOID base_address, PVOID buffer, SIZE_T size, return ReadProcessMemory ((HANDLE)user_context, base_address, buffer, size, read); } +MONO_EXTERN_C MONO_API_EXPORT DWORD OutOfProcessFunctionTableCallbackEx (ReadMemoryFunction read_memory, PVOID user_context, PVOID table_address, PDWORD entries, PRUNTIME_FUNCTION *functions) { @@ -50,7 +51,7 @@ OutOfProcessFunctionTableCallbackEx (ReadMemoryFunction read_memory, PVOID user_ if (read_memory (user_context, table_address, &func_table, sizeof (func_table), &reads)) { if (func_table.Context != NULL && read_memory (user_context, func_table.Context, &func_table_entry, sizeof (func_table_entry), &reads)) { if (func_table_entry.rt_funcs_current_count != 0) { - rt_funcs = HeapAlloc (GetProcessHeap (), HEAP_ZERO_MEMORY, func_table_entry.rt_funcs_current_count * sizeof (RUNTIME_FUNCTION)); + rt_funcs = (PRUNTIME_FUNCTION)HeapAlloc (GetProcessHeap (), HEAP_ZERO_MEMORY, func_table_entry.rt_funcs_current_count * sizeof (RUNTIME_FUNCTION)); if (rt_funcs) { if (read_memory (user_context, func_table_entry.rt_funcs, rt_funcs, func_table_entry.rt_funcs_current_count * sizeof (RUNTIME_FUNCTION), &reads)) { *entries = func_table_entry.rt_funcs_current_count; @@ -65,6 +66,7 @@ OutOfProcessFunctionTableCallbackEx (ReadMemoryFunction read_memory, PVOID user_ return result; } +MONO_EXTERN_C MONO_API_EXPORT DWORD OutOfProcessFunctionTableCallback (HANDLE process, PVOID table_address, PDWORD entries, PRUNTIME_FUNCTION *functions) { @@ -73,6 +75,7 @@ OutOfProcessFunctionTableCallback (HANDLE process, PVOID table_address, PDWORD e #endif /* defined(TARGET_AMD64) && !defined(DISABLE_JIT) */ #ifdef _MSC_VER +MONO_EXTERN_C BOOL APIENTRY DllMain (HMODULE module_handle, DWORD reason, LPVOID reserved) { diff --git a/mono/mini/mini-windows-dllmain.c b/mono/mini/mini-windows-dllmain.c index 2a8200500b..cc48308af8 100644 --- a/mono/mini/mini-windows-dllmain.c +++ b/mono/mini/mini-windows-dllmain.c @@ -17,6 +17,7 @@ #ifdef HOST_WIN32 #include +MONO_EXTERN_C BOOL APIENTRY DllMain (HMODULE module_handle, DWORD reason, LPVOID reserved) { if (!mono_gc_dllmain (module_handle, reason, reserved)) @@ -39,4 +40,3 @@ BOOL APIENTRY DllMain (HMODULE module_handle, DWORD reason, LPVOID reserved) return TRUE; } #endif - diff --git a/mono/mini/mini-windows.c b/mono/mini/mini-windows.c index 8291692299..1ddb7aa79c 100644 --- a/mono/mini/mini-windows.c +++ b/mono/mini/mini-windows.c @@ -397,11 +397,6 @@ mono_setup_thread_context(DWORD thread_id, MonoContext *mono_context) gboolean mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo *info, void *sigctx) { - MonoJitTlsData *jit_tls; - void *domain; - MonoLMF *lmf = NULL; - gpointer *addr; - tctx->valid = FALSE; tctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = NULL; tctx->unwind_data [MONO_UNWIND_DATA_LMF] = NULL; @@ -417,9 +412,9 @@ mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo } /* mono_set_jit_tls () sets this */ - jit_tls = mono_thread_info_tls_get (info, TLS_KEY_JIT_TLS); + void *jit_tls = mono_thread_info_tls_get (info, TLS_KEY_JIT_TLS); /* SET_APPDOMAIN () sets this */ - domain = mono_thread_info_tls_get (info, TLS_KEY_DOMAIN); + void *domain = mono_thread_info_tls_get (info, TLS_KEY_DOMAIN); /*Thread already started to cleanup, can no longer capture unwind state*/ if (!jit_tls || !domain) @@ -431,7 +426,8 @@ mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo * can be accessed through MonoThreadInfo. */ /* mono_set_lmf_addr () sets this */ - addr = mono_thread_info_tls_get (info, TLS_KEY_LMF_ADDR); + MonoLMF *lmf = NULL; + MonoLMF **addr = (MonoLMF**)mono_thread_info_tls_get (info, TLS_KEY_LMF_ADDR); if (addr) lmf = *addr; diff --git a/mono/mini/mini-x86.c.REMOVED.git-id b/mono/mini/mini-x86.c.REMOVED.git-id index f9def54412..2c5aa21b01 100644 --- a/mono/mini/mini-x86.c.REMOVED.git-id +++ b/mono/mini/mini-x86.c.REMOVED.git-id @@ -1 +1 @@ -ba5f3f673950c7e90479d726539b812ef95eabfe \ No newline at end of file +3b0e3b222a98cbdf22471684c127cb1614472536 \ No newline at end of file diff --git a/mono/mini/mini-x86.h b/mono/mini/mini-x86.h index 866407f67a..137b44f961 100644 --- a/mono/mini/mini-x86.h +++ b/mono/mini/mini-x86.h @@ -155,9 +155,9 @@ typedef struct { gboolean need_stack_frame_inited; gboolean need_stack_frame; int sp_fp_offset, param_area_size; - gpointer cinfo; - gpointer ss_tramp_var; - gpointer bp_tramp_var; + CallInfo *cinfo; + MonoInst *ss_tramp_var; + MonoInst *bp_tramp_var; } MonoCompileArch; #define MONO_CONTEXT_SET_LLVM_EXC_REG(ctx, exc) do { (ctx)->eax = (gsize)exc; } while (0) @@ -166,7 +166,6 @@ typedef struct { #define MONO_INIT_CONTEXT_FROM_FUNC(ctx, start_func) do { \ unsigned int stackptr; \ - mono_arch_flush_register_windows (); \ { \ __asm mov stackptr, ebp \ } \ @@ -178,7 +177,6 @@ typedef struct { #else #define MONO_INIT_CONTEXT_FROM_FUNC(ctx,start_func) do { \ - mono_arch_flush_register_windows (); \ MONO_CONTEXT_SET_IP ((ctx), (start_func)); \ MONO_CONTEXT_SET_BP ((ctx), __builtin_frame_address (0)); \ MONO_CONTEXT_SET_SP ((ctx), __builtin_frame_address (0)); \ @@ -310,7 +308,7 @@ typedef struct { guint8 pass_empty_struct : 1; // Set in scenarios when empty structs needs to be represented as argument. } ArgInfo; -typedef struct { +struct CallInfo { int nargs; guint32 stack_usage; guint32 reg_usage; @@ -326,7 +324,7 @@ typedef struct { ArgInfo ret; ArgInfo sig_cookie; ArgInfo args [1]; -} CallInfo; +}; guint32 mono_x86_get_this_arg_offset (MonoMethodSignature *sig); diff --git a/mono/mini/mini.c.REMOVED.git-id b/mono/mini/mini.c.REMOVED.git-id index db083b39d7..05b350ceb8 100644 --- a/mono/mini/mini.c.REMOVED.git-id +++ b/mono/mini/mini.c.REMOVED.git-id @@ -1 +1 @@ -95a16954baa4e86f8b831345b14d2d152ceec11f \ No newline at end of file +5e32a267a8d73b48dd3d039850d347af9d3f135e \ No newline at end of file diff --git a/mono/mini/mini.h.REMOVED.git-id b/mono/mini/mini.h.REMOVED.git-id index 974857809d..1dd837f5d6 100644 --- a/mono/mini/mini.h.REMOVED.git-id +++ b/mono/mini/mini.h.REMOVED.git-id @@ -1 +1 @@ -1ee5872c77a48d33f9f56fcda1d940fbbf612cc3 \ No newline at end of file +438aa6d7b5a20ce512ecb31cd610e36c5beadbc5 \ No newline at end of file diff --git a/mono/mini/mixed.cs b/mono/mini/mixed.cs index 5d4b808895..3acae875ce 100644 --- a/mono/mini/mixed.cs +++ b/mono/mini/mixed.cs @@ -283,4 +283,24 @@ class Tests return 5; return 0; } -} \ No newline at end of file + + // Finally exception will be thrown from this stack : interp -> jit -> eh -> interp + // Test that we propagate the finally exception over the jitted frames + public static int test_0_finex () { + bool called_finally = false; + try { + try { + JitClass.throw_ex (); + return 3; + } finally { + called_finally = true; + throw new Exception ("E2"); + } + } catch (Exception) { + if (!called_finally) + return 1; + return 0; + } + return 2; + } +} diff --git a/mono/mini/objects.cs b/mono/mini/objects.cs index 4ad7fb70ab..6477ee96e6 100644 --- a/mono/mini/objects.cs +++ b/mono/mini/objects.cs @@ -1389,6 +1389,7 @@ ncells ) { return 1.4e-45f; } +#if !NO_BITCODE [Category ("!BITCODE")] // bug #59953 public static int test_0_float_return_spill () { // The return value of return_float () is spilled because of the @@ -1397,6 +1398,7 @@ ncells ) { float f = return_float (); return (float)o == f ? 0 : 1; } +#endif class R4Holder { public static float pi = 3.14f; diff --git a/mono/mini/optflags-def.h b/mono/mini/optflags-def.h index 2fdccb2556..481abfee0c 100644 --- a/mono/mini/optflags-def.h +++ b/mono/mini/optflags-def.h @@ -1,3 +1,5 @@ +// This file must be sorted based on the second column. +// i.e. so that designated initializers are not required. OPTFLAG(PEEPHOLE ,0, "peephole", "Peephole postpass") OPTFLAG(BRANCH ,1, "branch", "Branch optimizations") OPTFLAG(INLINE ,2, "inline", "Inline method calls") diff --git a/mono/mini/seq-points.c b/mono/mini/seq-points.c index 091bdb33cf..849297cc38 100644 --- a/mono/mini/seq-points.c +++ b/mono/mini/seq-points.c @@ -37,7 +37,7 @@ recursively_make_pred_seq_points (MonoCompile *cfg, MonoBasicBlock *bb) GHashTable *seen = g_hash_table_new_full (g_direct_hash, NULL, NULL, NULL); // Insert/remove sentinel into the memoize table to detect loops containing bb - bb->pred_seq_points = MONO_SEQ_SEEN_LOOP; + bb->pred_seq_points = (MonoInst**)MONO_SEQ_SEEN_LOOP; for (int i = 0; i < bb->in_count; ++i) { MonoBasicBlock *in_bb = bb->in_bb [i]; @@ -78,7 +78,7 @@ recursively_make_pred_seq_points (MonoCompile *cfg, MonoBasicBlock *bb) bb->num_pred_seq_points = predecessors->len; for (int newer = 0; newer < bb->num_pred_seq_points; newer++) { - bb->pred_seq_points [newer] = g_array_index(predecessors, gpointer, newer); + bb->pred_seq_points [newer] = g_array_index(predecessors, MonoInst*, newer); } } @@ -124,7 +124,8 @@ mono_save_seq_point_info (MonoCompile *cfg, MonoJitInfo *jinfo) sp->native_offset = ins->inst_offset; if (ins->flags & MONO_INST_NONEMPTY_STACK) sp->flags |= MONO_SEQ_POINT_FLAG_NONEMPTY_STACK; - + if (ins->flags & MONO_INST_NESTED_CALL) + sp->flags |= MONO_SEQ_POINT_FLAG_NESTED_CALL; /* Used below */ ins->backend.size = i; } diff --git a/mono/mini/simd-intrinsics.c b/mono/mini/simd-intrinsics.c index 50c174aa7a..c2d2767269 100644 --- a/mono/mini/simd-intrinsics.c +++ b/mono/mini/simd-intrinsics.c @@ -605,7 +605,7 @@ static MonoInst* emit_sys_numerics_vectors_intrinsics (MonoCompile *cfg, MonoMet static int simd_intrinsic_compare_by_name (const void *key, const void *value) { - return strcmp (key, method_name (((SimdIntrinsic *)value)->name)); + return strcmp ((const char*)key, method_name (((SimdIntrinsic *)value)->name)); } typedef enum { @@ -817,6 +817,12 @@ mono_simd_simplify_indirection (MonoCompile *cfg) g_free (target_bb); } +/* +* Windows x64 value type ABI uses reg/stack references (ArgValuetypeAddrInIReg/ArgValuetypeAddrOnStack) +* for function arguments. When using SIMD intrinsics arguments optimized into OP_ARG needs to be decomposed +* into correspondig SIMD LOADX/STOREX instructions. +*/ +#if defined(TARGET_WIN32) && defined(TARGET_AMD64) static gboolean decompose_vtype_opt_uses_simd_intrinsics (MonoCompile *cfg, MonoInst *ins) { @@ -837,8 +843,9 @@ decompose_vtype_opt_uses_simd_intrinsics (MonoCompile *cfg, MonoInst *ins) } static void -decompose_vtype_opt_load_arg (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, guint32 *sreg) +decompose_vtype_opt_load_arg (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, gint32 *sreg_int32) { + guint32 *sreg = (guint32*)sreg_int32; MonoInst *src_var = get_vreg_to_inst (cfg, *sreg); if (src_var && src_var->opcode == OP_ARG && src_var->klass && MONO_CLASS_IS_SIMD (cfg, src_var->klass)) { MonoInst *varload_ins, *load_ins; @@ -854,12 +861,6 @@ decompose_vtype_opt_load_arg (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *in } } -/* -* Windows x64 value type ABI uses reg/stack references (ArgValuetypeAddrInIReg/ArgValuetypeAddrOnStack) -* for function arguments. When using SIMD intrinsics arguments optimized into OP_ARG needs to be decomposed -* into correspondig SIMD LOADX/STOREX instructions. -*/ -#if defined(TARGET_WIN32) && defined(TARGET_AMD64) void mono_simd_decompose_intrinsic (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins) { @@ -2408,7 +2409,7 @@ emit_vector_t_intrinsics (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSigna /* Load the array slice into the simd reg */ ldelema_ins = mini_emit_ldelema_1_ins (cfg, mono_class_from_mono_type (etype), array_ins, index_ins, TRUE); g_assert (args [0]->opcode == OP_LDADDR); - var = args [0]->inst_p0; + var = (MonoInst*)args [0]->inst_p0; EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADX_MEMBASE, var->dreg, ldelema_ins->dreg, 0); ins->klass = cmethod->klass; return args [0]; @@ -2552,7 +2553,7 @@ emit_vector_t_intrinsics (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSigna /* Load the simd reg into the array slice */ ldelema_ins = mini_emit_ldelema_1_ins (cfg, mono_class_from_mono_type (etype), array_ins, index_ins, TRUE); g_assert (args [0]->opcode == OP_LDADDR); - var = args [0]->inst_p0; + var = (MonoInst*)args [0]->inst_p0; EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STOREX_MEMBASE, ldelema_ins->dreg, 0, var->dreg); ins->klass = cmethod->klass; return args [0]; diff --git a/mono/mini/ssa.c b/mono/mini/ssa.c index da2776244c..5681a25784 100644 --- a/mono/mini/ssa.c +++ b/mono/mini/ssa.c @@ -465,7 +465,7 @@ mono_ssa_compute (MonoCompile *cfg) /* Renaming phase */ - stack = (MonoInst **)alloca (sizeof (MonoInst *) * cfg->num_varinfo); + stack = g_newa (MonoInst*, cfg->num_varinfo); memset (stack, 0, sizeof (MonoInst *) * cfg->num_varinfo); lvreg_stack = g_new0 (guint32, cfg->next_vreg); diff --git a/mono/mini/tasklets.c b/mono/mini/tasklets.c index 37feb280bf..1d85059720 100644 --- a/mono/mini/tasklets.c +++ b/mono/mini/tasklets.c @@ -9,9 +9,12 @@ #include "mono/metadata/icall-internals.h" #include "mini.h" #include "mini-runtime.h" +#include "mono/metadata/loader-internals.h" #if defined(MONO_SUPPORT_TASKLETS) +#include "mono/metadata/loader-internals.h" + static mono_mutex_t tasklets_mutex; #define tasklets_lock() mono_os_mutex_lock(&tasklets_mutex) #define tasklets_unlock() mono_os_mutex_unlock(&tasklets_mutex) @@ -114,7 +117,7 @@ continuation_store (MonoContinuation *cont, int state, MonoException **e) mono_gc_free_fixed (cont->saved_stack); cont->stack_used_size = num_bytes; cont->stack_alloc_size = num_bytes * 1.1; - cont->saved_stack = mono_gc_alloc_fixed (cont->stack_alloc_size, NULL, MONO_ROOT_SOURCE_THREADING, NULL, "Tasklet Saved Stack"); + cont->saved_stack = mono_gc_alloc_fixed_no_descriptor (cont->stack_alloc_size, MONO_ROOT_SOURCE_THREADING, NULL, "Tasklet Saved Stack"); tasklets_unlock (); } memcpy (cont->saved_stack, cont->return_sp, num_bytes); diff --git a/mono/mini/test_op_il_seq_point.sh b/mono/mini/test_op_il_seq_point.sh index ee235f5c73..e78c83d9a9 100755 --- a/mono/mini/test_op_il_seq_point.sh +++ b/mono/mini/test_op_il_seq_point.sh @@ -8,8 +8,14 @@ TMP_FILE_PREFIX=$(basename $0).tmp BASEDIR=$(dirname $0) case "$(uname -s)" in - CYGWIN*) PLATFORM_PATH_SEPARATOR=';';; - *) PLATFORM_PATH_SEPARATOR=':';; + CYGWIN*) + PLATFORM_PATH_SEPARATOR=';' + PLATFORM_AOT_ARGUMENT=--aot=asmonly + ;; + *) + PLATFORM_PATH_SEPARATOR=':' + PLATFORM_AOT_ARGUMENT=--aot + ;; esac MONO_PATH=$BASEDIR/../../mcs/class/lib/$DEFAULT_PROFILE$PLATFORM_PATH_SEPARATOR$BASEDIR @@ -22,7 +28,7 @@ tmp_file () { } clean_aot () { - rm -rf *.exe.so *.exe.dylib *.exe.dylib.dSYM *.exe.dll + rm -rf *.exe.so *.exe.dylib *.exe.dylib.dSYM *.exe.dll *.exe.s } # The test compares the generated native code size between a compilation with and without seq points. @@ -34,7 +40,7 @@ get_methods () { MONO_PATH=$1 $2 -v --compile-all=1 $3 | grep '^Method .*code length' | sed 's/emitted[^()]*//' | sort else clean_aot - MONO_PATH=$1 $2 -v --aot $3 | grep '^Method .*code length' | sed 's/emitted[^()]*//' | sort + MONO_PATH=$1 $2 -v $PLATFORM_AOT_ARGUMENT $3 | grep '^Method .*code length' | sed 's/emitted[^()]*//' | sort fi } @@ -43,7 +49,7 @@ get_method () { MONO_VERBOSE_METHOD="$4" MONO_PATH=$1 $2 --compile-all=1 $3 | sed 's/0x[0-9a-fA-F]*/0x0/g' else clean_aot - MONO_VERBOSE_METHOD="$4" MONO_PATH=$1 $2 --aot $3 | sed 's/0x[0-9a-fA-F]*/0x0/g' + MONO_VERBOSE_METHOD="$4" MONO_PATH=$1 $2 $PLATFORM_AOT_ARGUMENT $3 | sed 's/0x[0-9a-fA-F]*/0x0/g' fi } diff --git a/mono/mini/trace.c b/mono/mini/trace.c index 9c512c7c50..51ab0a5203 100644 --- a/mono/mini/trace.c +++ b/mono/mini/trace.c @@ -168,7 +168,7 @@ mono_trace_enter_method (MonoMethod *method, char *ebp) sig = mono_method_signature (method); - arg_info = (MonoJitArgumentInfo *)alloca (sizeof (MonoJitArgumentInfo) * (sig->param_count + 1)); + arg_info = g_newa (MonoJitArgumentInfo, sig->param_count + 1); if (method->is_inflated) { /* FIXME: Might be better to pass the ji itself */ diff --git a/mono/mini/tramp-amd64-gsharedvt.c b/mono/mini/tramp-amd64-gsharedvt.c index 2ea5645a9d..24bf1fe6f2 100644 --- a/mono/mini/tramp-amd64-gsharedvt.c +++ b/mono/mini/tramp-amd64-gsharedvt.c @@ -81,7 +81,7 @@ mono_amd64_start_gsharedvt_call (GSharedVtCallInfo *info, gpointer *caller, gpoi case GSHAREDVT_ARG_BYREF_TO_BYVAL: { int slot_count = (src >> SLOT_COUNT_SHIFT) & SLOT_COUNT_MASK; int j; - gpointer *addr = caller [source_reg]; + gpointer *addr = (gpointer*)caller [source_reg]; for (j = 0; j < slot_count; ++j) callee [dest_reg + j] = addr [j]; @@ -89,21 +89,21 @@ mono_amd64_start_gsharedvt_call (GSharedVtCallInfo *info, gpointer *caller, gpoi break; } case GSHAREDVT_ARG_BYREF_TO_BYVAL_U1: { - guint8 *addr = caller [source_reg]; + guint8 *addr = (guint8*)caller [source_reg]; callee [dest_reg] = (gpointer)(mgreg_t)*addr; DEBUG_AMD64_GSHAREDVT_PRINT ("[%d] <- (u1) [%d] (%p) <- (%p)\n", dest_reg, source_reg, &callee [dest_reg], &caller [source_reg]); break; } case GSHAREDVT_ARG_BYREF_TO_BYVAL_U2: { - guint16 *addr = caller [source_reg]; + guint16 *addr = (guint16*)caller [source_reg]; callee [dest_reg] = (gpointer)(mgreg_t)*addr; DEBUG_AMD64_GSHAREDVT_PRINT ("[%d] <- (u2) [%d] (%p) <- (%p)\n", dest_reg, source_reg, &callee [dest_reg], &caller [source_reg]); break; } case GSHAREDVT_ARG_BYREF_TO_BYVAL_U4: { - guint32 *addr = caller [source_reg]; + guint32 *addr = (guint32*)caller [source_reg]; callee [dest_reg] = (gpointer)(mgreg_t)*addr; DEBUG_AMD64_GSHAREDVT_PRINT ("[%d] <- (u4) [%d] (%p) <- (%p)\n", dest_reg, source_reg, &callee [dest_reg], &caller [source_reg]); @@ -117,7 +117,7 @@ mono_amd64_start_gsharedvt_call (GSharedVtCallInfo *info, gpointer *caller, gpoi //Can't handle for now if (info->vcall_offset != -1){ - MonoObject *this_obj = caller [0]; + MonoObject *this_obj = (MonoObject*)caller [0]; DEBUG_AMD64_GSHAREDVT_PRINT ("target is a vcall at offset %d\n", info->vcall_offset / 8); if (G_UNLIKELY (!this_obj)) @@ -176,7 +176,7 @@ mono_arch_get_gsharedvt_trampoline (MonoTrampInfo **info, gboolean aot) MonoJumpInfo *ji = NULL; int n_arg_regs, n_arg_fregs, framesize, i; int info_offset, offset, rgctx_arg_reg_offset; - int caller_reg_area_offset, callee_reg_area_offset, callee_stack_area_offset; + int caller_reg_area_offset, callee_reg_area_offset; guint8 *br_out, *br [64], *br_ret [64]; int b_ret_index; int reg_area_size; @@ -252,7 +252,6 @@ mono_arch_get_gsharedvt_trampoline (MonoTrampInfo **info, gboolean aot) /* Allocate callee register area just below the caller area so it can be accessed from start_gsharedvt_call using negative offsets */ /* XXX figure out alignment */ callee_reg_area_offset = reg_area_size - ((n_arg_regs + n_arg_fregs) * 8); /* Ensure alignment */ - callee_stack_area_offset = callee_reg_area_offset + reg_area_size; amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, reg_area_size); /* Allocate stack area used to pass arguments to the method */ diff --git a/mono/mini/tramp-arm-gsharedvt.c b/mono/mini/tramp-arm-gsharedvt.c index 39dbaa535a..a09343896c 100644 --- a/mono/mini/tramp-arm-gsharedvt.c +++ b/mono/mini/tramp-arm-gsharedvt.c @@ -69,7 +69,7 @@ mono_arm_start_gsharedvt_call (GSharedVtCallInfo *info, gpointer *caller, gpoint int nslots = (src >> 8) & 0xff; int src_slot = src & 0xff; int j; - gpointer *addr = caller [src_slot]; + gpointer *addr = (gpointer*)caller [src_slot]; for (j = 0; j < nslots; ++j) callee [dst + j] = addr [j]; @@ -77,28 +77,28 @@ mono_arm_start_gsharedvt_call (GSharedVtCallInfo *info, gpointer *caller, gpoint } case GSHAREDVT_ARG_BYREF_TO_BYVAL_I1: { int src_slot = src & 0xff; - gpointer *addr = caller [src_slot]; + gpointer *addr = (gpointer*)caller [src_slot]; callee [dst] = GINT_TO_POINTER ((int)*(gint8*)addr); break; } case GSHAREDVT_ARG_BYREF_TO_BYVAL_I2: { int src_slot = src & 0xff; - gpointer *addr = caller [src_slot]; + gpointer *addr = (gpointer*)caller [src_slot]; callee [dst] = GINT_TO_POINTER ((int)*(gint16*)addr); break; } case GSHAREDVT_ARG_BYREF_TO_BYVAL_U1: { int src_slot = src & 0xff; - gpointer *addr = caller [src_slot]; + gpointer *addr = (gpointer*)caller [src_slot]; callee [dst] = GUINT_TO_POINTER ((guint)*(guint8*)addr); break; } case GSHAREDVT_ARG_BYREF_TO_BYVAL_U2: { int src_slot = src & 0xff; - gpointer *addr = caller [src_slot]; + gpointer *addr = (gpointer*)caller [src_slot]; callee [dst] = GUINT_TO_POINTER ((guint)*(guint16*)addr); break; @@ -170,7 +170,7 @@ mono_arm_start_gsharedvt_call (GSharedVtCallInfo *info, gpointer *caller, gpoint } if (info->vcall_offset != -1) { - MonoObject *this_obj = caller [0]; + MonoObject *this_obj = (MonoObject*)caller [0]; if (G_UNLIKELY (!this_obj)) return NULL; @@ -291,7 +291,7 @@ mono_arch_get_gsharedvt_trampoline (MonoTrampInfo **info, gboolean aot) } else { ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0); ARM_B (code, 0); - *(gpointer*)code = mono_arm_start_gsharedvt_call; + *(gpointer*)code = (gpointer)mono_arm_start_gsharedvt_call; code += 4; } ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC); diff --git a/mono/mini/tramp-arm.c b/mono/mini/tramp-arm.c index 49be8d5783..129f2d35a2 100644 --- a/mono/mini/tramp-arm.c +++ b/mono/mini/tramp-arm.c @@ -332,7 +332,7 @@ mono_arch_create_generic_trampoline (MonoTrampolineType tramp_type, MonoTrampInf } else { ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0); ARM_B (code, 0); - *(gpointer*)code = mono_thread_force_interruption_checkpoint_noraise; + *(gpointer*)code = (gpointer)mono_thread_force_interruption_checkpoint_noraise; code += 4; } ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC); @@ -377,7 +377,7 @@ mono_arch_create_generic_trampoline (MonoTrampolineType tramp_type, MonoTrampInf if (!aot) { constants = (gpointer*)code; - constants [0] = mono_get_lmf_addr; + constants [0] = (gpointer)mono_get_lmf_addr; constants [1] = (gpointer)mono_get_trampoline_func (tramp_type); /* backpatch by emitting the missing instructions skipped above */ @@ -703,7 +703,7 @@ mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot, MonoTrampInfo **info code += 4; ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_R1); } else { - tramp = mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), &code_len); + tramp = (guint8*)mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), &code_len); /* Jump to the actual trampoline */ ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 0); /* temp reg */ @@ -815,9 +815,9 @@ mono_arch_create_sdb_trampoline (gboolean single_step, MonoTrampInfo **info, gbo ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0); ARM_B (code, 0); if (single_step) - *(gpointer*)code = mini_get_dbg_callbacks ()->single_step_from_context; + *(gpointer*)code = (gpointer)mini_get_dbg_callbacks ()->single_step_from_context; else - *(gpointer*)code = mini_get_dbg_callbacks ()->breakpoint_from_context; + *(gpointer*)code = (gpointer)mini_get_dbg_callbacks ()->breakpoint_from_context; code += 4; ARM_BLX_REG (code, ARMREG_IP); } diff --git a/mono/mini/tramp-arm64-gsharedvt.c b/mono/mini/tramp-arm64-gsharedvt.c index 1e35f6a852..5a2df86d38 100644 --- a/mono/mini/tramp-arm64-gsharedvt.c +++ b/mono/mini/tramp-arm64-gsharedvt.c @@ -84,7 +84,7 @@ mono_arm_start_gsharedvt_call (GSharedVtCallInfo *info, gpointer *caller, gpoint case GSHAREDVT_ARG_BYREF_TO_BYVAL: src_slot = src & 0x3f; dst_slot = dst & 0xffff; - src_ptr = caller [src_slot]; + src_ptr = (guint8*)caller [src_slot]; dst_ptr = (guint8*)(callee + dst_slot) + dst_offset; break; case GSHAREDVT_ARG_BYVAL_TO_BYREF_HFAR4: @@ -156,7 +156,7 @@ mono_arm_start_gsharedvt_call (GSharedVtCallInfo *info, gpointer *caller, gpoint int nslots = (src >> 6) & 0xff; int src_slot = src & 0x3f; int j; - gpointer *addr = caller [src_slot]; + gpointer *addr = (gpointer*)caller [src_slot]; for (j = 0; j < nslots; ++j) callee [dst + j] = addr [j]; @@ -186,7 +186,7 @@ mono_arm_start_gsharedvt_call (GSharedVtCallInfo *info, gpointer *caller, gpoint } if (info->vcall_offset != -1) { - MonoObject *this_obj = caller [0]; + MonoObject *this_obj = (MonoObject*)caller [0]; if (G_UNLIKELY (!this_obj)) return NULL; diff --git a/mono/mini/tramp-arm64.c b/mono/mini/tramp-arm64.c index 925026e586..1456a09a42 100644 --- a/mono/mini/tramp-arm64.c +++ b/mono/mini/tramp-arm64.c @@ -143,13 +143,21 @@ mono_arch_create_generic_trampoline (MonoTrampolineType tramp_type, MonoTrampInf /* Setup stack frame */ imm = frame_size; + mono_add_unwind_op_def_cfa (unwind_ops, code, buf, ARMREG_SP, 0); while (imm > 256) { arm_subx_imm (code, ARMREG_SP, ARMREG_SP, 256); imm -= 256; + mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, frame_size - imm); } arm_subx_imm (code, ARMREG_SP, ARMREG_SP, imm); + mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, frame_size); + arm_stpx (code, ARMREG_FP, ARMREG_LR, ARMREG_SP, 0); + mono_add_unwind_op_offset (unwind_ops, code, buf, ARMREG_LR, -frame_size + 8); + mono_add_unwind_op_offset (unwind_ops, code, buf, ARMREG_FP, -frame_size); + arm_movspx (code, ARMREG_FP, ARMREG_SP); + mono_add_unwind_op_def_cfa_reg (unwind_ops, code, buf, ARMREG_FP); /* Save gregs */ // FIXME: Optimize this @@ -465,7 +473,7 @@ mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot, MonoTrampInfo **info if (aot) { code = mono_arm_emit_aotconst (&ji, code, buf, ARMREG_IP0, MONO_PATCH_INFO_JIT_ICALL_ADDR, g_strdup_printf ("specific_trampoline_lazy_fetch_%u", slot)); } else { - tramp = mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), &code_len); + tramp = (guint8*)mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), &code_len); code = mono_arm_emit_imm64 (code, ARMREG_IP0, (guint64)tramp); } arm_brx (code, ARMREG_IP0); @@ -588,7 +596,7 @@ mono_arch_create_sdb_trampoline (gboolean single_step, MonoTrampInfo **info, gbo else code = mono_arm_emit_aotconst (&ji, code, buf, ARMREG_IP0, MONO_PATCH_INFO_JIT_ICALL_ADDR, "debugger_agent_breakpoint_from_context"); } else { - gpointer addr = single_step ? mini_get_dbg_callbacks ()->single_step_from_context : mini_get_dbg_callbacks ()->breakpoint_from_context; + void (*addr) (MonoContext *ctx) = single_step ? mini_get_dbg_callbacks ()->single_step_from_context : mini_get_dbg_callbacks ()->breakpoint_from_context; code = mono_arm_emit_imm64 (code, ARMREG_IP0, (guint64)addr); } diff --git a/mono/mini/tramp-mips.c b/mono/mini/tramp-mips.c index fd754349e8..1da1cc2f98 100644 --- a/mono/mini/tramp-mips.c +++ b/mono/mini/tramp-mips.c @@ -431,7 +431,7 @@ mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot, MonoTrampInfo **info mips_jr (code, mips_at); mips_nop (code); } else { - tramp = mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), &code_len); + tramp = (guint8*)mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), &code_len); mips_load (code, mips_at, tramp); mips_jr (code, mips_at); mips_nop (code); diff --git a/mono/mini/tramp-ppc.c b/mono/mini/tramp-ppc.c index 413dbf1c2d..840ceaaf22 100644 --- a/mono/mini/tramp-ppc.c +++ b/mono/mini/tramp-ppc.c @@ -646,7 +646,7 @@ mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot, MonoTrampInfo **info ppc_mtctr (code, ppc_r12); ppc_bcctr (code, PPC_BR_ALWAYS, 0); } else { - tramp = mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), + tramp = (guint8*)mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL); /* jump to the actual trampoline */ diff --git a/mono/mini/tramp-s390x.c b/mono/mini/tramp-s390x.c index 37859bfbeb..5e121dc2de 100644 --- a/mono/mini/tramp-s390x.c +++ b/mono/mini/tramp-s390x.c @@ -546,7 +546,7 @@ mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot, MonoTrampInfo **info s390_lgr (code, MONO_ARCH_VTABLE_REG, s390_r2); #endif - tramp = mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), + tramp = (guint8*)mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL); /* jump to the actual trampoline */ diff --git a/mono/mini/tramp-wasm.c b/mono/mini/tramp-wasm.c index 25486b6d4e..a1c7d78018 100644 --- a/mono/mini/tramp-wasm.c +++ b/mono/mini/tramp-wasm.c @@ -7,7 +7,9 @@ void mono_sdb_single_step_trampoline (void); gpointer mono_arch_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len) { - g_error ("mono_arch_create_specific_trampoline"); + //FUN FACT but this is a key used to do reverse lookups when resolving patch entries! + //it's seeded to mono_register_jit_icall_wrapper and then used to reverse that value in mini-llvm + return g_malloc (1); } guchar* @@ -53,7 +55,7 @@ mono_arch_get_interp_to_native_trampoline (MonoTrampInfo **info) { if (info) *info = mono_tramp_info_create ("interp_to_native_trampoline", (guint8*)mono_wasm_interp_to_native_trampoline, 1, NULL, NULL); - return mono_wasm_interp_to_native_trampoline; + return (gpointer)mono_wasm_interp_to_native_trampoline; } guint8* @@ -61,16 +63,48 @@ mono_arch_create_sdb_trampoline (gboolean single_step, MonoTrampInfo **info, gbo { g_assert (!aot); const char *name; - gpointer code; + guint8* code; if (single_step) { name = "sdb_single_step_trampoline"; - code = mono_sdb_single_step_trampoline; + code = (guint8*)mono_wasm_single_step_hit; } else { name = "sdb_breakpoint_trampoline"; - code = mono_wasm_breakpoint_hit; + code = (guint8*)mono_wasm_breakpoint_hit; } if (info) *info = mono_tramp_info_create (name, code, 1, NULL, NULL); return code; } + +guint8* +mono_arch_get_call_target (guint8 *code) +{ + g_error ("mono_arch_get_call_target"); +} + +/* + * mono_arch_get_plt_info_offset: + * + * Return the PLT info offset belonging to the plt entry PLT_ENTRY. + */ +guint32 +mono_arch_get_plt_info_offset (guint8 *plt_entry, mgreg_t *regs, guint8 *code) +{ + g_error ("mono_arch_get_plt_info_offset"); + return *(guint32*)(plt_entry + 6); +} + +gpointer +mono_arch_get_gsharedvt_arg_trampoline (MonoDomain *domain, gpointer arg, gpointer addr) +{ + g_assert_not_reached (); + return NULL; +} + +gpointer +mono_arch_get_gsharedvt_trampoline (MonoTrampInfo **info, gboolean aot) +{ + g_assert_not_reached (); + return NULL; +} diff --git a/mono/mini/tramp-x86-gsharedvt.c b/mono/mini/tramp-x86-gsharedvt.c index 857b99c99d..9a46637c01 100644 --- a/mono/mini/tramp-x86-gsharedvt.c +++ b/mono/mini/tramp-x86-gsharedvt.c @@ -60,7 +60,7 @@ mono_x86_start_gsharedvt_call (GSharedVtCallInfo *info, gpointer *caller, gpoint } if (info->vcall_offset != -1) { - MonoObject *this_obj = caller [0]; + MonoObject *this_obj = (MonoObject*)caller [0]; if (G_UNLIKELY (!this_obj)) return NULL; diff --git a/mono/mini/tramp-x86.c b/mono/mini/tramp-x86.c index 3c04690aa4..498a8f810e 100644 --- a/mono/mini/tramp-x86.c +++ b/mono/mini/tramp-x86.c @@ -493,7 +493,7 @@ mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot, MonoTrampInfo **info code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, g_strdup_printf ("specific_trampoline_lazy_fetch_%u", slot)); x86_jump_reg (code, X86_EAX); } else { - tramp = mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL); + tramp = (guint8*)mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL); /* jump to the actual trampoline */ x86_jump_code (code, tramp); @@ -556,7 +556,7 @@ void mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg) { /* FIXME: This is not thread safe */ - guint8 *code = ji->code_start; + guint8 *code = (guint8*)ji->code_start; x86_push_imm (code, func_arg); x86_call_code (code, (guint8*)func); diff --git a/mono/mini/version.h b/mono/mini/version.h index a3481147fd..db204fc12e 100644 --- a/mono/mini/version.h +++ b/mono/mini/version.h @@ -1 +1 @@ -#define FULL_VERSION "explicit/bcc1b83" +#define FULL_VERSION "explicit/8788708" diff --git a/mono/mini/wasm_m2n_invoke.g.h b/mono/mini/wasm_m2n_invoke.g.h index 8e9e1ebdd2..bb0e7a159a 100644 --- a/mono/mini/wasm_m2n_invoke.g.h +++ b/mono/mini/wasm_m2n_invoke.g.h @@ -5,8 +5,8 @@ static void wasm_invoke_v (void *target_func, InterpMethodArguments *margs) { - void (*func)(void) = target_func; - + typedef void (*T)(void); + T func = (T)target_func; func (); } @@ -14,8 +14,8 @@ wasm_invoke_v (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_vi (void *target_func, InterpMethodArguments *margs) { - void (*func)(int arg_0) = target_func; - + typedef void (*T)(int arg_0); + T func = (T)target_func; func ((int)margs->iargs [0]); } @@ -23,8 +23,8 @@ wasm_invoke_vi (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_vii (void *target_func, InterpMethodArguments *margs) { - void (*func)(int arg_0, int arg_1) = target_func; - + typedef void (*T)(int arg_0, int arg_1); + T func = (T)target_func; func ((int)margs->iargs [0], (int)margs->iargs [1]); } @@ -32,8 +32,8 @@ wasm_invoke_vii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_viii (void *target_func, InterpMethodArguments *margs) { - void (*func)(int arg_0, int arg_1, int arg_2) = target_func; - + typedef void (*T)(int arg_0, int arg_1, int arg_2); + T func = (T)target_func; func ((int)margs->iargs [0], (int)margs->iargs [1], (int)margs->iargs [2]); } @@ -41,8 +41,8 @@ wasm_invoke_viii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_viiii (void *target_func, InterpMethodArguments *margs) { - void (*func)(int arg_0, int arg_1, int arg_2, int arg_3) = target_func; - + typedef void (*T)(int arg_0, int arg_1, int arg_2, int arg_3); + T func = (T)target_func; func ((int)margs->iargs [0], (int)margs->iargs [1], (int)margs->iargs [2], (int)margs->iargs [3]); } @@ -50,8 +50,8 @@ wasm_invoke_viiii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_viiiii (void *target_func, InterpMethodArguments *margs) { - void (*func)(int arg_0, int arg_1, int arg_2, int arg_3, int arg_4) = target_func; - + typedef void (*T)(int arg_0, int arg_1, int arg_2, int arg_3, int arg_4); + T func = (T)target_func; func ((int)margs->iargs [0], (int)margs->iargs [1], (int)margs->iargs [2], (int)margs->iargs [3], (int)margs->iargs [4]); } @@ -59,8 +59,8 @@ wasm_invoke_viiiii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_viiiiii (void *target_func, InterpMethodArguments *margs) { - void (*func)(int arg_0, int arg_1, int arg_2, int arg_3, int arg_4, int arg_5) = target_func; - + typedef void (*T)(int arg_0, int arg_1, int arg_2, int arg_3, int arg_4, int arg_5); + T func = (T)target_func; func ((int)margs->iargs [0], (int)margs->iargs [1], (int)margs->iargs [2], (int)margs->iargs [3], (int)margs->iargs [4], (int)margs->iargs [5]); } @@ -68,8 +68,8 @@ wasm_invoke_viiiiii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_i (void *target_func, InterpMethodArguments *margs) { - int (*func)(void) = target_func; - + typedef int (*T)(void); + T func = (T)target_func; int res = func (); *(int*)margs->retval = res; @@ -78,8 +78,8 @@ wasm_invoke_i (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_ii (void *target_func, InterpMethodArguments *margs) { - int (*func)(int arg_0) = target_func; - + typedef int (*T)(int arg_0); + T func = (T)target_func; int res = func ((int)margs->iargs [0]); *(int*)margs->retval = res; @@ -88,8 +88,8 @@ wasm_invoke_ii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_iii (void *target_func, InterpMethodArguments *margs) { - int (*func)(int arg_0, int arg_1) = target_func; - + typedef int (*T)(int arg_0, int arg_1); + T func = (T)target_func; int res = func ((int)margs->iargs [0], (int)margs->iargs [1]); *(int*)margs->retval = res; @@ -98,8 +98,8 @@ wasm_invoke_iii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_iiii (void *target_func, InterpMethodArguments *margs) { - int (*func)(int arg_0, int arg_1, int arg_2) = target_func; - + typedef int (*T)(int arg_0, int arg_1, int arg_2); + T func = (T)target_func; int res = func ((int)margs->iargs [0], (int)margs->iargs [1], (int)margs->iargs [2]); *(int*)margs->retval = res; @@ -108,8 +108,8 @@ wasm_invoke_iiii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_iiiii (void *target_func, InterpMethodArguments *margs) { - int (*func)(int arg_0, int arg_1, int arg_2, int arg_3) = target_func; - + typedef int (*T)(int arg_0, int arg_1, int arg_2, int arg_3); + T func = (T)target_func; int res = func ((int)margs->iargs [0], (int)margs->iargs [1], (int)margs->iargs [2], (int)margs->iargs [3]); *(int*)margs->retval = res; @@ -118,8 +118,8 @@ wasm_invoke_iiiii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_iiiiii (void *target_func, InterpMethodArguments *margs) { - int (*func)(int arg_0, int arg_1, int arg_2, int arg_3, int arg_4) = target_func; - + typedef int (*T)(int arg_0, int arg_1, int arg_2, int arg_3, int arg_4); + T func = (T)target_func; int res = func ((int)margs->iargs [0], (int)margs->iargs [1], (int)margs->iargs [2], (int)margs->iargs [3], (int)margs->iargs [4]); *(int*)margs->retval = res; @@ -128,8 +128,8 @@ wasm_invoke_iiiiii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_iiiiiii (void *target_func, InterpMethodArguments *margs) { - int (*func)(int arg_0, int arg_1, int arg_2, int arg_3, int arg_4, int arg_5) = target_func; - + typedef int (*T)(int arg_0, int arg_1, int arg_2, int arg_3, int arg_4, int arg_5); + T func = (T)target_func; int res = func ((int)margs->iargs [0], (int)margs->iargs [1], (int)margs->iargs [2], (int)margs->iargs [3], (int)margs->iargs [4], (int)margs->iargs [5]); *(int*)margs->retval = res; @@ -138,8 +138,8 @@ wasm_invoke_iiiiiii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_iiiiiiii (void *target_func, InterpMethodArguments *margs) { - int (*func)(int arg_0, int arg_1, int arg_2, int arg_3, int arg_4, int arg_5, int arg_6) = target_func; - + typedef int (*T)(int arg_0, int arg_1, int arg_2, int arg_3, int arg_4, int arg_5, int arg_6); + T func = (T)target_func; int res = func ((int)margs->iargs [0], (int)margs->iargs [1], (int)margs->iargs [2], (int)margs->iargs [3], (int)margs->iargs [4], (int)margs->iargs [5], (int)margs->iargs [6]); *(int*)margs->retval = res; @@ -148,8 +148,8 @@ wasm_invoke_iiiiiiii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_iiiiiiiii (void *target_func, InterpMethodArguments *margs) { - int (*func)(int arg_0, int arg_1, int arg_2, int arg_3, int arg_4, int arg_5, int arg_6, int arg_7) = target_func; - + typedef int (*T)(int arg_0, int arg_1, int arg_2, int arg_3, int arg_4, int arg_5, int arg_6, int arg_7); + T func = (T)target_func; int res = func ((int)margs->iargs [0], (int)margs->iargs [1], (int)margs->iargs [2], (int)margs->iargs [3], (int)margs->iargs [4], (int)margs->iargs [5], (int)margs->iargs [6], (int)margs->iargs [7]); *(int*)margs->retval = res; @@ -158,8 +158,8 @@ wasm_invoke_iiiiiiiii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_iiliiii (void *target_func, InterpMethodArguments *margs) { - int (*func)(int arg_0, gint64 arg_1, int arg_2, int arg_3, int arg_4, int arg_5) = target_func; - + typedef int (*T)(int arg_0, gint64 arg_1, int arg_2, int arg_3, int arg_4, int arg_5); + T func = (T)target_func; int res = func ((int)margs->iargs [0], get_long_arg (margs, 1), (int)margs->iargs [3], (int)margs->iargs [4], (int)margs->iargs [5], (int)margs->iargs [6]); *(int*)margs->retval = res; @@ -168,8 +168,8 @@ wasm_invoke_iiliiii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_l (void *target_func, InterpMethodArguments *margs) { - gint64 (*func)(void) = target_func; - + typedef gint64 (*T)(void); + T func = (T)target_func; gint64 res = func (); *(gint64*)margs->retval = res; @@ -178,8 +178,8 @@ wasm_invoke_l (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_ll (void *target_func, InterpMethodArguments *margs) { - gint64 (*func)(gint64 arg_0) = target_func; - + typedef gint64 (*T)(gint64 arg_0); + T func = (T)target_func; gint64 res = func (get_long_arg (margs, 0)); *(gint64*)margs->retval = res; @@ -188,8 +188,8 @@ wasm_invoke_ll (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_li (void *target_func, InterpMethodArguments *margs) { - gint64 (*func)(int arg_0) = target_func; - + typedef gint64 (*T)(int arg_0); + T func = (T)target_func; gint64 res = func ((int)margs->iargs [0]); *(gint64*)margs->retval = res; @@ -198,8 +198,8 @@ wasm_invoke_li (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_lil (void *target_func, InterpMethodArguments *margs) { - gint64 (*func)(int arg_0, gint64 arg_1) = target_func; - + typedef gint64 (*T)(int arg_0, gint64 arg_1); + T func = (T)target_func; gint64 res = func ((int)margs->iargs [0], get_long_arg (margs, 1)); *(gint64*)margs->retval = res; @@ -208,8 +208,8 @@ wasm_invoke_lil (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_lilii (void *target_func, InterpMethodArguments *margs) { - gint64 (*func)(int arg_0, gint64 arg_1, int arg_2, int arg_3) = target_func; - + typedef gint64 (*T)(int arg_0, gint64 arg_1, int arg_2, int arg_3); + T func = (T)target_func; gint64 res = func ((int)margs->iargs [0], get_long_arg (margs, 1), (int)margs->iargs [3], (int)margs->iargs [4]); *(gint64*)margs->retval = res; @@ -218,8 +218,8 @@ wasm_invoke_lilii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_dd (void *target_func, InterpMethodArguments *margs) { - double (*func)(double arg_0) = target_func; - + typedef double (*T)(double arg_0); + T func = (T)target_func; double res = func (margs->fargs [FIDX (0)]); *(double*)margs->retval = res; @@ -228,8 +228,8 @@ wasm_invoke_dd (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_ddd (void *target_func, InterpMethodArguments *margs) { - double (*func)(double arg_0, double arg_1) = target_func; - + typedef double (*T)(double arg_0, double arg_1); + T func = (T)target_func; double res = func (margs->fargs [FIDX (0)], margs->fargs [FIDX (1)]); *(double*)margs->retval = res; @@ -238,8 +238,8 @@ wasm_invoke_ddd (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_vif (void *target_func, InterpMethodArguments *margs) { - void (*func)(int arg_0, float arg_1) = target_func; - + typedef void (*T)(int arg_0, float arg_1); + T func = (T)target_func; func ((int)margs->iargs [0], *(float*)&margs->fargs [FIDX (0)]); } @@ -247,8 +247,8 @@ wasm_invoke_vif (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_viff (void *target_func, InterpMethodArguments *margs) { - void (*func)(int arg_0, float arg_1, float arg_2) = target_func; - + typedef void (*T)(int arg_0, float arg_1, float arg_2); + T func = (T)target_func; func ((int)margs->iargs [0], *(float*)&margs->fargs [FIDX (0)], *(float*)&margs->fargs [FIDX (1)]); } @@ -256,8 +256,8 @@ wasm_invoke_viff (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_viffff (void *target_func, InterpMethodArguments *margs) { - void (*func)(int arg_0, float arg_1, float arg_2, float arg_3, float arg_4) = target_func; - + typedef void (*T)(int arg_0, float arg_1, float arg_2, float arg_3, float arg_4); + T func = (T)target_func; func ((int)margs->iargs [0], *(float*)&margs->fargs [FIDX (0)], *(float*)&margs->fargs [FIDX (1)], *(float*)&margs->fargs [FIDX (2)], *(float*)&margs->fargs [FIDX (3)]); } @@ -265,8 +265,8 @@ wasm_invoke_viffff (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_vifffffi (void *target_func, InterpMethodArguments *margs) { - void (*func)(int arg_0, float arg_1, float arg_2, float arg_3, float arg_4, float arg_5, int arg_6) = target_func; - + typedef void (*T)(int arg_0, float arg_1, float arg_2, float arg_3, float arg_4, float arg_5, int arg_6); + T func = (T)target_func; func ((int)margs->iargs [0], *(float*)&margs->fargs [FIDX (0)], *(float*)&margs->fargs [FIDX (1)], *(float*)&margs->fargs [FIDX (2)], *(float*)&margs->fargs [FIDX (3)], *(float*)&margs->fargs [FIDX (4)], (int)margs->iargs [1]); } @@ -274,8 +274,8 @@ wasm_invoke_vifffffi (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_ff (void *target_func, InterpMethodArguments *margs) { - float (*func)(float arg_0) = target_func; - + typedef float (*T)(float arg_0); + T func = (T)target_func; float res = func (*(float*)&margs->fargs [FIDX (0)]); *(float*)margs->retval = res; @@ -284,8 +284,8 @@ wasm_invoke_ff (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_fff (void *target_func, InterpMethodArguments *margs) { - float (*func)(float arg_0, float arg_1) = target_func; - + typedef float (*T)(float arg_0, float arg_1); + T func = (T)target_func; float res = func (*(float*)&margs->fargs [FIDX (0)], *(float*)&margs->fargs [FIDX (1)]); *(float*)margs->retval = res; @@ -294,8 +294,8 @@ wasm_invoke_fff (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_di (void *target_func, InterpMethodArguments *margs) { - double (*func)(int arg_0) = target_func; - + typedef double (*T)(int arg_0); + T func = (T)target_func; double res = func ((int)margs->iargs [0]); *(double*)margs->retval = res; @@ -304,8 +304,8 @@ wasm_invoke_di (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_fi (void *target_func, InterpMethodArguments *margs) { - float (*func)(int arg_0) = target_func; - + typedef float (*T)(int arg_0); + T func = (T)target_func; float res = func ((int)margs->iargs [0]); *(float*)margs->retval = res; @@ -314,8 +314,8 @@ wasm_invoke_fi (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_iil (void *target_func, InterpMethodArguments *margs) { - int (*func)(int arg_0, gint64 arg_1) = target_func; - + typedef int (*T)(int arg_0, gint64 arg_1); + T func = (T)target_func; int res = func ((int)margs->iargs [0], get_long_arg (margs, 1)); *(int*)margs->retval = res; @@ -324,8 +324,8 @@ wasm_invoke_iil (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_iili (void *target_func, InterpMethodArguments *margs) { - int (*func)(int arg_0, gint64 arg_1, int arg_2) = target_func; - + typedef int (*T)(int arg_0, gint64 arg_1, int arg_2); + T func = (T)target_func; int res = func ((int)margs->iargs [0], get_long_arg (margs, 1), (int)margs->iargs [3]); *(int*)margs->retval = res; @@ -334,8 +334,8 @@ wasm_invoke_iili (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_iillli (void *target_func, InterpMethodArguments *margs) { - int (*func)(int arg_0, gint64 arg_1, gint64 arg_2, gint64 arg_3, int arg_4) = target_func; - + typedef int (*T)(int arg_0, gint64 arg_1, gint64 arg_2, gint64 arg_3, int arg_4); + T func = (T)target_func; int res = func ((int)margs->iargs [0], get_long_arg (margs, 1), get_long_arg (margs, 3), get_long_arg (margs, 5), (int)margs->iargs [7]); *(int*)margs->retval = res; @@ -344,8 +344,8 @@ wasm_invoke_iillli (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_idiii (void *target_func, InterpMethodArguments *margs) { - int (*func)(double arg_0, int arg_1, int arg_2, int arg_3) = target_func; - + typedef int (*T)(double arg_0, int arg_1, int arg_2, int arg_3); + T func = (T)target_func; int res = func (margs->fargs [FIDX (0)], (int)margs->iargs [0], (int)margs->iargs [1], (int)margs->iargs [2]); *(int*)margs->retval = res; @@ -354,8 +354,8 @@ wasm_invoke_idiii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_lii (void *target_func, InterpMethodArguments *margs) { - gint64 (*func)(int arg_0, int arg_1) = target_func; - + typedef gint64 (*T)(int arg_0, int arg_1); + T func = (T)target_func; gint64 res = func ((int)margs->iargs [0], (int)margs->iargs [1]); *(gint64*)margs->retval = res; @@ -364,8 +364,8 @@ wasm_invoke_lii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_vid (void *target_func, InterpMethodArguments *margs) { - void (*func)(int arg_0, double arg_1) = target_func; - + typedef void (*T)(int arg_0, double arg_1); + T func = (T)target_func; func ((int)margs->iargs [0], margs->fargs [FIDX (0)]); } @@ -373,8 +373,8 @@ wasm_invoke_vid (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_viiiiiii (void *target_func, InterpMethodArguments *margs) { - void (*func)(int arg_0, int arg_1, int arg_2, int arg_3, int arg_4, int arg_5, int arg_6) = target_func; - + typedef void (*T)(int arg_0, int arg_1, int arg_2, int arg_3, int arg_4, int arg_5, int arg_6); + T func = (T)target_func; func ((int)margs->iargs [0], (int)margs->iargs [1], (int)margs->iargs [2], (int)margs->iargs [3], (int)margs->iargs [4], (int)margs->iargs [5], (int)margs->iargs [6]); } @@ -382,8 +382,8 @@ wasm_invoke_viiiiiii (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_villi (void *target_func, InterpMethodArguments *margs) { - void (*func)(int arg_0, gint64 arg_1, gint64 arg_2, int arg_3) = target_func; - + typedef void (*T)(int arg_0, gint64 arg_1, gint64 arg_2, int arg_3); + T func = (T)target_func; func ((int)margs->iargs [0], get_long_arg (margs, 1), get_long_arg (margs, 3), (int)margs->iargs [5]); } @@ -391,8 +391,8 @@ wasm_invoke_villi (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_did (void *target_func, InterpMethodArguments *margs) { - double (*func)(int arg_0, double arg_1) = target_func; - + typedef double (*T)(int arg_0, double arg_1); + T func = (T)target_func; double res = func ((int)margs->iargs [0], margs->fargs [FIDX (0)]); *(double*)margs->retval = res; @@ -401,8 +401,8 @@ wasm_invoke_did (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_didd (void *target_func, InterpMethodArguments *margs) { - double (*func)(int arg_0, double arg_1, double arg_2) = target_func; - + typedef double (*T)(int arg_0, double arg_1, double arg_2); + T func = (T)target_func; double res = func ((int)margs->iargs [0], margs->fargs [FIDX (0)], margs->fargs [FIDX (1)]); *(double*)margs->retval = res; @@ -411,8 +411,8 @@ wasm_invoke_didd (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_fif (void *target_func, InterpMethodArguments *margs) { - float (*func)(int arg_0, float arg_1) = target_func; - + typedef float (*T)(int arg_0, float arg_1); + T func = (T)target_func; float res = func ((int)margs->iargs [0], *(float*)&margs->fargs [FIDX (0)]); *(float*)margs->retval = res; @@ -421,8 +421,8 @@ wasm_invoke_fif (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_fiff (void *target_func, InterpMethodArguments *margs) { - float (*func)(int arg_0, float arg_1, float arg_2) = target_func; - + typedef float (*T)(int arg_0, float arg_1, float arg_2); + T func = (T)target_func; float res = func ((int)margs->iargs [0], *(float*)&margs->fargs [FIDX (0)], *(float*)&margs->fargs [FIDX (1)]); *(float*)margs->retval = res; @@ -431,8 +431,8 @@ wasm_invoke_fiff (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_lill (void *target_func, InterpMethodArguments *margs) { - gint64 (*func)(int arg_0, gint64 arg_1, gint64 arg_2) = target_func; - + typedef gint64 (*T)(int arg_0, gint64 arg_1, gint64 arg_2); + T func = (T)target_func; gint64 res = func ((int)margs->iargs [0], get_long_arg (margs, 1), get_long_arg (margs, 3)); *(gint64*)margs->retval = res; @@ -441,8 +441,8 @@ wasm_invoke_lill (void *target_func, InterpMethodArguments *margs) static void wasm_invoke_vil (void *target_func, InterpMethodArguments *margs) { - void (*func)(int arg_0, gint64 arg_1) = target_func; - + typedef void (*T)(int arg_0, gint64 arg_1); + T func = (T)target_func; func ((int)margs->iargs [0], get_long_arg (margs, 1)); } diff --git a/mono/mini/xdebug.c b/mono/mini/xdebug.c index 855e8c5789..aeed67a164 100644 --- a/mono/mini/xdebug.c +++ b/mono/mini/xdebug.c @@ -79,10 +79,13 @@ typedef enum JIT_UNREGISTER_FN } jit_actions_t; +struct jit_code_entry; +typedef struct jit_code_entry jit_code_entry; + struct jit_code_entry { - struct jit_code_entry *next_entry; - struct jit_code_entry *prev_entry; + jit_code_entry *next_entry; + jit_code_entry *prev_entry; const char *symfile_addr; /* * The gdb code in gdb/jit.c which reads this structure ignores alignment @@ -91,15 +94,17 @@ struct jit_code_entry guint32 symfile_size1, symfile_size2; }; -struct jit_descriptor +typedef struct jit_descriptor { - guint32 version; - /* This type should be jit_actions_t, but we use guint32 - to be explicit about the bitwidth. */ - guint32 action_flag; - struct jit_code_entry *relevant_entry; - struct jit_code_entry *first_entry; -}; + guint32 version; + /* This type should be jit_actions_t, but we use guint32 + to be explicit about the bitwidth. */ + guint32 action_flag; + jit_code_entry *relevant_entry; + jit_code_entry *first_entry; +} jit_descriptor; + +G_BEGIN_DECLS /* GDB puts a breakpoint in this function. */ void MONO_NEVER_INLINE __jit_debug_register_code(void); @@ -108,7 +113,7 @@ void MONO_NEVER_INLINE __jit_debug_register_code(void); /* LLVM already defines these */ -extern struct jit_descriptor __jit_debug_descriptor; +extern jit_descriptor __jit_debug_descriptor; #else @@ -121,10 +126,12 @@ void MONO_NEVER_INLINE __jit_debug_register_code(void) { /* Make sure to specify the version statically, because the debugger may check the version before we can set it. */ -struct jit_descriptor __jit_debug_descriptor = { 1, 0, 0, 0 }; +jit_descriptor __jit_debug_descriptor = { 1, 0, 0, 0 }; #endif +G_END_DECLS + static MonoImageWriter *xdebug_w; static MonoDwarfWriter *xdebug_writer; static FILE *xdebug_fp, *il_file; @@ -202,7 +209,7 @@ xdebug_end_emit (MonoImageWriter *w, MonoDwarfWriter *dw, MonoMethod *method) { guint8 *img; guint32 img_size; - struct jit_code_entry *entry; + jit_code_entry *entry; guint64 *psize; il_file_line_index = mono_dwarf_writer_get_il_file_line_index (dw); @@ -232,7 +239,7 @@ xdebug_end_emit (MonoImageWriter *w, MonoDwarfWriter *dw, MonoMethod *method) /* Register the image with GDB */ - entry = g_malloc0 (sizeof (struct jit_code_entry)); + entry = g_malloc0 (sizeof (jit_code_entry)); entry->symfile_addr = (const char*)img; psize = (guint64*)&entry->symfile_size1; @@ -295,7 +302,7 @@ mono_save_xdebug_info (MonoCompile *cfg) dmji = mono_debug_find_method (jinfo_get_method (cfg->jit_info), mono_domain_get ());; mono_dwarf_writer_emit_method (xdebug_writer, cfg, jinfo_get_method (cfg->jit_info), NULL, NULL, NULL, - cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, dmji); + (guint8*)cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, dmji); mono_debug_free_method_jit_info (dmji); #if 0 @@ -325,7 +332,7 @@ mono_save_xdebug_info (MonoCompile *cfg) mono_loader_lock (); dmji = mono_debug_find_method (jinfo_get_method (cfg->jit_info), mono_domain_get ()); mono_dwarf_writer_emit_method (xdebug_writer, cfg, jinfo_get_method (cfg->jit_info), NULL, NULL, NULL, - cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, dmji); + (guint8*)cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, dmji); mono_debug_free_method_jit_info (dmji); fflush (xdebug_fp); mono_loader_unlock (); diff --git a/mono/native/Makefile.am b/mono/native/Makefile.am new file mode 100644 index 0000000000..7846ab1994 --- /dev/null +++ b/mono/native/Makefile.am @@ -0,0 +1,135 @@ +if MONO_NATIVE_COMPAT +lib_LTLIBRARIES = libmono-native-compat.la libmono-native-unified.la +else +lib_LTLIBRARIES = libmono-native.la +endif + +CC = $(MONO_NATIVE_CC) +CCLD = $(MONO_NATIVE_CC) +CCAS = $(MONO_NATIVE_CC) +CPP = $(MONO_NATIVE_CC) -E +CXX = $(MONO_NATIVE_CXX) +CXXCPP = $(MONO_NATIVE_CXX) -E +CC_FOR_BUILD = $(MONO_NATIVE_CC) +CPPFLAGS = $(MONO_NATIVE_CPPFLAGS) +CXXFLAGS = $(MONO_NATIVE_CXXFLAGS) +LDFLAGS = $(MONO_NATIVE_LDFLAGS) + +AM_CPPFLAGS = -I$(top_srcdir) -I$(top_srcdir)/mono $(LIBGC_CPPFLAGS) $(GLIB_CFLAGS) $(SHARED_CFLAGS) + +common_sources = \ + pal_config.h \ + mono-native-platform.h \ + mono-native-platform.c \ + ../../external/corefx/src/Native/Unix/Common/pal_compiler.h \ + ../../external/corefx/src/Native/Unix/Common/pal_safecrt.h \ + ../../external/corefx/src/Native/Unix/Common/pal_types.h \ + ../../external/corefx/src/Native/Unix/Common/pal_utilities.h \ + ../../external/corefx/src/Native/Unix/System.Native/pal_errno.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_errno.h \ + ../../external/corefx/src/Native/Unix/System.Native/pal_maphardwaretype.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_maphardwaretype.h \ + ../../external/corefx/src/Native/Unix/System.Native/pal_memory.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_memory.h + +macos_sources = $(unix_sources) + +ios_sources = \ + pal-icalls.h \ + pal-icalls.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_io.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_io.h \ + ../../external/corefx/src/Native/Unix/System.Native/pal_networking.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_networking.h \ + ../../external/corefx/src/Native/Unix/System.Native/pal_tcpstate.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_tcpstate.h \ + ../../external/corefx/src/Native/Unix/System.Native/pal_random.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_random.h + +linux_sources = $(unix_sources) + +android_sources = \ + pal-android.h \ + pal-android.c \ + pal-icalls.h \ + pal-icalls.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_io.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_io.h \ + ../../external/corefx/src/Native/Unix/System.Native/pal_networkstatistics.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_networkstatistics.h \ + ../../external/corefx/src/Native/Unix/System.Native/pal_random.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_random.h + + +unix_sources = \ + pal-icalls.h \ + pal-icalls.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_io.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_io.h \ + ../../external/corefx/src/Native/Unix/System.Native/pal_networking.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_networking.h \ + ../../external/corefx/src/Native/Unix/System.Native/pal_networkstatistics.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_networkstatistics.h \ + ../../external/corefx/src/Native/Unix/System.Native/pal_tcpstate.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_tcpstate.h \ + ../../external/corefx/src/Native/Unix/System.Native/pal_random.c \ + ../../external/corefx/src/Native/Unix/System.Native/pal_random.h + +gss_sources = \ + ../../external/corefx/src/Native/Unix/System.Net.Security.Native/pal_gssapi.c \ + ../../external/corefx/src/Native/Unix/System.Net.Security.Native/pal_gssapi.h + +if ENABLE_GSS +macos_sources += $(gss_sources) + +ios_sources += $(gss_sources) +endif + +EXTRA_libmono_native_la_SOURCES = $(common_sources) $(macos_sources) $(ios_sources) $(linux_sources) $(unix_sources) $(gss_sources) + +if MONO_NATIVE_PLATFORM_MACOS +platform_sources = $(macos_sources) +else +if MONO_NATIVE_PLATFORM_IOS +platform_sources = $(ios_sources) +else +if MONO_NATIVE_PLATFORM_LINUX +platform_sources = $(linux_sources) +else +if MONO_NATIVE_PLATFORM_ANDROID +platform_sources = $(android_sources) +endif +endif +endif +endif + +common_cflags = \ + -I$(abs_top_srcdir)/external/corefx/src/Native/Unix/Common \ + -I$(abs_top_srcdir)/external/corefx/src/Native/Unix/System.Native \ + -Wno-typedef-redefinition + +libmono_native_la_SOURCES = $(common_sources) $(platform_sources) platform-type.c + +libmono_native_la_CFLAGS = $(MONO_NATIVE_CFLAGS) $(common_cflags) + +libmono_native_la_LDFLAGS = $(MONO_NATIVE_LDFLAGS) + +libmono_native_la_LIBADD = $(MONO_NATIVE_LIBADD) + +libmono_native_compat_la_SOURCES = $(common_sources) $(platform_sources) platform-type-compat.c + +libmono_native_compat_la_CFLAGS = $(MONO_NATIVE_COMPAT_CFLAGS) $(common_cflags) + +libmono_native_compat_la_LDFLAGS = $(MONO_NATIVE_COMPAT_LDFLAGS) + +libmono_native_compat_la_LIBADD = $(MONO_NATIVE_LIBADD) + +libmono_native_unified_la_SOURCES = $(common_sources) $(platform_sources) platform-type-unified.c + +libmono_native_unified_la_CFLAGS = $(MONO_NATIVE_UNIFIED_CFLAGS) $(common_cflags) + +libmono_native_unified_la_LDFLAGS = $(MONO_NATIVE_UNIFIED_LDFLAGS) + +libmono_native_unified_la_LIBADD = $(MONO_NATIVE_LIBADD) + + diff --git a/mono/native/Makefile.in.REMOVED.git-id b/mono/native/Makefile.in.REMOVED.git-id new file mode 100644 index 0000000000..69c98b93fc --- /dev/null +++ b/mono/native/Makefile.in.REMOVED.git-id @@ -0,0 +1 @@ +da164f562c7282819b05a1e727f0ca5f3da9aada \ No newline at end of file diff --git a/mono/native/mono-native-platform.c b/mono/native/mono-native-platform.c new file mode 100644 index 0000000000..108b144ba2 --- /dev/null +++ b/mono/native/mono-native-platform.c @@ -0,0 +1,39 @@ +#include +#include +#include "mono/utils/mono-threads-api.h" +#include "mono/utils/atomic.h" +#include "mono/metadata/loader-internals.h" +#include "mono/metadata/icall-internals.h" + +#include "mono-native-platform.h" + +extern MonoNativePlatformType mono_native_platform_type; +volatile static gboolean module_initialized; +volatile static gint32 module_counter; + +int32_t +mono_native_get_platform_type (void) +{ + return mono_native_platform_type; +} + +static int32_t +ves_icall_MonoNativePlatform_IncrementInternalCounter (void) +{ + return mono_atomic_inc_i32 (&module_counter); +} + +int32_t +mono_native_is_initialized (void) +{ + return module_initialized; +} + +void +mono_native_initialize (void) +{ + if (mono_atomic_cas_i32 (&module_initialized, TRUE, FALSE) != FALSE) + return; + + mono_add_internal_call_with_flags ("Mono.MonoNativePlatform::IncrementInternalCounter", ves_icall_MonoNativePlatform_IncrementInternalCounter, TRUE); +} diff --git a/mono/native/mono-native-platform.h b/mono/native/mono-native-platform.h new file mode 100644 index 0000000000..4af3b7fdff --- /dev/null +++ b/mono/native/mono-native-platform.h @@ -0,0 +1,32 @@ +#pragma once + +#include "mono/utils/mono-publib.h" + +// Keep in sync with mcs/class/System/Mono/MonoNativePlatformType.cs + +typedef enum { + MONO_NATIVE_PLATFORM_TYPE_UNKNOWN = 0, + MONO_NATIVE_PLATFORM_TYPE_MACOS = 1, + MONO_NATIVE_PLATFORM_TYPE_IOS = 2, + MONO_NATIVE_PLATFORM_TYPE_LINUX = 3, + MONO_NATIVE_PLATFORM_TYPE_ANDROID = 5, + + MONO_NATIVE_PLATFORM_TYPE_IPHONE = 0x100, + MONO_NATIVE_PLATFORM_TYPE_TV = 0x200, + MONO_NATIVE_PLATFORM_TYPE_WATCH = 0x400, + + MONO_NATIVE_PLATFORM_TYPE_COMPAT = 0x1000, + MONO_NATIVE_PLATFORM_TYPE_UNIFIED = 0x2000, + + MONO_NATIVE_PLATFORM_TYPE_SIMULATOR = 0x4000, + MONO_NATIVE_PLATFORM_TYPE_DEVICE = 0x8000 +} MonoNativePlatformType; + +MONO_API int32_t +mono_native_get_platform_type (void); + +MONO_API int32_t +mono_native_is_initialized (void); + +MONO_API void +mono_native_initialize (void); diff --git a/mono/native/pal-android.c b/mono/native/pal-android.c new file mode 100644 index 0000000000..3db94bd484 --- /dev/null +++ b/mono/native/pal-android.c @@ -0,0 +1,7 @@ +/** + * \file + * System.Native PAL internal calls (Android) + * Adapter code between the Mono runtime and the CoreFX Platform Abstraction Layer (PAL) + * Copyright 2018 Microsoft + * Licensed under the MIT license. See LICENSE file in the project root for full license information. +*/ diff --git a/mono/native/pal-android.h b/mono/native/pal-android.h new file mode 100644 index 0000000000..5de4ca375e --- /dev/null +++ b/mono/native/pal-android.h @@ -0,0 +1,18 @@ +/** + * \file + * System.Native PAL internal calls (Android) + * Adapter code between the Mono runtime and the CoreFX Platform Abstraction Layer (PAL) + * Copyright 2018 Microsoft + * Licensed under the MIT license. See LICENSE file in the project root for full license information. +*/ + +#include "pal_compiler.h" + +/** + * Reads the number of bytes specified into the provided buffer from the specified, opened file descriptor. + * + * Returns the number of bytes read on success; otherwise, -1 is returned an errno is set. + * + * Note - on fail. the position of the stream may change depending on the platform; consult man 2 read for more info + */ +DLLEXPORT int32_t SystemNative_Read(intptr_t fd, void* buffer, int32_t bufferSize); diff --git a/mono/metadata/pal-icalls.c b/mono/native/pal-icalls.c similarity index 86% rename from mono/metadata/pal-icalls.c rename to mono/native/pal-icalls.c index 99f4ee583e..a43d26008f 100644 --- a/mono/metadata/pal-icalls.c +++ b/mono/native/pal-icalls.c @@ -6,15 +6,17 @@ * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ +#if !defined (HOST_WATCHOS) && !defined (TARGET_APPLETVOS) /* These platforms don't support async suspend and do not need this code for now */ + #include #include -#include "pal_io.h" #include "mono/utils/mono-threads-api.h" #include "mono/utils/atomic.h" +#include "mono/metadata/loader-internals.h" #include "mono/metadata/icall-internals.h" - #include "pal-icalls.h" + /* * mono_pal_init: * @@ -56,7 +58,7 @@ static void interrupt_CFRunLoop (gpointer data) { g_assert (data); - CFRunLoopStop (data); + CFRunLoopStop ((CFRunLoopRef)data); } void @@ -77,3 +79,5 @@ ves_icall_Interop_RunLoop_CFRunLoopRun (void) } #endif + +#endif /* !defined (HOST_WATCHOS) && !defined (TARGET_APPLETVOS) */ diff --git a/mono/metadata/pal-icalls.h b/mono/native/pal-icalls.h similarity index 83% rename from mono/metadata/pal-icalls.h rename to mono/native/pal-icalls.h index 6f17ea9275..25dfd7ab42 100644 --- a/mono/metadata/pal-icalls.h +++ b/mono/native/pal-icalls.h @@ -9,12 +9,13 @@ #ifndef __MONO_METADATA_PAL_ICALLS_H__ #define __MONO_METADATA_PAL_ICALLS_H__ -#include "metadata.h" -#include "class-internals.h" +#include "mono/metadata/metadata.h" +#include "mono/metadata/class-internals.h" MONO_API void mono_pal_init (void); extern void mono_marshal_set_last_error (void); +extern int32_t SystemNative_Read(intptr_t fd, void* buffer, int32_t bufferSize); gint32 ves_icall_Interop_Sys_Read (intptr_t fd, gchar* buffer, gint32 count); #if defined(__APPLE__) diff --git a/mono/native/pal_config.h b/mono/native/pal_config.h new file mode 100644 index 0000000000..59878769cd --- /dev/null +++ b/mono/native/pal_config.h @@ -0,0 +1,15 @@ +#include + +#define MONO 1 +/* clock_gettime () is found by configure on Apple builds, but its only present from ios 10, macos 10.12, tvos 10 and watchos 3 */ +#if defined (TARGET_WASM) || defined (TARGET_IOS) || defined (TARGET_OSX) || defined (TARGET_WATCHOS) || defined (TARGET_TVOS) +#undef HAVE_CLOCK_MONOTONIC +#undef HAVE_CLOCK_MONOTONIC_COARSE +#endif + +#ifdef TARGET_ANDROID +/* arc4random_buf() is not available even when configure seems to find it */ +#undef HAVE_ARC4RANDOM_BUF +/* sendfile() is not available for what seems like x86+older API levels */ +#undef HAVE_SENDFILE_4 +#endif diff --git a/mono/native/platform-type-compat.c b/mono/native/platform-type-compat.c new file mode 100644 index 0000000000..00eb2c9407 --- /dev/null +++ b/mono/native/platform-type-compat.c @@ -0,0 +1,3 @@ +#include "mono-native-platform.h" + +MonoNativePlatformType mono_native_platform_type = MONO_NATIVE_PLATFORM_TYPE_LINUX | MONO_NATIVE_PLATFORM_TYPE_COMPAT; diff --git a/mono/native/platform-type-compat.c.in b/mono/native/platform-type-compat.c.in new file mode 100644 index 0000000000..3e1116cf4d --- /dev/null +++ b/mono/native/platform-type-compat.c.in @@ -0,0 +1,3 @@ +#include "mono-native-platform.h" + +MonoNativePlatformType mono_native_platform_type = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@; diff --git a/mono/native/platform-type-unified.c b/mono/native/platform-type-unified.c new file mode 100644 index 0000000000..495b074d4d --- /dev/null +++ b/mono/native/platform-type-unified.c @@ -0,0 +1,4 @@ +#include "mono-native-platform.h" + +MonoNativePlatformType mono_native_platform_type = MONO_NATIVE_PLATFORM_TYPE_LINUX | MONO_NATIVE_PLATFORM_TYPE_UNIFIED; + diff --git a/mono/native/platform-type-unified.c.in b/mono/native/platform-type-unified.c.in new file mode 100644 index 0000000000..031926ea2d --- /dev/null +++ b/mono/native/platform-type-unified.c.in @@ -0,0 +1,4 @@ +#include "mono-native-platform.h" + +MonoNativePlatformType mono_native_platform_type = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@; + diff --git a/mono/native/platform-type.c b/mono/native/platform-type.c new file mode 100644 index 0000000000..31344e5a68 --- /dev/null +++ b/mono/native/platform-type.c @@ -0,0 +1,3 @@ +#include "mono-native-platform.h" + +MonoNativePlatformType mono_native_platform_type = MONO_NATIVE_PLATFORM_TYPE_LINUX; diff --git a/mono/native/platform-type.c.in b/mono/native/platform-type.c.in new file mode 100644 index 0000000000..cb5cd81789 --- /dev/null +++ b/mono/native/platform-type.c.in @@ -0,0 +1,3 @@ +#include "mono-native-platform.h" + +MonoNativePlatformType mono_native_platform_type = @MONO_NATIVE_PLATFORM_TYPE@; diff --git a/mono/profiler/Makefile.am b/mono/profiler/Makefile.am index edb3ecd7dd..c11fa85cdb 100644 --- a/mono/profiler/Makefile.am +++ b/mono/profiler/Makefile.am @@ -142,6 +142,7 @@ endif mprof_report_SOURCES = mprof-report.c mprof_report_LDADD = $(glib_libs) $(zlib_dep) +mprof_report_LDFLAGS = -no-undefined PLOG_TESTS_SRC = \ test-alloc.cs \ diff --git a/mono/profiler/Makefile.in b/mono/profiler/Makefile.in index 45d540bc9f..69984ba4b9 100644 --- a/mono/profiler/Makefile.in +++ b/mono/profiler/Makefile.in @@ -87,7 +87,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ @DISABLE_LIBRARIES_FALSE@@DISABLE_PROFILER_FALSE@@HOST_WIN32_FALSE@bin_PROGRAMS = mprof-report$(EXEEXT) subdir = mono/profiler ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -234,6 +235,9 @@ PROGRAMS = $(bin_PROGRAMS) am_mprof_report_OBJECTS = mprof-report.$(OBJEXT) mprof_report_OBJECTS = $(am_mprof_report_OBJECTS) mprof_report_DEPENDENCIES = $(glib_libs) $(am__DEPENDENCIES_2) +mprof_report_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(mprof_report_LDFLAGS) $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false @@ -343,6 +347,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -416,6 +421,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ @@ -632,6 +653,7 @@ libmono_profiler_coverage_static_la_LDFLAGS = -static @HAVE_VTUNE_TRUE@libmono_profiler_vtune_static_la_LIBADD = $(VTUNE_LIBS) mprof_report_SOURCES = mprof-report.c mprof_report_LDADD = $(glib_libs) $(zlib_dep) +mprof_report_LDFLAGS = -no-undefined PLOG_TESTS_SRC = \ test-alloc.cs \ test-busy.cs \ @@ -797,7 +819,7 @@ clean-binPROGRAMS: mprof-report$(EXEEXT): $(mprof_report_OBJECTS) $(mprof_report_DEPENDENCIES) $(EXTRA_mprof_report_DEPENDENCIES) @rm -f mprof-report$(EXEEXT) - $(AM_V_CCLD)$(LINK) $(mprof_report_OBJECTS) $(mprof_report_LDADD) $(LIBS) + $(AM_V_CCLD)$(mprof_report_LINK) $(mprof_report_OBJECTS) $(mprof_report_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) diff --git a/mono/profiler/log.c.REMOVED.git-id b/mono/profiler/log.c.REMOVED.git-id index a1ada224f3..3a12a45aa5 100644 --- a/mono/profiler/log.c.REMOVED.git-id +++ b/mono/profiler/log.c.REMOVED.git-id @@ -1 +1 @@ -6b6f88d1f40666b792a333eb6f94248292baeaee \ No newline at end of file +6ab2e45f8d6a092d01d7cc2ebf03d032e29e8571 \ No newline at end of file diff --git a/mono/sgen/Makefile.in b/mono/sgen/Makefile.in index 65d5271a48..4c42b8e6f2 100644 --- a/mono/sgen/Makefile.in +++ b/mono/sgen/Makefile.in @@ -84,7 +84,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(top_srcdir)/depcomp subdir = mono/sgen ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -222,6 +223,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -295,6 +297,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/sgen/sgen-alloc.c b/mono/sgen/sgen-alloc.c index 3a9bac55dc..b6931261e0 100644 --- a/mono/sgen/sgen-alloc.c +++ b/mono/sgen/sgen-alloc.c @@ -73,8 +73,9 @@ alloc_degraded (GCVTable vtable, size_t size, gboolean for_mature) SGEN_ATOMIC_ADD_P (sgen_degraded_mode, size); sgen_ensure_free_space (size, GENERATION_OLD); } else { - if (sgen_need_major_collection (size)) - sgen_perform_collection (size, GENERATION_OLD, "mature allocation failure", !for_mature, TRUE); + gboolean forced; + if (sgen_need_major_collection (size, &forced)) + sgen_perform_collection (size, GENERATION_OLD, "mature allocation failure", !for_mature || forced, TRUE); } diff --git a/mono/sgen/sgen-cardtable.c b/mono/sgen/sgen-cardtable.c index bbd0dfd67b..4c8a94fe1a 100644 --- a/mono/sgen/sgen-cardtable.c +++ b/mono/sgen/sgen-cardtable.c @@ -133,7 +133,7 @@ sgen_card_table_wbarrier_generic_nostore (gpointer ptr) } static void -sgen_card_table_wbarrier_range_copy (gpointer _dest, gpointer _src, int size) +sgen_card_table_wbarrier_range_copy (gpointer _dest, gconstpointer _src, int size) { GCObject **dest = (GCObject **)_dest; GCObject **src = (GCObject **)_src; @@ -475,7 +475,7 @@ sgen_get_card_table_configuration (int *shift_bits, gpointer *mask) } guint8* -sgen_get_target_card_table_configuration (int *shift_bits, gpointer *mask) +sgen_get_target_card_table_configuration (int *shift_bits, target_mgreg_t *mask) { #ifndef MANAGED_WBARRIER return NULL; @@ -485,9 +485,9 @@ sgen_get_target_card_table_configuration (int *shift_bits, gpointer *mask) *shift_bits = CARD_BITS; #ifdef SGEN_TARGET_HAVE_OVERLAPPING_CARDS - *mask = (gpointer)CARD_MASK; + *mask = CARD_MASK; #else - *mask = NULL; + *mask = 0; #endif return sgen_cardtable; diff --git a/mono/sgen/sgen-cardtable.h b/mono/sgen/sgen-cardtable.h index 0ed55279b4..1ea3055fce 100644 --- a/mono/sgen/sgen-cardtable.h +++ b/mono/sgen/sgen-cardtable.h @@ -28,7 +28,7 @@ void sgen_card_table_update_mod_union (guint8 *dest, char *obj, mword obj_size, void sgen_card_table_preclean_mod_union (guint8 *cards, guint8 *cards_preclean, size_t num_cards); guint8* sgen_get_card_table_configuration (int *shift_bits, gpointer *mask); -guint8* sgen_get_target_card_table_configuration (int *shift_bits, gpointer *mask); +guint8* sgen_get_target_card_table_configuration (int *shift_bits, target_mgreg_t *mask); void sgen_card_table_init (SgenRememberedSet *remset); diff --git a/mono/sgen/sgen-fin-weak-hash.c b/mono/sgen/sgen-fin-weak-hash.c index 0a953bf27b..29a1d3b504 100644 --- a/mono/sgen/sgen-fin-weak-hash.c +++ b/mono/sgen/sgen-fin-weak-hash.c @@ -421,7 +421,7 @@ static gint64 stat_entry_invalidated = 0; #endif static int -add_stage_entry (int num_entries, volatile gint32 *next_entry, StageEntry *entries, GCObject *obj, void *user_data) +add_stage_entry (int num_entries, volatile gint32 *next_entry, StageEntry *entries, GCObject *obj, SGenFinalizationProc user_data) { gint32 index, new_next_entry, old_next_entry; gint32 previous_state; @@ -497,8 +497,8 @@ add_stage_entry (int num_entries, volatile gint32 *next_entry, StageEntry *entri SGEN_ASSERT (0, index >= 0 && index < num_entries, "Invalid index"); - UnlockedWritePointer ((void *)&entries [index].obj, obj); - UnlockedWritePointer (&entries [index].user_data, user_data); + UnlockedWritePointer ((volatile gpointer*)&entries [index].obj, obj); + UnlockedWritePointer (&entries [index].user_data, (gpointer)user_data); mono_memory_write_barrier (); @@ -518,7 +518,7 @@ add_stage_entry (int num_entries, volatile gint32 *next_entry, StageEntry *entri } SGEN_ASSERT (0, previous_state == STAGE_ENTRY_INVALID, "Invalid state transition - other thread can only make busy state invalid"); - UnlockedWritePointer ((void *)&entries [index].obj, NULL); + UnlockedWritePointer ((volatile gpointer*)&entries [index].obj, NULL); UnlockedWritePointer (&entries [index].user_data, NULL); mono_memory_write_barrier (); /* INVALID -> FREE */ diff --git a/mono/sgen/sgen-gc.c.REMOVED.git-id b/mono/sgen/sgen-gc.c.REMOVED.git-id index 72c0632f30..26be4c221f 100644 --- a/mono/sgen/sgen-gc.c.REMOVED.git-id +++ b/mono/sgen/sgen-gc.c.REMOVED.git-id @@ -1 +1 @@ -2c5e5579c73c90847069c21016680e84c7e149f8 \ No newline at end of file +adb9bb63856dc458c28cd4e04e63e3847de5ec27 \ No newline at end of file diff --git a/mono/sgen/sgen-gc.h b/mono/sgen/sgen-gc.h index c34de3af4f..66a5b3dd57 100644 --- a/mono/sgen/sgen-gc.h +++ b/mono/sgen/sgen-gc.h @@ -17,7 +17,7 @@ #ifdef HAVE_SGEN_GC -typedef struct _SgenThreadInfo SgenThreadInfo; +#include #undef THREAD_INFO_TYPE #define THREAD_INFO_TYPE SgenThreadInfo @@ -394,7 +394,7 @@ enum { extern SgenHashTable sgen_roots_hash [ROOT_TYPE_NUM]; -int sgen_register_root (char *start, size_t size, SgenDescriptor descr, int root_type, int source, void *key, const char *msg) +int sgen_register_root (char *start, size_t size, SgenDescriptor descr, int root_type, MonoGCRootSource source, void *key, const char *msg) MONO_PERMIT (need (sgen_lock_gc)); void sgen_deregister_root (char* addr) MONO_PERMIT (need (sgen_lock_gc)); @@ -440,7 +440,14 @@ typedef struct SgenGrayQueue *queue; } ScanCopyContext; -#define CONTEXT_FROM_OBJECT_OPERATIONS(ops, queue) ((ScanCopyContext) { (ops), (queue) }) +// error C4576: a parenthesized type followed by an initializer list is a non-standard explicit type conversion +// An inline function or constructor would work here too. +#ifdef _MSC_VER +#define MONO_MSC_WARNING_SUPPRESS(warn, body) __pragma (warning (suppress:warn)) body +#else +#define MONO_MSC_WARNING_SUPPRESS(warn, body) body +#endif +#define CONTEXT_FROM_OBJECT_OPERATIONS(ops, queue) MONO_MSC_WARNING_SUPPRESS (4576, ((ScanCopyContext) { (ops), (queue) })) void sgen_report_internal_mem_usage (void); void sgen_dump_internal_mem_usage (FILE *heap_dump_file); @@ -702,7 +709,7 @@ typedef struct _SgenRememberedSet { void (*wbarrier_object_copy) (GCObject* obj, GCObject *src); void (*wbarrier_generic_nostore) (gpointer ptr); void (*record_pointer) (gpointer ptr); - void (*wbarrier_range_copy) (gpointer dest, gpointer src, int count); + void (*wbarrier_range_copy) (gpointer dest, gconstpointer src, int count); void (*start_scan_remsets) (void); @@ -723,7 +730,7 @@ void mono_gc_wbarrier_generic_nostore (gpointer ptr); void mono_gc_wbarrier_generic_store (gpointer ptr, GCObject* value); void mono_gc_wbarrier_generic_store_atomic (gpointer ptr, GCObject *value); -void sgen_wbarrier_range_copy (gpointer _dest, gpointer _src, int size); +void sgen_wbarrier_range_copy (gpointer _dest, gconstpointer _src, int size); static inline SgenDescriptor sgen_obj_get_descriptor (GCObject *obj) diff --git a/mono/sgen/sgen-gchandles.c b/mono/sgen/sgen-gchandles.c index 1a383f719a..0725d8681a 100644 --- a/mono/sgen/sgen-gchandles.c +++ b/mono/sgen/sgen-gchandles.c @@ -155,7 +155,7 @@ sgen_gc_handles_report_roots (SgenUserReportRootFunc report_func, void *gc_data) revealed = MONO_GC_REVEAL_POINTER (hidden, FALSE); if (MONO_GC_HANDLE_IS_OBJECT_POINTER (hidden)) - report_func ((void*)slot, revealed, gc_data); + report_func ((void*)slot, (GCObject*)revealed, gc_data); } SGEN_ARRAY_LIST_END_FOREACH_SLOT; } @@ -186,7 +186,7 @@ alloc_handle (HandleData *handles, GCObject *obj, gboolean track) /* Ensure that a GC handle cannot be given to another thread without the slot having been set. */ mono_memory_write_barrier (); res = MONO_GC_HANDLE (index, handles->type); - sgen_client_gchandle_created (handles->type, obj, res); + sgen_client_gchandle_created ((GCHandleType)handles->type, obj, res); return res; } @@ -386,7 +386,7 @@ sgen_gchandle_free (guint32 gchandle) } else { /* print a warning? */ } - sgen_client_gchandle_destroyed (handles->type, gchandle); + sgen_client_gchandle_destroyed ((GCHandleType)handles->type, gchandle); } /* diff --git a/mono/sgen/sgen-marksweep-drain-gray-stack.h b/mono/sgen/sgen-marksweep-drain-gray-stack.h index 856df09695..889fa6077f 100644 --- a/mono/sgen/sgen-marksweep-drain-gray-stack.h +++ b/mono/sgen/sgen-marksweep-drain-gray-stack.h @@ -48,9 +48,11 @@ COPY_OR_MARK_FUNCTION_NAME (GCObject **ptr, GCObject *obj, SgenGrayQueue *queue) if (sgen_ptr_in_nursery (obj)) { #if !defined(COPY_OR_MARK_CONCURRENT) && !defined(COPY_OR_MARK_CONCURRENT_WITH_EVACUATION) int word, bit; - gboolean first = TRUE; + gboolean first; + first = TRUE; GCObject *forwarded, *old_obj; - mword vtable_word = *(mword*)obj; + mword vtable_word; + vtable_word = *(mword*)obj; HEAVY_STAT (++stat_optimized_copy_nursery); diff --git a/mono/sgen/sgen-marksweep.c b/mono/sgen/sgen-marksweep.c index 0bbe570218..c90c589a55 100644 --- a/mono/sgen/sgen-marksweep.c +++ b/mono/sgen/sgen-marksweep.c @@ -1059,8 +1059,8 @@ static void major_dump_heap (FILE *heap_dump_file) { MSBlockInfo *block; - int *slots_available = (int *)alloca (sizeof (int) * num_block_obj_sizes); - int *slots_used = (int *)alloca (sizeof (int) * num_block_obj_sizes); + int *slots_available = g_newa (int, num_block_obj_sizes); + int *slots_used = g_newa (int, num_block_obj_sizes); int i; for (i = 0; i < num_block_obj_sizes; ++i) @@ -2504,9 +2504,9 @@ scan_card_table_for_block (MSBlockInfo *block, CardTableScanType scan_type, Scan * size is no longer required to be a multiple of the system page size. */ #ifndef SGEN_HAVE_OVERLAPPING_CARDS - guint8 *cards_copy = alloca (sizeof (guint8) * CARDS_PER_BLOCK); + guint8 *cards_copy = g_newa (guint8, CARDS_PER_BLOCK); #endif - guint8 *cards_preclean = alloca (sizeof (guint8) * CARDS_PER_BLOCK); + guint8 *cards_preclean = g_newa (guint8, CARDS_PER_BLOCK); gboolean small_objects; int block_obj_size; char *block_start; @@ -2609,7 +2609,8 @@ scan_card_table_for_block (MSBlockInfo *block, CardTableScanType scan_type, Scan goto next_object; } - GCObject *object = (GCObject*)obj; + GCObject *object; + object = (GCObject*)obj; if (small_objects) { HEAVY_STAT (++scanned_objects); diff --git a/mono/sgen/sgen-memory-governor.c b/mono/sgen/sgen-memory-governor.c index fad08626a0..bd63548fbe 100644 --- a/mono/sgen/sgen-memory-governor.c +++ b/mono/sgen/sgen-memory-governor.c @@ -137,10 +137,12 @@ get_heap_size (void) } gboolean -sgen_need_major_collection (mword space_needed) +sgen_need_major_collection (mword space_needed, gboolean *forced) { size_t heap_size; + *forced = FALSE; + if (sgen_get_concurrent_collection_in_progress ()) { heap_size = get_heap_size (); @@ -169,6 +171,7 @@ sgen_need_major_collection (mword space_needed) heap_size = get_heap_size (); + *forced = heap_size > soft_heap_limit; return heap_size > major_collection_trigger_size; } @@ -355,7 +358,7 @@ sgen_memgov_collection_end (int generation, gint64 stw_time) SGEN_ASSERT (0, !sgen_is_world_stopped (), "We can't log if the world is stopped"); mono_os_mutex_lock (&log_entries_mutex); for (i = 0; i < log_entries.next_slot; i++) { - sgen_output_log_entry (log_entries.data [i], stw_time, generation); + sgen_output_log_entry ((SgenLogEntry*)log_entries.data [i], stw_time, generation); sgen_free_internal (log_entries.data [i], INTERNAL_MEM_LOG_ENTRY); } sgen_pointer_queue_clear (&log_entries); diff --git a/mono/sgen/sgen-memory-governor.h b/mono/sgen/sgen-memory-governor.h index 81c02dab5b..ecb2cf6908 100644 --- a/mono/sgen/sgen-memory-governor.h +++ b/mono/sgen/sgen-memory-governor.h @@ -25,7 +25,7 @@ void sgen_memgov_major_collection_end (gboolean forced, gboolean concurrent, con void sgen_memgov_collection_start (int generation); void sgen_memgov_collection_end (int generation, gint64 stw); -gboolean sgen_need_major_collection (mword space_needed); +gboolean sgen_need_major_collection (mword space_needed, gboolean *forced); typedef enum { diff --git a/mono/sgen/sgen-pinning.c b/mono/sgen/sgen-pinning.c index c73e7a1f8b..37f5ce46c9 100644 --- a/mono/sgen/sgen-pinning.c +++ b/mono/sgen/sgen-pinning.c @@ -334,7 +334,7 @@ sgen_cement_lookup_or_register (GCObject *obj) if (!hash [i].obj) { GCObject *old_obj; - old_obj = mono_atomic_cas_ptr ((gpointer*)&hash [i].obj, obj, NULL); + old_obj = (GCObject*)mono_atomic_cas_ptr ((gpointer*)&hash [i].obj, obj, NULL); /* Check if the slot was occupied by some other object */ if (old_obj != NULL && old_obj != obj) return FALSE; diff --git a/mono/sgen/sgen-protocol.c b/mono/sgen/sgen-protocol.c index 7184e6aebe..c1261020a1 100644 --- a/mono/sgen/sgen-protocol.c +++ b/mono/sgen/sgen-protocol.c @@ -23,11 +23,11 @@ #include #include -#if defined(HAVE_UNISTD_H) +#if defined(HOST_WIN32) +#include +#elif defined(HAVE_UNISTD_H) #include #include -#elif defined(HOST_WIN32) -#include #endif #if defined(HOST_WIN32) @@ -96,7 +96,9 @@ binary_protocol_open_file (gboolean assert_on_failure) else filename = filename_or_prefix; -#if defined(HAVE_UNISTD_H) +#if defined(HOST_WIN32) + binary_protocol_file = CreateFileA (filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); +#elif defined(HAVE_UNISTD_H) do { binary_protocol_file = open (filename, O_CREAT | O_WRONLY, 0644); if (binary_protocol_file == -1) { @@ -114,12 +116,9 @@ binary_protocol_open_file (gboolean assert_on_failure) ftruncate (binary_protocol_file, 0); } } while (binary_protocol_file == -1); -#elif defined(HOST_WIN32) - binary_protocol_file = CreateFileA (filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); #else g_error ("sgen binary protocol: not supported"); #endif - if (binary_protocol_file == invalid_file_value && assert_on_failure) g_error ("sgen binary protocol: failed to open file"); @@ -160,11 +159,11 @@ sgen_binary_protocol_is_enabled (void) static void close_binary_protocol_file (void) { -#if defined(HAVE_UNISTD_H) +#if defined(HOST_WIN32) + CloseHandle (binary_protocol_file); +#elif defined(HAVE_UNISTD_H) while (close (binary_protocol_file) == -1 && errno == EINTR) ; -#elif defined(HOST_WIN32) - CloseHandle (binary_protocol_file); #endif binary_protocol_file = invalid_file_value; } @@ -224,22 +223,20 @@ binary_protocol_flush_buffer (BinaryProtocolBuffer *buffer) size_t written = 0; g_assert (buffer->index > 0); - while (written < to_write) { -#if defined(HAVE_UNISTD_H) + while (binary_protocol_file != invalid_file_value && written < to_write) { +#if defined(HOST_WIN32) + DWORD tmp_written; + if (WriteFile (binary_protocol_file, buffer->buffer + written, to_write - written, &tmp_written, NULL)) + written += tmp_written; +#elif defined(HAVE_UNISTD_H) ret = write (binary_protocol_file, buffer->buffer + written, to_write - written); if (ret >= 0) written += ret; else if (errno == EINTR) continue; - else - close_binary_protocol_file (); -#elif defined(HOST_WIN32) - int tmp_written; - if (WriteFile (binary_protocol_file, buffer->buffer + written, to_write - written, &tmp_written, NULL)) - written += tmp_written; - else - close_binary_protocol_file (); #endif + else + close_binary_protocol_file (); } current_file_size += buffer->index; diff --git a/mono/sgen/sgen-qsort.c b/mono/sgen/sgen-qsort.c index e8144244a6..dfcc9371d0 100644 --- a/mono/sgen/sgen-qsort.c +++ b/mono/sgen/sgen-qsort.c @@ -109,13 +109,8 @@ void sgen_qsort ( const size_t element_size, int (*compare) (const void *, const void *)) { -#ifndef _MSC_VER - unsigned char pivot_tmp [element_size]; - unsigned char swap_tmp [element_size]; -#else - unsigned char *pivot_tmp = (unsigned char *)alloca (element_size); - unsigned char *swap_tmp = (unsigned char *)alloca (element_size); -#endif + unsigned char *pivot_tmp = g_newa (unsigned char, element_size); + unsigned char *swap_tmp = g_newa (unsigned char, element_size); sgen_qsort_rec ( array, element_size, diff --git a/mono/sgen/sgen-thread-pool.c b/mono/sgen/sgen-thread-pool.c index c9aaaa2667..4c999df6f3 100644 --- a/mono/sgen/sgen-thread-pool.c +++ b/mono/sgen/sgen-thread-pool.c @@ -237,7 +237,7 @@ thread_func (void *data) } } - return (mono_native_thread_return_t)0; + return 0; } int @@ -285,7 +285,7 @@ sgen_thread_pool_start (void) threadpool_shutdown = FALSE; for (i = 0; i < threads_num; i++) { - mono_native_thread_create (&threads [i], thread_func, (void*)(gsize)i); + mono_native_thread_create (&threads [i], (gpointer)thread_func, (void*)(gsize)i); } } diff --git a/mono/tests/Makefile.am.REMOVED.git-id b/mono/tests/Makefile.am.REMOVED.git-id index 8fc44c5fbd..624168426d 100644 --- a/mono/tests/Makefile.am.REMOVED.git-id +++ b/mono/tests/Makefile.am.REMOVED.git-id @@ -1 +1 @@ -6e8986276fc609bd4d2c34d26ae2b399744f3fcd \ No newline at end of file +780acdb545f62c065569f3c8c62e6e0fde0e6a9d \ No newline at end of file diff --git a/mono/tests/Makefile.in.REMOVED.git-id b/mono/tests/Makefile.in.REMOVED.git-id index 00aa9dfd36..de730de21b 100644 --- a/mono/tests/Makefile.in.REMOVED.git-id +++ b/mono/tests/Makefile.in.REMOVED.git-id @@ -1 +1 @@ -4988fc44d1852615c7e57a0f2a5d26e678f5dbfe \ No newline at end of file +2566b872df834e82f92091dc4dde85a0b6ed7ce7 \ No newline at end of file diff --git a/mono/tests/assembly-load-reference/Makefile.in b/mono/tests/assembly-load-reference/Makefile.in index fec0d99d20..a2afcef465 100644 --- a/mono/tests/assembly-load-reference/Makefile.in +++ b/mono/tests/assembly-load-reference/Makefile.in @@ -93,7 +93,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ subdir = mono/tests/assembly-load-reference ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -162,6 +163,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -235,6 +237,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/tests/delegate16.cs b/mono/tests/delegate16.cs new file mode 100644 index 0000000000..e9f1680796 --- /dev/null +++ b/mono/tests/delegate16.cs @@ -0,0 +1,12 @@ +using System; + +public static class Program +{ + public static int Main () + { + if (typeof(Delegate).GetMethod("Invoke") != null) + return 1; + + return 0; + } +} \ No newline at end of file diff --git a/mono/tests/exception18.cs b/mono/tests/exception18.cs index a9bb00d4e0..84a38a29fc 100644 --- a/mono/tests/exception18.cs +++ b/mono/tests/exception18.cs @@ -46,8 +46,8 @@ class C } } catch (Exception ex) { int frames = FrameCount (ex); - if (frames != 3) - throw new Exception (String.Format("Exception carried {0} frames along with it when it should have reported three.", frames)); + if (frames != 4) + throw new Exception (String.Format("Exception carried {0} frames along with it when it should have reported four.", frames)); } try { diff --git a/mono/tests/exception21.cs b/mono/tests/exception21.cs new file mode 100644 index 0000000000..1456e46d87 --- /dev/null +++ b/mono/tests/exception21.cs @@ -0,0 +1,26 @@ +using System; +using System.Threading; + +public class Program { + + public static void Main (string[] args) { + int caughts = 0; + int finallys = 0; + try { + try { + throw new Exception (); + } finally { + finallys++; + throw new Exception (); + } + } catch (Exception) { + caughts++; + Console.WriteLine ("Caught"); + } + if (caughts != 1) + Environment.Exit (1); + if (finallys != 1) + Environment.Exit (2); + Console.WriteLine ("Exit"); + } +} diff --git a/mono/tests/gc-descriptors/Makefile.in b/mono/tests/gc-descriptors/Makefile.in index 4f03cf0f00..2ec6ad453d 100644 --- a/mono/tests/gc-descriptors/Makefile.in +++ b/mono/tests/gc-descriptors/Makefile.in @@ -82,7 +82,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ $(srcdir)/Makefile.am $(top_srcdir)/mkinstalldirs subdir = mono/tests/gc-descriptors ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -151,6 +152,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -224,6 +226,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/tests/merp-crash-test.cs b/mono/tests/merp-crash-test.cs index 29287c197f..c08dd08bc6 100644 --- a/mono/tests/merp-crash-test.cs +++ b/mono/tests/merp-crash-test.cs @@ -180,6 +180,8 @@ class C if (!silent) Console.WriteLine ("Xml file {0}", text); File.Delete (xmlFilePath); + } else { + Console.WriteLine ("Xml file missing"); } if (paramsFileExists) { @@ -187,6 +189,8 @@ class C if (!silent) Console.WriteLine ("Params file {0}", text); File.Delete (paramsFilePath); + } else { + Console.WriteLine ("Params file missing"); } if (crashFileExists) { @@ -206,6 +210,8 @@ class C File.Delete (crashFilePath); // Assert it has the required merp fields + } else { + Console.WriteLine ("Crash file missing"); } if (!xmlFileExists) @@ -328,7 +334,7 @@ class C } if (failure_count > 0) - return; + throw new Exception ("Failed MERP basic correctness tests."); Console.WriteLine ("\n\n##################"); Console.WriteLine ("Merp Stress Test:"); diff --git a/mono/tests/merp-json-valid.cs b/mono/tests/merp-json-valid.cs index 9c914d5140..f4ef1bb214 100644 --- a/mono/tests/merp-json-valid.cs +++ b/mono/tests/merp-json-valid.cs @@ -22,7 +22,7 @@ class C JsonValidateMerp () { var monoType = Type.GetType ("Mono.Runtime", false); - var m = monoType.GetMethod("EnableMicrosoftTelemetryNext", BindingFlags.NonPublic | BindingFlags.Static); + var m = monoType.GetMethod("EnableMicrosoftTelemetry", BindingFlags.NonPublic | BindingFlags.Static); // This leads to open -a /bin/cat, which errors out, but errors // in invoking merp are only logged errors, not fatal assertions. diff --git a/mono/tests/test-runner.cs b/mono/tests/test-runner.cs index 8dcef6644c..6c8fd0a9ef 100644 --- a/mono/tests/test-runner.cs +++ b/mono/tests/test-runner.cs @@ -62,6 +62,7 @@ public class TestRunner string mono_path = null; string runtime_args = null; string mono_gac_prefix = null; + string xunit_output_path = null; var opt_sets = new List (); // Process options @@ -134,6 +135,14 @@ public class TestRunner return 1; } testsuiteName = args [i + 1]; + i += 2; + } else if (args [i] == "--xunit") { + if (i + 1 >= args.Length) { + Console.WriteLine ("Missing argument to --xunit command line option."); + return 1; + } + xunit_output_path = args [i + 1].Substring(0, args [i + 1].Length); + i += 2; } else if (args [i] == "--input-file") { if (i + 1 >= args.Length) { @@ -390,16 +399,72 @@ public class TestRunner TimeSpan test_time = DateTime.UtcNow - test_start_time; - int npassed = passed.Count; - int nfailed = failed.Count; - int ntimedout = timedout.Count; + if (xunit_output_path != null) { + WriteXUnitOutput (xunit_output_path, testsuiteName, test_time, passed, failed, timedout); + } + else { + var xmlPath = String.Format ("TestResult-{0}.xml", testsuiteName); + WriteNUnitOutput (xmlPath, testsuiteName, test_time, passed, failed, timedout); + string babysitterXmlList = Environment.GetEnvironmentVariable("MONO_BABYSITTER_NUNIT_XML_LIST_FILE"); + if (!String.IsNullOrEmpty(babysitterXmlList)) { + try { + string fullXmlPath = Path.GetFullPath(xmlPath); + File.AppendAllText(babysitterXmlList, fullXmlPath + Environment.NewLine); + } catch (Exception e) { + Console.WriteLine("Attempted to record XML path to file {0} but failed.", babysitterXmlList); + } + } + } + if (verbose) { + Console.WriteLine (); + Console.WriteLine ("Time: {0}", test_time.ToString (TEST_TIME_FORMAT)); + Console.WriteLine (); + Console.WriteLine ("{0,4} test(s) passed", passed.Count); + Console.WriteLine ("{0,4} test(s) failed", failed.Count); + Console.WriteLine ("{0,4} test(s) timed out", timedout.Count); + } else { + Console.WriteLine (); + Console.WriteLine (String.Format ("{0} test(s) passed, {1} test(s) did not pass.", passed.Count, failed.Count)); + } + + if (failed.Count > 0) { + Console.WriteLine (); + Console.WriteLine ("Failed test(s):"); + foreach (ProcessData pd in failed) { + Console.WriteLine (); + Console.WriteLine (pd.test); + DumpFile (pd.stdoutName, pd.stdout.ToString ()); + DumpFile (pd.stderrName, pd.stderr.ToString ()); + } + } + + if (timedout.Count > 0) { + Console.WriteLine (); + Console.WriteLine ("Timed out test(s):"); + foreach (ProcessData pd in timedout) { + Console.WriteLine (); + Console.WriteLine (pd.test); + DumpFile (pd.stdoutName, pd.stdout.ToString ()); + DumpFile (pd.stderrName, pd.stderr.ToString ()); + } + } + + return (timedout.Count == 0 && failed.Count == 0) ? 0 : 1; + } + + static void DumpFile (string filename, string text) { + Console.WriteLine ("=============== {0} ===============", filename); + Console.WriteLine (text); + Console.WriteLine ("=============== EOF ==============="); + } + + static void WriteNUnitOutput (string path, string testsuiteName, TimeSpan test_time, List passed, List failed, List timedout) { XmlWriterSettings xmlWriterSettings = new XmlWriterSettings (); xmlWriterSettings.NewLineOnAttributes = true; xmlWriterSettings.Indent = true; - string xmlPath = String.Format ("TestResult-{0}.xml", testsuiteName); - using (XmlWriter writer = XmlWriter.Create (xmlPath, xmlWriterSettings)) { + using (XmlWriter writer = XmlWriter.Create (path, xmlWriterSettings)) { // writer.WriteStartDocument (); // @@ -407,8 +472,8 @@ public class TestRunner // writer.WriteStartElement ("test-results"); writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName)); - writer.WriteAttributeString ("total", (npassed + nfailed + ntimedout).ToString()); - writer.WriteAttributeString ("failures", (nfailed + ntimedout).ToString()); + writer.WriteAttributeString ("total", (passed.Count + failed.Count + timedout.Count).ToString()); + writer.WriteAttributeString ("failures", (failed.Count + timedout.Count).ToString()); writer.WriteAttributeString ("not-run", "0"); writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd")); writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss")); @@ -431,25 +496,25 @@ public class TestRunner // writer.WriteStartElement ("test-suite"); writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName)); - writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString()); + writer.WriteAttributeString ("success", (failed.Count + timedout.Count == 0).ToString()); writer.WriteAttributeString ("time", test_time.TotalSeconds.ToString(CultureInfo.InvariantCulture)); - writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString()); + writer.WriteAttributeString ("asserts", (failed.Count + timedout.Count).ToString()); // writer.WriteStartElement ("results"); // writer.WriteStartElement ("test-suite"); writer.WriteAttributeString ("name","MonoTests"); - writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString()); + writer.WriteAttributeString ("success", (failed.Count + timedout.Count == 0).ToString()); writer.WriteAttributeString ("time", test_time.TotalSeconds.ToString(CultureInfo.InvariantCulture)); - writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString()); + writer.WriteAttributeString ("asserts", (failed.Count + timedout.Count).ToString()); // writer.WriteStartElement ("results"); // writer.WriteStartElement ("test-suite"); writer.WriteAttributeString ("name", testsuiteName); - writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString()); + writer.WriteAttributeString ("success", (failed.Count + timedout.Count == 0).ToString()); writer.WriteAttributeString ("time", test_time.TotalSeconds.ToString(CultureInfo.InvariantCulture)); - writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString()); + writer.WriteAttributeString ("asserts", (failed.Count + timedout.Count).ToString()); // writer.WriteStartElement ("results"); // Dump all passing tests first @@ -516,59 +581,88 @@ public class TestRunner // writer.WriteEndElement (); writer.WriteEndDocument (); - - string babysitterXmlList = Environment.GetEnvironmentVariable("MONO_BABYSITTER_NUNIT_XML_LIST_FILE"); - if (!String.IsNullOrEmpty(babysitterXmlList)) { - try { - string fullXmlPath = Path.GetFullPath(xmlPath); - File.AppendAllText(babysitterXmlList, fullXmlPath + Environment.NewLine); - } catch (Exception e) { - Console.WriteLine("Attempted to record XML path to file {0} but failed.", babysitterXmlList); - } - } } - - if (verbose) { - Console.WriteLine (); - Console.WriteLine ("Time: {0}", test_time.ToString (TEST_TIME_FORMAT)); - Console.WriteLine (); - Console.WriteLine ("{0,4} test(s) passed", npassed); - Console.WriteLine ("{0,4} test(s) failed", nfailed); - Console.WriteLine ("{0,4} test(s) timed out", ntimedout); - } else { - Console.WriteLine (); - Console.WriteLine (String.Format ("{0} test(s) passed, {1} test(s) did not pass.", npassed, nfailed)); - } - - if (nfailed > 0) { - Console.WriteLine (); - Console.WriteLine ("Failed test(s):"); - foreach (ProcessData pd in failed) { - Console.WriteLine (); - Console.WriteLine (pd.test); - DumpFile (pd.stdoutName, pd.stdout.ToString ()); - DumpFile (pd.stderrName, pd.stderr.ToString ()); - } - } - - if (ntimedout > 0) { - Console.WriteLine (); - Console.WriteLine ("Timed out test(s):"); - foreach (ProcessData pd in timedout) { - Console.WriteLine (); - Console.WriteLine (pd.test); - DumpFile (pd.stdoutName, pd.stdout.ToString ()); - DumpFile (pd.stderrName, pd.stderr.ToString ()); - } - } - - return (ntimedout == 0 && nfailed == 0) ? 0 : 1; } - - static void DumpFile (string filename, string text) { - Console.WriteLine ("=============== {0} ===============", filename); - Console.WriteLine (text); - Console.WriteLine ("=============== EOF ==============="); + + static void WriteXUnitOutput (string path, string testsuiteName, TimeSpan test_time, List passed, List failed, List timedout) { + XmlWriterSettings xmlWriterSettings = new XmlWriterSettings (); + xmlWriterSettings.Indent = true; + + using (XmlWriter writer = XmlWriter.Create (path, xmlWriterSettings)) { + + writer.WriteStartDocument (); + + writer.WriteStartElement ("assemblies"); + + writer.WriteStartElement ("assembly"); + + writer.WriteAttributeString ("name", testsuiteName); + writer.WriteAttributeString ("environment", $"test-runner-version: {System.Reflection.Assembly.GetExecutingAssembly ().GetName ()}, clr-version: {Environment.Version}, os-version: {Environment.OSVersion}, platform: {Environment.OSVersion.Platform}, cwd: {Environment.CurrentDirectory}, machine-name: {Environment.MachineName}, user: {Environment.UserName}, user-domain: {Environment.UserDomainName}"); + writer.WriteAttributeString ("test-framework", "test-runner"); + writer.WriteAttributeString ("run-date", XmlConvert.ToString (DateTime.Now, "yyyy-MM-dd")); + writer.WriteAttributeString ("run-time", XmlConvert.ToString (DateTime.Now, "HH:mm:ss")); + + writer.WriteAttributeString ("total", (passed.Count + failed.Count + timedout.Count).ToString ()); + writer.WriteAttributeString ("errors", 0.ToString ()); + writer.WriteAttributeString ("failed", (failed.Count + timedout.Count).ToString ()); + writer.WriteAttributeString ("skipped", 0.ToString ()); + + writer.WriteAttributeString ("passed", passed.Count.ToString ()); + + writer.WriteStartElement ("collection"); + writer.WriteAttributeString ("name", "tests"); + + foreach (var pd in passed) { + writer.WriteStartElement ("test"); + writer.WriteAttributeString ("name", testsuiteName + ".tests." + pd.test); + writer.WriteAttributeString ("type", testsuiteName + ".tests"); + writer.WriteAttributeString ("method", pd.test.ToString ()); + writer.WriteAttributeString ("result", "Pass"); + writer.WriteAttributeString ("time", pd.duration.TotalSeconds.ToString(CultureInfo.InvariantCulture)); + writer.WriteEndElement (); // test element + } + + foreach (var pd in failed) { + writer.WriteStartElement ("test"); + writer.WriteAttributeString ("name", testsuiteName + ".tests." + pd.test); + writer.WriteAttributeString ("type", testsuiteName + ".tests"); + writer.WriteAttributeString ("method", pd.test.ToString ()); + writer.WriteAttributeString ("result", "Fail"); + writer.WriteAttributeString ("time", pd.duration.TotalSeconds.ToString(CultureInfo.InvariantCulture)); + + writer.WriteStartElement ("failure"); + writer.WriteAttributeString ("exception-type", "TestRunnerException"); + writer.WriteStartElement ("message"); + writer.WriteCData (FilterInvalidXmlChars ("STDOUT:\n" + pd.stdout.ToString () + "\n\nSTDERR:\n" + pd.stderr.ToString ())); + writer.WriteEndElement (); // message element + writer.WriteEndElement (); // failure element + + writer.WriteEndElement(); // test element + } + + foreach (var pd in timedout) { + writer.WriteStartElement ("test"); + writer.WriteAttributeString ("name", testsuiteName + ".tests." + pd.test + "_timedout"); + writer.WriteAttributeString ("type", testsuiteName + ".tests"); + writer.WriteAttributeString ("method", pd.test.ToString ()); + writer.WriteAttributeString ("result", "Fail"); + writer.WriteAttributeString ("time", pd.duration.TotalSeconds.ToString(CultureInfo.InvariantCulture)); + + writer.WriteStartElement ("failure"); + writer.WriteAttributeString ("exception-type", "TestRunnerException"); + writer.WriteStartElement ("message"); + writer.WriteCData (FilterInvalidXmlChars ("STDOUT:\n" + pd.stdout.ToString () + "\n\nSTDERR:\n" + pd.stderr.ToString ())); + writer.WriteEndElement (); // message element + writer.WriteEndElement (); // failure element + + writer.WriteEndElement(); // test element + } + + writer.WriteEndElement (); // collection + writer.WriteEndElement (); // assembly + writer.WriteEndElement (); // assemblies + writer.WriteEndDocument (); + } } static string FilterInvalidXmlChars (string text) { diff --git a/mono/tests/testing_gac/Makefile.in b/mono/tests/testing_gac/Makefile.in index 6450e2a173..750b62d174 100644 --- a/mono/tests/testing_gac/Makefile.in +++ b/mono/tests/testing_gac/Makefile.in @@ -84,7 +84,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ @HYBRID_AOT_TESTS_TRUE@am__append_2 = --runtime-args "$(AOT_RUN_FLAGS)" subdir = mono/tests/testing_gac ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -153,6 +154,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -226,6 +228,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/unit-tests/Makefile.am b/mono/unit-tests/Makefile.am index fa430ba889..5e9ac561f6 100644 --- a/mono/unit-tests/Makefile.am +++ b/mono/unit-tests/Makefile.am @@ -48,47 +48,57 @@ if !DISABLE_DEBUGGER_AGENT mini_libs += $(monodir)/mono/mini/libmono-dbg.la endif +CFLAGS = $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) + if !CROSS_COMPILE if !HOST_WIN32 noinst_LTLIBRARIES = libtestlib.la -libtestlib_la_SOURCES = +libtestlib_la_CFLAGS = @CXX_ADD_CFLAGS@ +libtestlib_la_SOURCES = \ + test-sgen-qsort.c \ + test-memfuncs.c \ + test-mono-linked-list-set.c \ + test-conc-hashtable.c \ + test-mono-handle.c \ + test-mono-callspec.c \ + test-mono-string.c libtestlib_la_LIBADD = ../metadata/libmonoruntimesgen.la ../sgen/libmonosgen.la ../utils/libmonoutils.la -test_sgen_qsort_SOURCES = test-sgen-qsort.c -test_sgen_qsort_CFLAGS = $(test_cflags) -test_sgen_qsort_LDADD = $(test_ldadd) +test_sgen_qsort_SOURCES = main.c +test_sgen_qsort_CFLAGS = $(test_cflags) -DMAIN=test_sgen_qsort_main +test_sgen_qsort_LDADD = $(test_ldadd) libtestlib_la-test-sgen-qsort.lo test_sgen_qsort_LDFLAGS = $(test_ldflags) -test_memfuncs_SOURCES = test-memfuncs.c -test_memfuncs_CFLAGS = $(test_cflags) -test_memfuncs_LDADD = $(test_ldadd) +test_memfuncs_SOURCES = main.c +test_memfuncs_CFLAGS = $(test_cflags) -DMAIN=test_memfuncs_main +test_memfuncs_LDADD = $(test_ldadd) libtestlib_la-test-memfuncs.lo test_memfuncs_LDFLAGS = $(test_ldflags) -test_mono_linked_list_set_SOURCES = test-mono-linked-list-set.c -test_mono_linked_list_set_CFLAGS = $(test_cflags) -test_mono_linked_list_set_LDADD = $(test_ldadd) +test_mono_linked_list_set_SOURCES = main.c +test_mono_linked_list_set_CFLAGS = $(test_cflags) -DMAIN=test_mono_linked_list_set_main +test_mono_linked_list_set_LDADD = $(test_ldadd) libtestlib_la-test-mono-linked-list-set.lo test_mono_linked_list_set_LDFLAGS = $(test_ldflags) -test_conc_hashtable_SOURCES = test-conc-hashtable.c -test_conc_hashtable_CFLAGS = $(test_cflags) -test_conc_hashtable_LDADD = $(test_ldadd) +test_conc_hashtable_SOURCES = main.c +test_conc_hashtable_CFLAGS = $(test_cflags) -DMAIN=test_conc_hashtable_main +test_conc_hashtable_LDADD = $(test_ldadd) libtestlib_la-test-conc-hashtable.lo test_conc_hashtable_LDFLAGS = $(test_ldflags) -test_mono_handle_SOURCES = test-mono-handle.c -test_mono_handle_CFLAGS = $(test_cflags) -test_mono_handle_LDADD = $(test_ldadd) +test_mono_handle_SOURCES = main.c +test_mono_handle_CFLAGS = $(test_cflags) -DMAIN=test_mono_handle_main +test_mono_handle_LDADD = $(test_ldadd) libtestlib_la-test-mono-handle.lo test_mono_handle_LDFLAGS = $(test_ldflags) -test_mono_callspec_SOURCES = test-mono-callspec.c -test_mono_callspec_CFLAGS = $(AM_CFLAGS) -test_mono_callspec_LDADD = $(test_ldadd) $(mini_libs) $(sgen_libs) +test_mono_callspec_SOURCES = main.c +test_mono_callspec_CFLAGS = $(AM_CFLAGS) -DMAIN=test_mono_callspec_main +test_mono_callspec_LDADD = $(test_ldadd) $(mini_libs) $(sgen_libs) libtestlib_la-test-mono-callspec.lo test_mono_callspec_LDFLAGS = $(test_ldflags) test_mono_callspec_DEPENDENCIES = callspec.exe -test_mono_string_SOURCES = test-mono-string.c -test_mono_string_CFLAGS = $(test-cflags) -test_mono_string_LDADD = $(test_ldadd) $(mini_libs) $(sgen_libs) +test_mono_string_SOURCES = main.c +test_mono_string_CFLAGS = $(test-cflags) -DMAIN=test_mono_string_main +test_mono_string_LDADD = $(test_ldadd) $(mini_libs) $(sgen_libs) libtestlib_la-test-mono-string.lo test_mono_string_LDFLAGS = $(test_ldflags) check_PROGRAMS = test-sgen-qsort test-memfuncs test-mono-linked-list-set test-conc-hashtable test-mono-handle \ @@ -117,4 +127,3 @@ clean-local: endif !HOST_WIN32 endif !CROSS_COMPILE - diff --git a/mono/unit-tests/Makefile.in b/mono/unit-tests/Makefile.in index 2809feef36..8e432f1aca 100644 --- a/mono/unit-tests/Makefile.in +++ b/mono/unit-tests/Makefile.in @@ -100,7 +100,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk $(srcdir)/Makefile.in \ @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ test-mono-string$(EXEEXT) subdir = mono/unit-tests ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -116,76 +117,93 @@ LTLIBRARIES = $(noinst_LTLIBRARIES) @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@libtestlib_la_DEPENDENCIES = ../metadata/libmonoruntimesgen.la \ @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ ../sgen/libmonosgen.la \ @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ ../utils/libmonoutils.la -am_libtestlib_la_OBJECTS = +am__libtestlib_la_SOURCES_DIST = test-sgen-qsort.c test-memfuncs.c \ + test-mono-linked-list-set.c test-conc-hashtable.c \ + test-mono-handle.c test-mono-callspec.c test-mono-string.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_libtestlib_la_OBJECTS = libtestlib_la-test-sgen-qsort.lo \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ libtestlib_la-test-memfuncs.lo \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ libtestlib_la-test-mono-linked-list-set.lo \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ libtestlib_la-test-conc-hashtable.lo \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ libtestlib_la-test-mono-handle.lo \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ libtestlib_la-test-mono-callspec.lo \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ libtestlib_la-test-mono-string.lo libtestlib_la_OBJECTS = $(am_libtestlib_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = +libtestlib_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(libtestlib_la_CFLAGS) \ + $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_libtestlib_la_rpath = -am__test_conc_hashtable_SOURCES_DIST = test-conc-hashtable.c -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_test_conc_hashtable_OBJECTS = test_conc_hashtable-test-conc-hashtable.$(OBJEXT) +am__test_conc_hashtable_SOURCES_DIST = main.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_test_conc_hashtable_OBJECTS = test_conc_hashtable-main.$(OBJEXT) test_conc_hashtable_OBJECTS = $(am_test_conc_hashtable_OBJECTS) am__DEPENDENCIES_1 = am__DEPENDENCIES_2 = libtestlib.la $(am__DEPENDENCIES_1) $(glib_libs) \ $(am__DEPENDENCIES_1) @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_conc_hashtable_DEPENDENCIES = \ -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ $(am__DEPENDENCIES_2) +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ $(am__DEPENDENCIES_2) \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ libtestlib_la-test-conc-hashtable.lo test_conc_hashtable_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_conc_hashtable_CFLAGS) $(CFLAGS) \ $(test_conc_hashtable_LDFLAGS) $(LDFLAGS) -o $@ -am__test_memfuncs_SOURCES_DIST = test-memfuncs.c -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_test_memfuncs_OBJECTS = test_memfuncs-test-memfuncs.$(OBJEXT) +am__test_memfuncs_SOURCES_DIST = main.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_test_memfuncs_OBJECTS = test_memfuncs-main.$(OBJEXT) test_memfuncs_OBJECTS = $(am_test_memfuncs_OBJECTS) @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_memfuncs_DEPENDENCIES = \ -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ $(am__DEPENDENCIES_2) +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ $(am__DEPENDENCIES_2) \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ libtestlib_la-test-memfuncs.lo test_memfuncs_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(test_memfuncs_CFLAGS) \ $(CFLAGS) $(test_memfuncs_LDFLAGS) $(LDFLAGS) -o $@ -am__test_mono_callspec_SOURCES_DIST = test-mono-callspec.c -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_test_mono_callspec_OBJECTS = test_mono_callspec-test-mono-callspec.$(OBJEXT) +am__test_mono_callspec_SOURCES_DIST = main.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_test_mono_callspec_OBJECTS = test_mono_callspec-main.$(OBJEXT) test_mono_callspec_OBJECTS = $(am_test_mono_callspec_OBJECTS) test_mono_callspec_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_mono_callspec_CFLAGS) $(CFLAGS) \ $(test_mono_callspec_LDFLAGS) $(LDFLAGS) -o $@ -am__test_mono_handle_SOURCES_DIST = test-mono-handle.c -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_test_mono_handle_OBJECTS = test_mono_handle-test-mono-handle.$(OBJEXT) +am__test_mono_handle_SOURCES_DIST = main.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_test_mono_handle_OBJECTS = test_mono_handle-main.$(OBJEXT) test_mono_handle_OBJECTS = $(am_test_mono_handle_OBJECTS) @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_handle_DEPENDENCIES = \ -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ $(am__DEPENDENCIES_2) +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ $(am__DEPENDENCIES_2) \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ libtestlib_la-test-mono-handle.lo test_mono_handle_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_mono_handle_CFLAGS) $(CFLAGS) \ $(test_mono_handle_LDFLAGS) $(LDFLAGS) -o $@ -am__test_mono_linked_list_set_SOURCES_DIST = \ - test-mono-linked-list-set.c -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_test_mono_linked_list_set_OBJECTS = test_mono_linked_list_set-test-mono-linked-list-set.$(OBJEXT) +am__test_mono_linked_list_set_SOURCES_DIST = main.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_test_mono_linked_list_set_OBJECTS = test_mono_linked_list_set-main.$(OBJEXT) test_mono_linked_list_set_OBJECTS = \ $(am_test_mono_linked_list_set_OBJECTS) @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_linked_list_set_DEPENDENCIES = \ -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ $(am__DEPENDENCIES_2) +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ $(am__DEPENDENCIES_2) \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ libtestlib_la-test-mono-linked-list-set.lo test_mono_linked_list_set_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_mono_linked_list_set_CFLAGS) $(CFLAGS) \ $(test_mono_linked_list_set_LDFLAGS) $(LDFLAGS) -o $@ -am__test_mono_string_SOURCES_DIST = test-mono-string.c -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_test_mono_string_OBJECTS = test_mono_string-test-mono-string.$(OBJEXT) +am__test_mono_string_SOURCES_DIST = main.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_test_mono_string_OBJECTS = test_mono_string-main.$(OBJEXT) test_mono_string_OBJECTS = $(am_test_mono_string_OBJECTS) @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_string_DEPENDENCIES = \ @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ $(am__DEPENDENCIES_2) \ @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ $(mini_libs) \ -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ $(sgen_libs) +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ $(sgen_libs) \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ libtestlib_la-test-mono-string.lo test_mono_string_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_mono_string_CFLAGS) $(CFLAGS) \ $(test_mono_string_LDFLAGS) $(LDFLAGS) -o $@ -am__test_sgen_qsort_SOURCES_DIST = test-sgen-qsort.c -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_test_sgen_qsort_OBJECTS = test_sgen_qsort-test-sgen-qsort.$(OBJEXT) +am__test_sgen_qsort_SOURCES_DIST = main.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@am_test_sgen_qsort_OBJECTS = test_sgen_qsort-main.$(OBJEXT) test_sgen_qsort_OBJECTS = $(am_test_sgen_qsort_OBJECTS) @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_sgen_qsort_DEPENDENCIES = \ -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ $(am__DEPENDENCIES_2) +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ $(am__DEPENDENCIES_2) \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ libtestlib_la-test-sgen-qsort.lo test_sgen_qsort_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_sgen_qsort_CFLAGS) $(CFLAGS) $(test_sgen_qsort_LDFLAGS) \ @@ -225,7 +243,7 @@ SOURCES = $(libtestlib_la_SOURCES) $(test_conc_hashtable_SOURCES) \ $(test_mono_handle_SOURCES) \ $(test_mono_linked_list_set_SOURCES) \ $(test_mono_string_SOURCES) $(test_sgen_qsort_SOURCES) -DIST_SOURCES = $(libtestlib_la_SOURCES) \ +DIST_SOURCES = $(am__libtestlib_la_SOURCES_DIST) \ $(am__test_conc_hashtable_SOURCES_DIST) \ $(am__test_memfuncs_SOURCES_DIST) \ $(am__test_mono_callspec_SOURCES_DIST) \ @@ -488,7 +506,7 @@ CCASDEPMODE = @CCASDEPMODE@ CCASFLAGS = @CCASFLAGS@ CCDEPMODE = @CCDEPMODE@ CC_FOR_BUILD = @CC_FOR_BUILD@ -CFLAGS = @CFLAGS@ +CFLAGS = $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) CFLAGS_FOR_BUILD = @CFLAGS_FOR_BUILD@ CMAKE = @CMAKE@ CPP = @CPP@ @@ -498,6 +516,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -571,6 +590,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ @@ -723,36 +758,45 @@ sgen_libs = \ mini_libs = $(monodir)/mono/mini/libmini.la $(am__append_1) \ $(am__append_2) @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@noinst_LTLIBRARIES = libtestlib.la -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@libtestlib_la_SOURCES = +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@libtestlib_la_CFLAGS = @CXX_ADD_CFLAGS@ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@libtestlib_la_SOURCES = \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ test-sgen-qsort.c \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ test-memfuncs.c \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ test-mono-linked-list-set.c \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ test-conc-hashtable.c \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ test-mono-handle.c \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ test-mono-callspec.c \ +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@ test-mono-string.c + @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@libtestlib_la_LIBADD = ../metadata/libmonoruntimesgen.la ../sgen/libmonosgen.la ../utils/libmonoutils.la -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_sgen_qsort_SOURCES = test-sgen-qsort.c -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_sgen_qsort_CFLAGS = $(test_cflags) -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_sgen_qsort_LDADD = $(test_ldadd) +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_sgen_qsort_SOURCES = main.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_sgen_qsort_CFLAGS = $(test_cflags) -DMAIN=test_sgen_qsort_main +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_sgen_qsort_LDADD = $(test_ldadd) libtestlib_la-test-sgen-qsort.lo @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_sgen_qsort_LDFLAGS = $(test_ldflags) -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_memfuncs_SOURCES = test-memfuncs.c -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_memfuncs_CFLAGS = $(test_cflags) -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_memfuncs_LDADD = $(test_ldadd) +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_memfuncs_SOURCES = main.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_memfuncs_CFLAGS = $(test_cflags) -DMAIN=test_memfuncs_main +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_memfuncs_LDADD = $(test_ldadd) libtestlib_la-test-memfuncs.lo @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_memfuncs_LDFLAGS = $(test_ldflags) -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_linked_list_set_SOURCES = test-mono-linked-list-set.c -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_linked_list_set_CFLAGS = $(test_cflags) -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_linked_list_set_LDADD = $(test_ldadd) +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_linked_list_set_SOURCES = main.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_linked_list_set_CFLAGS = $(test_cflags) -DMAIN=test_mono_linked_list_set_main +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_linked_list_set_LDADD = $(test_ldadd) libtestlib_la-test-mono-linked-list-set.lo @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_linked_list_set_LDFLAGS = $(test_ldflags) -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_conc_hashtable_SOURCES = test-conc-hashtable.c -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_conc_hashtable_CFLAGS = $(test_cflags) -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_conc_hashtable_LDADD = $(test_ldadd) +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_conc_hashtable_SOURCES = main.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_conc_hashtable_CFLAGS = $(test_cflags) -DMAIN=test_conc_hashtable_main +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_conc_hashtable_LDADD = $(test_ldadd) libtestlib_la-test-conc-hashtable.lo @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_conc_hashtable_LDFLAGS = $(test_ldflags) -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_handle_SOURCES = test-mono-handle.c -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_handle_CFLAGS = $(test_cflags) -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_handle_LDADD = $(test_ldadd) +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_handle_SOURCES = main.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_handle_CFLAGS = $(test_cflags) -DMAIN=test_mono_handle_main +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_handle_LDADD = $(test_ldadd) libtestlib_la-test-mono-handle.lo @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_handle_LDFLAGS = $(test_ldflags) -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_callspec_SOURCES = test-mono-callspec.c -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_callspec_CFLAGS = $(AM_CFLAGS) -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_callspec_LDADD = $(test_ldadd) $(mini_libs) $(sgen_libs) +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_callspec_SOURCES = main.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_callspec_CFLAGS = $(AM_CFLAGS) -DMAIN=test_mono_callspec_main +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_callspec_LDADD = $(test_ldadd) $(mini_libs) $(sgen_libs) libtestlib_la-test-mono-callspec.lo @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_callspec_LDFLAGS = $(test_ldflags) @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_callspec_DEPENDENCIES = callspec.exe -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_string_SOURCES = test-mono-string.c -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_string_CFLAGS = $(test-cflags) -@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_string_LDADD = $(test_ldadd) $(mini_libs) $(sgen_libs) +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_string_SOURCES = main.c +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_string_CFLAGS = $(test-cflags) -DMAIN=test_mono_string_main +@CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_string_LDADD = $(test_ldadd) $(mini_libs) $(sgen_libs) libtestlib_la-test-mono-string.lo @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@test_mono_string_LDFLAGS = $(test_ldflags) @CROSS_COMPILE_FALSE@@HOST_WIN32_FALSE@AM_TESTS_ENVIRONMENT = export MONO_PATH=$(mcs_topdir)/class/lib/build; all: all-am @@ -803,7 +847,7 @@ clean-noinstLTLIBRARIES: } libtestlib.la: $(libtestlib_la_OBJECTS) $(libtestlib_la_DEPENDENCIES) $(EXTRA_libtestlib_la_DEPENDENCIES) - $(AM_V_CCLD)$(LINK) $(am_libtestlib_la_rpath) $(libtestlib_la_OBJECTS) $(libtestlib_la_LIBADD) $(LIBS) + $(AM_V_CCLD)$(libtestlib_la_LINK) $(am_libtestlib_la_rpath) $(libtestlib_la_OBJECTS) $(libtestlib_la_LIBADD) $(LIBS) clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ @@ -848,13 +892,20 @@ mostlyclean-compile: distclean-compile: -rm -f *.tab.c -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_conc_hashtable-test-conc-hashtable.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_memfuncs-test-memfuncs.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_mono_callspec-test-mono-callspec.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_mono_handle-test-mono-handle.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_mono_linked_list_set-test-mono-linked-list-set.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_mono_string-test-mono-string.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_sgen_qsort-test-sgen-qsort.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libtestlib_la-test-conc-hashtable.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libtestlib_la-test-memfuncs.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libtestlib_la-test-mono-callspec.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libtestlib_la-test-mono-handle.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libtestlib_la-test-mono-linked-list-set.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libtestlib_la-test-mono-string.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libtestlib_la-test-sgen-qsort.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_conc_hashtable-main.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_memfuncs-main.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_mono_callspec-main.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_mono_handle-main.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_mono_linked_list_set-main.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_mono_string-main.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_sgen_qsort-main.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @@ -880,103 +931,152 @@ distclean-compile: @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< -test_conc_hashtable-test-conc-hashtable.o: test-conc-hashtable.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_conc_hashtable_CFLAGS) $(CFLAGS) -MT test_conc_hashtable-test-conc-hashtable.o -MD -MP -MF $(DEPDIR)/test_conc_hashtable-test-conc-hashtable.Tpo -c -o test_conc_hashtable-test-conc-hashtable.o `test -f 'test-conc-hashtable.c' || echo '$(srcdir)/'`test-conc-hashtable.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_conc_hashtable-test-conc-hashtable.Tpo $(DEPDIR)/test_conc_hashtable-test-conc-hashtable.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-conc-hashtable.c' object='test_conc_hashtable-test-conc-hashtable.o' libtool=no @AMDEPBACKSLASH@ +libtestlib_la-test-sgen-qsort.lo: test-sgen-qsort.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestlib_la_CFLAGS) $(CFLAGS) -MT libtestlib_la-test-sgen-qsort.lo -MD -MP -MF $(DEPDIR)/libtestlib_la-test-sgen-qsort.Tpo -c -o libtestlib_la-test-sgen-qsort.lo `test -f 'test-sgen-qsort.c' || echo '$(srcdir)/'`test-sgen-qsort.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libtestlib_la-test-sgen-qsort.Tpo $(DEPDIR)/libtestlib_la-test-sgen-qsort.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-sgen-qsort.c' object='libtestlib_la-test-sgen-qsort.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_conc_hashtable_CFLAGS) $(CFLAGS) -c -o test_conc_hashtable-test-conc-hashtable.o `test -f 'test-conc-hashtable.c' || echo '$(srcdir)/'`test-conc-hashtable.c +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestlib_la_CFLAGS) $(CFLAGS) -c -o libtestlib_la-test-sgen-qsort.lo `test -f 'test-sgen-qsort.c' || echo '$(srcdir)/'`test-sgen-qsort.c -test_conc_hashtable-test-conc-hashtable.obj: test-conc-hashtable.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_conc_hashtable_CFLAGS) $(CFLAGS) -MT test_conc_hashtable-test-conc-hashtable.obj -MD -MP -MF $(DEPDIR)/test_conc_hashtable-test-conc-hashtable.Tpo -c -o test_conc_hashtable-test-conc-hashtable.obj `if test -f 'test-conc-hashtable.c'; then $(CYGPATH_W) 'test-conc-hashtable.c'; else $(CYGPATH_W) '$(srcdir)/test-conc-hashtable.c'; fi` -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_conc_hashtable-test-conc-hashtable.Tpo $(DEPDIR)/test_conc_hashtable-test-conc-hashtable.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-conc-hashtable.c' object='test_conc_hashtable-test-conc-hashtable.obj' libtool=no @AMDEPBACKSLASH@ +libtestlib_la-test-memfuncs.lo: test-memfuncs.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestlib_la_CFLAGS) $(CFLAGS) -MT libtestlib_la-test-memfuncs.lo -MD -MP -MF $(DEPDIR)/libtestlib_la-test-memfuncs.Tpo -c -o libtestlib_la-test-memfuncs.lo `test -f 'test-memfuncs.c' || echo '$(srcdir)/'`test-memfuncs.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libtestlib_la-test-memfuncs.Tpo $(DEPDIR)/libtestlib_la-test-memfuncs.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-memfuncs.c' object='libtestlib_la-test-memfuncs.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_conc_hashtable_CFLAGS) $(CFLAGS) -c -o test_conc_hashtable-test-conc-hashtable.obj `if test -f 'test-conc-hashtable.c'; then $(CYGPATH_W) 'test-conc-hashtable.c'; else $(CYGPATH_W) '$(srcdir)/test-conc-hashtable.c'; fi` +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestlib_la_CFLAGS) $(CFLAGS) -c -o libtestlib_la-test-memfuncs.lo `test -f 'test-memfuncs.c' || echo '$(srcdir)/'`test-memfuncs.c -test_memfuncs-test-memfuncs.o: test-memfuncs.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_memfuncs_CFLAGS) $(CFLAGS) -MT test_memfuncs-test-memfuncs.o -MD -MP -MF $(DEPDIR)/test_memfuncs-test-memfuncs.Tpo -c -o test_memfuncs-test-memfuncs.o `test -f 'test-memfuncs.c' || echo '$(srcdir)/'`test-memfuncs.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_memfuncs-test-memfuncs.Tpo $(DEPDIR)/test_memfuncs-test-memfuncs.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-memfuncs.c' object='test_memfuncs-test-memfuncs.o' libtool=no @AMDEPBACKSLASH@ +libtestlib_la-test-mono-linked-list-set.lo: test-mono-linked-list-set.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestlib_la_CFLAGS) $(CFLAGS) -MT libtestlib_la-test-mono-linked-list-set.lo -MD -MP -MF $(DEPDIR)/libtestlib_la-test-mono-linked-list-set.Tpo -c -o libtestlib_la-test-mono-linked-list-set.lo `test -f 'test-mono-linked-list-set.c' || echo '$(srcdir)/'`test-mono-linked-list-set.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libtestlib_la-test-mono-linked-list-set.Tpo $(DEPDIR)/libtestlib_la-test-mono-linked-list-set.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-mono-linked-list-set.c' object='libtestlib_la-test-mono-linked-list-set.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_memfuncs_CFLAGS) $(CFLAGS) -c -o test_memfuncs-test-memfuncs.o `test -f 'test-memfuncs.c' || echo '$(srcdir)/'`test-memfuncs.c +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestlib_la_CFLAGS) $(CFLAGS) -c -o libtestlib_la-test-mono-linked-list-set.lo `test -f 'test-mono-linked-list-set.c' || echo '$(srcdir)/'`test-mono-linked-list-set.c -test_memfuncs-test-memfuncs.obj: test-memfuncs.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_memfuncs_CFLAGS) $(CFLAGS) -MT test_memfuncs-test-memfuncs.obj -MD -MP -MF $(DEPDIR)/test_memfuncs-test-memfuncs.Tpo -c -o test_memfuncs-test-memfuncs.obj `if test -f 'test-memfuncs.c'; then $(CYGPATH_W) 'test-memfuncs.c'; else $(CYGPATH_W) '$(srcdir)/test-memfuncs.c'; fi` -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_memfuncs-test-memfuncs.Tpo $(DEPDIR)/test_memfuncs-test-memfuncs.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-memfuncs.c' object='test_memfuncs-test-memfuncs.obj' libtool=no @AMDEPBACKSLASH@ +libtestlib_la-test-conc-hashtable.lo: test-conc-hashtable.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestlib_la_CFLAGS) $(CFLAGS) -MT libtestlib_la-test-conc-hashtable.lo -MD -MP -MF $(DEPDIR)/libtestlib_la-test-conc-hashtable.Tpo -c -o libtestlib_la-test-conc-hashtable.lo `test -f 'test-conc-hashtable.c' || echo '$(srcdir)/'`test-conc-hashtable.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libtestlib_la-test-conc-hashtable.Tpo $(DEPDIR)/libtestlib_la-test-conc-hashtable.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-conc-hashtable.c' object='libtestlib_la-test-conc-hashtable.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_memfuncs_CFLAGS) $(CFLAGS) -c -o test_memfuncs-test-memfuncs.obj `if test -f 'test-memfuncs.c'; then $(CYGPATH_W) 'test-memfuncs.c'; else $(CYGPATH_W) '$(srcdir)/test-memfuncs.c'; fi` +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestlib_la_CFLAGS) $(CFLAGS) -c -o libtestlib_la-test-conc-hashtable.lo `test -f 'test-conc-hashtable.c' || echo '$(srcdir)/'`test-conc-hashtable.c -test_mono_callspec-test-mono-callspec.o: test-mono-callspec.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_callspec_CFLAGS) $(CFLAGS) -MT test_mono_callspec-test-mono-callspec.o -MD -MP -MF $(DEPDIR)/test_mono_callspec-test-mono-callspec.Tpo -c -o test_mono_callspec-test-mono-callspec.o `test -f 'test-mono-callspec.c' || echo '$(srcdir)/'`test-mono-callspec.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_callspec-test-mono-callspec.Tpo $(DEPDIR)/test_mono_callspec-test-mono-callspec.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-mono-callspec.c' object='test_mono_callspec-test-mono-callspec.o' libtool=no @AMDEPBACKSLASH@ +libtestlib_la-test-mono-handle.lo: test-mono-handle.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestlib_la_CFLAGS) $(CFLAGS) -MT libtestlib_la-test-mono-handle.lo -MD -MP -MF $(DEPDIR)/libtestlib_la-test-mono-handle.Tpo -c -o libtestlib_la-test-mono-handle.lo `test -f 'test-mono-handle.c' || echo '$(srcdir)/'`test-mono-handle.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libtestlib_la-test-mono-handle.Tpo $(DEPDIR)/libtestlib_la-test-mono-handle.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-mono-handle.c' object='libtestlib_la-test-mono-handle.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_callspec_CFLAGS) $(CFLAGS) -c -o test_mono_callspec-test-mono-callspec.o `test -f 'test-mono-callspec.c' || echo '$(srcdir)/'`test-mono-callspec.c +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestlib_la_CFLAGS) $(CFLAGS) -c -o libtestlib_la-test-mono-handle.lo `test -f 'test-mono-handle.c' || echo '$(srcdir)/'`test-mono-handle.c -test_mono_callspec-test-mono-callspec.obj: test-mono-callspec.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_callspec_CFLAGS) $(CFLAGS) -MT test_mono_callspec-test-mono-callspec.obj -MD -MP -MF $(DEPDIR)/test_mono_callspec-test-mono-callspec.Tpo -c -o test_mono_callspec-test-mono-callspec.obj `if test -f 'test-mono-callspec.c'; then $(CYGPATH_W) 'test-mono-callspec.c'; else $(CYGPATH_W) '$(srcdir)/test-mono-callspec.c'; fi` -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_callspec-test-mono-callspec.Tpo $(DEPDIR)/test_mono_callspec-test-mono-callspec.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-mono-callspec.c' object='test_mono_callspec-test-mono-callspec.obj' libtool=no @AMDEPBACKSLASH@ +libtestlib_la-test-mono-callspec.lo: test-mono-callspec.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestlib_la_CFLAGS) $(CFLAGS) -MT libtestlib_la-test-mono-callspec.lo -MD -MP -MF $(DEPDIR)/libtestlib_la-test-mono-callspec.Tpo -c -o libtestlib_la-test-mono-callspec.lo `test -f 'test-mono-callspec.c' || echo '$(srcdir)/'`test-mono-callspec.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libtestlib_la-test-mono-callspec.Tpo $(DEPDIR)/libtestlib_la-test-mono-callspec.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-mono-callspec.c' object='libtestlib_la-test-mono-callspec.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_callspec_CFLAGS) $(CFLAGS) -c -o test_mono_callspec-test-mono-callspec.obj `if test -f 'test-mono-callspec.c'; then $(CYGPATH_W) 'test-mono-callspec.c'; else $(CYGPATH_W) '$(srcdir)/test-mono-callspec.c'; fi` +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestlib_la_CFLAGS) $(CFLAGS) -c -o libtestlib_la-test-mono-callspec.lo `test -f 'test-mono-callspec.c' || echo '$(srcdir)/'`test-mono-callspec.c -test_mono_handle-test-mono-handle.o: test-mono-handle.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_handle_CFLAGS) $(CFLAGS) -MT test_mono_handle-test-mono-handle.o -MD -MP -MF $(DEPDIR)/test_mono_handle-test-mono-handle.Tpo -c -o test_mono_handle-test-mono-handle.o `test -f 'test-mono-handle.c' || echo '$(srcdir)/'`test-mono-handle.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_handle-test-mono-handle.Tpo $(DEPDIR)/test_mono_handle-test-mono-handle.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-mono-handle.c' object='test_mono_handle-test-mono-handle.o' libtool=no @AMDEPBACKSLASH@ +libtestlib_la-test-mono-string.lo: test-mono-string.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestlib_la_CFLAGS) $(CFLAGS) -MT libtestlib_la-test-mono-string.lo -MD -MP -MF $(DEPDIR)/libtestlib_la-test-mono-string.Tpo -c -o libtestlib_la-test-mono-string.lo `test -f 'test-mono-string.c' || echo '$(srcdir)/'`test-mono-string.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libtestlib_la-test-mono-string.Tpo $(DEPDIR)/libtestlib_la-test-mono-string.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-mono-string.c' object='libtestlib_la-test-mono-string.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_handle_CFLAGS) $(CFLAGS) -c -o test_mono_handle-test-mono-handle.o `test -f 'test-mono-handle.c' || echo '$(srcdir)/'`test-mono-handle.c +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestlib_la_CFLAGS) $(CFLAGS) -c -o libtestlib_la-test-mono-string.lo `test -f 'test-mono-string.c' || echo '$(srcdir)/'`test-mono-string.c -test_mono_handle-test-mono-handle.obj: test-mono-handle.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_handle_CFLAGS) $(CFLAGS) -MT test_mono_handle-test-mono-handle.obj -MD -MP -MF $(DEPDIR)/test_mono_handle-test-mono-handle.Tpo -c -o test_mono_handle-test-mono-handle.obj `if test -f 'test-mono-handle.c'; then $(CYGPATH_W) 'test-mono-handle.c'; else $(CYGPATH_W) '$(srcdir)/test-mono-handle.c'; fi` -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_handle-test-mono-handle.Tpo $(DEPDIR)/test_mono_handle-test-mono-handle.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-mono-handle.c' object='test_mono_handle-test-mono-handle.obj' libtool=no @AMDEPBACKSLASH@ +test_conc_hashtable-main.o: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_conc_hashtable_CFLAGS) $(CFLAGS) -MT test_conc_hashtable-main.o -MD -MP -MF $(DEPDIR)/test_conc_hashtable-main.Tpo -c -o test_conc_hashtable-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_conc_hashtable-main.Tpo $(DEPDIR)/test_conc_hashtable-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='test_conc_hashtable-main.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_handle_CFLAGS) $(CFLAGS) -c -o test_mono_handle-test-mono-handle.obj `if test -f 'test-mono-handle.c'; then $(CYGPATH_W) 'test-mono-handle.c'; else $(CYGPATH_W) '$(srcdir)/test-mono-handle.c'; fi` +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_conc_hashtable_CFLAGS) $(CFLAGS) -c -o test_conc_hashtable-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c -test_mono_linked_list_set-test-mono-linked-list-set.o: test-mono-linked-list-set.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_linked_list_set_CFLAGS) $(CFLAGS) -MT test_mono_linked_list_set-test-mono-linked-list-set.o -MD -MP -MF $(DEPDIR)/test_mono_linked_list_set-test-mono-linked-list-set.Tpo -c -o test_mono_linked_list_set-test-mono-linked-list-set.o `test -f 'test-mono-linked-list-set.c' || echo '$(srcdir)/'`test-mono-linked-list-set.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_linked_list_set-test-mono-linked-list-set.Tpo $(DEPDIR)/test_mono_linked_list_set-test-mono-linked-list-set.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-mono-linked-list-set.c' object='test_mono_linked_list_set-test-mono-linked-list-set.o' libtool=no @AMDEPBACKSLASH@ +test_conc_hashtable-main.obj: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_conc_hashtable_CFLAGS) $(CFLAGS) -MT test_conc_hashtable-main.obj -MD -MP -MF $(DEPDIR)/test_conc_hashtable-main.Tpo -c -o test_conc_hashtable-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_conc_hashtable-main.Tpo $(DEPDIR)/test_conc_hashtable-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='test_conc_hashtable-main.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_linked_list_set_CFLAGS) $(CFLAGS) -c -o test_mono_linked_list_set-test-mono-linked-list-set.o `test -f 'test-mono-linked-list-set.c' || echo '$(srcdir)/'`test-mono-linked-list-set.c +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_conc_hashtable_CFLAGS) $(CFLAGS) -c -o test_conc_hashtable-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` -test_mono_linked_list_set-test-mono-linked-list-set.obj: test-mono-linked-list-set.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_linked_list_set_CFLAGS) $(CFLAGS) -MT test_mono_linked_list_set-test-mono-linked-list-set.obj -MD -MP -MF $(DEPDIR)/test_mono_linked_list_set-test-mono-linked-list-set.Tpo -c -o test_mono_linked_list_set-test-mono-linked-list-set.obj `if test -f 'test-mono-linked-list-set.c'; then $(CYGPATH_W) 'test-mono-linked-list-set.c'; else $(CYGPATH_W) '$(srcdir)/test-mono-linked-list-set.c'; fi` -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_linked_list_set-test-mono-linked-list-set.Tpo $(DEPDIR)/test_mono_linked_list_set-test-mono-linked-list-set.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-mono-linked-list-set.c' object='test_mono_linked_list_set-test-mono-linked-list-set.obj' libtool=no @AMDEPBACKSLASH@ +test_memfuncs-main.o: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_memfuncs_CFLAGS) $(CFLAGS) -MT test_memfuncs-main.o -MD -MP -MF $(DEPDIR)/test_memfuncs-main.Tpo -c -o test_memfuncs-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_memfuncs-main.Tpo $(DEPDIR)/test_memfuncs-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='test_memfuncs-main.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_linked_list_set_CFLAGS) $(CFLAGS) -c -o test_mono_linked_list_set-test-mono-linked-list-set.obj `if test -f 'test-mono-linked-list-set.c'; then $(CYGPATH_W) 'test-mono-linked-list-set.c'; else $(CYGPATH_W) '$(srcdir)/test-mono-linked-list-set.c'; fi` +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_memfuncs_CFLAGS) $(CFLAGS) -c -o test_memfuncs-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c -test_mono_string-test-mono-string.o: test-mono-string.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_string_CFLAGS) $(CFLAGS) -MT test_mono_string-test-mono-string.o -MD -MP -MF $(DEPDIR)/test_mono_string-test-mono-string.Tpo -c -o test_mono_string-test-mono-string.o `test -f 'test-mono-string.c' || echo '$(srcdir)/'`test-mono-string.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_string-test-mono-string.Tpo $(DEPDIR)/test_mono_string-test-mono-string.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-mono-string.c' object='test_mono_string-test-mono-string.o' libtool=no @AMDEPBACKSLASH@ +test_memfuncs-main.obj: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_memfuncs_CFLAGS) $(CFLAGS) -MT test_memfuncs-main.obj -MD -MP -MF $(DEPDIR)/test_memfuncs-main.Tpo -c -o test_memfuncs-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_memfuncs-main.Tpo $(DEPDIR)/test_memfuncs-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='test_memfuncs-main.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_string_CFLAGS) $(CFLAGS) -c -o test_mono_string-test-mono-string.o `test -f 'test-mono-string.c' || echo '$(srcdir)/'`test-mono-string.c +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_memfuncs_CFLAGS) $(CFLAGS) -c -o test_memfuncs-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` -test_mono_string-test-mono-string.obj: test-mono-string.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_string_CFLAGS) $(CFLAGS) -MT test_mono_string-test-mono-string.obj -MD -MP -MF $(DEPDIR)/test_mono_string-test-mono-string.Tpo -c -o test_mono_string-test-mono-string.obj `if test -f 'test-mono-string.c'; then $(CYGPATH_W) 'test-mono-string.c'; else $(CYGPATH_W) '$(srcdir)/test-mono-string.c'; fi` -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_string-test-mono-string.Tpo $(DEPDIR)/test_mono_string-test-mono-string.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-mono-string.c' object='test_mono_string-test-mono-string.obj' libtool=no @AMDEPBACKSLASH@ +test_mono_callspec-main.o: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_callspec_CFLAGS) $(CFLAGS) -MT test_mono_callspec-main.o -MD -MP -MF $(DEPDIR)/test_mono_callspec-main.Tpo -c -o test_mono_callspec-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_callspec-main.Tpo $(DEPDIR)/test_mono_callspec-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='test_mono_callspec-main.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_string_CFLAGS) $(CFLAGS) -c -o test_mono_string-test-mono-string.obj `if test -f 'test-mono-string.c'; then $(CYGPATH_W) 'test-mono-string.c'; else $(CYGPATH_W) '$(srcdir)/test-mono-string.c'; fi` +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_callspec_CFLAGS) $(CFLAGS) -c -o test_mono_callspec-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c -test_sgen_qsort-test-sgen-qsort.o: test-sgen-qsort.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_sgen_qsort_CFLAGS) $(CFLAGS) -MT test_sgen_qsort-test-sgen-qsort.o -MD -MP -MF $(DEPDIR)/test_sgen_qsort-test-sgen-qsort.Tpo -c -o test_sgen_qsort-test-sgen-qsort.o `test -f 'test-sgen-qsort.c' || echo '$(srcdir)/'`test-sgen-qsort.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sgen_qsort-test-sgen-qsort.Tpo $(DEPDIR)/test_sgen_qsort-test-sgen-qsort.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-sgen-qsort.c' object='test_sgen_qsort-test-sgen-qsort.o' libtool=no @AMDEPBACKSLASH@ +test_mono_callspec-main.obj: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_callspec_CFLAGS) $(CFLAGS) -MT test_mono_callspec-main.obj -MD -MP -MF $(DEPDIR)/test_mono_callspec-main.Tpo -c -o test_mono_callspec-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_callspec-main.Tpo $(DEPDIR)/test_mono_callspec-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='test_mono_callspec-main.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_sgen_qsort_CFLAGS) $(CFLAGS) -c -o test_sgen_qsort-test-sgen-qsort.o `test -f 'test-sgen-qsort.c' || echo '$(srcdir)/'`test-sgen-qsort.c +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_callspec_CFLAGS) $(CFLAGS) -c -o test_mono_callspec-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` -test_sgen_qsort-test-sgen-qsort.obj: test-sgen-qsort.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_sgen_qsort_CFLAGS) $(CFLAGS) -MT test_sgen_qsort-test-sgen-qsort.obj -MD -MP -MF $(DEPDIR)/test_sgen_qsort-test-sgen-qsort.Tpo -c -o test_sgen_qsort-test-sgen-qsort.obj `if test -f 'test-sgen-qsort.c'; then $(CYGPATH_W) 'test-sgen-qsort.c'; else $(CYGPATH_W) '$(srcdir)/test-sgen-qsort.c'; fi` -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sgen_qsort-test-sgen-qsort.Tpo $(DEPDIR)/test_sgen_qsort-test-sgen-qsort.Po -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-sgen-qsort.c' object='test_sgen_qsort-test-sgen-qsort.obj' libtool=no @AMDEPBACKSLASH@ +test_mono_handle-main.o: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_handle_CFLAGS) $(CFLAGS) -MT test_mono_handle-main.o -MD -MP -MF $(DEPDIR)/test_mono_handle-main.Tpo -c -o test_mono_handle-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_handle-main.Tpo $(DEPDIR)/test_mono_handle-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='test_mono_handle-main.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_sgen_qsort_CFLAGS) $(CFLAGS) -c -o test_sgen_qsort-test-sgen-qsort.obj `if test -f 'test-sgen-qsort.c'; then $(CYGPATH_W) 'test-sgen-qsort.c'; else $(CYGPATH_W) '$(srcdir)/test-sgen-qsort.c'; fi` +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_handle_CFLAGS) $(CFLAGS) -c -o test_mono_handle-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c + +test_mono_handle-main.obj: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_handle_CFLAGS) $(CFLAGS) -MT test_mono_handle-main.obj -MD -MP -MF $(DEPDIR)/test_mono_handle-main.Tpo -c -o test_mono_handle-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_handle-main.Tpo $(DEPDIR)/test_mono_handle-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='test_mono_handle-main.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_handle_CFLAGS) $(CFLAGS) -c -o test_mono_handle-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` + +test_mono_linked_list_set-main.o: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_linked_list_set_CFLAGS) $(CFLAGS) -MT test_mono_linked_list_set-main.o -MD -MP -MF $(DEPDIR)/test_mono_linked_list_set-main.Tpo -c -o test_mono_linked_list_set-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_linked_list_set-main.Tpo $(DEPDIR)/test_mono_linked_list_set-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='test_mono_linked_list_set-main.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_linked_list_set_CFLAGS) $(CFLAGS) -c -o test_mono_linked_list_set-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c + +test_mono_linked_list_set-main.obj: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_linked_list_set_CFLAGS) $(CFLAGS) -MT test_mono_linked_list_set-main.obj -MD -MP -MF $(DEPDIR)/test_mono_linked_list_set-main.Tpo -c -o test_mono_linked_list_set-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_linked_list_set-main.Tpo $(DEPDIR)/test_mono_linked_list_set-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='test_mono_linked_list_set-main.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_linked_list_set_CFLAGS) $(CFLAGS) -c -o test_mono_linked_list_set-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` + +test_mono_string-main.o: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_string_CFLAGS) $(CFLAGS) -MT test_mono_string-main.o -MD -MP -MF $(DEPDIR)/test_mono_string-main.Tpo -c -o test_mono_string-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_string-main.Tpo $(DEPDIR)/test_mono_string-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='test_mono_string-main.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_string_CFLAGS) $(CFLAGS) -c -o test_mono_string-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c + +test_mono_string-main.obj: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_string_CFLAGS) $(CFLAGS) -MT test_mono_string-main.obj -MD -MP -MF $(DEPDIR)/test_mono_string-main.Tpo -c -o test_mono_string-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_mono_string-main.Tpo $(DEPDIR)/test_mono_string-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='test_mono_string-main.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_mono_string_CFLAGS) $(CFLAGS) -c -o test_mono_string-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` + +test_sgen_qsort-main.o: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_sgen_qsort_CFLAGS) $(CFLAGS) -MT test_sgen_qsort-main.o -MD -MP -MF $(DEPDIR)/test_sgen_qsort-main.Tpo -c -o test_sgen_qsort-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sgen_qsort-main.Tpo $(DEPDIR)/test_sgen_qsort-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='test_sgen_qsort-main.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_sgen_qsort_CFLAGS) $(CFLAGS) -c -o test_sgen_qsort-main.o `test -f 'main.c' || echo '$(srcdir)/'`main.c + +test_sgen_qsort-main.obj: main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_sgen_qsort_CFLAGS) $(CFLAGS) -MT test_sgen_qsort-main.obj -MD -MP -MF $(DEPDIR)/test_sgen_qsort-main.Tpo -c -o test_sgen_qsort-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sgen_qsort-main.Tpo $(DEPDIR)/test_sgen_qsort-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='main.c' object='test_sgen_qsort-main.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_sgen_qsort_CFLAGS) $(CFLAGS) -c -o test_sgen_qsort-main.obj `if test -f 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi` mostlyclean-libtool: -rm -f *.lo diff --git a/mono/unit-tests/main.c b/mono/unit-tests/main.c new file mode 100644 index 0000000000..fb6dd80429 --- /dev/null +++ b/mono/unit-tests/main.c @@ -0,0 +1,11 @@ +#ifdef __cplusplus +extern "C" +#endif +int +MAIN (void); + +int +main (void) +{ + return MAIN (); +} diff --git a/mono/unit-tests/test-conc-hashtable.c b/mono/unit-tests/test-conc-hashtable.c index b7868f6bda..407d1a5208 100644 --- a/mono/unit-tests/test-conc-hashtable.c +++ b/mono/unit-tests/test-conc-hashtable.c @@ -323,9 +323,14 @@ thread_state_init (MonoThreadUnwindState *ctx) { } +#ifdef __cplusplus +extern "C" +#endif +int +test_conc_hashtable_main (void); int -main (void) +test_conc_hashtable_main (void) { MonoThreadInfoRuntimeCallbacks ticallbacks; int res = 0; diff --git a/mono/unit-tests/test-memfuncs.c b/mono/unit-tests/test-memfuncs.c index af116e1906..72fe5f5c34 100644 --- a/mono/unit-tests/test-memfuncs.c +++ b/mono/unit-tests/test-memfuncs.c @@ -26,8 +26,14 @@ #define MEMMOVE_SIZES 256 #define MEMMOVE_NONOVERLAP_START 1024 +#ifdef __cplusplus +extern "C" +#endif int -main (void) +test_memfuncs_main (void); + +int +test_memfuncs_main (void) { unsigned char *random_mem = (unsigned char *)malloc (POOL_SIZE); unsigned char *reference = (unsigned char *)malloc (POOL_SIZE); diff --git a/mono/unit-tests/test-mono-callspec.c b/mono/unit-tests/test-mono-callspec.c index a31fea84c1..15df8417c7 100644 --- a/mono/unit-tests/test-mono-callspec.c +++ b/mono/unit-tests/test-mono-callspec.c @@ -151,8 +151,14 @@ static MonoClass *test_mono_class_from_name (MonoImage *image, return klass; } +#ifdef __cplusplus +extern "C" +#endif int -main (void) +test_mono_callspec_main (void); + +int +test_mono_callspec_main (void) { int res = 0; MonoDomain *domain = NULL; diff --git a/mono/unit-tests/test-mono-handle.c b/mono/unit-tests/test-mono-handle.c index 0d8febaa70..6bd0d1d672 100644 --- a/mono/unit-tests/test-mono-handle.c +++ b/mono/unit-tests/test-mono-handle.c @@ -19,8 +19,14 @@ test2_arena_push_pop (void) mono_handle_stack_free (h); } +#ifdef __cplusplus +extern "C" +#endif int -main (int argc, const char* argv[]) +test_mono_handle_main (void); + +int +test_mono_handle_main (void) { test2_arena_push_pop (); diff --git a/mono/unit-tests/test-mono-linked-list-set.c b/mono/unit-tests/test-mono-linked-list-set.c index 3b15f91bea..f49c99e9cd 100644 --- a/mono/unit-tests/test-mono-linked-list-set.c +++ b/mono/unit-tests/test-mono-linked-list-set.c @@ -112,8 +112,14 @@ worker (void *arg) return NULL; } +#ifdef __cplusplus +extern "C" +#endif int -main (int argc, char *argv []) +test_mono_linked_list_set_main (void); + +int +test_mono_linked_list_set_main (void) { int primes [] = { 1, 2, 3, 5, 7, 11, 13, 17 }; thread_data_t thread_data [NUM_THREADS]; diff --git a/mono/unit-tests/test-mono-string.c b/mono/unit-tests/test-mono-string.c index 62514cfb2d..335166901c 100644 --- a/mono/unit-tests/test-mono-string.c +++ b/mono/unit-tests/test-mono-string.c @@ -25,8 +25,8 @@ new_string_utf8 (void) { ERROR_DECL (error); const gunichar2 snowman = 0x2603; - static const char bytes[] = { 0xE2, 0x98, 0x83, 0x00 }; /* U+2603 NUL */ - MonoString *s = mono_string_new_checked (mono_domain_get (), bytes, error); + static const unsigned char bytes[] = { 0xE2, 0x98, 0x83, 0x00 }; /* U+2603 NUL */ + MonoString *s = mono_string_new_checked (mono_domain_get (), (const char*)bytes, error); mono_error_assert_ok (error); gunichar2* c = mono_string_chars (s); g_assert (c != NULL && @@ -39,8 +39,8 @@ static int new_string_conv_err (void) { ERROR_DECL (error); - static const char bytes[] = { 'a', 0xFC, 'b', 'c', 0 }; - MonoString G_GNUC_UNUSED *s = mono_string_new_checked (mono_domain_get (), bytes, error); + static const unsigned char bytes[] = { 'a', 0xFC, 'b', 'c', 0 }; + MonoString G_GNUC_UNUSED *s = mono_string_new_checked (mono_domain_get (), (const char*)bytes, error); g_assert (!mono_error_ok (error)); const char *msg = mono_error_get_message (error); g_assert (msg != NULL); @@ -49,8 +49,14 @@ new_string_conv_err (void) return 0; } +#ifdef __cplusplus +extern "C" +#endif int -main (void) +test_mono_string_main (void); + +int +test_mono_string_main (void) { mono_jit_init_version ("test-mono-string", "v4.0.30319"); diff --git a/mono/unit-tests/test-sgen-qsort.c b/mono/unit-tests/test-sgen-qsort.c index f1420d5f05..93c339fbdc 100644 --- a/mono/unit-tests/test-sgen-qsort.c +++ b/mono/unit-tests/test-sgen-qsort.c @@ -8,6 +8,8 @@ #include "config.h" +#define HAVE_SGEN_GC + #include #include @@ -104,8 +106,15 @@ compare_sorts2 (void *base, size_t nel) free (b1); free (b2); } + +#ifdef __cplusplus +extern "C" +#endif int -main (void) +test_sgen_qsort_main (void); + +int +test_sgen_qsort_main (void) { int i; for (i = 1; i < 4000; ++i) { diff --git a/mono/utils/Makefile.am b/mono/utils/Makefile.am index e7b6c2436a..6efa0ba5e2 100644 --- a/mono/utils/Makefile.am +++ b/mono/utils/Makefile.am @@ -1,6 +1,8 @@ include $(top_srcdir)/mk/common.mk -noinst_LTLIBRARIES = libmonoutils.la +noinst_LTLIBRARIES = \ + libmonomath.la \ + libmonoutils.la if ENABLE_LLVM if INTERNAL_LLVM @@ -85,7 +87,6 @@ monoutils_sources = \ mono-io-portability.h \ monobitset.c \ mono-filemap.c \ - mono-math.c \ mono-mmap.c \ mono-mmap-windows.c \ mono-mmap.h \ @@ -136,6 +137,7 @@ monoutils_sources = \ mono-counters.h \ mono-digest.h \ mono-error.h \ + mono-forward-internal.h \ mono-machine.h \ mono-math.h \ mono-membar.h \ @@ -299,9 +301,13 @@ arch_sources += mono-hwcap-cross.c endif libmonoutils_la_SOURCES = $(monoutils_sources) $(arch_sources) -libmonoutils_la_CFLAGS = $(JEMALLOC_CFLAGS) +libmonoutils_la_CFLAGS = $(JEMALLOC_CFLAGS) @CXX_ADD_CFLAGS@ libmonoutils_la_LDFLAGS = $(JEMALLOC_LDFLAGS) libmonoutilsincludedir = $(includedir)/mono-$(API_VER)/mono/utils +libmonoutils_la_LIBADD = mono-math-c.lo + +libmonomath_la_SOURCES = mono-math-c.c +libmonomath_la_CFLAGS = @CXX_REMOVE_CFLAGS@ # These are public headers. # They should not use glib.h, G_BEGIN_DECLS, guint, etc. @@ -309,12 +315,13 @@ libmonoutilsincludedir = $(includedir)/mono-$(API_VER)/mono/utils libmonoutilsinclude_HEADERS = \ mono-logger.h \ mono-error.h \ + mono-forward.h \ mono-publib.h \ mono-jemalloc.h \ mono-dl-fallback.h \ mono-counters.h -EXTRA_DIST = mono-embed.h mono-embed.c +EXTRA_DIST = mono-embed.h mono-embed.c ../../support/libm/complex.c DIST_SUBDIRS = jemalloc @@ -322,4 +329,4 @@ if MONO_JEMALLOC_ENABLED SUBDIRS = jemalloc endif -CFLAGS := $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) @CXX_ADD_CFLAGS@ +CFLAGS := $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) diff --git a/mono/utils/Makefile.in.REMOVED.git-id b/mono/utils/Makefile.in.REMOVED.git-id index 1a4265700a..a5ec9f641b 100644 --- a/mono/utils/Makefile.in.REMOVED.git-id +++ b/mono/utils/Makefile.in.REMOVED.git-id @@ -1 +1 @@ -71b2e7107f57cfdb66cab141459f7fb8267f8824 \ No newline at end of file +f4560877d7780a2f79ff71bc6eeb173411825c2a \ No newline at end of file diff --git a/mono/utils/checked-build.c b/mono/utils/checked-build.c index a7e5ef8fe5..cc5dd91dd4 100644 --- a/mono/utils/checked-build.c +++ b/mono/utils/checked-build.c @@ -134,7 +134,7 @@ backtrace_mutex_unlock (void) static CheckState* get_state (void) { - CheckState *state = mono_native_tls_get_value (thread_status); + CheckState *state = (CheckState*)mono_native_tls_get_value (thread_status); if (!state) { state = (CheckState*) g_malloc0 (sizeof (CheckState) + sizeof(ThreadTransition) * MAX_TRANSITIONS); mono_native_tls_set_value (thread_status, state); @@ -288,7 +288,7 @@ checked_build_thread_transition (const char *transition, void *info, int from_st return; /* We currently don't record external changes as those are hard to reason about. */ - if (!mono_thread_info_is_current (info)) + if (!mono_thread_info_is_current ((THREAD_INFO_TYPE*)info)) return; CheckState *state = get_state (); @@ -573,7 +573,7 @@ check_image_may_reference_image(MonoImage *from, MonoImage *to) int current_idx; for(current_idx = 0; current_idx < current->len; current_idx++) { - MonoImage *checking = g_ptr_array_index (current, current_idx); // CAST? + MonoImage *checking = (MonoImage*)g_ptr_array_index (current, current_idx); mono_image_lock (checking); diff --git a/mono/utils/checked-build.h b/mono/utils/checked-build.h index 2f8eafcb63..537f47b179 100644 --- a/mono/utils/checked-build.h +++ b/mono/utils/checked-build.h @@ -25,6 +25,8 @@ typedef enum { MONO_CHECK_MODE_UNKNOWN = 0x8 } MonoCheckMode; +G_ENUM_FUNCTIONS (MonoCheckMode) + mono_bool mono_check_mode_enabled (MonoCheckMode query); // This is for metadata writes which we have chosen not to check at the current time. diff --git a/mono/utils/dlmalloc.c.REMOVED.git-id b/mono/utils/dlmalloc.c.REMOVED.git-id index 5607724a2c..269ad7da4d 100644 --- a/mono/utils/dlmalloc.c.REMOVED.git-id +++ b/mono/utils/dlmalloc.c.REMOVED.git-id @@ -1 +1 @@ -39850671934fb48e88695894b26e470308a7f2ee \ No newline at end of file +2c41663d870ba3faa415f418827287c897e5dc2c \ No newline at end of file diff --git a/mono/utils/dlmalloc.h b/mono/utils/dlmalloc.h index 44a8f6b7c7..db2614fa6c 100644 --- a/mono/utils/dlmalloc.h +++ b/mono/utils/dlmalloc.h @@ -25,13 +25,13 @@ #ifndef MALLOC_280_H #define MALLOC_280_H +#include /* for size_t */ +#include + #ifdef __cplusplus extern "C" { #endif -#include /* for size_t */ -#include - #if !ONLY_MSPACES #ifndef USE_DL_PREFIX diff --git a/mono/utils/jemalloc/Makefile.in b/mono/utils/jemalloc/Makefile.in index 1fede5af4c..b931c4f123 100644 --- a/mono/utils/jemalloc/Makefile.in +++ b/mono/utils/jemalloc/Makefile.in @@ -89,7 +89,8 @@ DIST_COMMON = $(top_srcdir)/mk/common.mk \ $(top_srcdir)/mkinstalldirs subdir = mono/utils/jemalloc ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -158,6 +159,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -231,6 +233,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/mono/utils/lock-free-alloc.c b/mono/utils/lock-free-alloc.c index 18ed45656a..a4eeb3560c 100644 --- a/mono/utils/lock-free-alloc.c +++ b/mono/utils/lock-free-alloc.c @@ -357,7 +357,7 @@ alloc_from_active_or_partial (MonoLockFreeAllocator *heap) do { unsigned int next; - new_anchor = old_anchor = *(volatile Anchor*)&desc->anchor.value; + new_anchor.value = old_anchor.value = ((volatile Anchor*)&desc->anchor)->value; if (old_anchor.data.state == STATE_EMPTY) { /* We must free it because we own it. */ desc_retire (desc); @@ -464,7 +464,7 @@ mono_lock_free_free (gpointer ptr, size_t block_size) sb = desc->sb; do { - new_anchor = old_anchor = *(volatile Anchor*)&desc->anchor.value; + new_anchor.value = old_anchor.value = ((volatile Anchor*)&desc->anchor)->value; *(unsigned int*)ptr = old_anchor.data.avail; new_anchor.data.avail = ((char*)ptr - (char*)sb) / desc->slot_size; g_assert (new_anchor.data.avail < LOCK_FREE_ALLOC_SB_USABLE_SIZE (block_size) / desc->slot_size); @@ -528,11 +528,7 @@ descriptor_check_consistency (Descriptor *desc, gboolean print) { int count = desc->anchor.data.count; int max_count = LOCK_FREE_ALLOC_SB_USABLE_SIZE (desc->block_size) / desc->slot_size; -#if _MSC_VER - gboolean* linked = alloca(max_count*sizeof(gboolean)); -#else - gboolean linked [max_count]; -#endif + gboolean* linked = g_newa (gboolean, max_count); int i, last; unsigned int index; diff --git a/mono/utils/lock-free-alloc.h b/mono/utils/lock-free-alloc.h index dd2e952b5a..c05610fabc 100644 --- a/mono/utils/lock-free-alloc.h +++ b/mono/utils/lock-free-alloc.h @@ -53,6 +53,7 @@ MONO_API void mono_lock_free_allocator_init_size_class (MonoLockFreeAllocSizeCla MONO_API void mono_lock_free_allocator_init_allocator (MonoLockFreeAllocator *heap, MonoLockFreeAllocSizeClass *sc, MonoMemAccountType account_type); MONO_API gpointer mono_lock_free_alloc (MonoLockFreeAllocator *heap); + MONO_API void mono_lock_free_free (gpointer ptr, size_t block_size); MONO_API gboolean mono_lock_free_allocator_check_consistency (MonoLockFreeAllocator *heap); diff --git a/mono/utils/mach-support-arm64.c b/mono/utils/mach-support-arm64.c index 1fd2338e55..2cf906679d 100644 --- a/mono/utils/mach-support-arm64.c +++ b/mono/utils/mach-support-arm64.c @@ -87,6 +87,9 @@ mono_mach_arch_get_thread_fpstate_size () kern_return_t mono_mach_arch_get_thread_states (thread_port_t thread, thread_state_t state, mach_msg_type_number_t *count, thread_state_t fpstate, mach_msg_type_number_t *fpcount) { +#if defined(HOST_WATCHOS) + g_error ("thread_get_state() is not supported by this platform"); +#else arm_unified_thread_state_t *arch_state = (arm_unified_thread_state_t *) state; arm_neon_state64_t *arch_fpstate = (arm_neon_state64_t *) fpstate; kern_return_t ret; @@ -99,17 +102,22 @@ mono_mach_arch_get_thread_states (thread_port_t thread, thread_state_t state, ma *fpcount = ARM_NEON_STATE64_COUNT; ret = thread_get_state (thread, ARM_NEON_STATE64, (thread_state_t) arch_fpstate, fpcount); return ret; +#endif } kern_return_t mono_mach_arch_set_thread_states (thread_port_t thread, thread_state_t state, mach_msg_type_number_t count, thread_state_t fpstate, mach_msg_type_number_t fpcount) { +#if defined(HOST_WATCHOS) + g_error ("thread_set_state() is not supported by this platform"); +#else kern_return_t ret; ret = thread_set_state (thread, ARM_UNIFIED_THREAD_STATE, state, count); if (ret != KERN_SUCCESS) return ret; ret = thread_set_state (thread, ARM_NEON_STATE64, fpstate, fpcount); return ret; +#endif } #endif diff --git a/mono/utils/memfuncs.h b/mono/utils/memfuncs.h index b750293848..e15e31d7a7 100644 --- a/mono/utils/memfuncs.h +++ b/mono/utils/memfuncs.h @@ -5,7 +5,6 @@ * Copyright (C) 2015 Xamarin Inc * * Licensed under the MIT license. See LICENSE file in the project root for full license information. - * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #ifndef __MONO_UTILS_MEMFUNCS_H__ diff --git a/mono/utils/mono-codeman.c b/mono/utils/mono-codeman.c index 698a21f670..973ccc2df8 100644 --- a/mono/utils/mono-codeman.c +++ b/mono/utils/mono-codeman.c @@ -440,7 +440,7 @@ new_codechunk (CodeChunk *last, int dynamic, int size) * \returns the pointer to the allocated memory or NULL on failure */ void* -mono_code_manager_reserve_align (MonoCodeManager *cman, int size, int alignment) +(mono_code_manager_reserve_align) (MonoCodeManager *cman, int size, int alignment) { CodeChunk *chunk, *prev; void *ptr; @@ -514,7 +514,7 @@ mono_code_manager_reserve_align (MonoCodeManager *cman, int size, int alignment) * \returns the pointer to the allocated memory or NULL on failure */ void* -mono_code_manager_reserve (MonoCodeManager *cman, int size) +(mono_code_manager_reserve) (MonoCodeManager *cman, int size) { return mono_code_manager_reserve_align (cman, size, MIN_ALIGN); } diff --git a/mono/utils/mono-codeman.h b/mono/utils/mono-codeman.h index 64cff52da7..e7139a0907 100644 --- a/mono/utils/mono-codeman.h +++ b/mono/utils/mono-codeman.h @@ -21,8 +21,10 @@ MONO_API void mono_code_manager_invalidate (MonoCodeManager *cman); MONO_API void mono_code_manager_set_read_only (MonoCodeManager *cman); MONO_API void* mono_code_manager_reserve_align (MonoCodeManager *cman, int size, int alignment); +#define mono_code_manager_reserve_align(cman, size, align) (g_cast (mono_code_manager_reserve_align ((cman), (size), (align)))) MONO_API void* mono_code_manager_reserve (MonoCodeManager *cman, int size); +#define mono_code_manager_reserve(cman, size) (g_cast (mono_code_manager_reserve ((cman), (size)))) MONO_API void mono_code_manager_commit (MonoCodeManager *cman, void *data, int size, int newsize); MONO_API int mono_code_manager_size (MonoCodeManager *cman, int *used_size); MONO_API void mono_code_manager_init (void); diff --git a/mono/utils/mono-compiler.h b/mono/utils/mono-compiler.h index 950a38be30..d90290e0c9 100644 --- a/mono/utils/mono-compiler.h +++ b/mono/utils/mono-compiler.h @@ -30,42 +30,22 @@ #ifdef _MSC_VER #include - -#if _MSC_VER < 1800 /* VS 2013 */ -#define strtoull _strtoui64 -#endif - #include -#define trunc(x) (((x) < 0) ? ceil((x)) : floor((x))) -#if _MSC_VER < 1800 /* VS 2013 */ -#define isnan(x) _isnan(x) -#define isinf(x) (_isnan(x) ? 0 : (_fpclass(x) == _FPCLASS_NINF) ? -1 : (_fpclass(x) == _FPCLASS_PINF) ? 1 : 0) -#define isnormal(x) _finite(x) -#endif #define popen _popen #define pclose _pclose - #include #define mkdir(x) _mkdir(x) #define __func__ __FUNCTION__ -#include -typedef SSIZE_T ssize_t; +#include +#include -/* - * SSIZE_MAX is not defined in MSVC, so define it here. - * - * These values come from MinGW64, and are public domain. - * - */ +// ssize_t and SSIZE_MAX are Posix, define for Windows. +typedef ptrdiff_t ssize_t; #ifndef SSIZE_MAX -#ifdef _WIN64 -#define SSIZE_MAX _I64_MAX -#else -#define SSIZE_MAX INT_MAX -#endif +#define SSIZE_MAX INTPTR_MAX #endif #endif /* _MSC_VER */ diff --git a/mono/utils/mono-complex.h b/mono/utils/mono-complex.h index 385eee9b15..ebc679c296 100644 --- a/mono/utils/mono-complex.h +++ b/mono/utils/mono-complex.h @@ -11,24 +11,38 @@ #include #include - -#if !defined (HAVE_COMPLEX_H) || (defined (ANDROID_UNIFIED_HEADERS) && __ANDROID_API__ < 23) -#include <../../support/libm/complex.h> -#else -#include -#endif - #define _USE_MATH_DEFINES // needed by MSVC to define math constants #include -#ifdef _MSC_VER +#undef cabs +#undef cimag +#undef creal +#define cabs mono_cabs +#define cimag mono_cimag +#define creal mono_creal -#define double_complex _C_double_complex +typedef struct double_complex { + double real; + double imag; +} double_complex; + +static inline double +creal (double_complex c) +{ + return c.real; +} + +static inline double +cimag (double_complex c) +{ + return c.imag; +} static inline double_complex mono_double_complex_make(gdouble re, gdouble im) { - return _Cbuild (re, im); + double_complex const a = { re, im }; + return a; } static inline @@ -60,38 +74,4 @@ double_complex mono_double_complex_sub(double_complex left, double_complex right - cimag(right)); } -#else - -#define double_complex double complex - -static inline -double_complex mono_double_complex_make(gdouble re, gdouble im) -{ - return re + im * I; -} - -static inline -double_complex mono_double_complex_scalar_div(double_complex c, gdouble s) -{ - return c / s; -} - -static inline -double_complex mono_double_complex_scalar_mul(double_complex c, gdouble s) -{ - return c * s; -} - -static inline -double_complex mono_double_complex_div(double_complex left, double_complex right) -{ - return left / right; -} - -static inline -double_complex mono_double_complex_sub(double_complex left, double_complex right) -{ - return left - right; -} - -#endif +#include "../../support/libm/complex.c" diff --git a/mono/utils/mono-context.c b/mono/utils/mono-context.c index f426685487..17982731a0 100644 --- a/mono/utils/mono-context.c +++ b/mono/utils/mono-context.c @@ -414,7 +414,7 @@ mono_sigctx_to_monoctx (void *sigctx, MonoContext *mctx) /* Why are we only copying 16 registers?! There are 32! */ memcpy (&mctx->fregs, &context->D, sizeof (double) * 16); #else - arm_ucontext *my_uc = sigctx; + arm_ucontext *my_uc = (arm_ucontext*)sigctx; mctx->pc = UCONTEXT_REG_PC (my_uc); mctx->regs [ARMREG_SP] = UCONTEXT_REG_SP (my_uc); @@ -441,7 +441,7 @@ mono_monoctx_to_sigctx (MonoContext *mctx, void *ctx) /* Why are we only copying 16 registers?! There are 32! */ memcpy (&context->D, &mctx->fregs, sizeof (double) * 16); #else - arm_ucontext *my_uc = ctx; + arm_ucontext *my_uc = (arm_ucontext*)ctx; UCONTEXT_REG_PC (my_uc) = mctx->pc; UCONTEXT_REG_SP (my_uc) = mctx->regs [ARMREG_SP]; @@ -550,4 +550,20 @@ mono_monoctx_to_sigctx (MonoContext *mctx, void *sigctx) UCONTEXT_REG_Rn(uc, 1) = mctx->sc_sp; } +#elif defined (TARGET_WASM) + +#include + +void +mono_sigctx_to_monoctx (void *sigctx, MonoContext *mctx) +{ + g_error ("MonoContext not supported"); +} + +void +mono_monoctx_to_sigctx (MonoContext *mctx, void *sigctx) +{ + g_error ("MonoContext not supported"); +} + #endif /* #if defined(__i386__) */ diff --git a/mono/utils/mono-context.h b/mono/utils/mono-context.h index 77909ab594..488258af31 100644 --- a/mono/utils/mono-context.h +++ b/mono/utils/mono-context.h @@ -290,7 +290,8 @@ typedef struct { #if defined (HOST_WIN32) && !defined(__GNUC__) /* msvc doesn't support inline assembly, so have to use a separate .asm file */ -extern void mono_context_get_current (void *); +// G_EXTERN_C due to being written in assembly. +G_EXTERN_C void mono_context_get_current (void *); #define MONO_CONTEXT_GET_CURRENT(ctx) do { mono_context_get_current((void*)&(ctx)); } while (0) #else @@ -415,7 +416,7 @@ typedef struct { #define MONO_CONTEXT_GET_CURRENT(ctx) do { \ gpointer _dummy; \ - ctx.regs [ARMREG_SP] = &_dummy; \ + ctx.regs [ARMREG_SP] = (mgreg_t)&_dummy; \ } while (0); #else @@ -489,6 +490,13 @@ typedef struct { mach_port_deallocate (current_task (), self); \ } while (0); +#elif defined(HOST_WATCHOS) + +#define MONO_CONTEXT_GET_CURRENT(ctx) do { \ + gpointer _dummy; \ + ctx.regs [ARMREG_SP] = (mgreg_t)(gsize)&_dummy; \ +} while (0); + #else #define MONO_CONTEXT_GET_CURRENT(ctx) do { \ diff --git a/mono/utils/mono-dl-posix.c b/mono/utils/mono-dl-posix.c index f8e71e1356..a3d9bf567f 100644 --- a/mono/utils/mono-dl-posix.c +++ b/mono/utils/mono-dl-posix.c @@ -65,6 +65,8 @@ mono_dl_open_file (const char *file, int flags) /* Bionic doesn't support NULL filenames */ if (!file) return NULL; + if (!g_file_test (file, G_FILE_TEST_EXISTS)) + return NULL; #endif #if defined(_AIX) /* diff --git a/mono/utils/mono-dl-windows.c b/mono/utils/mono-dl-windows.c index 8dce945ae8..0332a61cee 100644 --- a/mono/utils/mono-dl-windows.c +++ b/mono/utils/mono-dl-windows.c @@ -85,7 +85,7 @@ void mono_dl_close_handle (MonoDl *module) { if (!module->main_module) - FreeLibrary (module->handle); + FreeLibrary ((HMODULE)module->handle); } #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) @@ -126,7 +126,7 @@ mono_dl_lookup_symbol_in_process (const char *symbol_name) } for (i = 0; i < needed / sizeof (HANDLE); i++) { - proc = GetProcAddress (modules [i], symbol_name); + proc = (gpointer)GetProcAddress (modules [i], symbol_name); if (proc != NULL) { g_free (modules); return proc; @@ -145,10 +145,10 @@ mono_dl_lookup_symbol (MonoDl *module, const char *symbol_name) /* get the symbol directly from the specified module */ if (!module->main_module) - return GetProcAddress (module->handle, symbol_name); + return (void*)GetProcAddress ((HMODULE)module->handle, symbol_name); /* get the symbol from the main module */ - proc = GetProcAddress (module->handle, symbol_name); + proc = (gpointer)GetProcAddress ((HMODULE)module->handle, symbol_name); if (proc != NULL) return proc; diff --git a/mono/utils/mono-error-internals.h b/mono/utils/mono-error-internals.h index 97360549d2..e603dc32fd 100644 --- a/mono/utils/mono-error-internals.h +++ b/mono/utils/mono-error-internals.h @@ -244,6 +244,18 @@ mono_error_set_null_reference (MonoError *error) mono_error_set_generic_error (error, "System", "NullReferenceException", ""); } +static inline void +mono_error_set_duplicate_wait_object (MonoError *error) +{ + mono_error_set_generic_error (error, "System", "DuplicateWaitObjectException", "Duplicate objects in argument."); +} + +static inline void +mono_error_set_cannot_unload_appdomain (MonoError *error, const char *message) +{ + mono_error_set_generic_error (error, "System", "CannotUnloadAppDomainException", "%s", message); +} + void mono_error_set_argument_out_of_range (MonoError *error, const char *name); diff --git a/mono/utils/mono-error.c b/mono/utils/mono-error.c index e5b8622256..ef6f9f824c 100644 --- a/mono/utils/mono-error.c +++ b/mono/utils/mono-error.c @@ -768,7 +768,7 @@ mono_error_box (const MonoError *ierror, MonoImage *image) MonoErrorInternal *from = (MonoErrorInternal*)ierror; /* Don't know how to box a gchandle */ g_assert (!is_managed_exception (from)); - MonoErrorBoxed* box = mono_image_alloc (image, sizeof (MonoErrorBoxed)); + MonoErrorBoxed* box = (MonoErrorBoxed*)mono_image_alloc (image, sizeof (MonoErrorBoxed)); box->image = image; mono_error_init_flags (&box->error, MONO_ERROR_MEMPOOL_BOXED); MonoErrorInternal *to = (MonoErrorInternal*)&box->error; diff --git a/mono/utils/mono-flight-recorder.c b/mono/utils/mono-flight-recorder.c index 9246c5b545..7ff4b59d73 100644 --- a/mono/utils/mono-flight-recorder.c +++ b/mono/utils/mono-flight-recorder.c @@ -94,7 +94,7 @@ mono_flight_recorder_init (size_t max_count, size_t payload_size) size_t size_of_items = item_size * max_count; size_t size_of_item_ptrs = sizeof (gpointer) * max_count; size_t size_of_recorder_prefix = offsetof(MonoFlightRecorder, items); - MonoFlightRecorder *recorder = g_malloc0 (size_of_recorder_prefix + size_of_item_ptrs + size_of_items); + MonoFlightRecorder *recorder = (MonoFlightRecorder*)g_malloc0 (size_of_recorder_prefix + size_of_item_ptrs + size_of_items); intptr_t end_of_memory = ((intptr_t) recorder) + (size_of_recorder_prefix + size_of_item_ptrs + size_of_items); recorder->max_count = max_count; diff --git a/mono/utils/mono-forward-internal.h b/mono/utils/mono-forward-internal.h new file mode 100644 index 0000000000..d5057c1f4f --- /dev/null +++ b/mono/utils/mono-forward-internal.h @@ -0,0 +1,20 @@ +/** + * \file + * + * (C) 2018 Microsoft, Inc. + * + */ +#ifndef _MONO_UTILS_FORWARD_INTERNAL_ +#define _MONO_UTILS_FORWARD_INTERNAL_ + +#include "mono-forward.h" + +typedef struct MonoAotModule MonoAotModule; +typedef struct MonoHandleStack MonoHandleStack; +typedef struct MonoJitTlsData MonoJitTlsData; +typedef struct MonoLMF MonoLMF; +typedef struct MonoTrampInfo MonoTrampInfo; +typedef struct _MonoInternalThread MonoInternalThread; +typedef struct _SgenThreadInfo SgenThreadInfo; + +#endif diff --git a/mono/utils/mono-forward.h b/mono/utils/mono-forward.h new file mode 100644 index 0000000000..9f270f2bbc --- /dev/null +++ b/mono/utils/mono-forward.h @@ -0,0 +1,13 @@ +/** + * \file + * + * (C) 2018 Microsoft, Inc. + * + */ +#ifndef _MONO_UTILS_FORWARD_ +#define _MONO_UTILS_FORWARD_ + +typedef struct _MonoDomain MonoDomain; +typedef struct _MonoJitInfo MonoJitInfo; + +#endif diff --git a/mono/utils/mono-io-portability.c b/mono/utils/mono-io-portability.c index 8adecaeed7..9231320780 100644 --- a/mono/utils/mono-io-portability.c +++ b/mono/utils/mono-io-portability.c @@ -136,7 +136,7 @@ static inline gchar *mono_portability_find_file_internal (const gchar *pathname, } /* First turn '\' into '/' and strip any drive letters */ - g_strdelimit (new_pathname, "\\", '/'); + g_strdelimit (new_pathname, '\\', '/'); #ifdef DEBUG g_message ("%s: Fixed slashes, now have [%s]\n", __func__, diff --git a/mono/utils/mono-log-darwin.c b/mono/utils/mono-log-darwin.c index d0ba23cb51..7ab40628de 100644 --- a/mono/utils/mono-log-darwin.c +++ b/mono/utils/mono-log-darwin.c @@ -5,7 +5,69 @@ */ #include -#if defined(HOST_IOS) +#if defined(HOST_WATCHOS) && (__WATCH_OS_VERSION_MIN_REQUIRED >= __WATCHOS_3_0) +/* emitted by clang: + * > /Users/lewurm/work/mono-watch4/mono/utils/mono-log-darwin.c:35:2: error: 'asl_log' is \ + * > deprecated: first deprecated in watchOS 3.0 - os_log(3) has replaced \ + * > asl(3) [-Werror,-Wdeprecated-declarations] + */ + +/* untested stuff: */ +#include +#include "mono-logger-internals.h" +void +mono_log_open_asl (const char *path, void *userData) +{ +} + +void +mono_log_write_asl (const char *log_domain, GLogLevelFlags level, mono_bool hdr, const char *message) +{ + switch (level & G_LOG_LEVEL_MASK) + { + case G_LOG_LEVEL_MESSAGE: + os_log (OS_LOG_DEFAULT, "%s%s%s\n", + log_domain != NULL ? log_domain : "", + log_domain != NULL ? ": " : "", + message); + break; + case G_LOG_LEVEL_INFO: + os_log_info (OS_LOG_DEFAULT, "%s%s%s\n", + log_domain != NULL ? log_domain : "", + log_domain != NULL ? ": " : "", + message); + break; + case G_LOG_LEVEL_DEBUG: + os_log_debug (OS_LOG_DEFAULT, "%s%s%s\n", + log_domain != NULL ? log_domain : "", + log_domain != NULL ? ": " : "", + message); + break; + case G_LOG_LEVEL_ERROR: + case G_LOG_LEVEL_WARNING: + os_log_error (OS_LOG_DEFAULT, "%s%s%s\n", + log_domain != NULL ? log_domain : "", + log_domain != NULL ? ": " : "", + message); + case G_LOG_LEVEL_CRITICAL: + default: + os_log_fault (OS_LOG_DEFAULT, "%s%s%s\n", + log_domain != NULL ? log_domain : "", + log_domain != NULL ? ": " : "", + message); + break; + } + + if (level & G_LOG_LEVEL_ERROR) + abort(); +} + +void +mono_log_close_asl () +{ +} + +#elif defined(HOST_IOS) #include #include "mono-logger-internals.h" diff --git a/mono/utils/mono-log-windows.c b/mono/utils/mono-log-windows.c index db3575a09d..bd71347440 100644 --- a/mono/utils/mono-log-windows.c +++ b/mono/utils/mono-log-windows.c @@ -29,7 +29,7 @@ static FILE *logFile = NULL; static void *logUserData = NULL; -static wchar_t *logFileName = L".//mono.log"; +static const wchar_t *logFileName = L".//mono.log"; // FIXME double slash /** * mapSyslogLevel: diff --git a/mono/utils/mono-logger.c b/mono/utils/mono-logger.c index ba915ae293..89de7edb45 100644 --- a/mono/utils/mono-logger.c +++ b/mono/utils/mono-logger.c @@ -17,8 +17,8 @@ typedef struct { MonoTraceMask mask; } MonoLogLevelEntry; -GLogLevelFlags mono_internal_current_level = INT_MAX; -MonoTraceMask mono_internal_current_mask = ~((MonoTraceMask)0); +GLogLevelFlags mono_internal_current_level = (GLogLevelFlags)INT_MAX; +MonoTraceMask mono_internal_current_mask = (MonoTraceMask)~0; gboolean mono_trace_log_header = FALSE; static GQueue *level_stack = NULL; @@ -304,18 +304,18 @@ mono_trace_set_mask_string (const char *value) { "io-layer-semaphore", MONO_TRACE_IO_LAYER_SEMAPHORE }, { "io-layer-mutex", MONO_TRACE_IO_LAYER_MUTEX }, { "io-layer-handle", MONO_TRACE_IO_LAYER_HANDLE }, - { "io-layer", MONO_TRACE_IO_LAYER_PROCESS + { "io-layer", (MonoTraceMask)(MONO_TRACE_IO_LAYER_PROCESS | MONO_TRACE_IO_LAYER_SOCKET | MONO_TRACE_IO_LAYER_FILE | MONO_TRACE_IO_LAYER_EVENT | MONO_TRACE_IO_LAYER_SEMAPHORE | MONO_TRACE_IO_LAYER_MUTEX - | MONO_TRACE_IO_LAYER_HANDLE }, + | MONO_TRACE_IO_LAYER_HANDLE) }, { "w32handle", MONO_TRACE_IO_LAYER_HANDLE }, { "tailcall", MONO_TRACE_TAILCALL }, { "profiler", MONO_TRACE_PROFILER }, - { "all", ~((MonoTraceMask)0) }, - { NULL, 0 }, + { "all", (MonoTraceMask)~0 }, // FIXMEcxx there is a better way -- operator overloads of enums + { NULL, (MonoTraceMask)0 }, }; if(!value) @@ -391,7 +391,7 @@ log_level_get_name (GLogLevelFlags log_level) static void callback_adapter (const char *domain, GLogLevelFlags level, mono_bool fatal, const char *message) { - UserSuppliedLoggerUserData *ll =logCallback.user_data; + UserSuppliedLoggerUserData *ll = (UserSuppliedLoggerUserData*)logCallback.user_data; ll->legacy_callback (domain, log_level_get_name(level), message, fatal, ll->user_data); } @@ -399,7 +399,7 @@ callback_adapter (const char *domain, GLogLevelFlags level, mono_bool fatal, con static void eglib_log_adapter (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) { - UserSuppliedLoggerUserData *ll = logCallback.user_data; + UserSuppliedLoggerUserData *ll = (UserSuppliedLoggerUserData*)logCallback.user_data; ll->legacy_callback (log_domain, log_level_get_name (log_level), message, log_level & G_LOG_LEVEL_ERROR, ll->user_data); } @@ -450,7 +450,7 @@ mono_trace_set_log_handler (MonoLogCallback callback, void *user_data) if (logCallback.closer != NULL) logCallback.closer(); - UserSuppliedLoggerUserData *ll = g_malloc (sizeof (UserSuppliedLoggerUserData)); + UserSuppliedLoggerUserData *ll = (UserSuppliedLoggerUserData*)g_malloc (sizeof (UserSuppliedLoggerUserData)); ll->legacy_callback = callback; ll->user_data = user_data; logCallback.opener = legacy_opener; diff --git a/mono/utils/mono-math-c.c b/mono/utils/mono-math-c.c new file mode 100644 index 0000000000..804665b4ce --- /dev/null +++ b/mono/utils/mono-math-c.c @@ -0,0 +1,24 @@ +// This file bridges C++ to C runtime math functions +// without any chance of a C++ library dependency. +// In time it can probably be removed. +#include "config.h" +#include "glib.h" +#define MONO_MATH_DECLARE_ALL 1 +#include "mono-math.h" + +#if defined (__cplusplus) && !defined (_MSC_VER) +#error This file should be compiled as C. +#endif + +int mono_isfinite_float (float a) { return isfinite (a); } +int mono_isfinite_double (double a) { return isfinite (a); } +int mono_isinf_float (float a) { return isinf (a); } +int mono_isinf_double (double a) { return isinf (a); } +int mono_isnan_float (float a) { return isnan (a); } +int mono_isnan_double (double a) { return isnan (a); } +int mono_isunordered_float (float a, float b) { return isunordered (a, b); } +int mono_isunordered_double (double a, double b) { return isunordered (a, b); } +int mono_signbit_float (float a) { return signbit (a); } +int mono_signbit_double (double a) { return signbit (a); } +float mono_trunc_float (float a) { return trunc (a); } +double mono_trunc_double (double a) { return trunc (a); } diff --git a/mono/utils/mono-math.c b/mono/utils/mono-math.c deleted file mode 100644 index 7672b0cca9..0000000000 --- a/mono/utils/mono-math.c +++ /dev/null @@ -1,39 +0,0 @@ -/** - * \file - */ - -#include "mono-math.h" - -#ifndef HAVE_SIGNBIT - -/** - * mono_signbit_float: - */ -int -mono_signbit_float (float x) -{ - union { float f; int i; } u; - - u.f = x; - - return u.i < 0; -} - -/** - * mono_signbit_double: - */ -int -mono_signbit_double (double x) -{ - union { double d; int i[2]; } u; - - u.d = x; - -#if G_BYTE_ORDER == G_LITTLE_ENDIAN - return u.i [1] < 0; -#else - return u.i [0] < 0; -#endif -} - -#endif diff --git a/mono/utils/mono-math.h b/mono/utils/mono-math.h index 438964ba64..8b11cbe76f 100644 --- a/mono/utils/mono-math.h +++ b/mono/utils/mono-math.h @@ -2,22 +2,81 @@ * \file */ -#ifndef __MONO_SIGNBIT_H__ -#define __MONO_SIGNBIT_H__ +#ifndef __MONO_MATH_H__ +#define __MONO_MATH_H__ #include #include -#ifdef HAVE_SIGNBIT -#define mono_signbit signbit +// Instead of isfinite, isinf, isnan, etc., +// use mono_isfininite, mono_isinf, mono_isnan, etc. +// These functions are implemented in C in order to avoid +// a C++ runtime dependency and for more portable binding +// from C++, esp. across Android versions/architectures. +// WebAssembly, and Win32/gcc. +// See https://github.com/mono/mono/pull/10701 for what +// this systematically and more portably cleans up. + +#if defined (__cplusplus) || defined (MONO_MATH_DECLARE_ALL) + +// These declarations are usually hidden, in order +// to encourage using the overloaded names instead of +// the type-specific names. + +G_EXTERN_C int mono_isfinite_float (float); +G_EXTERN_C int mono_isfinite_double (double); +G_EXTERN_C int mono_isinf_float (float); +G_EXTERN_C int mono_isinf_double (double); +G_EXTERN_C int mono_isnan_float (float); +G_EXTERN_C int mono_isnan_double (double); +G_EXTERN_C int mono_isunordered_float (float, float); +G_EXTERN_C int mono_isunordered_double (double, double); +G_EXTERN_C int mono_signbit_float (float a); +G_EXTERN_C int mono_signbit_double (double a); +G_EXTERN_C float mono_trunc_float (float); +G_EXTERN_C double mono_trunc_double (double); + +#endif + +#ifdef __cplusplus + +// There are three or four possible approaches here. +// 1. C++ mono_foo => foo +// 2. C++ mono_foo => std::foo +// 3. C++ mono_foo => C mono_foo_[float,double] => C foo +// 4. using std::foo -- this works mostly but not quite -- it doesn't +// work when there is already a global foo. +// +// Approach 1 works on non-wasm, non-android non-Win32/gcc. +// Approach 2 should work everywhere, but might incur a new dependency, might. +// Approach 3 should work everywhere, with identical dependencies as mono/C. +// This is approach 3. +// Approach 4 lets code keep calling foo instead of mono_foo. +// Approaches 1, 2, 4 are most efficient. 1, 2 require inlining, 4 does not. + +inline int mono_isfinite (float a) { return mono_isfinite_float (a); } +inline int mono_isfinite (double a) { return mono_isfinite_double (a); } +inline int mono_isinf (float a) { return mono_isinf_float (a); } +inline int mono_isinf (double a) { return mono_isinf_double (a); } +inline int mono_isnan (float a) { return mono_isnan_float (a); } +inline int mono_isnan (double a) { return mono_isnan_double (a); } +inline int mono_isunordered (float a, float b) { return mono_isunordered_float (a, b); } +inline int mono_isunordered (double a, double b) { return mono_isunordered_double (a, b); } +inline int mono_signbit (float a) { return mono_signbit_float (a); } +inline int mono_signbit (double a) { return mono_signbit_double (a); } +inline float mono_trunc (float a) { return mono_trunc_float (a); } +inline double mono_trunc (double a) { return mono_trunc_double (a); } + #else -#define mono_signbit(x) (sizeof (x) == sizeof (float) ? mono_signbit_float (x) : mono_signbit_double (x)) -MONO_API int -mono_signbit_double (double x); - -MONO_API int -mono_signbit_float (float x); +// Direct macros for C. +// This will also work for many C++ platforms, i.e. other than Android and WebAssembly and Win32/gcc. +#define mono_isfinite isfinite +#define mono_isinf isinf +#define mono_isnan isnan +#define mono_isunordered isunordered +#define mono_signbit signbit +#define mono_trunc trunc #endif diff --git a/mono/utils/mono-merp.c b/mono/utils/mono-merp.c index e5de5e81c0..9844f4d430 100644 --- a/mono/utils/mono-merp.c +++ b/mono/utils/mono-merp.c @@ -111,7 +111,7 @@ typedef struct { const char *osVersion; int uiLidArg; // Application LCID - const char systemModel [100]; + char systemModel [100]; const char *systemManufacturer; const char *eventType; @@ -237,6 +237,8 @@ static int merp_file_permissions = S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH; static gboolean mono_merp_write_params (MERPStruct *merp) { + g_async_safe_printf("Writing MERP params to: %s\n", merp->merpFilePath); + int handle = g_open (merp->merpFilePath, O_TRUNC | O_WRONLY | O_CREAT, merp_file_permissions); g_assertf (handle != -1, "Could not open MERP file at %s", merp->merpFilePath); @@ -367,6 +369,8 @@ mono_init_merp (const intptr_t crashed_pid, const char *signal, MonoStackHash *h static gboolean mono_merp_write_fingerprint_payload (const char *non_param_data, const MERPStruct *merp) { + g_async_safe_printf("Writing MERP crash file to: %s\n", merp->crashLogPath); + int handle = g_open (merp->crashLogPath, O_TRUNC | O_WRONLY | O_CREAT, merp_file_permissions); g_assertf (handle != -1, "Could not open crash log file at %s", merp->crashLogPath); @@ -420,6 +424,8 @@ mono_write_wer_template (MERPStruct *merp) // there is no image that would make any semantic sense to send either. // It's a nuanced problem, each way we can run mono would need a separate fix. + g_async_safe_printf("Writing MERP XML file to: %s\n", merp->werXmlPath); + int handle = g_open (merp->werXmlPath, O_WRONLY | O_CREAT | O_TRUNC, merp_file_permissions); g_assertf (handle != -1, "Could not open WER XML file at %s", merp->werXmlPath); diff --git a/mono/utils/mono-mmap-internals.h b/mono/utils/mono-mmap-internals.h index 42fa8a3f8c..d66dcd095a 100644 --- a/mono/utils/mono-mmap-internals.h +++ b/mono/utils/mono-mmap-internals.h @@ -27,8 +27,4 @@ mono_valloc_can_alloc (size_t size); void mono_valloc_set_limit (size_t size); -int -mono_pages_not_faulted (void *addr, size_t length); - #endif /* __MONO_UTILS_MMAP_INTERNAL_H__ */ - diff --git a/mono/utils/mono-mmap-windows.c b/mono/utils/mono-mmap-windows.c index cd267194e4..ba48bf9dc1 100644 --- a/mono/utils/mono-mmap-windows.c +++ b/mono/utils/mono-mmap-windows.c @@ -85,7 +85,7 @@ void* mono_valloc_aligned (size_t length, size_t alignment, int flags, MonoMemAccountType type) { int prot = mono_mmap_win_prot_from_flags (flags); - char *mem = VirtualAlloc (NULL, length + alignment, MEM_RESERVE, prot); + char *mem = (char*)VirtualAlloc (NULL, length + alignment, MEM_RESERVE, prot); char *aligned; if (!mem) @@ -96,7 +96,7 @@ mono_valloc_aligned (size_t length, size_t alignment, int flags, MonoMemAccountT aligned = mono_aligned_address (mem, length, alignment); - aligned = VirtualAlloc (aligned, length, MEM_COMMIT, prot); + aligned = (char*)VirtualAlloc (aligned, length, MEM_COMMIT, prot); g_assert (aligned); mono_account_mem (type, (ssize_t)length); diff --git a/mono/utils/mono-mmap.c b/mono/utils/mono-mmap.c index 0fbdb3355e..05aa7a5c7a 100644 --- a/mono/utils/mono-mmap.c +++ b/mono/utils/mono-mmap.c @@ -137,7 +137,7 @@ mono_mem_account_register_counters (void) { for (int i = 0; i < MONO_MEM_ACCOUNT_MAX; ++i) { const char *prefix = "Valloc "; - const char *name = mono_mem_account_type_name (i); + const char *name = mono_mem_account_type_name ((MonoMemAccountType)i); char descr [128]; g_assert (strlen (prefix) + strlen (name) < sizeof (descr)); sprintf (descr, "%s%s", prefix, name); @@ -709,39 +709,3 @@ mono_valloc_aligned (size_t size, size_t alignment, int flags, MonoMemAccountTyp return aligned; } #endif - -int -mono_pages_not_faulted (void *addr, size_t size) -{ -#ifdef HAVE_MINCORE - int i; - gint64 count; - int pagesize = mono_pagesize (); - int npages = (size + pagesize - 1) / pagesize; - char *faulted = (char *) g_malloc0 (sizeof (char*) * npages); - - /* - * We cast `faulted` to void* because Linux wants an unsigned - * char* while BSD wants a char*. - */ -#ifdef __linux__ - if (mincore (addr, size, (unsigned char *)faulted) != 0) { -#else - if (mincore (addr, size, (char *)faulted) != 0) { -#endif - count = -1; - } else { - count = 0; - for (i = 0; i < npages; ++i) { - if (faulted [i] != 0) - ++count; - } - } - - g_free (faulted); - - return count; -#else - return -1; -#endif -} diff --git a/mono/utils/mono-mmap.h b/mono/utils/mono-mmap.h index d6270c2c13..5b5c27c099 100644 --- a/mono/utils/mono-mmap.h +++ b/mono/utils/mono-mmap.h @@ -59,11 +59,14 @@ MONO_API void* mono_valloc (void *addr, size_t length, int flags, MonoMemAcc MONO_API void* mono_valloc_aligned (size_t length, size_t alignment, int flags, MonoMemAccountType type); MONO_API int mono_vfree (void *addr, size_t length, MonoMemAccountType type); MONO_API void* mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle); + // Last two parameters are optional. // This is mono_file_map but with optionally returning an error message. // See https://github.com/mono/mono/issues/8225. -#ifdef HOST_WIN32 +#if defined (HOST_WIN32) MONO_API +#elif defined (__cplusplus) +G_EXTERN_C #endif void* mono_file_map_error (size_t length, int flags, int fd, guint64 offset, void **ret_handle, const char *filepath, char **error_message); diff --git a/mono/utils/mono-os-wait-win32.c b/mono/utils/mono-os-wait-win32.c index 160f4048a7..04e5d4b28b 100644 --- a/mono/utils/mono-os-wait-win32.c +++ b/mono/utils/mono-os-wait-win32.c @@ -8,9 +8,11 @@ * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ -#include -#include -#include +#include "mono-os-wait.h" +#include "mono-threads.h" +#include "mono-threads-debug.h" +#include "mono-logger-internals.h" +#include "mono-error-internals.h" enum ThreadWaitInfo { THREAD_WAIT_INFO_CLEARED = 0, @@ -121,29 +123,48 @@ mono_win32_wait_for_single_object_ex (HANDLE handle, DWORD timeout, BOOL alertab // NOTE, leave_alertable_wait should not affect GetLastError but // if changed, GetLastError needs to be preserved and reset before returning. - if (alertable && info) { + if (info) leave_alertable_wait (info); - } return result; } DWORD -mono_win32_wait_for_multiple_objects_ex (DWORD count, CONST HANDLE *handles, BOOL waitAll, DWORD timeout, BOOL alertable) +mono_win32_wait_for_multiple_objects_ex (DWORD count, CONST HANDLE *handles, BOOL waitAll, DWORD timeout, BOOL alertable, MonoError *error) { - DWORD result = WAIT_FAILED; MonoThreadInfo * const info = alertable ? mono_thread_info_current_unchecked () : NULL; if (info) enter_alertable_wait (info); - result = WaitForMultipleObjectsEx (count, handles, waitAll, timeout, alertable); + DWORD const result = WaitForMultipleObjectsEx (count, handles, waitAll, timeout, alertable); // NOTE, leave_alertable_wait should not affect GetLastError but // if changed, GetLastError needs to be preserved and reset before returning. if (info) leave_alertable_wait (info); + // This is not perfect, but it is the best you can do in usermode and matches CoreCLR. + // i.e. handle-based instead of object-based. + + if (result == WAIT_FAILED && waitAll && error && + count > 1 && count <= MAXIMUM_WAIT_OBJECTS + && GetLastError () == ERROR_INVALID_PARAMETER) { + gpointer handles_sorted [MAXIMUM_WAIT_OBJECTS]; // 64 + memcpy (handles_sorted, handles, count * sizeof (handles [0])); + qsort (handles_sorted, count, sizeof (handles_sorted [0]), g_direct_equal); + for (DWORD i = 1; i < count; ++i) { + if (handles_sorted [i - 1] == handles_sorted [i]) { + mono_error_set_duplicate_wait_object (error); + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_HANDLE, "%s: handle %p is duplicated", __func__, handles_sorted [i]); + // Preserve LastError, but reduce triggering write breakpoints. + if (GetLastError () != ERROR_INVALID_PARAMETER) + SetLastError (ERROR_INVALID_PARAMETER); + break; + } + } + } + return result; } diff --git a/mono/utils/mono-os-wait.h b/mono/utils/mono-os-wait.h index 566ed9757d..b4572bf31a 100644 --- a/mono/utils/mono-os-wait.h +++ b/mono/utils/mono-os-wait.h @@ -10,6 +10,7 @@ #include #include +#include "mono-error.h" DWORD mono_win32_sleep_ex (DWORD timeout, BOOL alertable); @@ -18,7 +19,7 @@ DWORD mono_win32_wait_for_single_object_ex (HANDLE handle, DWORD timeout, BOOL alertable); DWORD -mono_win32_wait_for_multiple_objects_ex (DWORD count, CONST HANDLE *handles, BOOL waitAll, DWORD timeout, BOOL alertable); +mono_win32_wait_for_multiple_objects_ex (DWORD count, CONST HANDLE *handles, BOOL waitAll, DWORD timeout, BOOL alertable, MonoError *error); DWORD mono_win32_signal_object_and_wait (HANDLE toSignal, HANDLE toWait, DWORD timeout, BOOL alertable); diff --git a/mono/utils/mono-path.c b/mono/utils/mono-path.c index 5fd4cf11a3..dc222ac12b 100644 --- a/mono/utils/mono-path.c +++ b/mono/utils/mono-path.c @@ -51,7 +51,7 @@ mono_path_canonicalize (const char *path) } #ifdef HOST_WIN32 - g_strdelimit (abspath, "/", '\\'); + g_strdelimit (abspath, '/', '\\'); #endif abspath = g_strreverse (abspath); @@ -189,7 +189,7 @@ mono_path_resolve_symlinks (const char *path) gboolean mono_path_filename_in_basedir (const char *filename, const char *basedir) { - char *p = NULL; + const char *p = NULL; if ((p = strstr (filename, basedir))) { p += strlen (basedir); if (*p != G_DIR_SEPARATOR) diff --git a/mono/utils/mono-publib.h b/mono/utils/mono-publib.h index d902e0dc66..42f9cfbaca 100644 --- a/mono/utils/mono-publib.h +++ b/mono/utils/mono-publib.h @@ -15,8 +15,8 @@ #define MONO_BEGIN_DECLS extern "C" { #define MONO_END_DECLS } #else -#define MONO_BEGIN_DECLS -#define MONO_END_DECLS +#define MONO_BEGIN_DECLS /* nothing */ +#define MONO_END_DECLS /* nothing */ #endif MONO_BEGIN_DECLS @@ -87,7 +87,14 @@ typedef unsigned __int64 uint64_t; typedef int32_t mono_bool; typedef uint8_t mono_byte; +#ifdef _WIN32 +MONO_END_DECLS +#include +typedef wchar_t mono_unichar2; +MONO_BEGIN_DECLS +#else typedef uint16_t mono_unichar2; +#endif typedef uint32_t mono_unichar4; typedef void (*MonoFunc) (void* data, void* user_data); diff --git a/mono/utils/mono-rand.c b/mono/utils/mono-rand.c index 89d15f08d5..ecd5ee47b6 100644 --- a/mono/utils/mono-rand.c +++ b/mono/utils/mono-rand.c @@ -228,7 +228,7 @@ gpointer mono_rand_init (const guchar *seed, gssize seed_size) { // file < 0 is expected in the egd case - return (!use_egd && file < 0) ? NULL : GINT_TO_POINTER (file); + return (!use_egd && file < 0) ? (gpointer)NULL : GINT_TO_POINTER (file); } gboolean diff --git a/mono/utils/mono-state.c b/mono/utils/mono-state.c index 801bb7262f..35a683d376 100644 --- a/mono/utils/mono-state.c +++ b/mono/utils/mono-state.c @@ -800,22 +800,25 @@ mono_native_state_add_version (MonoStateWriter *writer) mono_state_writer_printf(writer, "\"disabled\",\n"); #endif + const char *susp_policy = mono_threads_suspend_policy_name (); + assert_has_space (writer); + mono_state_writer_indent (writer); + mono_state_writer_object_key (writer, "suspend"); + mono_state_writer_printf(writer, "\"%s\",\n", susp_policy); + assert_has_space (writer); mono_state_writer_indent (writer); mono_state_writer_object_key (writer, "llvm_support"); #ifdef MONO_ARCH_LLVM_SUPPORTED #ifdef ENABLE_LLVM - mono_state_writer_printf(writer, "\"%d\",\n", LLVM_API_VERSION); + mono_state_writer_printf (writer, "\"%d\"\n", LLVM_API_VERSION); #else - mono_state_writer_printf(writer, "\"disabled\",\n"); + mono_state_writer_printf (writer, "\"disabled\"\n"); #endif #endif - const char *susp_policy = mono_threads_suspend_policy_name (); - assert_has_space (writer); - mono_state_writer_indent (writer); - mono_state_writer_object_key (writer, "suspend"); - mono_state_writer_printf(writer, "\"%s\"\n", susp_policy); + // Don't put any new fields here without adding commas above. + // Easier to add new fields above llvm_support assert_has_space (writer); mono_state_writer_indent (writer); @@ -1004,7 +1007,6 @@ mono_crash_dump (const char *jsonFile, MonoStackHash *hashes) { size_t size = strlen (jsonFile); - pid_t pid = getpid (); gboolean success = FALSE; // Save up to 100 dump files for a given stacktrace hash diff --git a/mono/utils/mono-threads-coop.c b/mono/utils/mono-threads-coop.c index 0d42f556ce..80c12d3332 100644 --- a/mono/utils/mono-threads-coop.c +++ b/mono/utils/mono-threads-coop.c @@ -58,7 +58,7 @@ coop_tls_push (gpointer cookie) { GArray *stack; - stack = mono_native_tls_get_value (coop_reset_count_stack_key); + stack = (GArray*)mono_native_tls_get_value (coop_reset_count_stack_key); if (!stack) { stack = g_array_new (FALSE, FALSE, sizeof(gpointer)); mono_native_tls_set_value (coop_reset_count_stack_key, stack); @@ -73,7 +73,7 @@ coop_tls_pop (gpointer received_cookie) GArray *stack; gpointer expected_cookie; - stack = mono_native_tls_get_value (coop_reset_count_stack_key); + stack = (GArray*)mono_native_tls_get_value (coop_reset_count_stack_key); if (!stack || 0 == stack->len) mono_fatal_with_history ("Received cookie %p but found no stack at all\n", received_cookie); @@ -508,18 +508,16 @@ mono_threads_assert_gc_unsafe_region (void) MONO_REQ_GC_UNSAFE_MODE; } -static MonoThreadsSuspendPolicy +static int threads_suspend_policy_default (void) { #if defined (ENABLE_COOP_SUSPEND) return MONO_THREADS_SUSPEND_FULL_COOP; -#else -#if defined (ENABLE_HYBRID_SUSPEND) +#elif defined (ENABLE_HYBRID_SUSPEND) return MONO_THREADS_SUSPEND_HYBRID; #else return 0; /* unset */ #endif -#endif } /* Look up whether an env var is set, warn that it's obsolete and offer a new @@ -542,10 +540,10 @@ hasenv_obsolete (const char *name, const char* newval) return FALSE; } -static MonoThreadsSuspendPolicy +static int threads_suspend_policy_getenv_compat (void) { - MonoThreadsSuspendPolicy policy = 0; + int policy = 0; if (hasenv_obsolete ("MONO_ENABLE_COOP", "coop") || hasenv_obsolete ("MONO_ENABLE_COOP_SUSPEND", "coop")) { g_assertf (!hasenv_obsolete ("MONO_ENABLE_HYBRID_SUSPEND", "hybrid"), "Environment variables set to enable both hybrid and cooperative suspend simultaneously"); @@ -555,10 +553,10 @@ threads_suspend_policy_getenv_compat (void) return policy; } -static MonoThreadsSuspendPolicy +static int threads_suspend_policy_getenv (void) { - MonoThreadsSuspendPolicy policy = 0; + int policy = 0; if (g_hasenv ("MONO_THREADS_SUSPEND")) { gchar *str = g_getenv ("MONO_THREADS_SUSPEND"); if (!strcmp (str, "coop")) @@ -574,34 +572,39 @@ threads_suspend_policy_getenv (void) return policy; } -static MonoThreadsSuspendPolicy threads_suspend_policy = -1; +static char threads_suspend_policy; static MonoThreadsSuspendPolicy mono_threads_suspend_policy (void) { - MonoThreadsSuspendPolicy policy = threads_suspend_policy; - if (G_UNLIKELY (policy == -1)) { + int policy = threads_suspend_policy; + if (G_UNLIKELY (policy == 0)) { // thread suspend policy: // if the MONO_THREADS_SUSPEND env is set, use it. // otherwise if there's a compiled-in default, use it. // otherwise if one of the old environment variables is set, use that. // otherwise use full preemptive suspend. - MonoThreadsSuspendPolicy env_policy = threads_suspend_policy_getenv (); - MonoThreadsSuspendPolicy default_policy = threads_suspend_policy_default (); - MonoThreadsSuspendPolicy env_compat_policy = threads_suspend_policy_getenv_compat (); - if (env_policy) - policy = env_policy; - else if (default_policy) - policy = default_policy; - else if (env_compat_policy) - policy = env_compat_policy; - else - policy = MONO_THREADS_SUSPEND_FULL_PREEMPTIVE; - - g_assert (policy > 0); - threads_suspend_policy = policy; + (policy = threads_suspend_policy_getenv ()) + || (policy = threads_suspend_policy_default ()) + || (policy = threads_suspend_policy_getenv_compat ()) + || (policy = MONO_THREADS_SUSPEND_FULL_PREEMPTIVE); + g_assert (policy); + threads_suspend_policy = (char)policy; + } + return (MonoThreadsSuspendPolicy)policy; +} + +static MonoThreadsSuspendPolicy +mono_threads_suspend_validate_policy (MonoThreadsSuspendPolicy policy) +{ + switch (policy) { + case MONO_THREADS_SUSPEND_FULL_COOP: + case MONO_THREADS_SUSPEND_FULL_PREEMPTIVE: + case MONO_THREADS_SUSPEND_HYBRID: + return policy; + default: + g_error ("Invalid suspend policy %d.", (int)policy); } - return policy; } /** @@ -614,7 +617,7 @@ mono_threads_suspend_policy (void) void mono_threads_suspend_override_policy (MonoThreadsSuspendPolicy new_policy) { - threads_suspend_policy = new_policy; + threads_suspend_policy = (char)mono_threads_suspend_validate_policy (new_policy); g_warning ("Overriding suspend policy. Using %s suspend.", mono_threads_suspend_policy_name ()); } @@ -670,7 +673,6 @@ mono_threads_is_hybrid_suspension_enabled (void) return (mono_threads_suspend_policy () == MONO_THREADS_SUSPEND_HYBRID); } - void mono_threads_coop_init (void) { diff --git a/mono/utils/mono-threads-coop.h b/mono/utils/mono-threads-coop.h index d86c8b4ad8..a75ef3208d 100644 --- a/mono/utils/mono-threads-coop.h +++ b/mono/utils/mono-threads-coop.h @@ -46,6 +46,13 @@ mono_threads_are_safepoints_enabled (void) return mono_threads_is_cooperative_suspension_enabled () || mono_threads_is_hybrid_suspension_enabled (); } +static inline gboolean +mono_threads_is_multiphase_stw_enabled (void) +{ + /* So far, hybrid suspend is the only one using a multi-phase STW */ + return mono_threads_is_hybrid_suspension_enabled (); +} + static inline void mono_threads_safepoint (void) { @@ -53,14 +60,11 @@ mono_threads_safepoint (void) mono_threads_state_poll (); } -/* -1 and 0 also used: - * -1 means uninitialized - * 0 means unset - */ +// 0 also used internally for uninitialized typedef enum { MONO_THREADS_SUSPEND_FULL_PREEMPTIVE = 1, - MONO_THREADS_SUSPEND_FULL_COOP, - MONO_THREADS_SUSPEND_HYBRID + MONO_THREADS_SUSPEND_FULL_COOP = 2, + MONO_THREADS_SUSPEND_HYBRID = 3, } MonoThreadsSuspendPolicy; /* Don't use this. */ @@ -74,9 +78,11 @@ void mono_threads_suspend_override_policy (MonoThreadsSuspendPolicy new_policy); * runtime assertion error when trying to switch the state of the current thread. */ +G_EXTERN_C // due to THREAD_INFO_TYPE varying gpointer mono_threads_enter_gc_safe_region_with_info (THREAD_INFO_TYPE *info, MonoStackData *stackdata); +G_EXTERN_C // due to THREAD_INFO_TYPE varying gpointer mono_threads_enter_gc_safe_region_with_info (THREAD_INFO_TYPE *info, MonoStackData *stackdata); @@ -87,9 +93,11 @@ mono_threads_enter_gc_safe_region_with_info (THREAD_INFO_TYPE *info, MonoStackDa #define MONO_EXIT_GC_SAFE_WITH_INFO MONO_EXIT_GC_SAFE +G_EXTERN_C // due to THREAD_INFO_TYPE varying gpointer mono_threads_enter_gc_unsafe_region_with_info (THREAD_INFO_TYPE *, MonoStackData *stackdata); +G_EXTERN_C // due to THREAD_INFO_TYPE varying gpointer mono_threads_enter_gc_unsafe_region_with_info (THREAD_INFO_TYPE *, MonoStackData *stackdata); @@ -100,6 +108,7 @@ mono_threads_enter_gc_unsafe_region_with_info (THREAD_INFO_TYPE *, MonoStackData #define MONO_EXIT_GC_UNSAFE_WITH_INFO MONO_EXIT_GC_UNSAFE +G_EXTERN_C // due to THREAD_INFO_TYPE varying gpointer mono_threads_enter_gc_unsafe_region_unbalanced_with_info (THREAD_INFO_TYPE *info, MonoStackData *stackdata); diff --git a/mono/utils/mono-threads-posix.c b/mono/utils/mono-threads-posix.c index e97701137b..2aabb05deb 100644 --- a/mono/utils/mono-threads-posix.c +++ b/mono/utils/mono-threads-posix.c @@ -34,7 +34,7 @@ extern int tkill (pid_t tid, int signal); #endif -#if defined(_POSIX_VERSION) && !defined (TARGET_WASM) +#if defined(_POSIX_VERSION) && !defined (HOST_WASM) #include diff --git a/mono/utils/mono-threads-state-machine.c b/mono/utils/mono-threads-state-machine.c index 39e04aa0d5..d1a4e2c523 100644 --- a/mono/utils/mono-threads-state-machine.c +++ b/mono/utils/mono-threads-state-machine.c @@ -469,6 +469,53 @@ If this turns to be a problem we should either implement [2] or make this an inv } } +/* +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; + 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, 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 (mono_atomic_cas_i32 (&info->thread_state, build_thread_state (STATE_BLOCKING_SUSPEND_REQUESTED, suspend_count), raw_state) != raw_state) + goto retry_state_change; + trace_state_change ("PULSE", info, raw_state, STATE_BLOCKING_SUSPEND_REQUESTED, -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)); + } +} + /* This performs the last step of preemptive suspend. @@ -489,11 +536,15 @@ retry_state_change: 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); if (mono_atomic_cas_i32 (&info->thread_state, build_thread_state (STATE_ASYNC_SUSPENDED, suspend_count), raw_state) != raw_state) goto retry_state_change; trace_state_change_sigsafe ("FINISH_ASYNC_SUSPEND", info, raw_state, STATE_ASYNC_SUSPENDED, 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 (mono_atomic_cas_i32 (&info->thread_state, build_thread_state (STATE_BLOCKING_ASYNC_SUSPENDED, suspend_count), raw_state) != raw_state) goto retry_state_change; trace_state_change_sigsafe ("FINISH_ASYNC_SUSPEND", info, raw_state, STATE_BLOCKING_ASYNC_SUSPENDED, 0, ""); diff --git a/mono/utils/mono-threads-wasm.c b/mono/utils/mono-threads-wasm.c index 8c8347e3ff..dbc53ca66e 100644 --- a/mono/utils/mono-threads-wasm.c +++ b/mono/utils/mono-threads-wasm.c @@ -130,7 +130,7 @@ mono_threads_platform_yield (void) void mono_threads_platform_get_stack_bounds (guint8 **staddr, size_t *stsize) { - *staddr = (void*)wasm_get_stack_base (); + *staddr = (guint8*)wasm_get_stack_base (); *stsize = wasm_get_stack_size (); } @@ -158,7 +158,7 @@ mono_threads_platform_in_critical_region (MonoNativeThreadId tid) return FALSE; } - +G_EXTERN_C extern void schedule_background_exec (void); static GSList *jobs; @@ -169,10 +169,11 @@ mono_threads_schedule_background_job (background_job_cb cb) if (!jobs) schedule_background_exec (); - if (!g_slist_find (jobs, cb)) - jobs = g_slist_prepend (jobs, cb); + if (!g_slist_find (jobs, (gconstpointer)cb)) + jobs = g_slist_prepend (jobs, (gpointer)cb); } +G_EXTERN_C EMSCRIPTEN_KEEPALIVE void mono_background_exec (void) { diff --git a/mono/utils/mono-threads-windows.c b/mono/utils/mono-threads-windows.c index 1d40263552..244a8c53ad 100644 --- a/mono/utils/mono-threads-windows.c +++ b/mono/utils/mono-threads-windows.c @@ -110,7 +110,8 @@ mono_threads_suspend_begin_async_resume (MonoThreadInfo *info) ctx = info->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX].ctx; mono_threads_get_runtime_callbacks ()->setup_async_callback (&ctx, info->async_target, info->user_data); - info->async_target = info->user_data = NULL; + info->async_target = NULL; + info->user_data = NULL; context.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL; @@ -233,7 +234,7 @@ mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2) gboolean mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg) { - return CreateThread (NULL, 0, (func), (arg), 0, (tid)) != NULL; + return CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)func, arg, 0, tid) != NULL; } gboolean diff --git a/mono/utils/mono-threads.c b/mono/utils/mono-threads.c index 715294cebb..c672edeafa 100644 --- a/mono/utils/mono-threads.c +++ b/mono/utils/mono-threads.c @@ -503,7 +503,7 @@ unregister_thread (void *arg) MonoThreadInfo *info; int small_id; gboolean result; - gpointer handle; + MonoThreadHandle* handle; info = (MonoThreadInfo *) arg; g_assert (info); @@ -779,14 +779,14 @@ thread_info_key_dtor (void *arg) MonoThreadInfoFlags mono_thread_info_get_flags (MonoThreadInfo *info) { - return mono_atomic_load_i32 (&info->flags); + return (MonoThreadInfoFlags)mono_atomic_load_i32 (&info->flags); } void mono_thread_info_set_flags (MonoThreadInfoFlags flags) { MonoThreadInfo *info = mono_thread_info_current (); - MonoThreadInfoFlags old = mono_atomic_load_i32 (&info->flags); + MonoThreadInfoFlags old = (MonoThreadInfoFlags)mono_atomic_load_i32 (&info->flags); if (threads_callbacks.thread_flags_changing) threads_callbacks.thread_flags_changing (old, flags); @@ -797,11 +797,6 @@ mono_thread_info_set_flags (MonoThreadInfoFlags flags) threads_callbacks.thread_flags_changed (old, flags); } -struct GSList { - gpointer data; - GSList *next; -}; - #define MONO_END_INIT_CB GINT_TO_POINTER(-1) static GSList *init_callbacks; @@ -810,14 +805,14 @@ mono_thread_info_wait_inited (void) { MonoSemType cb; mono_os_sem_init (&cb, 0); - gpointer old = init_callbacks; + GSList *old = init_callbacks; GSList wait_request; wait_request.data = &cb; wait_request.next = old; while (mono_threads_inited != TRUE) { - gpointer old_read = mono_atomic_cas_ptr ((gpointer *) &init_callbacks, &wait_request, old); + GSList *old_read = (GSList*)mono_atomic_cas_ptr ((gpointer *) &init_callbacks, &wait_request, old); // Queued up waiter, need to be unstuck if (old_read == old) { @@ -851,7 +846,7 @@ mono_thread_info_set_inited (void) GSList *old = init_callbacks; while (TRUE) { - gpointer old_read = mono_atomic_cas_ptr ((gpointer *) &init_callbacks, MONO_END_INIT_CB, (gpointer) old); + GSList* old_read = (GSList*)mono_atomic_cas_ptr ((gpointer *) &init_callbacks, MONO_END_INIT_CB, (gpointer) old); if (old == old_read) break; else @@ -869,13 +864,20 @@ mono_thread_info_set_inited (void) GSList *curr = (GSList *) old; GSList *next = old->next; - mono_os_sem_post (curr->data); + mono_os_sem_post ((MonoSemType*)curr->data); old = next; } return; } +void +mono_thread_info_cleanup () +{ + mono_native_tls_free (thread_info_key); + mono_native_tls_free (thread_exited_key); +} + void mono_thread_info_init (size_t info_size) { @@ -976,6 +978,25 @@ mono_thread_info_core_resume (MonoThreadInfo *info) return res; } +/* + * Current thread must hold the global_suspend_semaphore. + * The given MonoThreadInfo* is a suspended thread. + * Must be using hybrid suspend. + */ +static gboolean +mono_thread_info_core_pulse (MonoThreadInfo *info) +{ + gboolean res = FALSE; + + switch (mono_threads_transition_request_pulse (info)) { + case PulseInitAsyncPulse: + resume_async_suspended (info); + res = TRUE; + break; + } + return res; +} + gboolean mono_thread_info_resume (MonoNativeThreadId tid) { @@ -1115,6 +1136,21 @@ mono_thread_info_begin_resume (MonoThreadInfo *info) return mono_thread_info_core_resume (info); } +gboolean +mono_thread_info_begin_pulse_resume_and_request_suspension (MonoThreadInfo *info) +{ + /* For two-phase suspend, we want to atomically resume the thread and + * request that it try to cooperatively suspend again. Specifically, + * we really don't want it to transition from GC Safe to GC Unsafe + * because we then it could (in GC Unsafe) try to take a lock that's + * held by another preemptively-suspended thread, essentially + * recreating the same problem that two-phase suspend intends to + * fix. */ + if (mono_threads_is_multiphase_stw_enabled ()) + return mono_thread_info_core_pulse (info); + else + return mono_thread_info_core_resume (info); +} /* FIXME fix cardtable WB to be out of line and check with the runtime if the target is not the WB trampoline. Another option is to encode wb ranges in MonoJitInfo, but that is somewhat hard. @@ -1465,8 +1501,18 @@ mono_thread_info_set_is_async_context (gboolean async_context) { MonoThreadInfo *info = mono_thread_info_current (); - if (info) + if (info) { + // If this assert fails, that means there is recursion and/or + // concurrency, such that setting async_context to FALSE + // that all the callers do after this, is incorrect, + // and this should instead be incremented/decremented. + // + // As the value is only accessed via current(), that + // limits the case to recursion, but increment/decrement + // is still fast and correct and simple. + g_assert (!async_context || !info->is_async_context); info->is_async_context = async_context; + } } gboolean @@ -1699,6 +1745,8 @@ mono_threads_open_thread_handle (MonoThreadHandle *thread_handle) void mono_threads_close_thread_handle (MonoThreadHandle *thread_handle) { + if (!thread_handle) + return; mono_refcount_dec (thread_handle); } @@ -1949,7 +1997,7 @@ mono_thread_info_wait_multiple_handle (MonoThreadHandle **thread_handles, gsize res = mono_os_event_wait_multiple (thread_events, nhandles, waitall, timeout, alertable); if (res >= MONO_OS_EVENT_WAIT_RET_SUCCESS_0 && res <= MONO_OS_EVENT_WAIT_RET_SUCCESS_0 + nhandles - 1) - return MONO_THREAD_INFO_WAIT_RET_SUCCESS_0 + (res - MONO_OS_EVENT_WAIT_RET_SUCCESS_0); + return (MonoThreadInfoWaitRet)(MONO_THREAD_INFO_WAIT_RET_SUCCESS_0 + (res - MONO_OS_EVENT_WAIT_RET_SUCCESS_0)); else if (res == MONO_OS_EVENT_WAIT_RET_ALERTED) return MONO_THREAD_INFO_WAIT_RET_ALERTED; else if (res == MONO_OS_EVENT_WAIT_RET_TIMEOUT) diff --git a/mono/utils/mono-threads.h b/mono/utils/mono-threads.h index 0b94bd11d5..22014e7a2b 100644 --- a/mono/utils/mono-threads.h +++ b/mono/utils/mono-threads.h @@ -11,6 +11,7 @@ #ifndef __MONO_THREADS_H__ #define __MONO_THREADS_H__ +#include #include #include #include @@ -153,8 +154,6 @@ enum { ASYNC_SUSPEND_STATE_INDEX = 1, }; -typedef struct _MonoThreadInfoInterruptToken MonoThreadInfoInterruptToken; - /* * These flags control how the rest of the runtime will see and interact with * a thread. @@ -177,6 +176,10 @@ typedef enum { MONO_THREAD_INFO_FLAGS_NO_SAMPLE = 2, } MonoThreadInfoFlags; +G_ENUM_FUNCTIONS (MonoThreadInfoFlags) + +typedef struct _MonoThreadInfoInterruptToken MonoThreadInfoInterruptToken; + typedef struct _MonoThreadInfo { MonoLinkedListSetNode node; guint32 small_id; /*Used by hazard pointers */ @@ -244,12 +247,12 @@ typedef struct _MonoThreadInfo { /* Set when the thread is started, or in _wapi_thread_duplicate () */ MonoThreadHandle *handle; - void *jit_data; + MonoJitTlsData *jit_data; MonoThreadInfoInterruptToken *interrupt_token; /* HandleStack for coop handles */ - gpointer handle_stack; + MonoHandleStack *handle_stack; /* Stack mark for targets that explicitly require one */ gpointer stack_mark; @@ -365,6 +368,8 @@ mono_thread_info_set_tid (THREAD_INFO_TYPE *info, MonoNativeThreadId tid) ((MonoThreadInfo*) info)->node.key = (uintptr_t) MONO_NATIVE_THREAD_ID_TO_UINT (tid); } +void +mono_thread_info_cleanup (void); /* * @thread_info_size is sizeof (GcThreadInfo), a struct the GC defines to make it possible to have @@ -412,6 +417,9 @@ mono_thread_info_unset_internal_thread_gchandle (THREAD_INFO_TYPE *info); gboolean mono_thread_info_is_exiting (void); +#ifdef HOST_WIN32 +G_EXTERN_C // due to THREAD_INFO_TYPE varying +#endif THREAD_INFO_TYPE * mono_thread_info_current (void); @@ -503,6 +511,7 @@ mono_thread_info_is_interrupt_state (THREAD_INFO_TYPE *info); void mono_thread_info_describe_interrupt_token (THREAD_INFO_TYPE *info, GString *text); +G_EXTERN_C // due to THREAD_INFO_TYPE varying gboolean mono_thread_info_is_live (THREAD_INFO_TYPE *info); @@ -592,9 +601,22 @@ mono_native_thread_id_get (void); MONO_API gboolean mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2); +//FIXMEcxx typedef mono_native_thread_return_t (MONO_STDCALL * MonoNativeThreadStart)(void*); +// mono_native_thread_return_t func +// and remove the template + MONO_API gboolean mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg); +#ifdef __cplusplus +template +inline gboolean +mono_native_thread_create (MonoNativeThreadId *tid, T func, gpointer arg) +{ + return mono_native_thread_create (tid, (gpointer)func, arg); +} +#endif + MONO_API void mono_native_thread_set_name (MonoNativeThreadId tid, const char *name); @@ -633,6 +655,10 @@ typedef enum { ResumeInitBlockingResume, } MonoResumeResult; +typedef enum { + PulseInitAsyncPulse, +} MonoPulseResult; + typedef enum { SelfSuspendResumed, SelfSuspendNotifyAndWait, @@ -669,13 +695,14 @@ gboolean mono_threads_transition_detach (THREAD_INFO_TYPE *info); MonoRequestSuspendResult mono_threads_transition_request_suspension (THREAD_INFO_TYPE *info); MonoSelfSupendResult mono_threads_transition_state_poll (THREAD_INFO_TYPE *info); MonoResumeResult mono_threads_transition_request_resume (THREAD_INFO_TYPE* info); +MonoPulseResult mono_threads_transition_request_pulse (THREAD_INFO_TYPE* info); gboolean mono_threads_transition_finish_async_suspend (THREAD_INFO_TYPE* info); MonoDoBlockingResult mono_threads_transition_do_blocking (THREAD_INFO_TYPE* info, const char* func); MonoDoneBlockingResult mono_threads_transition_done_blocking (THREAD_INFO_TYPE* info, const char* func); MonoAbortBlockingResult mono_threads_transition_abort_blocking (THREAD_INFO_TYPE* info, const char* func); gboolean mono_threads_transition_peek_blocking_suspend_requested (THREAD_INFO_TYPE* info); - +G_EXTERN_C // due to THREAD_INFO_TYPE varying MonoThreadUnwindState* mono_thread_info_get_suspend_state (THREAD_INFO_TYPE *info); gpointer @@ -684,8 +711,10 @@ mono_threads_enter_gc_unsafe_region_cookie (void); void mono_thread_info_wait_for_resume (THREAD_INFO_TYPE *info); /* Advanced suspend API, used for suspending multiple threads as once. */ +G_EXTERN_C // due to THREAD_INFO_TYPE varying gboolean mono_thread_info_is_running (THREAD_INFO_TYPE *info); gboolean mono_thread_info_is_live (THREAD_INFO_TYPE *info); +G_EXTERN_C // due to THREAD_INFO_TYPE varying int mono_thread_info_suspend_count (THREAD_INFO_TYPE *info); int mono_thread_info_current_state (THREAD_INFO_TYPE *info); const char* mono_thread_state_name (int state); @@ -708,12 +737,11 @@ gboolean mono_thread_is_gc_unsafe_mode (void); * BLOCKING_SUSPEND_REQUESTED state, in which case they are preemptively * suspended. */ -typedef enum { - MONO_THREAD_SUSPEND_PHASE_INITIAL = 0, - MONO_THREAD_SUSPEND_PHASE_MOPUP = 1, - // number of phases - MONO_THREAD_SUSPEND_PHASE_COUNT = 2, -} MonoThreadSuspendPhase; +#define MONO_THREAD_SUSPEND_PHASE_INITIAL (0) +#define MONO_THREAD_SUSPEND_PHASE_MOPUP (1) +// number of phases +#define MONO_THREAD_SUSPEND_PHASE_COUNT (2) +typedef int MonoThreadSuspendPhase; typedef enum { MONO_THREAD_BEGIN_SUSPEND_SKIP = 0, @@ -721,9 +749,15 @@ typedef enum { MONO_THREAD_BEGIN_SUSPEND_NEXT_PHASE = 2, } MonoThreadBeginSuspendResult; +G_EXTERN_C // due to THREAD_INFO_TYPE varying gboolean mono_thread_info_in_critical_location (THREAD_INFO_TYPE *info); +G_EXTERN_C // due to THREAD_INFO_TYPE varying MonoThreadBeginSuspendResult mono_thread_info_begin_suspend (THREAD_INFO_TYPE *info, MonoThreadSuspendPhase phase); +G_EXTERN_C // due to THREAD_INFO_TYPE varying gboolean mono_thread_info_begin_resume (THREAD_INFO_TYPE *info); +G_EXTERN_C // due to THREAD_INFO_TYPE varying +gboolean mono_thread_info_begin_pulse_resume_and_request_suspension (THREAD_INFO_TYPE *info); + void mono_threads_add_to_pending_operation_set (THREAD_INFO_TYPE* info); //XXX rename to something to reflect the fact that this is used for both suspend and resume gboolean mono_threads_wait_pending_operations (void); diff --git a/mono/utils/mono-tls.c b/mono/utils/mono-tls.c index 2c7342c4ba..10c57b0280 100644 --- a/mono/utils/mono-tls.c +++ b/mono/utils/mono-tls.c @@ -158,14 +158,21 @@ #endif -/* Tls variables for each MonoTlsKey */ +#ifdef __cplusplus +// static and anonymous namespace both fail to link otherwise; Linux/amd64/gcc. +#define MONO_TLS_STATIC /* nothing */ +#else +#define MONO_TLS_STATIC static +#endif -static MONO_KEYWORD_THREAD gpointer mono_tls_thread MONO_TLS_FAST; -static MONO_KEYWORD_THREAD gpointer mono_tls_jit_tls MONO_TLS_FAST; -static MONO_KEYWORD_THREAD gpointer mono_tls_domain MONO_TLS_FAST; -static MONO_KEYWORD_THREAD gpointer mono_tls_lmf MONO_TLS_FAST; -static MONO_KEYWORD_THREAD gpointer mono_tls_sgen_thread_info MONO_TLS_FAST; -static MONO_KEYWORD_THREAD gpointer mono_tls_lmf_addr MONO_TLS_FAST; +/* Tls variables for each MonoTlsKey */ +MONO_TLS_STATIC MONO_KEYWORD_THREAD MonoInternalThread *mono_tls_thread MONO_TLS_FAST; +MONO_TLS_STATIC MONO_KEYWORD_THREAD MonoJitTlsData *mono_tls_jit_tls MONO_TLS_FAST; +MONO_TLS_STATIC MONO_KEYWORD_THREAD MonoDomain *mono_tls_domain MONO_TLS_FAST; +MONO_TLS_STATIC MONO_KEYWORD_THREAD SgenThreadInfo *mono_tls_sgen_thread_info MONO_TLS_FAST; +MONO_TLS_STATIC MONO_KEYWORD_THREAD MonoLMF **mono_tls_lmf_addr MONO_TLS_FAST; + +#undef MONO_TLS_STATIC // no further uses #else @@ -294,54 +301,56 @@ mono_tls_get_tls_setter (MonoTlsKey key, gboolean name) return NULL; } +// Casts on getters are for the !MONO_KEYWORD_THREAD case. + /* Getters for each tls key */ -gpointer mono_tls_get_thread (void) +MonoInternalThread *mono_tls_get_thread (void) { - return MONO_TLS_GET_VALUE (mono_tls_thread, mono_tls_key_thread); + return (MonoInternalThread*)MONO_TLS_GET_VALUE (mono_tls_thread, mono_tls_key_thread); } -gpointer mono_tls_get_jit_tls (void) +MonoJitTlsData *mono_tls_get_jit_tls (void) { - return MONO_TLS_GET_VALUE (mono_tls_jit_tls, mono_tls_key_jit_tls); + return (MonoJitTlsData*)MONO_TLS_GET_VALUE (mono_tls_jit_tls, mono_tls_key_jit_tls); } -gpointer mono_tls_get_domain (void) +MonoDomain *mono_tls_get_domain (void) { - return MONO_TLS_GET_VALUE (mono_tls_domain, mono_tls_key_domain); + return (MonoDomain*)MONO_TLS_GET_VALUE (mono_tls_domain, mono_tls_key_domain); } -gpointer mono_tls_get_sgen_thread_info (void) +SgenThreadInfo *mono_tls_get_sgen_thread_info (void) { - return MONO_TLS_GET_VALUE (mono_tls_sgen_thread_info, mono_tls_key_sgen_thread_info); + return (SgenThreadInfo*)MONO_TLS_GET_VALUE (mono_tls_sgen_thread_info, mono_tls_key_sgen_thread_info); } -gpointer mono_tls_get_lmf_addr (void) +MonoLMF **mono_tls_get_lmf_addr (void) { - return MONO_TLS_GET_VALUE (mono_tls_lmf_addr, mono_tls_key_lmf_addr); + return (MonoLMF**)MONO_TLS_GET_VALUE (mono_tls_lmf_addr, mono_tls_key_lmf_addr); } /* Setters for each tls key */ -void mono_tls_set_thread (gpointer value) +void mono_tls_set_thread (MonoInternalThread *value) { MONO_TLS_SET_VALUE (mono_tls_thread, mono_tls_key_thread, value); } -void mono_tls_set_jit_tls (gpointer value) +void mono_tls_set_jit_tls (MonoJitTlsData *value) { MONO_TLS_SET_VALUE (mono_tls_jit_tls, mono_tls_key_jit_tls, value); } -void mono_tls_set_domain (gpointer value) +void mono_tls_set_domain (MonoDomain *value) { MONO_TLS_SET_VALUE (mono_tls_domain, mono_tls_key_domain, value); } -void mono_tls_set_sgen_thread_info (gpointer value) +void mono_tls_set_sgen_thread_info (SgenThreadInfo *value) { MONO_TLS_SET_VALUE (mono_tls_sgen_thread_info, mono_tls_key_sgen_thread_info, value); } -void mono_tls_set_lmf_addr (gpointer value) +void mono_tls_set_lmf_addr (MonoLMF **value) { MONO_TLS_SET_VALUE (mono_tls_lmf_addr, mono_tls_key_lmf_addr, value); } diff --git a/mono/utils/mono-tls.h b/mono/utils/mono-tls.h index 1b864a187c..255aa34cd9 100644 --- a/mono/utils/mono-tls.h +++ b/mono/utils/mono-tls.h @@ -15,6 +15,7 @@ #include #include +#include /* TLS entries used by the runtime */ typedef enum { @@ -85,16 +86,16 @@ gint32 mono_tls_get_tls_offset (MonoTlsKey key); gpointer mono_tls_get_tls_getter (MonoTlsKey key, gboolean name); gpointer mono_tls_get_tls_setter (MonoTlsKey key, gboolean name); -gpointer mono_tls_get_thread (void); -gpointer mono_tls_get_jit_tls (void); -gpointer mono_tls_get_domain (void); -gpointer mono_tls_get_sgen_thread_info (void); -gpointer mono_tls_get_lmf_addr (void); +G_EXTERN_C MonoInternalThread *mono_tls_get_thread (void); +G_EXTERN_C MonoJitTlsData *mono_tls_get_jit_tls (void); +G_EXTERN_C MonoDomain *mono_tls_get_domain (void); +G_EXTERN_C SgenThreadInfo *mono_tls_get_sgen_thread_info (void); +G_EXTERN_C MonoLMF **mono_tls_get_lmf_addr (void); -void mono_tls_set_thread (gpointer value); -void mono_tls_set_jit_tls (gpointer value); -void mono_tls_set_domain (gpointer value); -void mono_tls_set_sgen_thread_info (gpointer value); -void mono_tls_set_lmf_addr (gpointer value); +G_EXTERN_C void mono_tls_set_thread (MonoInternalThread *value); +G_EXTERN_C void mono_tls_set_jit_tls (MonoJitTlsData *value); +G_EXTERN_C void mono_tls_set_domain (MonoDomain *value); +G_EXTERN_C void mono_tls_set_sgen_thread_info (SgenThreadInfo *value); +G_EXTERN_C void mono_tls_set_lmf_addr (MonoLMF **value); #endif /* __MONO_TLS_H__ */ diff --git a/mono/utils/mono-utility-thread.c b/mono/utils/mono-utility-thread.c index 1943467d24..ce248018d1 100644 --- a/mono/utils/mono-utility-thread.c +++ b/mono/utils/mono-utility-thread.c @@ -82,7 +82,7 @@ utility_thread (void *arg) MonoUtilityThread * mono_utility_thread_launch (size_t payload_size, MonoUtilityThreadCallbacks *callbacks, MonoMemAccountType accountType) { - MonoUtilityThread *thread = g_malloc0 (sizeof (MonoUtilityThread)); + MonoUtilityThread *thread = (MonoUtilityThread*)g_malloc0 (sizeof (MonoUtilityThread)); size_t entry_size = offsetof (UtilityThreadQueueEntry, payload) + payload_size; thread->message_block_size = mono_pagesize (); @@ -125,7 +125,7 @@ mono_utility_thread_send (MonoUtilityThread *thread, gpointer message) return; } - UtilityThreadQueueEntry *entry = mono_lock_free_alloc (&thread->message_allocator); + UtilityThreadQueueEntry *entry = (UtilityThreadQueueEntry*)mono_lock_free_alloc (&thread->message_allocator); entry->response_sem = NULL; entry->thread = thread; memcpy (entry->payload, message, thread->payload_size); @@ -151,7 +151,7 @@ mono_utility_thread_send_sync (MonoUtilityThread *thread, gpointer message) MonoSemType sem; mono_os_sem_init (&sem, 0); - UtilityThreadQueueEntry *entry = mono_lock_free_alloc (&thread->message_allocator); + UtilityThreadQueueEntry *entry = (UtilityThreadQueueEntry*)mono_lock_free_alloc (&thread->message_allocator); gboolean done; entry->finished = &done; diff --git a/mono/utils/mono-utils-debug.c b/mono/utils/mono-utils-debug.c index acc4115c4b..98ae4ba569 100644 --- a/mono/utils/mono-utils-debug.c +++ b/mono/utils/mono-utils-debug.c @@ -32,6 +32,9 @@ mono_is_usermode_native_debugger_present (void) #if defined (__NetBSD__) #include #endif +#if defined (_AIX) +#include +#endif static gboolean mono_is_usermode_native_debugger_present_slow (void) @@ -79,6 +82,14 @@ mono_is_usermode_native_debugger_present_slow (void) kvm_close (kd); return traced; +#elif defined (_AIX) + + struct procentry64 proc; + pid_t pid; + pid = getpid (); + getprocs64 (&proc, sizeof (proc), NULL, 0, &pid, 1); + return (proc.pi_flags & STRC) != 0; // SMPTRACE or SWTED might work too + #else return FALSE; // FIXME Other operating systems. #endif diff --git a/mono/utils/networking-posix.c b/mono/utils/networking-posix.c index 85a6eba551..142f4f846f 100644 --- a/mono/utils/networking-posix.c +++ b/mono/utils/networking-posix.c @@ -127,7 +127,24 @@ mono_get_address_info (const char *hostname, int port, int flags, MonoAddressInf #endif -#ifdef HAVE_GETPROTOBYNAME +#if defined(__linux__) && defined(HAVE_GETPROTOBYNAME_R) + +static int +fetch_protocol (const char *proto_name, int *cache, int *proto, int default_val) +{ + if (!*cache) { + struct protoent protoent_buf = { 0 }; + struct protoent *pent = NULL; + char buf[1024]; + + getprotobyname_r (proto_name, &protoent_buf, buf, 1024, &pent); + *proto = pent ? pent->p_proto : default_val; + *cache = 1; + } + return *proto; +} + +#elif HAVE_GETPROTOBYNAME static int fetch_protocol (const char *proto_name, int *cache, int *proto, int default_val) @@ -142,6 +159,8 @@ fetch_protocol (const char *proto_name, int *cache, int *proto, int default_val) return *proto; } +#endif + int mono_networking_get_tcp_protocol (void) { @@ -163,8 +182,6 @@ mono_networking_get_ipv6_protocol (void) return fetch_protocol ("ipv6", &cache, &proto, 41); //41 is SOL_IPV6 on linux } -#endif - #if defined (HAVE_SIOCGIFCONF) #define IFCONF_BUFF_SIZE 1024 diff --git a/mono/utils/os-event-unix.c b/mono/utils/os-event-unix.c index 9493501bb3..24b0b1d9a2 100644 --- a/mono/utils/os-event-unix.c +++ b/mono/utils/os-event-unix.c @@ -182,7 +182,7 @@ mono_os_event_wait_multiple (MonoOSEvent **events, gsize nevents, gboolean waita signalled = (count > 0); if (signalled) { - ret = MONO_OS_EVENT_WAIT_RET_SUCCESS_0 + lowest; + ret = (MonoOSEventWaitRet)(MONO_OS_EVENT_WAIT_RET_SUCCESS_0 + lowest); goto done; } diff --git a/mono/utils/os-event-win32.c b/mono/utils/os-event-win32.c index 095669a0e4..d85c31c74d 100644 --- a/mono/utils/os-event-win32.c +++ b/mono/utils/os-event-win32.c @@ -106,9 +106,9 @@ mono_os_event_wait_multiple (MonoOSEvent **events, gsize nevents, gboolean waita handles [i] = events [i]->handle; } - res = mono_win32_wait_for_multiple_objects_ex ((DWORD)nevents, handles, waitall, timeout, alertable); + res = mono_win32_wait_for_multiple_objects_ex ((DWORD)nevents, handles, waitall, timeout, alertable, NULL); if (res >= WAIT_OBJECT_0 && res < WAIT_OBJECT_0 + MONO_OS_EVENT_WAIT_MAXIMUM_OBJECTS) - return MONO_OS_EVENT_WAIT_RET_SUCCESS_0 + (res - WAIT_OBJECT_0); + return (MonoOSEventWaitRet)(MONO_OS_EVENT_WAIT_RET_SUCCESS_0 + (res - WAIT_OBJECT_0)); else if (res == WAIT_IO_COMPLETION) return MONO_OS_EVENT_WAIT_RET_ALERTED; else if (res == WAIT_TIMEOUT) diff --git a/mono/utils/w32api.h b/mono/utils/w32api.h index 45544c78fc..e7a0ce4c4c 100644 --- a/mono/utils/w32api.h +++ b/mono/utils/w32api.h @@ -7,8 +7,6 @@ #include -G_BEGIN_DECLS - #ifndef HOST_WIN32 #define WAIT_FAILED ((gint) 0xFFFFFFFF) @@ -57,6 +55,4 @@ typedef struct pollfd { #endif /* HOST_WIN32 */ -G_END_DECLS - #endif /* __MONO_UTILS_W32API_H__ */ diff --git a/msvc/Makefile.in b/msvc/Makefile.in index 230bab4fca..da162c720d 100644 --- a/msvc/Makefile.in +++ b/msvc/Makefile.in @@ -82,7 +82,8 @@ subdir = msvc DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs README ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -151,6 +152,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -224,6 +226,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/msvc/eglib.vcxproj b/msvc/eglib.vcxproj index c4845c3674..d8d275a00f 100644 --- a/msvc/eglib.vcxproj +++ b/msvc/eglib.vcxproj @@ -146,6 +146,11 @@ true + + + CompileAsCpp + + diff --git a/msvc/libgcmonosgen.vcxproj b/msvc/libgcmonosgen.vcxproj index f27c6652da..3db4e154d2 100644 --- a/msvc/libgcmonosgen.vcxproj +++ b/msvc/libgcmonosgen.vcxproj @@ -158,6 +158,11 @@ true + + + CompileAsCpp + + diff --git a/msvc/libmini.vcxproj b/msvc/libmini.vcxproj index 62e9def9d7..5e411d0eb6 100644 --- a/msvc/libmini.vcxproj +++ b/msvc/libmini.vcxproj @@ -194,6 +194,11 @@ %(AdditionalLibraryDirectories) + + + CompileAsCpp + + diff --git a/msvc/libmono-dynamic.vcxproj b/msvc/libmono-dynamic.vcxproj index 21e64c3495..cbb0d9a0d0 100644 --- a/msvc/libmono-dynamic.vcxproj +++ b/msvc/libmono-dynamic.vcxproj @@ -239,6 +239,11 @@ false + + + CompileAsCpp + + {b7098dfa-31e6-4006-8a15-1c9a4e925149} diff --git a/msvc/libmono-static.vcxproj b/msvc/libmono-static.vcxproj index 0c606ddb6a..19e7071fc1 100644 --- a/msvc/libmono-static.vcxproj +++ b/msvc/libmono-static.vcxproj @@ -194,6 +194,11 @@ true + + + CompileAsCpp + + {158073ed-99ae-4196-9edc-ddb2344f8466} diff --git a/msvc/libmonodac.vcxproj b/msvc/libmonodac.vcxproj index 57b5fdaea0..90f75e603e 100644 --- a/msvc/libmonodac.vcxproj +++ b/msvc/libmonodac.vcxproj @@ -131,6 +131,11 @@ + + + CompileAsCpp + + diff --git a/msvc/libmonoruntime.vcxproj b/msvc/libmonoruntime.vcxproj index b9b512dddb..0694b198a7 100644 --- a/msvc/libmonoruntime.vcxproj +++ b/msvc/libmonoruntime.vcxproj @@ -166,6 +166,11 @@ + + + CompileAsCpp + + diff --git a/msvc/libmonoutils.vcxproj b/msvc/libmonoutils.vcxproj index fd727132bc..e49c85fdbc 100644 --- a/msvc/libmonoutils.vcxproj +++ b/msvc/libmonoutils.vcxproj @@ -172,6 +172,11 @@ + + + CompileAsCpp + + \ No newline at end of file diff --git a/msvc/mono.props b/msvc/mono.props index 6098d6bf22..dd88cc7ab8 100644 --- a/msvc/mono.props +++ b/msvc/mono.props @@ -11,7 +11,7 @@ sgen true - + true false @@ -19,6 +19,8 @@ false false + + false .. @@ -109,6 +111,9 @@ $(MONO_ENABLE_LLVM) + + $(MONO_COMPILE_AS_CPP) + __default_codegen__;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_DEPRECATE;HAVE_CONFIG_H;GC_NOT_DLL;WIN32_THREADS;WINVER=0x0601;_WIN32_WINNT=0x0601;_WIN32_IE=0x0501;_UNICODE;UNICODE;FD_SETSIZE=1024;NVALGRIND;$(MONO_ADDITIONAL_PREPROCESSOR_DEFINITIONS) diff --git a/msvc/mono.vcxproj b/msvc/mono.vcxproj index 7567c5e3b9..b8de263f6c 100644 --- a/msvc/mono.vcxproj +++ b/msvc/mono.vcxproj @@ -181,6 +181,11 @@ Console + + + CompileAsCpp + + diff --git a/msvc/monodis.vcxproj b/msvc/monodis.vcxproj index 9f0bb69efb..a0a41bb6d7 100644 --- a/msvc/monodis.vcxproj +++ b/msvc/monodis.vcxproj @@ -178,6 +178,11 @@ $(MONO_STATIC_LIBMONO_LIB);%(AdditionalDependencies) + + + CompileAsCpp + + diff --git a/msvc/monograph.vcxproj b/msvc/monograph.vcxproj index 29ca2e961b..63b6b8bda8 100644 --- a/msvc/monograph.vcxproj +++ b/msvc/monograph.vcxproj @@ -178,6 +178,11 @@ $(MONO_STATIC_LIBMONO_LIB);%(AdditionalDependencies) + + + CompileAsCpp + + diff --git a/msvc/pedump.vcxproj b/msvc/pedump.vcxproj index d491a5bd26..c406117d73 100644 --- a/msvc/pedump.vcxproj +++ b/msvc/pedump.vcxproj @@ -178,6 +178,11 @@ Console + + + CompileAsCpp + + diff --git a/msvc/test_eglib.vcxproj b/msvc/test_eglib.vcxproj index 7ee098d017..cc2f07c237 100644 --- a/msvc/test_eglib.vcxproj +++ b/msvc/test_eglib.vcxproj @@ -170,6 +170,7 @@ + diff --git a/po/Makefile.in b/po/Makefile.in index 319bba5111..982726fd92 100644 --- a/po/Makefile.in +++ b/po/Makefile.in @@ -82,7 +82,8 @@ subdir = po DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -211,6 +212,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -284,6 +286,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/po/mcs/de.gmo b/po/mcs/de.gmo index 7c5457da17..6fc6cdd01c 100644 Binary files a/po/mcs/de.gmo and b/po/mcs/de.gmo differ diff --git a/po/mcs/de.po.REMOVED.git-id b/po/mcs/de.po.REMOVED.git-id index 366043d222..f19940309f 100644 --- a/po/mcs/de.po.REMOVED.git-id +++ b/po/mcs/de.po.REMOVED.git-id @@ -1 +1 @@ -0d6f9e68b14637f01fc605aab907a68465689bf5 \ No newline at end of file +73c024cfb2dccfe08f9b4d2038d16bacd0363749 \ No newline at end of file diff --git a/po/mcs/es.gmo b/po/mcs/es.gmo index 7176b46fec..326b3f00b6 100644 Binary files a/po/mcs/es.gmo and b/po/mcs/es.gmo differ diff --git a/po/mcs/es.po.REMOVED.git-id b/po/mcs/es.po.REMOVED.git-id index 05c47cbe77..9710057f61 100644 --- a/po/mcs/es.po.REMOVED.git-id +++ b/po/mcs/es.po.REMOVED.git-id @@ -1 +1 @@ -c4f4eb1c020a078a7099101fc4176449f64861d0 \ No newline at end of file +5e157b7f40154e83bbc6a001a22c6d09f86f4004 \ No newline at end of file diff --git a/po/mcs/ja.gmo b/po/mcs/ja.gmo index 170e312c4b..886e0f023f 100644 Binary files a/po/mcs/ja.gmo and b/po/mcs/ja.gmo differ diff --git a/po/mcs/ja.po.REMOVED.git-id b/po/mcs/ja.po.REMOVED.git-id index 22a9764683..e244c13327 100644 --- a/po/mcs/ja.po.REMOVED.git-id +++ b/po/mcs/ja.po.REMOVED.git-id @@ -1 +1 @@ -eff913c7db9bb2b96e499e48c6f74e15ac24cedb \ No newline at end of file +975e5a6f1b8467bca4ba7296b481e49b63b5d661 \ No newline at end of file diff --git a/po/mcs/mcs.pot b/po/mcs/mcs.pot index 91f80ddc87..276ce50eb1 100644 --- a/po/mcs/mcs.pot +++ b/po/mcs/mcs.pot @@ -6,9 +6,9 @@ #, fuzzy msgid "" msgstr "" -"Project-Id-Version: mono 5.18.0.252\n" +"Project-Id-Version: mono 5.20.0.180\n" "Report-Msgid-Bugs-To: http://www.mono-project.com/Bugs\n" -"POT-Creation-Date: 2019-02-04 08:06+0000\n" +"POT-Creation-Date: 2019-02-04 19:35+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -2475,15 +2475,15 @@ msgid "" "it returns by reference" msgstr "" -#: mcs/mcs/expression.cs:13332 +#: mcs/mcs/expression.cs:13336 msgid "An expression tree cannot contain a discard" msgstr "" -#: mcs/mcs/expression.cs:13346 +#: mcs/mcs/expression.cs:13350 msgid "Cannot infer the type of implicitly-typed discard" msgstr "" -#: mcs/mcs/expression.cs:13352 +#: mcs/mcs/expression.cs:13356 msgid "Cannot assign void to a discard" msgstr "" diff --git a/po/mcs/pt_BR.gmo b/po/mcs/pt_BR.gmo index 16584ff431..62999f4223 100644 Binary files a/po/mcs/pt_BR.gmo and b/po/mcs/pt_BR.gmo differ diff --git a/po/mcs/pt_BR.po.REMOVED.git-id b/po/mcs/pt_BR.po.REMOVED.git-id index 08f3362d4d..8963da9414 100644 --- a/po/mcs/pt_BR.po.REMOVED.git-id +++ b/po/mcs/pt_BR.po.REMOVED.git-id @@ -1 +1 @@ -fad36abef036a0b2f2053499b8327cc7c5b2ef52 \ No newline at end of file +4fa44b03007589288279cefa50910e57f96b7655 \ No newline at end of file diff --git a/runtime/Makefile.am b/runtime/Makefile.am index c9351859da..1503a84492 100644 --- a/runtime/Makefile.am +++ b/runtime/Makefile.am @@ -216,12 +216,12 @@ etc/mono/config: ../data/config Makefile $(symlinks) else \ echo "Unknown directory '$(abs_top_builddir)/support'" && false; \ fi - if test -d "$(abs_top_builddir)/mono/metadata"; then \ - sed 's,target="$$mono_libdir/libmono-system-native$(libsuffix)",target="$(abs_top_builddir)/mono/metadata/libmono-system-native.la",' $@ > $@.tmp \ + if test -d "$(abs_top_builddir)/mono/native"; then \ + sed 's,target="$$mono_libdir/$(MONO_NATIVE_LIBRARY_NAME)$(libsuffix)",target="$(abs_top_builddir)/mono/native/$(MONO_NATIVE_LIBRARY_NAME).la",' $@ > $@.tmp \ && mv $@.tmp $@ \ ; \ else \ - echo "Unknown directory '$(abs_top_builddir)/mono/metadata'" && false; \ + echo "Unknown directory '$(abs_top_builddir)/mono/native'" && false; \ fi if test -d "$(abs_top_builddir)/mono/btls/build-shared"; then \ sed 's,target="$$mono_libdir/libmono-btls-shared$(libsuffix)",target="$(abs_top_builddir)/mono/btls/build-shared/libmono-btls-shared$(libsuffix)",' $@ > $@.tmp \ diff --git a/runtime/Makefile.in b/runtime/Makefile.in index 1cdca75dfe..020a2248de 100644 --- a/runtime/Makefile.in +++ b/runtime/Makefile.in @@ -105,7 +105,8 @@ DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs $(srcdir)/mono-wrapper.in \ $(srcdir)/monodis-wrapper.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -175,6 +176,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -248,6 +250,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ @@ -681,12 +699,12 @@ etc/mono/config: ../data/config Makefile $(symlinks) else \ echo "Unknown directory '$(abs_top_builddir)/support'" && false; \ fi - if test -d "$(abs_top_builddir)/mono/metadata"; then \ - sed 's,target="$$mono_libdir/libmono-system-native$(libsuffix)",target="$(abs_top_builddir)/mono/metadata/libmono-system-native.la",' $@ > $@.tmp \ + if test -d "$(abs_top_builddir)/mono/native"; then \ + sed 's,target="$$mono_libdir/$(MONO_NATIVE_LIBRARY_NAME)$(libsuffix)",target="$(abs_top_builddir)/mono/native/$(MONO_NATIVE_LIBRARY_NAME).la",' $@ > $@.tmp \ && mv $@.tmp $@ \ ; \ else \ - echo "Unknown directory '$(abs_top_builddir)/mono/metadata'" && false; \ + echo "Unknown directory '$(abs_top_builddir)/mono/native'" && false; \ fi if test -d "$(abs_top_builddir)/mono/btls/build-shared"; then \ sed 's,target="$$mono_libdir/libmono-btls-shared$(libsuffix)",target="$(abs_top_builddir)/mono/btls/build-shared/libmono-btls-shared$(libsuffix)",' $@ > $@.tmp \ diff --git a/samples/Makefile.in b/samples/Makefile.in index 0a588aa72d..1e47755352 100644 --- a/samples/Makefile.in +++ b/samples/Makefile.in @@ -82,7 +82,8 @@ subdir = samples DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -151,6 +152,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -224,6 +226,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/scripts/Makefile.in b/scripts/Makefile.in index 5dcf0f31ad..5669881889 100644 --- a/scripts/Makefile.in +++ b/scripts/Makefile.in @@ -85,7 +85,8 @@ DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs $(srcdir)/mono-find-provides.in \ $(srcdir)/mono-find-requires.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -183,6 +184,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -256,6 +258,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/scripts/mono-package-runtime b/scripts/mono-package-runtime index 10e26f2693..e46266d074 100755 --- a/scripts/mono-package-runtime +++ b/scripts/mono-package-runtime @@ -1,7 +1,7 @@ -#!/bin/sh -extension=".dylib" +#!/bin/bash +extension="${LIBEXT:-.dylib}" if test `uname -o` = GNU/Linux; then - extension=".so" + extension="${LIBEXT:-.so}" fi if test x$2 = x; then diff --git a/scripts/mono-test-install b/scripts/mono-test-install index 3c1f74a889..0fd1b2bc32 100755 --- a/scripts/mono-test-install +++ b/scripts/mono-test-install @@ -110,7 +110,7 @@ class X { EOF if mcs -pkg:dotnet $temp_cs >& /dev/null; then if mono $temp_exe >& /dev/null; then - echo Your have a working System.Drawing setup + echo You have a working System.Drawing setup else echo Your system has a broken System.Drawing setup if mono $temp_exe 2>&1 | grep 'System.DllNotFoundException: gdiplus.dll' > /dev/null; then diff --git a/support/Makefile.in b/support/Makefile.in index 8ea35453a0..36f48f5b15 100644 --- a/support/Makefile.in +++ b/support/Makefile.in @@ -83,7 +83,8 @@ subdir = support DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs $(top_srcdir)/depcomp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -269,6 +270,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -342,6 +344,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/support/errno.c b/support/errno.c index 76b4b388e9..4864375e83 100644 --- a/support/errno.c +++ b/support/errno.c @@ -41,7 +41,7 @@ Mono_Posix_Stdlib_SetLastError (int error_number) * we assume that the XPG version is present. */ -#ifdef _GNU_SOURCE +#ifdef STRERROR_R_CHAR_P #define mph_min(x,y) ((x) <= (y) ? (x) : (y)) /* If you pass an invalid errno value to glibc 2.3.2's strerror_r, you get @@ -128,7 +128,7 @@ Mono_Posix_Syscall_strerror_r (int errnum, char *buf, mph_size_t n) return 0; } -#else /* !def _GNU_SOURCE */ +#else /* !def STRERROR_R_CHAR_P */ gint32 Mono_Posix_Syscall_strerror_r (int errnum, char *buf, mph_size_t n) @@ -137,7 +137,7 @@ Mono_Posix_Syscall_strerror_r (int errnum, char *buf, mph_size_t n) return strerror_r (errnum, buf, (size_t) n); } -#endif /* def _GNU_SOURCE */ +#endif /* def STRERROR_R_CHAR_P */ #endif /* def HAVE_STRERROR_R */ diff --git a/support/libm/complex.c b/support/libm/complex.c index 18a4f9bb8b..1eb004dd9a 100644 --- a/support/libm/complex.c +++ b/support/libm/complex.c @@ -10,14 +10,9 @@ * ==================================================== */ -#include - #include #include -#include "complex.h" -#include "math_private.h" - /*- * Copyright (c) 2004 Stefan Farfeleder * All rights reserved. @@ -46,20 +41,6 @@ * $FreeBSD$ */ -double -creal(double complex z) -{ - return z; -} - -double -cimag(double complex z) -{ - const double_complex z1 = { .f = z }; - - return (IMAGPART(z1)); -} - /* * cabs() wrapper for hypot(). * @@ -67,8 +48,13 @@ cimag(double complex z) * Placed into the Public Domain, 1994. */ +static inline double -cabs(double complex z) +cabs(double_complex z) { +#ifdef _MSC_VER // older versions deprecate hypot + return _hypot (creal (z), cimag (z)); +#else return hypot(creal(z), cimag(z)); +#endif } diff --git a/support/sys-mman.c b/support/sys-mman.c index 30b9897154..abf5015c74 100644 --- a/support/sys-mman.c +++ b/support/sys-mman.c @@ -89,7 +89,7 @@ Mono_Posix_Syscall_msync (void *start, mph_size_t len, int flags) int Mono_Posix_Syscall_mlock (void *start, mph_size_t len) { -#if !defined(HAVE_MINCORE) +#if !defined (HAVE_MLOCK) return ENOSYS; #else mph_return_if_size_t_overflow (len); @@ -101,7 +101,7 @@ Mono_Posix_Syscall_mlock (void *start, mph_size_t len) int Mono_Posix_Syscall_munlock (void *start, mph_size_t len) { -#if defined(__HAIKU__) +#if !defined (HAVE_MUNLOCK) return ENOSYS; #else mph_return_if_size_t_overflow (len); @@ -138,12 +138,17 @@ Mono_Posix_Syscall_mremap (void *old_address, mph_size_t old_size, int Mono_Posix_Syscall_mincore (void *start, mph_size_t length, unsigned char *vec) { -#if defined(__HAIKU__) +#if !defined (HAVE_MINCORE) return ENOSYS; #else mph_return_if_size_t_overflow (length); - return mincore (start, (size_t) length, (void*)vec); +#if defined (__linux__) || defined (HOST_WASM) + typedef unsigned char T; +#else + typedef char T; +#endif + return mincore (start, (size_t) length, (T*)vec); #endif } diff --git a/tools/Makefile.in b/tools/Makefile.in index 167d4544ee..7078dc9b70 100644 --- a/tools/Makefile.in +++ b/tools/Makefile.in @@ -82,7 +82,8 @@ subdir = tools DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -211,6 +212,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -284,6 +286,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/tools/locale-builder/Makefile.in b/tools/locale-builder/Makefile.in index 407ee9fd74..188cbf18d6 100644 --- a/tools/locale-builder/Makefile.in +++ b/tools/locale-builder/Makefile.in @@ -82,7 +82,8 @@ subdir = tools/locale-builder DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs README ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -151,6 +152,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -224,6 +226,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ diff --git a/tools/monograph/Makefile.am b/tools/monograph/Makefile.am index 10fb6c34e7..7c31726b17 100644 --- a/tools/monograph/Makefile.am +++ b/tools/monograph/Makefile.am @@ -25,15 +25,23 @@ bin_PROGRAMS = else if SUPPORT_SGEN bin_PROGRAMS = monograph +noinst_LIBRARIES = libmonograph.a endif endif endif +CFLAGS = $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) +libmonograph_a_CFLAGS = @CXX_ADD_CFLAGS@ + +monograph_SOURCES = +libmonograph_a_SOURCES = monograph.c + AM_CPPFLAGS = \ -I$(top_srcdir) \ $(GLIB_CFLAGS) monograph_LDADD = \ + libmonograph_a-monograph.$(OBJEXT) \ $(runtime_lib) \ $(glib_libs) \ $(LLVM_LIBS) @@ -50,5 +58,3 @@ graphs: $(OUT) %.jpeg: monograph ./monograph -n -o $*.png corlib.dll $* convert -geometry '480x360>' $*.png $*.jpeg - - diff --git a/tools/monograph/Makefile.in b/tools/monograph/Makefile.in index ddbf95aa81..36e484922d 100644 --- a/tools/monograph/Makefile.in +++ b/tools/monograph/Makefile.in @@ -14,6 +14,7 @@ @SET_MAKE@ + VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ @@ -84,7 +85,8 @@ subdir = tools/monograph DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs $(top_srcdir)/depcomp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -96,11 +98,22 @@ mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = +LIBRARIES = $(noinst_LIBRARIES) +ARFLAGS = cru +AM_V_AR = $(am__v_AR_@AM_V@) +am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@) +am__v_AR_0 = @echo " AR " $@; +am__v_AR_1 = +libmonograph_a_AR = $(AR) $(ARFLAGS) +libmonograph_a_LIBADD = +am_libmonograph_a_OBJECTS = libmonograph_a-monograph.$(OBJEXT) +libmonograph_a_OBJECTS = $(am_libmonograph_a_OBJECTS) am__installdirs = "$(DESTDIR)$(bindir)" PROGRAMS = $(bin_PROGRAMS) -monograph_SOURCES = monograph.c -monograph_OBJECTS = monograph.$(OBJEXT) -monograph_DEPENDENCIES = $(runtime_lib) $(glib_libs) +am_monograph_OBJECTS = +monograph_OBJECTS = $(am_monograph_OBJECTS) +monograph_DEPENDENCIES = libmonograph_a-monograph.$(OBJEXT) \ + $(runtime_lib) $(glib_libs) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent @@ -138,8 +151,8 @@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = -SOURCES = monograph.c -DIST_SOURCES = monograph.c +SOURCES = $(libmonograph_a_SOURCES) $(monograph_SOURCES) +DIST_SOURCES = $(libmonograph_a_SOURCES) $(monograph_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ @@ -191,7 +204,7 @@ CCASDEPMODE = @CCASDEPMODE@ CCASFLAGS = @CCASFLAGS@ CCDEPMODE = @CCDEPMODE@ CC_FOR_BUILD = @CC_FOR_BUILD@ -CFLAGS = @CFLAGS@ +CFLAGS = $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) CFLAGS_FOR_BUILD = @CFLAGS_FOR_BUILD@ CMAKE = @CMAKE@ CPP = @CPP@ @@ -201,6 +214,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -274,6 +288,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ @@ -405,11 +435,16 @@ glib_libs = $(top_builddir)/mono/eglib/libeglib.la @DISABLE_EXECUTABLES_FALSE@ $(top_builddir)/mono/utils/libmonoutils.la \ @DISABLE_EXECUTABLES_FALSE@ $(glib_libs) +@DISABLE_EXECUTABLES_FALSE@@DISABLE_LIBRARIES_FALSE@@SUPPORT_SGEN_TRUE@noinst_LIBRARIES = libmonograph.a +libmonograph_a_CFLAGS = @CXX_ADD_CFLAGS@ +monograph_SOURCES = +libmonograph_a_SOURCES = monograph.c AM_CPPFLAGS = \ -I$(top_srcdir) \ $(GLIB_CFLAGS) monograph_LDADD = \ + libmonograph_a-monograph.$(OBJEXT) \ $(runtime_lib) \ $(glib_libs) \ $(LLVM_LIBS) @@ -451,6 +486,14 @@ $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): + +clean-noinstLIBRARIES: + -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) + +libmonograph.a: $(libmonograph_a_OBJECTS) $(libmonograph_a_DEPENDENCIES) $(EXTRA_libmonograph_a_DEPENDENCIES) + $(AM_V_at)-rm -f libmonograph.a + $(AM_V_AR)$(libmonograph_a_AR) libmonograph.a $(libmonograph_a_OBJECTS) $(libmonograph_a_LIBADD) + $(AM_V_at)$(RANLIB) libmonograph.a install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ @@ -511,7 +554,7 @@ mostlyclean-compile: distclean-compile: -rm -f *.tab.c -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/monograph.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmonograph_a-monograph.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @@ -537,6 +580,20 @@ distclean-compile: @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< +libmonograph_a-monograph.o: monograph.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonograph_a_CFLAGS) $(CFLAGS) -MT libmonograph_a-monograph.o -MD -MP -MF $(DEPDIR)/libmonograph_a-monograph.Tpo -c -o libmonograph_a-monograph.o `test -f 'monograph.c' || echo '$(srcdir)/'`monograph.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmonograph_a-monograph.Tpo $(DEPDIR)/libmonograph_a-monograph.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='monograph.c' object='libmonograph_a-monograph.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonograph_a_CFLAGS) $(CFLAGS) -c -o libmonograph_a-monograph.o `test -f 'monograph.c' || echo '$(srcdir)/'`monograph.c + +libmonograph_a-monograph.obj: monograph.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonograph_a_CFLAGS) $(CFLAGS) -MT libmonograph_a-monograph.obj -MD -MP -MF $(DEPDIR)/libmonograph_a-monograph.Tpo -c -o libmonograph_a-monograph.obj `if test -f 'monograph.c'; then $(CYGPATH_W) 'monograph.c'; else $(CYGPATH_W) '$(srcdir)/monograph.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmonograph_a-monograph.Tpo $(DEPDIR)/libmonograph_a-monograph.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='monograph.c' object='libmonograph_a-monograph.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonograph_a_CFLAGS) $(CFLAGS) -c -o libmonograph_a-monograph.obj `if test -f 'monograph.c'; then $(CYGPATH_W) 'monograph.c'; else $(CYGPATH_W) '$(srcdir)/monograph.c'; fi` + mostlyclean-libtool: -rm -f *.lo @@ -627,7 +684,7 @@ distdir: $(DISTFILES) done check-am: all-am check: check-am -all-am: Makefile $(PROGRAMS) +all-am: Makefile $(LIBRARIES) $(PROGRAMS) installdirs: for dir in "$(DESTDIR)$(bindir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ @@ -664,7 +721,8 @@ maintainer-clean-generic: @echo "it deletes files that may require special tools to rebuild." clean: clean-am -clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am +clean-am: clean-binPROGRAMS clean-generic clean-libtool \ + clean-noinstLIBRARIES mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) @@ -735,15 +793,16 @@ uninstall-am: uninstall-binPROGRAMS .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean \ - clean-binPROGRAMS clean-generic clean-libtool cscopelist-am \ - ctags ctags-am distclean distclean-compile distclean-generic \ - distclean-libtool distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-binPROGRAMS \ - install-data install-data-am install-dvi install-dvi-am \ - install-exec install-exec-am install-html install-html-am \ - install-info install-info-am install-man install-pdf \ - install-pdf-am install-ps install-ps-am install-strip \ - installcheck installcheck-am installdirs maintainer-clean \ + clean-binPROGRAMS clean-generic clean-libtool \ + clean-noinstLIBRARIES cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-binPROGRAMS install-data \ + install-data-am install-dvi install-dvi-am install-exec \ + install-exec-am install-html install-html-am install-info \ + install-info-am install-man install-pdf install-pdf-am \ + install-ps install-ps-am install-strip installcheck \ + installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am uninstall-binPROGRAMS diff --git a/tools/monograph/monograph.c b/tools/monograph/monograph.c index 13fce57c6c..6d4c7b9bac 100644 --- a/tools/monograph/monograph.c +++ b/tools/monograph/monograph.c @@ -35,7 +35,7 @@ output_type_edge (MonoClass *first, MonoClass *second) { } static void -print_subtypes (MonoImage *image, MonoClass *class, int depth) { +print_subtypes (MonoImage *image, MonoClass *klass, int depth) { int i, token; const MonoTableInfo *t; MonoClass *child; @@ -45,7 +45,7 @@ print_subtypes (MonoImage *image, MonoClass *class, int depth) { t = mono_image_get_table_info (image, MONO_TABLE_TYPEDEF); - token = mono_metadata_token_index (mono_class_get_type_token (class)); + token = mono_metadata_token_index (mono_class_get_type_token (klass)); token <<= MONO_TYPEDEFORREF_BITS; token |= MONO_TYPEDEFORREF_TYPEDEF; @@ -53,22 +53,22 @@ print_subtypes (MonoImage *image, MonoClass *class, int depth) { for (i = 0; i < mono_table_info_get_rows (t); ++i) { if (token == mono_metadata_decode_row_col (t, i, MONO_TYPEDEF_EXTENDS)) { child = mono_class_get (image, MONO_TOKEN_TYPE_DEF | (i + 1)); - output_type_edge (class, child); + output_type_edge (klass, child); print_subtypes (image, child, depth); } } } static void -type_graph (MonoImage *image, const char* cname) { - MonoClass *class; +type_graph (MonoImage *image, const char* const_cname) { + MonoClass *klass; MonoClass *parent; MonoClass *child; const char *name_space; char *p; int depth = 0; - cname = g_strdup (cname); + char *cname = g_strdup (const_cname); p = strrchr (cname, '.'); if (p) { name_space = cname; @@ -77,26 +77,26 @@ type_graph (MonoImage *image, const char* cname) { } else { name_space = ""; } - class = mono_class_from_name (image, name_space, cname); - if (!class) { + klass = mono_class_from_name (image, name_space, cname); + if (!klass) { g_print ("class %s.%s not found\n", name_space, cname); exit (1); } fprintf (output, "digraph blah {\n"); fprintf (output, "%s", graph_properties); - child = class; + child = klass; /* go back and print the parents for the node as well: not sure it's a good idea */ - for (parent = mono_class_get_parent (class); parent; parent = mono_class_get_parent (parent)) { + for (parent = mono_class_get_parent (klass); parent; parent = mono_class_get_parent (parent)) { output_type_edge (parent, child); child = parent; } - print_subtypes (image, class, depth); + print_subtypes (image, klass, depth); fprintf (output, "}\n"); } static void -interface_graph (MonoImage *image, const char* cname) { - MonoClass *class; +interface_graph (MonoImage *image, const char* const_cname) { + MonoClass *klass; MonoClass *child; const char *name_space; char *p; @@ -104,7 +104,7 @@ interface_graph (MonoImage *image, const char* cname) { guint32 token, i, count = 0; const MonoTableInfo *intf = mono_image_get_table_info (image, MONO_TABLE_INTERFACEIMPL); - cname = g_strdup (cname); + char *cname = g_strdup (const_cname); p = strrchr (cname, '.'); if (p) { name_space = cname; @@ -113,8 +113,8 @@ interface_graph (MonoImage *image, const char* cname) { } else { name_space = ""; } - class = mono_class_from_name (image, name_space, cname); - if (!class) { + klass = mono_class_from_name (image, name_space, cname); + if (!klass) { g_print ("interface %s.%s not found\n", name_space, cname); exit (1); } @@ -122,7 +122,7 @@ interface_graph (MonoImage *image, const char* cname) { fprintf (output, "digraph interface {\n"); fprintf (output, "%s", graph_properties); /* TODO: handle inetrface defined in one image and class defined in another. */ - token = mono_metadata_token_index (mono_class_get_type_token (class)); + token = mono_metadata_token_index (mono_class_get_type_token (klass)); token <<= MONO_TYPEDEFORREF_BITS; token |= MONO_TYPEDEFORREF_TYPEDEF; for (i = 0; i < mono_table_info_get_rows (intf); ++i) { @@ -130,13 +130,13 @@ interface_graph (MonoImage *image, const char* cname) { /*g_print ("index: %d [%d implements %d]\n", index, cols [MONO_INTERFACEIMPL_CLASS], cols [MONO_INTERFACEIMPL_INTERFACE]);*/ if (token == cols [MONO_INTERFACEIMPL_INTERFACE]) { child = mono_class_get (image, MONO_TOKEN_TYPE_DEF | cols [MONO_INTERFACEIMPL_CLASS]); - output_type_edge (class, child); + output_type_edge (klass, child); count++; } } fprintf (output, "}\n"); if (verbose && !count) - g_print ("No class implements %s.%s\n", mono_class_get_namespace (class), mono_class_get_name (class)); + g_print ("No class implements %s.%s\n", mono_class_get_namespace (klass), mono_class_get_name (klass)); } @@ -554,7 +554,7 @@ get_signature (MonoMethod *method) { if (!hash) hash = g_hash_table_new (g_direct_hash, g_direct_equal); - if ((result = g_hash_table_lookup (hash, method))) + if ((result = (char*)g_hash_table_lookup (hash, method))) return result; res = g_string_new (""); @@ -743,8 +743,8 @@ link_bblock (MonoBasicBlock *from, MonoBasicBlock* to) static int compare_bblock (const void *a, const void *b) { - MonoBasicBlock * const *ab = a; - MonoBasicBlock * const *bb = b; + MonoBasicBlock * const *ab = (MonoBasicBlock * const *)a; + MonoBasicBlock * const *bb = (MonoBasicBlock * const *)b; return (*ab)->cil_code - (*bb)->cil_code; } @@ -752,7 +752,7 @@ compare_bblock (const void *a, const void *b) static GPtrArray* mono_method_find_bblocks (MonoMethodHeader *header) { - const unsigned char *ip, *end, *start; + const unsigned char *ip, *end; const MonoOpcode *opcode; guint32 i, block_end = 0; GPtrArray *result = g_ptr_array_new (); @@ -777,8 +777,7 @@ mono_method_find_bblocks (MonoMethodHeader *header) /* handle exception code blocks... */ while (ip < end) { - start = ip; - if ((target = g_hash_table_lookup (table, ip)) && target != bb) { + if ((target = (MonoBasicBlock*)g_hash_table_lookup (table, ip)) && target != bb) { if (!block_end) link_bblock (bb, target); bb = target; @@ -786,7 +785,7 @@ mono_method_find_bblocks (MonoMethodHeader *header) } if (block_end) { /*fprintf (stderr, "processing bbclok at IL_%04x\n", ip - header->code);*/ - if (!(bb = g_hash_table_lookup (table, ip))) { + if (!(bb = (MonoBasicBlock*)g_hash_table_lookup (table, ip))) { bb = g_new0 (MonoBasicBlock, 1); bb->cil_code = ip; g_ptr_array_add (result, bb); @@ -849,7 +848,7 @@ mono_method_find_bblocks (MonoMethodHeader *header) ip += 4; } if (opcode->flow_type == MONO_FLOW_COND_BRANCH) { - if (!(target = g_hash_table_lookup (table, ip))) { + if (!(target = (MonoBasicBlock*)g_hash_table_lookup (table, ip))) { target = g_new0 (MonoBasicBlock, 1); target->cil_code = ip; g_ptr_array_add (result, target); @@ -857,7 +856,7 @@ mono_method_find_bblocks (MonoMethodHeader *header) } link_bblock (bb, target); } - if (!(target = g_hash_table_lookup (table, ip + i))) { + if (!(target = (MonoBasicBlock*)g_hash_table_lookup (table, ip + i))) { target = g_new0 (MonoBasicBlock, 1); target->cil_code = ip + i; g_ptr_array_add (result, target); @@ -877,7 +876,7 @@ mono_method_find_bblocks (MonoMethodHeader *header) for (i = 0; i < n; i++) { itarget = st + read32 (ip); ip += 4; - if (!(target = g_hash_table_lookup (table, itarget))) { + if (!(target = (MonoBasicBlock*)g_hash_table_lookup (table, itarget))) { target = g_new0 (MonoBasicBlock, 1); target->cil_code = (const guchar*)itarget; g_ptr_array_add (result, target); @@ -940,7 +939,7 @@ df_visit (MonoBasicBlock *bb, int *dfn, const unsigned char* code) ++(*dfn); bb->dfn = *dfn; for (tmp = bb->out_bb; tmp; tmp = tmp->next) { - next = tmp->data; + next = (MonoBasicBlock*)tmp->data; if (!next->dfn) { if (!bb->cil_code) fprintf (output, "\t\"DF entry\" -> \"IL_%04x (%d)\"\n", (unsigned int)(next->cil_code - code), *dfn + 1); @@ -979,7 +978,7 @@ print_method_cfg (MonoMethod *method) { for (i = 0; i < bblocks->len; ++i) { bb = (MonoBasicBlock*)g_ptr_array_index (bblocks, i); for (tmp = bb->out_bb; tmp; tmp = tmp->next) { - target = tmp->data; + target = (MonoBasicBlock*)tmp->data; fprintf (output, "\tB%p -> B%p\n", bb, target); } } diff --git a/tools/pedump/Makefile.am b/tools/pedump/Makefile.am index 1babe62018..f45fce5b1e 100644 --- a/tools/pedump/Makefile.am +++ b/tools/pedump/Makefile.am @@ -11,14 +11,18 @@ bin_PROGRAMS = else if SUPPORT_SGEN bin_PROGRAMS = pedump +noinst_LIBRARIES = libpedump.a endif endif endif -pedump_SOURCES = \ - pedump.c +CFLAGS = $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) +libpedump_a_CFLAGS = @CXX_ADD_CFLAGS@ +pedump_SOURCES = +libpedump_a_SOURCES = pedump.c pedump_LDADD = \ + libpedump_a-pedump.$(OBJEXT) \ $(top_builddir)/mono/metadata/libmonoruntimesgen.la \ $(top_builddir)/mono/sgen/libmonosgen.la \ $(top_builddir)/mono/utils/libmonoutils.la \ diff --git a/tools/pedump/Makefile.in b/tools/pedump/Makefile.in index 6d008f2900..31d5ad5233 100644 --- a/tools/pedump/Makefile.in +++ b/tools/pedump/Makefile.in @@ -14,6 +14,7 @@ @SET_MAKE@ + VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ @@ -84,7 +85,8 @@ subdir = tools/pedump DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs $(top_srcdir)/depcomp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -96,11 +98,21 @@ mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = +LIBRARIES = $(noinst_LIBRARIES) +ARFLAGS = cru +AM_V_AR = $(am__v_AR_@AM_V@) +am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@) +am__v_AR_0 = @echo " AR " $@; +am__v_AR_1 = +libpedump_a_AR = $(AR) $(ARFLAGS) +libpedump_a_LIBADD = +am_libpedump_a_OBJECTS = libpedump_a-pedump.$(OBJEXT) +libpedump_a_OBJECTS = $(am_libpedump_a_OBJECTS) am__installdirs = "$(DESTDIR)$(bindir)" PROGRAMS = $(bin_PROGRAMS) -am_pedump_OBJECTS = pedump.$(OBJEXT) +am_pedump_OBJECTS = pedump_OBJECTS = $(am_pedump_OBJECTS) -pedump_DEPENDENCIES = \ +pedump_DEPENDENCIES = libpedump_a-pedump.$(OBJEXT) \ $(top_builddir)/mono/metadata/libmonoruntimesgen.la \ $(top_builddir)/mono/sgen/libmonosgen.la \ $(top_builddir)/mono/utils/libmonoutils.la $(glib_libs) @@ -141,8 +153,8 @@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = -SOURCES = $(pedump_SOURCES) -DIST_SOURCES = $(pedump_SOURCES) +SOURCES = $(libpedump_a_SOURCES) $(pedump_SOURCES) +DIST_SOURCES = $(libpedump_a_SOURCES) $(pedump_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ @@ -194,7 +206,7 @@ CCASDEPMODE = @CCASDEPMODE@ CCASFLAGS = @CCASFLAGS@ CCDEPMODE = @CCDEPMODE@ CC_FOR_BUILD = @CC_FOR_BUILD@ -CFLAGS = @CFLAGS@ +CFLAGS = $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) CFLAGS_FOR_BUILD = @CFLAGS_FOR_BUILD@ CMAKE = @CMAKE@ CPP = @CPP@ @@ -204,6 +216,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -277,6 +290,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ @@ -401,10 +430,12 @@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = -I$(top_srcdir) -I$(top_srcdir)/mono $(LIBGC_CPPFLAGS) $(GLIB_CFLAGS) $(SHARED_CFLAGS) glib_libs = $(top_builddir)/mono/eglib/libeglib.la -pedump_SOURCES = \ - pedump.c - +@DISABLE_EXECUTABLES_FALSE@@DISABLE_LIBRARIES_FALSE@@SUPPORT_SGEN_TRUE@noinst_LIBRARIES = libpedump.a +libpedump_a_CFLAGS = @CXX_ADD_CFLAGS@ +pedump_SOURCES = +libpedump_a_SOURCES = pedump.c pedump_LDADD = \ + libpedump_a-pedump.$(OBJEXT) \ $(top_builddir)/mono/metadata/libmonoruntimesgen.la \ $(top_builddir)/mono/sgen/libmonosgen.la \ $(top_builddir)/mono/utils/libmonoutils.la \ @@ -447,6 +478,14 @@ $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): + +clean-noinstLIBRARIES: + -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) + +libpedump.a: $(libpedump_a_OBJECTS) $(libpedump_a_DEPENDENCIES) $(EXTRA_libpedump_a_DEPENDENCIES) + $(AM_V_at)-rm -f libpedump.a + $(AM_V_AR)$(libpedump_a_AR) libpedump.a $(libpedump_a_OBJECTS) $(libpedump_a_LIBADD) + $(AM_V_at)$(RANLIB) libpedump.a install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ @@ -507,7 +546,7 @@ mostlyclean-compile: distclean-compile: -rm -f *.tab.c -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pedump.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libpedump_a-pedump.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @@ -533,6 +572,20 @@ distclean-compile: @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< +libpedump_a-pedump.o: pedump.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libpedump_a_CFLAGS) $(CFLAGS) -MT libpedump_a-pedump.o -MD -MP -MF $(DEPDIR)/libpedump_a-pedump.Tpo -c -o libpedump_a-pedump.o `test -f 'pedump.c' || echo '$(srcdir)/'`pedump.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libpedump_a-pedump.Tpo $(DEPDIR)/libpedump_a-pedump.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='pedump.c' object='libpedump_a-pedump.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libpedump_a_CFLAGS) $(CFLAGS) -c -o libpedump_a-pedump.o `test -f 'pedump.c' || echo '$(srcdir)/'`pedump.c + +libpedump_a-pedump.obj: pedump.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libpedump_a_CFLAGS) $(CFLAGS) -MT libpedump_a-pedump.obj -MD -MP -MF $(DEPDIR)/libpedump_a-pedump.Tpo -c -o libpedump_a-pedump.obj `if test -f 'pedump.c'; then $(CYGPATH_W) 'pedump.c'; else $(CYGPATH_W) '$(srcdir)/pedump.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libpedump_a-pedump.Tpo $(DEPDIR)/libpedump_a-pedump.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='pedump.c' object='libpedump_a-pedump.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libpedump_a_CFLAGS) $(CFLAGS) -c -o libpedump_a-pedump.obj `if test -f 'pedump.c'; then $(CYGPATH_W) 'pedump.c'; else $(CYGPATH_W) '$(srcdir)/pedump.c'; fi` + mostlyclean-libtool: -rm -f *.lo @@ -623,7 +676,7 @@ distdir: $(DISTFILES) done check-am: all-am check: check-am -all-am: Makefile $(PROGRAMS) +all-am: Makefile $(LIBRARIES) $(PROGRAMS) installdirs: for dir in "$(DESTDIR)$(bindir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ @@ -660,7 +713,8 @@ maintainer-clean-generic: @echo "it deletes files that may require special tools to rebuild." clean: clean-am -clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am +clean-am: clean-binPROGRAMS clean-generic clean-libtool \ + clean-noinstLIBRARIES mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) @@ -731,15 +785,16 @@ uninstall-am: uninstall-binPROGRAMS .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean \ - clean-binPROGRAMS clean-generic clean-libtool cscopelist-am \ - ctags ctags-am distclean distclean-compile distclean-generic \ - distclean-libtool distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-binPROGRAMS \ - install-data install-data-am install-dvi install-dvi-am \ - install-exec install-exec-am install-html install-html-am \ - install-info install-info-am install-man install-pdf \ - install-pdf-am install-ps install-ps-am install-strip \ - installcheck installcheck-am installdirs maintainer-clean \ + clean-binPROGRAMS clean-generic clean-libtool \ + clean-noinstLIBRARIES cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-binPROGRAMS install-data \ + install-data-am install-dvi install-dvi-am install-exec \ + install-exec-am install-html install-html-am install-info \ + install-info-am install-man install-pdf install-pdf-am \ + install-ps install-ps-am install-strip installcheck \ + installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am uninstall-binPROGRAMS diff --git a/tools/sgen/Makefile.am b/tools/sgen/Makefile.am index ed7786e460..bcc2105051 100644 --- a/tools/sgen/Makefile.am +++ b/tools/sgen/Makefile.am @@ -5,6 +5,20 @@ AM_CPPFLAGS = $(GLIB_CFLAGS) -I$(top_srcdir) glib_libs = $(top_builddir)/mono/eglib/libeglib.la noinst_LIBRARIES = libsgen-grep-binprot.a libsgen-grep-binprot32p.a libsgen-grep-binprot64p.a + +# Main is in a library so it can be C++. +noinst_LIBRARIES += libmain.a + +# Default to C so the executable is linked as C and does not use libstdc++. +# Also the -xc++ flag mishandles .o and .a files. +CFLAGS = $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) + +# Libraries are C++ if enabled. +libmain_a_CFLAGS = @CXX_ADD_CFLAGS@ +libsgen_grep_binprot_a_CFLAGS = @CXX_ADD_CFLAGS@ +libsgen_grep_binprot32p_a_CFLAGS = @CXX_ADD_CFLAGS@ +libsgen_grep_binprot64p_a_CFLAGS = @CXX_ADD_CFLAGS@ + libsgen_grep_binprot_a_SOURCES = sgen-grep-binprot.c sgen-grep-binprot.h libsgen_grep_binprot_a_CPPFLAGS = $(GLIB_CFLAGS) -I$(top_srcdir) libsgen_grep_binprot32p_a_SOURCES = sgen-grep-binprot.c sgen-grep-binprot.h @@ -12,10 +26,16 @@ libsgen_grep_binprot32p_a_CPPFLAGS = $(GLIB_CFLAGS) -I$(top_srcdir) -DBINPROT_SI libsgen_grep_binprot64p_a_SOURCES = sgen-grep-binprot.c sgen-grep-binprot.h libsgen_grep_binprot64p_a_CPPFLAGS = $(GLIB_CFLAGS) -I$(top_srcdir) -DBINPROT_SIZEOF_VOID_P=8 -DBINPROT_HAS_HEADER -sgen_grep_binprot_SOURCES = \ +# Executable has no source files, just links to object files and libraries. +sgen_grep_binprot_SOURCES = + +libmain_a_SOURCES = \ sgen-grep-binprot-main.c \ sgen-entry-stream.c \ sgen-entry-stream.h +# Link to the libmain object files instead of library for higher fidelity with old behavior. sgen_grep_binprot_LDADD = \ + libmain_a-sgen-grep-binprot-main.$(OBJEXT) \ + libmain_a-sgen-entry-stream.$(OBJEXT) \ $(glib_libs) libsgen-grep-binprot.a libsgen-grep-binprot32p.a libsgen-grep-binprot64p.a diff --git a/tools/sgen/Makefile.in b/tools/sgen/Makefile.in index 80f345a76c..36e55810fc 100644 --- a/tools/sgen/Makefile.in +++ b/tools/sgen/Makefile.in @@ -85,7 +85,8 @@ subdir = tools/sgen DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs $(top_srcdir)/depcomp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_check_compile_flag.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/apple-target.m4 \ + $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/nls.m4 \ @@ -103,6 +104,11 @@ AM_V_AR = $(am__v_AR_@AM_V@) am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@) am__v_AR_0 = @echo " AR " $@; am__v_AR_1 = +libmain_a_AR = $(AR) $(ARFLAGS) +libmain_a_LIBADD = +am_libmain_a_OBJECTS = libmain_a-sgen-grep-binprot-main.$(OBJEXT) \ + libmain_a-sgen-entry-stream.$(OBJEXT) +libmain_a_OBJECTS = $(am_libmain_a_OBJECTS) libsgen_grep_binprot_a_AR = $(AR) $(ARFLAGS) libsgen_grep_binprot_a_LIBADD = am_libsgen_grep_binprot_a_OBJECTS = \ @@ -122,11 +128,13 @@ libsgen_grep_binprot64p_a_OBJECTS = \ $(am_libsgen_grep_binprot64p_a_OBJECTS) am__installdirs = "$(DESTDIR)$(bindir)" PROGRAMS = $(bin_PROGRAMS) -am_sgen_grep_binprot_OBJECTS = sgen-grep-binprot-main.$(OBJEXT) \ - sgen-entry-stream.$(OBJEXT) +am_sgen_grep_binprot_OBJECTS = sgen_grep_binprot_OBJECTS = $(am_sgen_grep_binprot_OBJECTS) -sgen_grep_binprot_DEPENDENCIES = $(glib_libs) libsgen-grep-binprot.a \ - libsgen-grep-binprot32p.a libsgen-grep-binprot64p.a +sgen_grep_binprot_DEPENDENCIES = \ + libmain_a-sgen-grep-binprot-main.$(OBJEXT) \ + libmain_a-sgen-entry-stream.$(OBJEXT) $(glib_libs) \ + libsgen-grep-binprot.a libsgen-grep-binprot32p.a \ + libsgen-grep-binprot64p.a AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent @@ -161,11 +169,11 @@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = -SOURCES = $(libsgen_grep_binprot_a_SOURCES) \ +SOURCES = $(libmain_a_SOURCES) $(libsgen_grep_binprot_a_SOURCES) \ $(libsgen_grep_binprot32p_a_SOURCES) \ $(libsgen_grep_binprot64p_a_SOURCES) \ $(sgen_grep_binprot_SOURCES) -DIST_SOURCES = $(libsgen_grep_binprot_a_SOURCES) \ +DIST_SOURCES = $(libmain_a_SOURCES) $(libsgen_grep_binprot_a_SOURCES) \ $(libsgen_grep_binprot32p_a_SOURCES) \ $(libsgen_grep_binprot64p_a_SOURCES) \ $(sgen_grep_binprot_SOURCES) @@ -220,7 +228,10 @@ CCASDEPMODE = @CCASDEPMODE@ CCASFLAGS = @CCASFLAGS@ CCDEPMODE = @CCDEPMODE@ CC_FOR_BUILD = @CC_FOR_BUILD@ -CFLAGS = @CFLAGS@ + +# Default to C so the executable is linked as C and does not use libstdc++. +# Also the -xc++ flag mishandles .o and .a files. +CFLAGS = $(filter-out @CXX_REMOVE_CFLAGS@, @CFLAGS@) CFLAGS_FOR_BUILD = @CFLAGS_FOR_BUILD@ CMAKE = @CMAKE@ CPP = @CPP@ @@ -230,6 +241,7 @@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ +CXXFLAGS_COMMON = @CXXFLAGS_COMMON@ CXX_ADD_CFLAGS = @CXX_ADD_CFLAGS@ CXX_REMOVE_CFLAGS = @CXX_REMOVE_CFLAGS@ CYGPATH_W = @CYGPATH_W@ @@ -303,6 +315,22 @@ MONO_DL_NEED_USCORE = @MONO_DL_NEED_USCORE@ MONO_JEMALLOC_ASSERT = @MONO_JEMALLOC_ASSERT@ MONO_JEMALLOC_DEFAULT = @MONO_JEMALLOC_DEFAULT@ MONO_JEMALLOC_ENABLED = @MONO_JEMALLOC_ENABLED@ +MONO_NATIVE_CC = @MONO_NATIVE_CC@ +MONO_NATIVE_CFLAGS = @MONO_NATIVE_CFLAGS@ +MONO_NATIVE_COMPAT_CFLAGS = @MONO_NATIVE_COMPAT_CFLAGS@ +MONO_NATIVE_COMPAT_LDFLAGS = @MONO_NATIVE_COMPAT_LDFLAGS@ +MONO_NATIVE_CPPFLAGS = @MONO_NATIVE_CPPFLAGS@ +MONO_NATIVE_CXX = @MONO_NATIVE_CXX@ +MONO_NATIVE_CXXFLAGS = @MONO_NATIVE_CXXFLAGS@ +MONO_NATIVE_LDFLAGS = @MONO_NATIVE_LDFLAGS@ +MONO_NATIVE_LIBADD = @MONO_NATIVE_LIBADD@ +MONO_NATIVE_LIBRARY_NAME = @MONO_NATIVE_LIBRARY_NAME@ +MONO_NATIVE_PLATFORM = @MONO_NATIVE_PLATFORM@ +MONO_NATIVE_PLATFORM_TYPE = @MONO_NATIVE_PLATFORM_TYPE@ +MONO_NATIVE_PLATFORM_TYPE_COMPAT = @MONO_NATIVE_PLATFORM_TYPE_COMPAT@ +MONO_NATIVE_PLATFORM_TYPE_UNIFIED = @MONO_NATIVE_PLATFORM_TYPE_UNIFIED@ +MONO_NATIVE_UNIFIED_CFLAGS = @MONO_NATIVE_UNIFIED_CFLAGS@ +MONO_NATIVE_UNIFIED_LDFLAGS = @MONO_NATIVE_UNIFIED_LDFLAGS@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ @@ -427,19 +455,35 @@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = $(GLIB_CFLAGS) -I$(top_srcdir) glib_libs = $(top_builddir)/mono/eglib/libeglib.la -noinst_LIBRARIES = libsgen-grep-binprot.a libsgen-grep-binprot32p.a libsgen-grep-binprot64p.a + +# Main is in a library so it can be C++. +noinst_LIBRARIES = libsgen-grep-binprot.a libsgen-grep-binprot32p.a \ + libsgen-grep-binprot64p.a libmain.a + +# Libraries are C++ if enabled. +libmain_a_CFLAGS = @CXX_ADD_CFLAGS@ +libsgen_grep_binprot_a_CFLAGS = @CXX_ADD_CFLAGS@ +libsgen_grep_binprot32p_a_CFLAGS = @CXX_ADD_CFLAGS@ +libsgen_grep_binprot64p_a_CFLAGS = @CXX_ADD_CFLAGS@ libsgen_grep_binprot_a_SOURCES = sgen-grep-binprot.c sgen-grep-binprot.h libsgen_grep_binprot_a_CPPFLAGS = $(GLIB_CFLAGS) -I$(top_srcdir) libsgen_grep_binprot32p_a_SOURCES = sgen-grep-binprot.c sgen-grep-binprot.h libsgen_grep_binprot32p_a_CPPFLAGS = $(GLIB_CFLAGS) -I$(top_srcdir) -DBINPROT_SIZEOF_VOID_P=4 -DBINPROT_HAS_HEADER libsgen_grep_binprot64p_a_SOURCES = sgen-grep-binprot.c sgen-grep-binprot.h libsgen_grep_binprot64p_a_CPPFLAGS = $(GLIB_CFLAGS) -I$(top_srcdir) -DBINPROT_SIZEOF_VOID_P=8 -DBINPROT_HAS_HEADER -sgen_grep_binprot_SOURCES = \ + +# Executable has no source files, just links to object files and libraries. +sgen_grep_binprot_SOURCES = +libmain_a_SOURCES = \ sgen-grep-binprot-main.c \ sgen-entry-stream.c \ sgen-entry-stream.h + +# Link to the libmain object files instead of library for higher fidelity with old behavior. sgen_grep_binprot_LDADD = \ + libmain_a-sgen-grep-binprot-main.$(OBJEXT) \ + libmain_a-sgen-entry-stream.$(OBJEXT) \ $(glib_libs) libsgen-grep-binprot.a libsgen-grep-binprot32p.a libsgen-grep-binprot64p.a all: all-am @@ -480,6 +524,11 @@ $(am__aclocal_m4_deps): clean-noinstLIBRARIES: -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) +libmain.a: $(libmain_a_OBJECTS) $(libmain_a_DEPENDENCIES) $(EXTRA_libmain_a_DEPENDENCIES) + $(AM_V_at)-rm -f libmain.a + $(AM_V_AR)$(libmain_a_AR) libmain.a $(libmain_a_OBJECTS) $(libmain_a_LIBADD) + $(AM_V_at)$(RANLIB) libmain.a + libsgen-grep-binprot.a: $(libsgen_grep_binprot_a_OBJECTS) $(libsgen_grep_binprot_a_DEPENDENCIES) $(EXTRA_libsgen_grep_binprot_a_DEPENDENCIES) $(AM_V_at)-rm -f libsgen-grep-binprot.a $(AM_V_AR)$(libsgen_grep_binprot_a_AR) libsgen-grep-binprot.a $(libsgen_grep_binprot_a_OBJECTS) $(libsgen_grep_binprot_a_LIBADD) @@ -554,11 +603,11 @@ mostlyclean-compile: distclean-compile: -rm -f *.tab.c +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmain_a-sgen-entry-stream.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmain_a-sgen-grep-binprot-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsgen_grep_binprot32p_a-sgen-grep-binprot.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsgen_grep_binprot64p_a-sgen-grep-binprot.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsgen_grep_binprot_a-sgen-grep-binprot.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sgen-entry-stream.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sgen-grep-binprot-main.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @@ -584,47 +633,75 @@ distclean-compile: @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< +libmain_a-sgen-grep-binprot-main.o: sgen-grep-binprot-main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmain_a_CFLAGS) $(CFLAGS) -MT libmain_a-sgen-grep-binprot-main.o -MD -MP -MF $(DEPDIR)/libmain_a-sgen-grep-binprot-main.Tpo -c -o libmain_a-sgen-grep-binprot-main.o `test -f 'sgen-grep-binprot-main.c' || echo '$(srcdir)/'`sgen-grep-binprot-main.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmain_a-sgen-grep-binprot-main.Tpo $(DEPDIR)/libmain_a-sgen-grep-binprot-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sgen-grep-binprot-main.c' object='libmain_a-sgen-grep-binprot-main.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmain_a_CFLAGS) $(CFLAGS) -c -o libmain_a-sgen-grep-binprot-main.o `test -f 'sgen-grep-binprot-main.c' || echo '$(srcdir)/'`sgen-grep-binprot-main.c + +libmain_a-sgen-grep-binprot-main.obj: sgen-grep-binprot-main.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmain_a_CFLAGS) $(CFLAGS) -MT libmain_a-sgen-grep-binprot-main.obj -MD -MP -MF $(DEPDIR)/libmain_a-sgen-grep-binprot-main.Tpo -c -o libmain_a-sgen-grep-binprot-main.obj `if test -f 'sgen-grep-binprot-main.c'; then $(CYGPATH_W) 'sgen-grep-binprot-main.c'; else $(CYGPATH_W) '$(srcdir)/sgen-grep-binprot-main.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmain_a-sgen-grep-binprot-main.Tpo $(DEPDIR)/libmain_a-sgen-grep-binprot-main.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sgen-grep-binprot-main.c' object='libmain_a-sgen-grep-binprot-main.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmain_a_CFLAGS) $(CFLAGS) -c -o libmain_a-sgen-grep-binprot-main.obj `if test -f 'sgen-grep-binprot-main.c'; then $(CYGPATH_W) 'sgen-grep-binprot-main.c'; else $(CYGPATH_W) '$(srcdir)/sgen-grep-binprot-main.c'; fi` + +libmain_a-sgen-entry-stream.o: sgen-entry-stream.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmain_a_CFLAGS) $(CFLAGS) -MT libmain_a-sgen-entry-stream.o -MD -MP -MF $(DEPDIR)/libmain_a-sgen-entry-stream.Tpo -c -o libmain_a-sgen-entry-stream.o `test -f 'sgen-entry-stream.c' || echo '$(srcdir)/'`sgen-entry-stream.c +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmain_a-sgen-entry-stream.Tpo $(DEPDIR)/libmain_a-sgen-entry-stream.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sgen-entry-stream.c' object='libmain_a-sgen-entry-stream.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmain_a_CFLAGS) $(CFLAGS) -c -o libmain_a-sgen-entry-stream.o `test -f 'sgen-entry-stream.c' || echo '$(srcdir)/'`sgen-entry-stream.c + +libmain_a-sgen-entry-stream.obj: sgen-entry-stream.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmain_a_CFLAGS) $(CFLAGS) -MT libmain_a-sgen-entry-stream.obj -MD -MP -MF $(DEPDIR)/libmain_a-sgen-entry-stream.Tpo -c -o libmain_a-sgen-entry-stream.obj `if test -f 'sgen-entry-stream.c'; then $(CYGPATH_W) 'sgen-entry-stream.c'; else $(CYGPATH_W) '$(srcdir)/sgen-entry-stream.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmain_a-sgen-entry-stream.Tpo $(DEPDIR)/libmain_a-sgen-entry-stream.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sgen-entry-stream.c' object='libmain_a-sgen-entry-stream.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmain_a_CFLAGS) $(CFLAGS) -c -o libmain_a-sgen-entry-stream.obj `if test -f 'sgen-entry-stream.c'; then $(CYGPATH_W) 'sgen-entry-stream.c'; else $(CYGPATH_W) '$(srcdir)/sgen-entry-stream.c'; fi` + libsgen_grep_binprot_a-sgen-grep-binprot.o: sgen-grep-binprot.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot_a_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsgen_grep_binprot_a-sgen-grep-binprot.o -MD -MP -MF $(DEPDIR)/libsgen_grep_binprot_a-sgen-grep-binprot.Tpo -c -o libsgen_grep_binprot_a-sgen-grep-binprot.o `test -f 'sgen-grep-binprot.c' || echo '$(srcdir)/'`sgen-grep-binprot.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot_a_CPPFLAGS) $(CPPFLAGS) $(libsgen_grep_binprot_a_CFLAGS) $(CFLAGS) -MT libsgen_grep_binprot_a-sgen-grep-binprot.o -MD -MP -MF $(DEPDIR)/libsgen_grep_binprot_a-sgen-grep-binprot.Tpo -c -o libsgen_grep_binprot_a-sgen-grep-binprot.o `test -f 'sgen-grep-binprot.c' || echo '$(srcdir)/'`sgen-grep-binprot.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libsgen_grep_binprot_a-sgen-grep-binprot.Tpo $(DEPDIR)/libsgen_grep_binprot_a-sgen-grep-binprot.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sgen-grep-binprot.c' object='libsgen_grep_binprot_a-sgen-grep-binprot.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot_a_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsgen_grep_binprot_a-sgen-grep-binprot.o `test -f 'sgen-grep-binprot.c' || echo '$(srcdir)/'`sgen-grep-binprot.c +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot_a_CPPFLAGS) $(CPPFLAGS) $(libsgen_grep_binprot_a_CFLAGS) $(CFLAGS) -c -o libsgen_grep_binprot_a-sgen-grep-binprot.o `test -f 'sgen-grep-binprot.c' || echo '$(srcdir)/'`sgen-grep-binprot.c libsgen_grep_binprot_a-sgen-grep-binprot.obj: sgen-grep-binprot.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot_a_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsgen_grep_binprot_a-sgen-grep-binprot.obj -MD -MP -MF $(DEPDIR)/libsgen_grep_binprot_a-sgen-grep-binprot.Tpo -c -o libsgen_grep_binprot_a-sgen-grep-binprot.obj `if test -f 'sgen-grep-binprot.c'; then $(CYGPATH_W) 'sgen-grep-binprot.c'; else $(CYGPATH_W) '$(srcdir)/sgen-grep-binprot.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot_a_CPPFLAGS) $(CPPFLAGS) $(libsgen_grep_binprot_a_CFLAGS) $(CFLAGS) -MT libsgen_grep_binprot_a-sgen-grep-binprot.obj -MD -MP -MF $(DEPDIR)/libsgen_grep_binprot_a-sgen-grep-binprot.Tpo -c -o libsgen_grep_binprot_a-sgen-grep-binprot.obj `if test -f 'sgen-grep-binprot.c'; then $(CYGPATH_W) 'sgen-grep-binprot.c'; else $(CYGPATH_W) '$(srcdir)/sgen-grep-binprot.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libsgen_grep_binprot_a-sgen-grep-binprot.Tpo $(DEPDIR)/libsgen_grep_binprot_a-sgen-grep-binprot.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sgen-grep-binprot.c' object='libsgen_grep_binprot_a-sgen-grep-binprot.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot_a_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsgen_grep_binprot_a-sgen-grep-binprot.obj `if test -f 'sgen-grep-binprot.c'; then $(CYGPATH_W) 'sgen-grep-binprot.c'; else $(CYGPATH_W) '$(srcdir)/sgen-grep-binprot.c'; fi` +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot_a_CPPFLAGS) $(CPPFLAGS) $(libsgen_grep_binprot_a_CFLAGS) $(CFLAGS) -c -o libsgen_grep_binprot_a-sgen-grep-binprot.obj `if test -f 'sgen-grep-binprot.c'; then $(CYGPATH_W) 'sgen-grep-binprot.c'; else $(CYGPATH_W) '$(srcdir)/sgen-grep-binprot.c'; fi` libsgen_grep_binprot32p_a-sgen-grep-binprot.o: sgen-grep-binprot.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot32p_a_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsgen_grep_binprot32p_a-sgen-grep-binprot.o -MD -MP -MF $(DEPDIR)/libsgen_grep_binprot32p_a-sgen-grep-binprot.Tpo -c -o libsgen_grep_binprot32p_a-sgen-grep-binprot.o `test -f 'sgen-grep-binprot.c' || echo '$(srcdir)/'`sgen-grep-binprot.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot32p_a_CPPFLAGS) $(CPPFLAGS) $(libsgen_grep_binprot32p_a_CFLAGS) $(CFLAGS) -MT libsgen_grep_binprot32p_a-sgen-grep-binprot.o -MD -MP -MF $(DEPDIR)/libsgen_grep_binprot32p_a-sgen-grep-binprot.Tpo -c -o libsgen_grep_binprot32p_a-sgen-grep-binprot.o `test -f 'sgen-grep-binprot.c' || echo '$(srcdir)/'`sgen-grep-binprot.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libsgen_grep_binprot32p_a-sgen-grep-binprot.Tpo $(DEPDIR)/libsgen_grep_binprot32p_a-sgen-grep-binprot.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sgen-grep-binprot.c' object='libsgen_grep_binprot32p_a-sgen-grep-binprot.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot32p_a_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsgen_grep_binprot32p_a-sgen-grep-binprot.o `test -f 'sgen-grep-binprot.c' || echo '$(srcdir)/'`sgen-grep-binprot.c +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot32p_a_CPPFLAGS) $(CPPFLAGS) $(libsgen_grep_binprot32p_a_CFLAGS) $(CFLAGS) -c -o libsgen_grep_binprot32p_a-sgen-grep-binprot.o `test -f 'sgen-grep-binprot.c' || echo '$(srcdir)/'`sgen-grep-binprot.c libsgen_grep_binprot32p_a-sgen-grep-binprot.obj: sgen-grep-binprot.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot32p_a_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsgen_grep_binprot32p_a-sgen-grep-binprot.obj -MD -MP -MF $(DEPDIR)/libsgen_grep_binprot32p_a-sgen-grep-binprot.Tpo -c -o libsgen_grep_binprot32p_a-sgen-grep-binprot.obj `if test -f 'sgen-grep-binprot.c'; then $(CYGPATH_W) 'sgen-grep-binprot.c'; else $(CYGPATH_W) '$(srcdir)/sgen-grep-binprot.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot32p_a_CPPFLAGS) $(CPPFLAGS) $(libsgen_grep_binprot32p_a_CFLAGS) $(CFLAGS) -MT libsgen_grep_binprot32p_a-sgen-grep-binprot.obj -MD -MP -MF $(DEPDIR)/libsgen_grep_binprot32p_a-sgen-grep-binprot.Tpo -c -o libsgen_grep_binprot32p_a-sgen-grep-binprot.obj `if test -f 'sgen-grep-binprot.c'; then $(CYGPATH_W) 'sgen-grep-binprot.c'; else $(CYGPATH_W) '$(srcdir)/sgen-grep-binprot.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libsgen_grep_binprot32p_a-sgen-grep-binprot.Tpo $(DEPDIR)/libsgen_grep_binprot32p_a-sgen-grep-binprot.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sgen-grep-binprot.c' object='libsgen_grep_binprot32p_a-sgen-grep-binprot.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot32p_a_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsgen_grep_binprot32p_a-sgen-grep-binprot.obj `if test -f 'sgen-grep-binprot.c'; then $(CYGPATH_W) 'sgen-grep-binprot.c'; else $(CYGPATH_W) '$(srcdir)/sgen-grep-binprot.c'; fi` +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot32p_a_CPPFLAGS) $(CPPFLAGS) $(libsgen_grep_binprot32p_a_CFLAGS) $(CFLAGS) -c -o libsgen_grep_binprot32p_a-sgen-grep-binprot.obj `if test -f 'sgen-grep-binprot.c'; then $(CYGPATH_W) 'sgen-grep-binprot.c'; else $(CYGPATH_W) '$(srcdir)/sgen-grep-binprot.c'; fi` libsgen_grep_binprot64p_a-sgen-grep-binprot.o: sgen-grep-binprot.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot64p_a_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsgen_grep_binprot64p_a-sgen-grep-binprot.o -MD -MP -MF $(DEPDIR)/libsgen_grep_binprot64p_a-sgen-grep-binprot.Tpo -c -o libsgen_grep_binprot64p_a-sgen-grep-binprot.o `test -f 'sgen-grep-binprot.c' || echo '$(srcdir)/'`sgen-grep-binprot.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot64p_a_CPPFLAGS) $(CPPFLAGS) $(libsgen_grep_binprot64p_a_CFLAGS) $(CFLAGS) -MT libsgen_grep_binprot64p_a-sgen-grep-binprot.o -MD -MP -MF $(DEPDIR)/libsgen_grep_binprot64p_a-sgen-grep-binprot.Tpo -c -o libsgen_grep_binprot64p_a-sgen-grep-binprot.o `test -f 'sgen-grep-binprot.c' || echo '$(srcdir)/'`sgen-grep-binprot.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libsgen_grep_binprot64p_a-sgen-grep-binprot.Tpo $(DEPDIR)/libsgen_grep_binprot64p_a-sgen-grep-binprot.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sgen-grep-binprot.c' object='libsgen_grep_binprot64p_a-sgen-grep-binprot.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot64p_a_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsgen_grep_binprot64p_a-sgen-grep-binprot.o `test -f 'sgen-grep-binprot.c' || echo '$(srcdir)/'`sgen-grep-binprot.c +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot64p_a_CPPFLAGS) $(CPPFLAGS) $(libsgen_grep_binprot64p_a_CFLAGS) $(CFLAGS) -c -o libsgen_grep_binprot64p_a-sgen-grep-binprot.o `test -f 'sgen-grep-binprot.c' || echo '$(srcdir)/'`sgen-grep-binprot.c libsgen_grep_binprot64p_a-sgen-grep-binprot.obj: sgen-grep-binprot.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot64p_a_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsgen_grep_binprot64p_a-sgen-grep-binprot.obj -MD -MP -MF $(DEPDIR)/libsgen_grep_binprot64p_a-sgen-grep-binprot.Tpo -c -o libsgen_grep_binprot64p_a-sgen-grep-binprot.obj `if test -f 'sgen-grep-binprot.c'; then $(CYGPATH_W) 'sgen-grep-binprot.c'; else $(CYGPATH_W) '$(srcdir)/sgen-grep-binprot.c'; fi` +@am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot64p_a_CPPFLAGS) $(CPPFLAGS) $(libsgen_grep_binprot64p_a_CFLAGS) $(CFLAGS) -MT libsgen_grep_binprot64p_a-sgen-grep-binprot.obj -MD -MP -MF $(DEPDIR)/libsgen_grep_binprot64p_a-sgen-grep-binprot.Tpo -c -o libsgen_grep_binprot64p_a-sgen-grep-binprot.obj `if test -f 'sgen-grep-binprot.c'; then $(CYGPATH_W) 'sgen-grep-binprot.c'; else $(CYGPATH_W) '$(srcdir)/sgen-grep-binprot.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libsgen_grep_binprot64p_a-sgen-grep-binprot.Tpo $(DEPDIR)/libsgen_grep_binprot64p_a-sgen-grep-binprot.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sgen-grep-binprot.c' object='libsgen_grep_binprot64p_a-sgen-grep-binprot.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot64p_a_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsgen_grep_binprot64p_a-sgen-grep-binprot.obj `if test -f 'sgen-grep-binprot.c'; then $(CYGPATH_W) 'sgen-grep-binprot.c'; else $(CYGPATH_W) '$(srcdir)/sgen-grep-binprot.c'; fi` +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsgen_grep_binprot64p_a_CPPFLAGS) $(CPPFLAGS) $(libsgen_grep_binprot64p_a_CFLAGS) $(CFLAGS) -c -o libsgen_grep_binprot64p_a-sgen-grep-binprot.obj `if test -f 'sgen-grep-binprot.c'; then $(CYGPATH_W) 'sgen-grep-binprot.c'; else $(CYGPATH_W) '$(srcdir)/sgen-grep-binprot.c'; fi` mostlyclean-libtool: -rm -f *.lo diff --git a/tools/sgen/sgen-grep-binprot.c b/tools/sgen/sgen-grep-binprot.c index 322f47a72a..fbee56d977 100644 --- a/tools/sgen/sgen-grep-binprot.c +++ b/tools/sgen/sgen-grep-binprot.c @@ -220,10 +220,10 @@ print_entry_content (int entries_size, PrintEntry *entries, gboolean color_outpu printf ("%lld", *(long long*) entries [i].data); break; case TYPE_SIZE: - printf ("%"MWORD_FORMAT_SPEC_D, *(mword*) entries [i].data); + printf ("%" MWORD_FORMAT_SPEC_D, *(mword*) entries [i].data); break; case TYPE_POINTER: - printf ("0x%"MWORD_FORMAT_SPEC_P, *(mword*) entries [i].data); + printf ("0x%" MWORD_FORMAT_SPEC_P, *(mword*) entries [i].data); break; case TYPE_BOOL: printf ("%s", *(gboolean*) entries [i].data ? "true" : "false"); @@ -265,7 +265,7 @@ print_entry (int type, void *data, int num_nums, int *match_indices, gboolean co printf ("%s", #method + strlen ("binary_protocol_")); #define BEGIN_PROTOCOL_ENTRY1(method,t1,f1) \ case PROTOCOL_ID(method): { \ - PROTOCOL_STRUCT (method) *entry = data; \ + PROTOCOL_STRUCT (method) *entry = (PROTOCOL_STRUCT (method)*)data; \ const int pes_size G_GNUC_UNUSED = 1; \ PrintEntry pes [1] G_GNUC_UNUSED; \ pes [0].type = t1; \ @@ -275,7 +275,7 @@ print_entry (int type, void *data, int num_nums, int *match_indices, gboolean co printf ("%s ", #method + strlen ("binary_protocol_")); #define BEGIN_PROTOCOL_ENTRY2(method,t1,f1,t2,f2) \ case PROTOCOL_ID(method): { \ - PROTOCOL_STRUCT (method) *entry = data; \ + PROTOCOL_STRUCT (method) *entry = (PROTOCOL_STRUCT (method)*)data; \ const int pes_size G_GNUC_UNUSED = 2; \ PrintEntry pes [2] G_GNUC_UNUSED; \ pes [0].type = t1; \ @@ -289,7 +289,7 @@ print_entry (int type, void *data, int num_nums, int *match_indices, gboolean co printf ("%s ", #method + strlen ("binary_protocol_")); #define BEGIN_PROTOCOL_ENTRY3(method,t1,f1,t2,f2,t3,f3) \ case PROTOCOL_ID(method): { \ - PROTOCOL_STRUCT (method) *entry = data; \ + PROTOCOL_STRUCT (method) *entry = (PROTOCOL_STRUCT (method)*)data; \ const int pes_size G_GNUC_UNUSED = 3; \ PrintEntry pes [3] G_GNUC_UNUSED; \ pes [0].type = t1; \ @@ -307,7 +307,7 @@ print_entry (int type, void *data, int num_nums, int *match_indices, gboolean co printf ("%s ", #method + strlen ("binary_protocol_")); #define BEGIN_PROTOCOL_ENTRY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \ case PROTOCOL_ID(method): { \ - PROTOCOL_STRUCT (method) *entry = data; \ + PROTOCOL_STRUCT (method) *entry = (PROTOCOL_STRUCT (method)*)data; \ const int pes_size G_GNUC_UNUSED = 4; \ PrintEntry pes [4] G_GNUC_UNUSED; \ pes [0].type = t1; \ @@ -329,7 +329,7 @@ print_entry (int type, void *data, int num_nums, int *match_indices, gboolean co printf ("%s ", #method + strlen ("binary_protocol_")); #define BEGIN_PROTOCOL_ENTRY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \ case PROTOCOL_ID(method): { \ - PROTOCOL_STRUCT (method) *entry = data; \ + PROTOCOL_STRUCT (method) *entry = (PROTOCOL_STRUCT (method)*)data; \ const int pes_size G_GNUC_UNUSED = 5; \ PrintEntry pes [5] G_GNUC_UNUSED; \ pes [0].type = t1; \ @@ -355,7 +355,7 @@ print_entry (int type, void *data, int num_nums, int *match_indices, gboolean co printf ("%s ", #method + strlen ("binary_protocol_")); #define BEGIN_PROTOCOL_ENTRY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \ case PROTOCOL_ID(method): { \ - PROTOCOL_STRUCT (method) *entry = data; \ + PROTOCOL_STRUCT (method) *entry = (PROTOCOL_STRUCT (method)*)data; \ const int pes_size G_GNUC_UNUSED = 6; \ PrintEntry pes [6] G_GNUC_UNUSED; \ pes [0].type = t1; \ @@ -452,22 +452,22 @@ match_index (mword ptr, int type, void *data) case PROTOCOL_ID (method): { #define BEGIN_PROTOCOL_ENTRY1(method,t1,f1) \ case PROTOCOL_ID (method): { \ - PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = data; + PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = (PROTOCOL_STRUCT (method)*)data; #define BEGIN_PROTOCOL_ENTRY2(method,t1,f1,t2,f2) \ case PROTOCOL_ID (method): { \ - PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = data; + PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = (PROTOCOL_STRUCT (method)*)data; #define BEGIN_PROTOCOL_ENTRY3(method,t1,f1,t2,f2,t3,f3) \ case PROTOCOL_ID (method): { \ - PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = data; + PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = (PROTOCOL_STRUCT (method)*)data; #define BEGIN_PROTOCOL_ENTRY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \ case PROTOCOL_ID (method): { \ - PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = data; + PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = (PROTOCOL_STRUCT (method)*)data; #define BEGIN_PROTOCOL_ENTRY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \ case PROTOCOL_ID (method): { \ - PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = data; + PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = (PROTOCOL_STRUCT (method)*)data; #define BEGIN_PROTOCOL_ENTRY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \ case PROTOCOL_ID (method): { \ - PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = data; + PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = (PROTOCOL_STRUCT (method)*)data; #define BEGIN_PROTOCOL_ENTRY_HEAVY0(method) \ BEGIN_PROTOCOL_ENTRY0 (method) @@ -515,22 +515,22 @@ is_vtable_match (mword ptr, int type, void *data) case PROTOCOL_ID (method): { #define BEGIN_PROTOCOL_ENTRY1(method,t1,f1) \ case PROTOCOL_ID (method): { \ - PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = data; + PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = (PROTOCOL_STRUCT (method)*)data; #define BEGIN_PROTOCOL_ENTRY2(method,t1,f1,t2,f2) \ case PROTOCOL_ID (method): { \ - PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = data; + PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = (PROTOCOL_STRUCT (method)*)data; #define BEGIN_PROTOCOL_ENTRY3(method,t1,f1,t2,f2,t3,f3) \ case PROTOCOL_ID (method): { \ - PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = data; + PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = (PROTOCOL_STRUCT (method)*)data; #define BEGIN_PROTOCOL_ENTRY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \ case PROTOCOL_ID (method): { \ - PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = data; + PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = (PROTOCOL_STRUCT (method)*)data; #define BEGIN_PROTOCOL_ENTRY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \ case PROTOCOL_ID (method): { \ - PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = data; + PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = (PROTOCOL_STRUCT (method)*)data; #define BEGIN_PROTOCOL_ENTRY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \ case PROTOCOL_ID (method): { \ - PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = data; + PROTOCOL_STRUCT (method) *entry G_GNUC_UNUSED = (PROTOCOL_STRUCT (method)*)data; #define BEGIN_PROTOCOL_ENTRY_HEAVY0(method) \ BEGIN_PROTOCOL_ENTRY0 (method) @@ -633,7 +633,7 @@ GREP_ENTRIES_FUNCTION_NAME (EntryStream *stream, int num_nums, long nums [], int if (pause_times) { switch (type) { case PROTOCOL_ID (binary_protocol_world_stopping): { - PROTOCOL_STRUCT (binary_protocol_world_stopping) *entry = data; + PROTOCOL_STRUCT (binary_protocol_world_stopping) *entry = (PROTOCOL_STRUCT (binary_protocol_world_stopping)*)data; assert (!pause_times_stopped); pause_times_concurrent = FALSE; pause_times_finish = FALSE; @@ -648,7 +648,7 @@ GREP_ENTRIES_FUNCTION_NAME (EntryStream *stream, int num_nums, long nums [], int pause_times_concurrent = TRUE; break; case PROTOCOL_ID (binary_protocol_world_restarted): { - PROTOCOL_STRUCT (binary_protocol_world_restarted) *entry = data; + PROTOCOL_STRUCT (binary_protocol_world_restarted) *entry = (PROTOCOL_STRUCT (binary_protocol_world_restarted)*)data; assert (pause_times_stopped); printf ("pause-time %d %d %d %lld %lld\n", entry->generation, diff --git a/winconfig.h b/winconfig.h index 178fb00894..23bb291430 100644 --- a/winconfig.h +++ b/winconfig.h @@ -107,9 +107,6 @@ /* Enable DTrace probes */ /* #undef ENABLE_DTRACE */ -/* Has the 'aintl' function */ -/* #undef HAVE_AINTL */ - /* Supports C99 array initialization */ /* #undef HAVE_ARRAY_ELEM_INIT */ @@ -201,9 +198,6 @@ /* Define to 1 if you have the `fgetpwent' function. */ /* #undef HAVE_FGETPWENT */ -/* Define to 1 if you have the `finite' function. */ -/* #undef HAVE_FINITE */ - /* Define to 1 if you have the header file. */ /* #undef HAVE_FSTAB_H */ @@ -258,9 +252,6 @@ /* Define to 1 if you have the header file. */ /* #undef HAVE_GRP_H */ -/* Define to 1 if you have the header file. */ -/* #undef HAVE_IEEEFP_H */ - /* Define to 1 if you have the `inet_aton' function. */ /* #undef HAVE_INET_ATON */ @@ -282,12 +273,6 @@ /* Have IP_PKTINFO */ /* #undef HAVE_IP_PKTINFO */ -/* Define to 1 if you have the `isfinite' function. */ -/* #undef HAVE_ISFINITE */ - -/* isinf available */ -#define HAVE_ISINF 1 - /* Define to 1 if you have the `kqueue' function. */ /* #undef HAVE_KQUEUE */ @@ -295,7 +280,8 @@ #ifdef _MSC_VER #define MONO_KEYWORD_THREAD __declspec (thread) #else -#define MONO_KEYWORD_THREAD __thread +// Cygwin/gcc emulates __thread. +#undef MONO_KEYWORD_THREAD #endif /* Have large file support */ @@ -412,9 +398,6 @@ /* Define to 1 if you have the header file. */ #define HAVE_SIGNAL_H 1 -/* Have signbit */ -/* #undef HAVE_SIGNBIT */ - /* Can get interface list */ /* #undef HAVE_SIOCGIFCONF */ @@ -574,9 +557,6 @@ /* Have tm_gmtoff */ /* #undef HAVE_TM_GMTOFF */ -/* Define to 1 if you have the `trunc' function. */ -#define HAVE_TRUNC 1 - /* Define to 1 if you have the `ttyname_r' function. */ /* #undef HAVE_TTYNAME_R */ @@ -679,6 +659,9 @@ #define SIZEOF_REGISTER SIZEOF_VOID_P +/* byte order of target */ +#define TARGET_BYTE_ORDER G_BYTE_ORDER + /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1